Skip to content

Commit

Permalink
♻️ pubsub timeout
Browse files Browse the repository at this point in the history
  • Loading branch information
fgladisch committed Jul 10, 2023
1 parent eb646fd commit 90da8c7
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
22 changes: 6 additions & 16 deletions src/models/pubsub-client.model.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { PubSub } from "@google-cloud/pubsub";
import { timeout } from "../util/timeout";
import { PubSubContactsMessage } from "./pubsub-contacts-message.model";
import { ServerError } from "./server-error.model";

const PUBLISH_TIMEOUT = 10_000;

export class PubSubClient {
private client: PubSub;
private topicName: string;
Expand All @@ -17,27 +18,16 @@ export class PubSubClient {
throw new Error("No pubsub topic name provided.");
}

const timeout = (ms: number) =>
new Promise((_, reject) =>
setTimeout(
() =>
reject(
new ServerError(
500,
"Could not publish message in time, did you forget to run gcloud auth application-default login?"
)
),
ms
)
);

const json = JSON.stringify(message);
const dataBuffer = Buffer.from(json);
const topic = this.client.topic(this.topicName);

await Promise.race([
topic.publishMessage({ data: dataBuffer }),
timeout(PUBLISH_TIMEOUT),
timeout(
PUBLISH_TIMEOUT,
"Could not publish message in time. Did you forget to authenticate with GCP? (gcloud auth application-default login)"
),
]);
}
}
6 changes: 6 additions & 0 deletions src/util/timeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { ServerError } from "../models";

export const timeout = (timeMs: number, errorMessage: string) =>
new Promise((_, reject) =>
setTimeout(() => reject(new ServerError(500, errorMessage)), timeMs)
);

0 comments on commit 90da8c7

Please sign in to comment.