@palmetto/pubsub 3.2.0 → 3.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bullmq/subscriber.js +1 -1
- package/dist/gcppubsub/config.d.ts +34 -2
- package/dist/gcppubsub/config.js +79 -12
- package/dist/gcppubsub/subscriber.js +61 -39
- package/dist/interfaces.d.ts +21 -4
- package/dist/interfaces.js +5 -3
- package/dist/message-logger.d.ts +2 -2
- package/dist/message-logger.js +2 -2
- package/dist/rabbitmq/subscriber.js +3 -3
- package/dist/subscriber.js +3 -3
- package/package.json +1 -1
- package/src/gcppubsub/README.md +96 -14
|
@@ -75,7 +75,7 @@ class BullMqSubscriber {
|
|
|
75
75
|
attemptsMade: job.attemptsMade,
|
|
76
76
|
firstSent: new Date(job.timestamp),
|
|
77
77
|
lastSent: undefined,
|
|
78
|
-
|
|
78
|
+
willAttemptRetry: this.willRetryJobOnFailure(job),
|
|
79
79
|
};
|
|
80
80
|
const result = yield onMessage(job.data, context);
|
|
81
81
|
if (result === interfaces_js_1.MessageResult.Ok) {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type PubSub } from "@google-cloud/pubsub";
|
|
1
|
+
import { type CreateSubscriptionOptions, type SubscriptionOptions, type PubSub, Topic } from "@google-cloud/pubsub";
|
|
2
2
|
import { MessageContext, PubSubConfiguration } from "../interfaces.js";
|
|
3
3
|
import { GCP_PUBSUB_TRANSPORT } from "./connection.js";
|
|
4
4
|
export interface GcpPubSubConfiguration extends PubSubConfiguration {
|
|
@@ -10,6 +10,10 @@ export interface GcpPubSubConfiguration extends PubSubConfiguration {
|
|
|
10
10
|
* The Pub/Sub topic name. Defaults to `name` if omitted.
|
|
11
11
|
*/
|
|
12
12
|
topicName?: string;
|
|
13
|
+
/**
|
|
14
|
+
* The Pub/Sub dead-letter topic name. Defaults to `${name}.dl` if omitted.
|
|
15
|
+
*/
|
|
16
|
+
deadLetterTopicName?: string;
|
|
13
17
|
/**
|
|
14
18
|
* The Pub/Sub subscription name. Required for subscribers. Defaults to `name` if omitted.
|
|
15
19
|
*/
|
|
@@ -18,7 +22,31 @@ export interface GcpPubSubConfiguration extends PubSubConfiguration {
|
|
|
18
22
|
* Flow control: max outstanding messages (default: 5)
|
|
19
23
|
*/
|
|
20
24
|
maxMessages?: number;
|
|
25
|
+
/**
|
|
26
|
+
* Maximum number of times to retry a message.
|
|
27
|
+
* Default: 0, no retries
|
|
28
|
+
* Max: 99 retries, see max_delivery_attempts in GCP docs
|
|
29
|
+
* Infinite retries: -1
|
|
30
|
+
*/
|
|
31
|
+
retries?: number;
|
|
32
|
+
/**
|
|
33
|
+
* Maximum amount of time to wait, in milliseconds, before retrying a message. Default: 600_000 (10 minutes)
|
|
34
|
+
*/
|
|
35
|
+
maxRetryDelay?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Subscription settings to override defaults when creating a new subscription
|
|
38
|
+
*/
|
|
39
|
+
createSubscriptionOptions?: CreateSubscriptionOptions;
|
|
40
|
+
/**
|
|
41
|
+
* subscription options to override defaults when starting a new subscription
|
|
42
|
+
*/
|
|
43
|
+
subscriptionOptions?: SubscriptionOptions;
|
|
44
|
+
/**
|
|
45
|
+
* During shutdown, pending acks will be waited for up to this amount of time (in milliseconds) after the last message is received before the subscription is closed. Default: 1_000 (1 second)
|
|
46
|
+
*/
|
|
47
|
+
shutdownDelay?: number;
|
|
21
48
|
}
|
|
49
|
+
export declare const RETRY_FOREVER = -1;
|
|
22
50
|
export type TopicType = "default" | "dead-letter";
|
|
23
51
|
export declare const TopicNameExtensions: Record<TopicType, string | undefined>;
|
|
24
52
|
export interface GcpPubSubMessageContext extends MessageContext {
|
|
@@ -31,4 +59,8 @@ export declare function getTopicName(config: GcpPubSubConfiguration, topicType:
|
|
|
31
59
|
export declare function getSubscriptionName(config: GcpPubSubConfiguration): string;
|
|
32
60
|
export declare function isGcpPubSubConfiguration(config: PubSubConfiguration): config is GcpPubSubConfiguration;
|
|
33
61
|
export declare function ensureTopic(client: PubSub, topicName: string): Promise<void>;
|
|
34
|
-
export declare function ensureSubscription(client: PubSub,
|
|
62
|
+
export declare function ensureSubscription(client: PubSub, config: GcpPubSubConfiguration): Promise<{
|
|
63
|
+
deadLetterTopic?: Topic;
|
|
64
|
+
retries: number;
|
|
65
|
+
created: boolean;
|
|
66
|
+
}>;
|
package/dist/gcppubsub/config.js
CHANGED
|
@@ -9,19 +9,24 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
9
9
|
});
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
-
exports.TopicNameExtensions = void 0;
|
|
12
|
+
exports.TopicNameExtensions = exports.RETRY_FOREVER = void 0;
|
|
13
13
|
exports.getTopicName = getTopicName;
|
|
14
14
|
exports.getSubscriptionName = getSubscriptionName;
|
|
15
15
|
exports.isGcpPubSubConfiguration = isGcpPubSubConfiguration;
|
|
16
16
|
exports.ensureTopic = ensureTopic;
|
|
17
17
|
exports.ensureSubscription = ensureSubscription;
|
|
18
|
+
const pubsub_1 = require("@google-cloud/pubsub");
|
|
18
19
|
const connection_js_1 = require("./connection.js");
|
|
20
|
+
exports.RETRY_FOREVER = -1;
|
|
19
21
|
exports.TopicNameExtensions = {
|
|
20
22
|
"dead-letter": ".dl",
|
|
21
23
|
default: undefined,
|
|
22
24
|
};
|
|
23
25
|
function getTopicName(config, topicType) {
|
|
24
26
|
var _a, _b;
|
|
27
|
+
if (topicType === "dead-letter" && config.deadLetterTopicName) {
|
|
28
|
+
return config.deadLetterTopicName;
|
|
29
|
+
}
|
|
25
30
|
const baseName = (_a = config.topicName) !== null && _a !== void 0 ? _a : config.name;
|
|
26
31
|
const extension = (_b = exports.TopicNameExtensions[topicType]) !== null && _b !== void 0 ? _b : "";
|
|
27
32
|
return `${baseName}${extension}`;
|
|
@@ -41,19 +46,81 @@ function ensureTopic(client, topicName) {
|
|
|
41
46
|
}
|
|
42
47
|
});
|
|
43
48
|
}
|
|
44
|
-
function ensureSubscription(client,
|
|
49
|
+
function ensureSubscription(client, config) {
|
|
45
50
|
return __awaiter(this, void 0, void 0, function* () {
|
|
51
|
+
var _a, _b, _c, _d, _e;
|
|
52
|
+
const topic = client.topic(getTopicName(config, "default"));
|
|
53
|
+
const subscriptions = (yield topic.getSubscriptions({
|
|
54
|
+
pageSize: 1000,
|
|
55
|
+
}))[0];
|
|
56
|
+
const subscriptionName = getSubscriptionName(config);
|
|
57
|
+
const subscription = subscriptions.find((s) => s.name.endsWith(`/${subscriptionName}`));
|
|
58
|
+
if (subscription) {
|
|
59
|
+
const meta = (_a = subscription.metadata) !== null && _a !== void 0 ? _a : (yield subscription.getMetadata())[0];
|
|
60
|
+
let deadLetterTopic = undefined;
|
|
61
|
+
let retries;
|
|
62
|
+
if ((_b = meta.deadLetterPolicy) === null || _b === void 0 ? void 0 : _b.deadLetterTopic) {
|
|
63
|
+
const dlp = pubsub_1.protos.google.pubsub.v1.DeadLetterPolicy.create(meta.deadLetterPolicy);
|
|
64
|
+
if (config.retries !== undefined && config.retries < 0) {
|
|
65
|
+
// If retries is negative, we want to retry forever, but GCP Pub/Sub doesn't support that, so we set it to the max allowed by the dead-letter policy
|
|
66
|
+
retries = dlp.maxDeliveryAttempts - 1;
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
// config.retries can override maxDeliveryAttempts, but it can't exceed the max allowed by the dead-letter policy
|
|
70
|
+
retries = Math.min((_c = config.retries) !== null && _c !== void 0 ? _c : 0, dlp.maxDeliveryAttempts - 1);
|
|
71
|
+
}
|
|
72
|
+
deadLetterTopic = client.topic(dlp.deadLetterTopic);
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
retries = exports.RETRY_FOREVER;
|
|
76
|
+
}
|
|
77
|
+
return {
|
|
78
|
+
deadLetterTopic,
|
|
79
|
+
retries,
|
|
80
|
+
created: false,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
const topicName = getTopicName(config, "default");
|
|
84
|
+
const dlTopicName = getTopicName(config, "dead-letter");
|
|
85
|
+
const minRetryDelay = (_d = config.retryDelay) !== null && _d !== void 0 ? _d : 30000;
|
|
86
|
+
const maxRetryDelay = config.maxRetryDelay;
|
|
87
|
+
const maxDeliveryAttempts = ((_e = config.retries) !== null && _e !== void 0 ? _e : 0) + 1;
|
|
88
|
+
const enableDeadLetter = maxDeliveryAttempts > 0;
|
|
89
|
+
if (enableDeadLetter) {
|
|
90
|
+
yield ensureSubscription(client, Object.assign(Object.assign({}, config), { retries: exports.RETRY_FOREVER, name: dlTopicName, topicName: dlTopicName, deadLetterTopicName: undefined, subscriptionName: `${dlTopicName}.sub`, retryDelay: minRetryDelay, maxRetryDelay }));
|
|
91
|
+
}
|
|
46
92
|
yield ensureTopic(client, topicName);
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
93
|
+
const enableRetryPolicy = minRetryDelay > 0 || maxRetryDelay !== undefined;
|
|
94
|
+
const deadLetterTopic = enableDeadLetter
|
|
95
|
+
? client.topic(dlTopicName)
|
|
96
|
+
: undefined;
|
|
97
|
+
const options = Object.assign(Object.assign(Object.assign({}, (enableDeadLetter
|
|
98
|
+
? {
|
|
99
|
+
deadLetterPolicy: {
|
|
100
|
+
deadLetterTopic: deadLetterTopic === null || deadLetterTopic === void 0 ? void 0 : deadLetterTopic.name,
|
|
101
|
+
maxDeliveryAttempts: Math.max(maxDeliveryAttempts, 5),
|
|
55
102
|
},
|
|
56
|
-
}
|
|
57
|
-
|
|
103
|
+
}
|
|
104
|
+
: {})), (enableRetryPolicy
|
|
105
|
+
? {
|
|
106
|
+
retryPolicy: Object.assign({ minimumBackoff: {
|
|
107
|
+
nanos: (minRetryDelay % 1000) * 1000000,
|
|
108
|
+
seconds: Math.floor(minRetryDelay / 1000),
|
|
109
|
+
} }, (maxRetryDelay !== undefined
|
|
110
|
+
? {
|
|
111
|
+
maximumBackoff: {
|
|
112
|
+
nanos: (maxRetryDelay % 1000) * 1000000,
|
|
113
|
+
seconds: Math.floor(maxRetryDelay / 1000),
|
|
114
|
+
},
|
|
115
|
+
}
|
|
116
|
+
: {})),
|
|
117
|
+
}
|
|
118
|
+
: {})), config.createSubscriptionOptions);
|
|
119
|
+
yield topic.createSubscription(subscriptionName, options);
|
|
120
|
+
return {
|
|
121
|
+
deadLetterTopic,
|
|
122
|
+
retries: maxDeliveryAttempts > 0 ? maxDeliveryAttempts - 1 : exports.RETRY_FOREVER,
|
|
123
|
+
created: true,
|
|
124
|
+
};
|
|
58
125
|
});
|
|
59
126
|
}
|
|
@@ -10,14 +10,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
10
10
|
};
|
|
11
11
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
12
|
exports.GcpPubSubSubscriber = void 0;
|
|
13
|
+
const pubsub_1 = require("@google-cloud/pubsub");
|
|
13
14
|
const trace_1 = require("@palmetto/trace");
|
|
14
15
|
const interfaces_js_1 = require("../interfaces.js");
|
|
15
16
|
const errors_js_1 = require("../errors.js");
|
|
16
17
|
const create_log_error_payload_js_1 = require("../create-log-error-payload.js");
|
|
17
18
|
const config_js_1 = require("./config.js");
|
|
18
19
|
const connection_js_1 = require("./connection.js");
|
|
19
|
-
const
|
|
20
|
-
const FIRST_PUBLISHED_ATTR = "x-first-published";
|
|
20
|
+
const subscriber_js_1 = require("@google-cloud/pubsub/build/src/subscriber.js");
|
|
21
21
|
const SHUTDOWN_DELAY = 1000;
|
|
22
22
|
class GcpPubSubSubscriber {
|
|
23
23
|
constructor(connection, logger) {
|
|
@@ -29,22 +29,33 @@ class GcpPubSubSubscriber {
|
|
|
29
29
|
}
|
|
30
30
|
startSubscribe(config, onMessage) {
|
|
31
31
|
return __awaiter(this, void 0, void 0, function* () {
|
|
32
|
-
var _a, _b;
|
|
32
|
+
var _a, _b, _c, _d;
|
|
33
33
|
const subscriptionName = (0, config_js_1.getSubscriptionName)(config);
|
|
34
34
|
if (this.subscriptions.has(subscriptionName)) {
|
|
35
35
|
throw new errors_js_1.AlreadySubscribingError(subscriptionName);
|
|
36
36
|
}
|
|
37
37
|
const topicName = (0, config_js_1.getTopicName)(config, "default");
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
38
|
+
const { deadLetterTopic, retries } = yield (0, config_js_1.ensureSubscription)(this.connection.client, config);
|
|
39
|
+
if (retries !== ((_a = config.retries) !== null && _a !== void 0 ? _a : 0)) {
|
|
40
|
+
const configRetries = (_b = config.retries) !== null && _b !== void 0 ? _b : 0;
|
|
41
|
+
const log = {
|
|
42
|
+
message: `GCP Pub/Sub subscription ${subscriptionName} retry configuration mismatch.`,
|
|
43
|
+
extra: {
|
|
44
|
+
subscriptionName,
|
|
45
|
+
configRetries,
|
|
46
|
+
subscriptionRetries: retries,
|
|
47
|
+
},
|
|
48
|
+
};
|
|
49
|
+
this.logger.warn(log);
|
|
50
|
+
}
|
|
51
|
+
const subscription = this.connection.client.subscription(subscriptionName, Object.assign({ flowControl: {
|
|
52
|
+
maxMessages: (_c = config.maxMessages) !== null && _c !== void 0 ? _c : 5,
|
|
53
|
+
}, closeOptions: {
|
|
54
|
+
behavior: subscriber_js_1.SubscriberCloseBehaviors.WaitForProcessing,
|
|
55
|
+
timeout: pubsub_1.Duration.from({
|
|
56
|
+
milliseconds: (_d = config.shutdownDelay) !== null && _d !== void 0 ? _d : SHUTDOWN_DELAY,
|
|
57
|
+
}),
|
|
58
|
+
} }, config.subscriptionOptions));
|
|
48
59
|
const messageHandler = (message) => {
|
|
49
60
|
void this.consumeMessage({
|
|
50
61
|
config,
|
|
@@ -52,8 +63,8 @@ class GcpPubSubSubscriber {
|
|
|
52
63
|
onMessage,
|
|
53
64
|
subscriptionName,
|
|
54
65
|
topicName,
|
|
55
|
-
|
|
56
|
-
|
|
66
|
+
deadLetterTopic,
|
|
67
|
+
retries,
|
|
57
68
|
});
|
|
58
69
|
};
|
|
59
70
|
const errorHandler = (err) => {
|
|
@@ -65,12 +76,12 @@ class GcpPubSubSubscriber {
|
|
|
65
76
|
};
|
|
66
77
|
subscription.on("message", messageHandler);
|
|
67
78
|
subscription.on("error", errorHandler);
|
|
68
|
-
this.subscriptions.set(subscriptionName, subscription);
|
|
79
|
+
this.subscriptions.set(subscriptionName, { subscription, config });
|
|
69
80
|
this.logger.log(`GCP Pub/Sub consumer started for ${subscriptionName}`);
|
|
70
81
|
return () => __awaiter(this, void 0, void 0, function* () {
|
|
71
82
|
subscription.removeListener("message", messageHandler);
|
|
72
83
|
subscription.removeListener("error", errorHandler);
|
|
73
|
-
yield this.waitForMessagesToComplete();
|
|
84
|
+
yield this.waitForMessagesToComplete(config.shutdownDelay);
|
|
74
85
|
yield subscription.close();
|
|
75
86
|
this.subscriptions.delete(subscriptionName);
|
|
76
87
|
this.logger.log(`GCP Pub/Sub consumer stopped for ${subscriptionName}`);
|
|
@@ -80,8 +91,8 @@ class GcpPubSubSubscriber {
|
|
|
80
91
|
close() {
|
|
81
92
|
return __awaiter(this, void 0, void 0, function* () {
|
|
82
93
|
yield Promise.all([...this.subscriptions.entries()].map((_a) => __awaiter(this, [_a], void 0, function* ([subscriptionName, sub]) {
|
|
83
|
-
yield this.waitForMessagesToComplete();
|
|
84
|
-
yield sub.close();
|
|
94
|
+
yield this.waitForMessagesToComplete(sub.config.shutdownDelay);
|
|
95
|
+
yield sub.subscription.close();
|
|
85
96
|
this.logger.log(`GCP Pub/Sub consumer stopped for ${subscriptionName}`);
|
|
86
97
|
})));
|
|
87
98
|
this.subscriptions.clear();
|
|
@@ -94,27 +105,28 @@ class GcpPubSubSubscriber {
|
|
|
94
105
|
};
|
|
95
106
|
}
|
|
96
107
|
consumeMessage(_a) {
|
|
97
|
-
return __awaiter(this, arguments, void 0, function* ({ config, message, onMessage, subscriptionName, topicName,
|
|
108
|
+
return __awaiter(this, arguments, void 0, function* ({ config, message, onMessage, subscriptionName, topicName, deadLetterTopic, retries, }) {
|
|
98
109
|
yield (0, trace_1.getTracer)().trace("pubsub.gcppubsub.consume", {
|
|
99
110
|
resource: `consume ${config.transport} ${subscriptionName}`,
|
|
100
111
|
}, (span) => __awaiter(this, void 0, void 0, function* () {
|
|
101
|
-
var _a, _b, _c, _d, _e, _f
|
|
112
|
+
var _a, _b, _c, _d, _e, _f;
|
|
102
113
|
try {
|
|
103
114
|
const firstPublished = message.publishTime;
|
|
104
115
|
let retryCount = message.deliveryAttempt - 1;
|
|
105
|
-
let
|
|
106
|
-
if (retryCount < 0) {
|
|
116
|
+
let willAttemptRetry;
|
|
117
|
+
if (retryCount < 0 || retries === config_js_1.RETRY_FOREVER) {
|
|
118
|
+
// in this case, we will retry forever
|
|
107
119
|
retryCount = 0;
|
|
108
|
-
|
|
120
|
+
willAttemptRetry = true;
|
|
109
121
|
}
|
|
110
122
|
else {
|
|
111
|
-
|
|
123
|
+
willAttemptRetry = retryCount < retries;
|
|
112
124
|
}
|
|
113
125
|
const context = {
|
|
114
126
|
attemptsMade: retryCount,
|
|
115
127
|
firstSent: firstPublished,
|
|
116
128
|
lastSent: undefined,
|
|
117
|
-
|
|
129
|
+
willAttemptRetry,
|
|
118
130
|
messageId: message.id,
|
|
119
131
|
subscriptionName,
|
|
120
132
|
topicName,
|
|
@@ -139,27 +151,37 @@ class GcpPubSubSubscriber {
|
|
|
139
151
|
}
|
|
140
152
|
this.lastMessageDate = Date.now();
|
|
141
153
|
if (messageResult === interfaces_js_1.MessageResult.Ok) {
|
|
142
|
-
(
|
|
154
|
+
(_b = (_a = this.logger).debug) === null || _b === void 0 ? void 0 : _b.call(_a, logPayload);
|
|
143
155
|
message.ack();
|
|
144
156
|
return;
|
|
145
157
|
}
|
|
146
|
-
if (messageResult === interfaces_js_1.MessageResult.Retry &&
|
|
158
|
+
if (messageResult === interfaces_js_1.MessageResult.Retry && willAttemptRetry) {
|
|
147
159
|
message.nack();
|
|
148
|
-
logPayload.message += " Retrying message via
|
|
149
|
-
(
|
|
160
|
+
logPayload.message += " Retrying message via gcp-pubsub.";
|
|
161
|
+
(_d = (_c = this.logger).debug) === null || _d === void 0 ? void 0 : _d.call(_c, logPayload);
|
|
150
162
|
return;
|
|
151
163
|
}
|
|
152
164
|
// Fail: either explicit Fail or Retry with no retries remaining
|
|
153
165
|
if (messageResult === interfaces_js_1.MessageResult.Retry) {
|
|
154
166
|
logPayload.message += " No more retries.";
|
|
155
167
|
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
168
|
+
(_f = (_e = this.logger).debug) === null || _f === void 0 ? void 0 : _f.call(_e, logPayload);
|
|
169
|
+
if (deadLetterTopic &&
|
|
170
|
+
(messageResult === interfaces_js_1.MessageResult.Fail || retryCount < 4)) {
|
|
171
|
+
// Send all failed messages to the dead-letter topic
|
|
172
|
+
// GCP Pub/Sub doesn't allow maxDeliveryAttempts less than 5, so we need to manually publish to the dead-letter topic for the first 4 retries
|
|
173
|
+
logPayload.message += " Publishing message to dead-letter topic.";
|
|
174
|
+
yield deadLetterTopic.publishMessage({
|
|
175
|
+
data: message.data,
|
|
176
|
+
});
|
|
177
|
+
message.ack(); // ack the message to remove it from the subscription
|
|
178
|
+
}
|
|
179
|
+
else if (messageResult === interfaces_js_1.MessageResult.Fail) {
|
|
180
|
+
message.ack(); // ack the message to remove it from the subscription
|
|
181
|
+
}
|
|
182
|
+
else {
|
|
183
|
+
message.nack(); // nack the message to let pubsub send it to the DLQ
|
|
184
|
+
}
|
|
163
185
|
}
|
|
164
186
|
catch (err) {
|
|
165
187
|
const logPayload = {
|
|
@@ -181,8 +203,8 @@ class GcpPubSubSubscriber {
|
|
|
181
203
|
* Wait for in-flight message handling to complete before shutting down
|
|
182
204
|
*/
|
|
183
205
|
waitForMessagesToComplete() {
|
|
184
|
-
return __awaiter(this,
|
|
185
|
-
const waitUntil = this.lastMessageDate +
|
|
206
|
+
return __awaiter(this, arguments, void 0, function* (shutdownDelay = SHUTDOWN_DELAY) {
|
|
207
|
+
const waitUntil = this.lastMessageDate + shutdownDelay;
|
|
186
208
|
const waitDuration = waitUntil - Date.now();
|
|
187
209
|
if (waitDuration > 0) {
|
|
188
210
|
yield new Promise((resolve) => setTimeout(resolve, waitDuration));
|
package/dist/interfaces.d.ts
CHANGED
|
@@ -66,15 +66,17 @@ export interface PubSubConfiguration {
|
|
|
66
66
|
}
|
|
67
67
|
export declare enum MessageResult {
|
|
68
68
|
/**
|
|
69
|
-
*
|
|
69
|
+
* The message was handled. The transport should not deliver this message again.
|
|
70
70
|
*/
|
|
71
71
|
Ok = "ok",
|
|
72
72
|
/**
|
|
73
|
-
* The message should be retried
|
|
73
|
+
* The message should be retried by the transport.
|
|
74
|
+
* Whether the message is retried immediately or after a delay depends on the transport and configuration.
|
|
75
|
+
* If the number of retries exceeds the configured limit for the transport, the message is considered failed.
|
|
74
76
|
*/
|
|
75
77
|
Retry = "retry",
|
|
76
78
|
/**
|
|
77
|
-
* The message failed and is either discarded or stored in a dead-letter queue
|
|
79
|
+
* The message failed and is either discarded or stored in a dead-letter queue, depending on the transport and configuration.
|
|
78
80
|
*/
|
|
79
81
|
Fail = "fail"
|
|
80
82
|
}
|
|
@@ -129,8 +131,23 @@ export type PubSubProvider = PublisherProvider & SubscriberProvider;
|
|
|
129
131
|
*/
|
|
130
132
|
export type PubOrSubProvider = PubSubProvider | PublisherProvider | SubscriberProvider;
|
|
131
133
|
export interface MessageContext {
|
|
134
|
+
/**
|
|
135
|
+
* When the message was first published.
|
|
136
|
+
*/
|
|
132
137
|
firstSent: Date | undefined;
|
|
138
|
+
/**
|
|
139
|
+
* When the message was last published. Not all transports provide this information.
|
|
140
|
+
*/
|
|
133
141
|
lastSent: Date | undefined;
|
|
142
|
+
/**
|
|
143
|
+
* The number of times the message has been attempted to be processed. This is 0 for the first attempt, 1 for the first retry, etc.
|
|
144
|
+
* Note that for some transports, this number is an approximation based on the number of times the message has been redelivered, or may always be 0.
|
|
145
|
+
*/
|
|
134
146
|
attemptsMade: number | undefined;
|
|
135
|
-
|
|
147
|
+
/**
|
|
148
|
+
* If the onMessage callback returns MessageResult.Retry or throws an exception:
|
|
149
|
+
* When true, the message will be retried
|
|
150
|
+
* When false, the message will not be retried
|
|
151
|
+
*/
|
|
152
|
+
willAttemptRetry: boolean;
|
|
136
153
|
}
|
package/dist/interfaces.js
CHANGED
|
@@ -14,15 +14,17 @@ exports.IdMetaSchema = zod_1.z.object({
|
|
|
14
14
|
var MessageResult;
|
|
15
15
|
(function (MessageResult) {
|
|
16
16
|
/**
|
|
17
|
-
*
|
|
17
|
+
* The message was handled. The transport should not deliver this message again.
|
|
18
18
|
*/
|
|
19
19
|
MessageResult["Ok"] = "ok";
|
|
20
20
|
/**
|
|
21
|
-
* The message should be retried
|
|
21
|
+
* The message should be retried by the transport.
|
|
22
|
+
* Whether the message is retried immediately or after a delay depends on the transport and configuration.
|
|
23
|
+
* If the number of retries exceeds the configured limit for the transport, the message is considered failed.
|
|
22
24
|
*/
|
|
23
25
|
MessageResult["Retry"] = "retry";
|
|
24
26
|
/**
|
|
25
|
-
* The message failed and is either discarded or stored in a dead-letter queue
|
|
27
|
+
* The message failed and is either discarded or stored in a dead-letter queue, depending on the transport and configuration.
|
|
26
28
|
*/
|
|
27
29
|
MessageResult["Fail"] = "fail";
|
|
28
30
|
})(MessageResult || (exports.MessageResult = MessageResult = {}));
|
package/dist/message-logger.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Logger, MessageLogLevel } from "./interfaces";
|
|
2
|
-
export declare function startTiming():
|
|
3
|
-
export declare function getDuration(start:
|
|
2
|
+
export declare function startTiming(): bigint;
|
|
3
|
+
export declare function getDuration(start: bigint): number;
|
|
4
4
|
export declare function logMessage({ note, message, logger, level, extra, }: {
|
|
5
5
|
note: string;
|
|
6
6
|
message: unknown;
|
package/dist/message-logger.js
CHANGED
|
@@ -4,10 +4,10 @@ exports.startTiming = startTiming;
|
|
|
4
4
|
exports.getDuration = getDuration;
|
|
5
5
|
exports.logMessage = logMessage;
|
|
6
6
|
function startTiming() {
|
|
7
|
-
return process.hrtime();
|
|
7
|
+
return process.hrtime.bigint();
|
|
8
8
|
}
|
|
9
9
|
function getDuration(start) {
|
|
10
|
-
return process.hrtime(start)
|
|
10
|
+
return Number(process.hrtime.bigint() - start) / 1000000; // convert to milliseconds
|
|
11
11
|
}
|
|
12
12
|
function logMessage({ note, message, logger, level = "debug", extra, }) {
|
|
13
13
|
var _a;
|
|
@@ -195,8 +195,8 @@ class RabbitMqSubscriber {
|
|
|
195
195
|
const json = msg.content.toString("utf8");
|
|
196
196
|
const attemptsMade = RabbitMqSubscriber.getAttemptsMade(msg);
|
|
197
197
|
const sentDates = RabbitMqSubscriber.getSentDates(msg);
|
|
198
|
-
const
|
|
199
|
-
const context = Object.assign(Object.assign({ attemptsMade }, sentDates), { queueName, exchangeName: msg.fields.exchange, retryExchangeName, routingKey: msg.fields.routingKey,
|
|
198
|
+
const willAttemptRetry = attemptsMade < ((_b = subscribedMessage.config.retries) !== null && _b !== void 0 ? _b : 0);
|
|
199
|
+
const context = Object.assign(Object.assign({ attemptsMade }, sentDates), { queueName, exchangeName: msg.fields.exchange, retryExchangeName, routingKey: msg.fields.routingKey, willAttemptRetry });
|
|
200
200
|
let messageResult;
|
|
201
201
|
let logPayload;
|
|
202
202
|
try {
|
|
@@ -220,7 +220,7 @@ class RabbitMqSubscriber {
|
|
|
220
220
|
return;
|
|
221
221
|
}
|
|
222
222
|
if (messageResult === interfaces_js_1.MessageResult.Retry) {
|
|
223
|
-
if (
|
|
223
|
+
if (willAttemptRetry) {
|
|
224
224
|
logPayload.message += " Retrying message.";
|
|
225
225
|
}
|
|
226
226
|
else {
|
package/dist/subscriber.js
CHANGED
|
@@ -108,13 +108,13 @@ class Subscriber {
|
|
|
108
108
|
(0, message_logger_js_1.logMessage)({
|
|
109
109
|
note: "Subscriber error when processing message",
|
|
110
110
|
message: decodeResult.data,
|
|
111
|
-
level: context.
|
|
111
|
+
level: context.willAttemptRetry ? "warn" : "error",
|
|
112
112
|
logger: this.logger,
|
|
113
113
|
extra: Object.assign(Object.assign({ transport: provider.transport, name: config.name, durationMs,
|
|
114
114
|
context }, enrichedConfig), { error: (0, create_log_error_payload_js_1.createLogErrorPayload)(err) }),
|
|
115
115
|
});
|
|
116
|
-
// in the messageHandled event, we always log as retry or fail based on
|
|
117
|
-
const result = context.
|
|
116
|
+
// in the messageHandled event, we always log as retry or fail based on willAttemptRetry
|
|
117
|
+
const result = context.willAttemptRetry
|
|
118
118
|
? interfaces_js_1.MessageResult.Retry
|
|
119
119
|
: interfaces_js_1.MessageResult.Fail;
|
|
120
120
|
const eventContext = {
|
package/package.json
CHANGED
package/src/gcppubsub/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @palmetto/pubsub
|
|
2
2
|
|
|
3
|
-
The GoogleCloud pubsub transport provider for @palmetto/pubsub
|
|
3
|
+
The GoogleCloud Pub/Sub (gcp-pubsub) transport provider for @palmetto/pubsub
|
|
4
4
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
@@ -48,7 +48,7 @@ yarn add @palmetto/pubsub @google-cloud/pubsub zod
|
|
|
48
48
|
]);
|
|
49
49
|
```
|
|
50
50
|
|
|
51
|
-
5. Create the
|
|
51
|
+
5. Create the topic/subscriber configuration
|
|
52
52
|
|
|
53
53
|
```ts
|
|
54
54
|
import {
|
|
@@ -66,8 +66,10 @@ yarn add @palmetto/pubsub @google-cloud/pubsub zod
|
|
|
66
66
|
subscriptionName: "my-subscription-name", // default: topicName or name
|
|
67
67
|
schema: MyModelSchema,
|
|
68
68
|
transport: GCP_PUBSUB_TRANSPORT,
|
|
69
|
-
retries: 10,
|
|
70
|
-
retryDelay: 1_000, // Note: retryDelay
|
|
69
|
+
retries: 10, // Note: enables dead-letter policy. Use RETRY_FOREVER to disable dead-letter. @palmetto/pubsub will not update an existing subscription.
|
|
70
|
+
retryDelay: 1_000, // Note: retryDelay is minimum retry milliseconds using the exponential backoff retry policy. @palmetto/pubsub will not update an existing subscription.
|
|
71
|
+
createSubscriptionOptions: { ... }, // set the specific createSubscription() options you want to use [optional]
|
|
72
|
+
subscriptionOptions: { ... }, // set any specific subscribe() options you want to use [optional]
|
|
71
73
|
};
|
|
72
74
|
```
|
|
73
75
|
|
|
@@ -87,7 +89,7 @@ yarn add @palmetto/pubsub @google-cloud/pubsub zod
|
|
|
87
89
|
await publisher.publish(config, message);
|
|
88
90
|
```
|
|
89
91
|
|
|
90
|
-
8. Subscribe to a
|
|
92
|
+
8. Subscribe to a topic
|
|
91
93
|
|
|
92
94
|
```ts
|
|
93
95
|
import { GcpPubSubMessageContext } from "@palmetto/pubsub";
|
|
@@ -114,21 +116,101 @@ yarn add @palmetto/pubsub @google-cloud/pubsub zod
|
|
|
114
116
|
});
|
|
115
117
|
```
|
|
116
118
|
|
|
117
|
-
## Message
|
|
119
|
+
## Message Handlers
|
|
118
120
|
|
|
119
|
-
Message
|
|
121
|
+
Message handlers can return one of 3 values:
|
|
122
|
+
|
|
123
|
+
- `MessageResult.Ok` - the message can be removed from subscription. Messages are always `ack()`'ed.
|
|
124
|
+
- `MessageResult.Retry` - the message can be retried, depending on the dead-letter/retry configuration. Messages are typically `nack()`'ed to use gcp-pubsub dead-letter policy. [See below](#retrying-messages)
|
|
125
|
+
- `MessageResult.Fail` - Remove it from the subscription and publish it to the dead-letter topic (if available). Messages are always `ack()`'ed. [See below](#failing-messages)
|
|
126
|
+
|
|
127
|
+
If a message handler throws an exception, this is the same as if it returned `MessageResult.Retry`.
|
|
120
128
|
|
|
121
129
|
### Retrying messages
|
|
122
130
|
|
|
123
|
-
|
|
131
|
+
By default gcp-pubsub subscriptions retry messages immediately, but `@palmetto/pubsub` subscriptions default to a 30 second retry policy.
|
|
132
|
+
|
|
133
|
+
- minimum backoff: default 30 seconds
|
|
134
|
+
- maximum backoff: default 10 minutes (gcp-pubsub default)
|
|
135
|
+
|
|
136
|
+
You can adjust these defaults using these two configuration settings:
|
|
137
|
+
|
|
138
|
+
- `retryDelay`
|
|
139
|
+
- 0 : immediate retry
|
|
140
|
+
- 1 to 600_000 : enable exponential backoff retry policy (values over 600_000 [10 minutes] are not supported by gcp-pubsub)
|
|
141
|
+
- `maxRetryDelay`
|
|
142
|
+
- any value here enables exponential backoff retry policy
|
|
143
|
+
- be sure this value is equal to or larger than the `retryDelay`
|
|
144
|
+
|
|
145
|
+
Messages can be retried when the handler throws an exception or when it returns `MessageResult.Retry`.
|
|
146
|
+
|
|
147
|
+
The `retries` property configures the subscription retry policy when `@palmetto/pubsub` creates the subscription. If `@palmetto/pubsub` didn't create the subscription, whatever retry policy in place is what will be used (by default there are infinite retries).
|
|
148
|
+
|
|
149
|
+
NOTE: If the subscription already exists, and there is no dead-letter policy, the configured `retries` value is ignored and assumes `RETRY_FOREVER` instead.
|
|
150
|
+
|
|
151
|
+
The following special values define how `@palmetto/pubsub` creates the subscription retry policy:
|
|
152
|
+
|
|
153
|
+
#### `{ retries: RETRY_FOREVER }`
|
|
154
|
+
|
|
155
|
+
Use `RETRY_FOREVER` or `-1` to disable dead-letter policy.
|
|
156
|
+
|
|
157
|
+
When a message handler throws an exception or returns `MessageResult.Retry` the message is retried. Messages are retried until the message retention period expires.
|
|
158
|
+
|
|
159
|
+
When a message handler returns `MessageResult.Fail` or `MessageResult.Ok`, `ack()` is called on the message to remove it from the subscription.
|
|
160
|
+
|
|
161
|
+
The `messageContext` includes `{ attemptsMade: 0 }` on every message.
|
|
162
|
+
|
|
163
|
+
#### `{ retries: undefined }` or `{ retries: 0 }`
|
|
164
|
+
|
|
165
|
+
There are no retries, but dead-letter topic is enabled.
|
|
166
|
+
|
|
167
|
+
An exception or return values of `MessageResult.Fail` or `MessageResult.Retry` the message is published to the dead-letter topic and `ack()` is called on the message to remove it from the subscription.
|
|
168
|
+
|
|
169
|
+
The `messageContext` includes `{ attemptsMade: 0 }` on the first message and will be a number greater than 0 if the message is retried due to the race condition.
|
|
124
170
|
|
|
125
|
-
|
|
126
|
-
- `retryDelay`: specifies the number of milliseconds between retries.
|
|
171
|
+
#### `{ retries: 1, 2 or 3 }`
|
|
127
172
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
173
|
+
Dead-letter topic is enabled.
|
|
174
|
+
|
|
175
|
+
An exception or return of `MessageResult.Retry` will `nack()` the message so it is retried by Google up to the specified retries.
|
|
176
|
+
At that point, the message is published to the dead-letter topic and `ack()` is called on the message.
|
|
177
|
+
|
|
178
|
+
A return of `MessageResult.Fail` will publish the message to the dead-letter topic and `ack()` is called on the message to remove it from the subscription.
|
|
179
|
+
|
|
180
|
+
The `messageContext` includes `{ attemptsMade: 0-3 }` for each retry. It's possible to be attemptsMade up to 4 due to the race condition above.
|
|
181
|
+
|
|
182
|
+
#### `{ retries: 4 to 99 }`
|
|
183
|
+
|
|
184
|
+
Dead-letter topic is enabled.
|
|
185
|
+
|
|
186
|
+
An exception or return of `MessageResult.Retry` will `nack()` the message so it is retried by Google up to the specified retries.
|
|
187
|
+
|
|
188
|
+
A return of `MessageResult.Fail` will publish the message to the dead-letter topic and `ack()` is called on the message.
|
|
189
|
+
|
|
190
|
+
The `messageContext` includes `{ attemptsMade: 0-99 }` for each retry.
|
|
191
|
+
|
|
192
|
+
#### `{ retries: 100 or more }`
|
|
193
|
+
|
|
194
|
+
These are not valid when creating a gcp-pubsub subscription. Creating a new subscription will fail.
|
|
131
195
|
|
|
132
196
|
### Failing messages
|
|
133
197
|
|
|
134
|
-
|
|
198
|
+
dead-letter topics are used when:
|
|
199
|
+
|
|
200
|
+
- `retries` is undefined or greater than or equal to 0
|
|
201
|
+
- or the subscription already has a dead-letter policy in place
|
|
202
|
+
|
|
203
|
+
dead-letter topics are NOT used when:
|
|
204
|
+
|
|
205
|
+
- `retries` is less than 0
|
|
206
|
+
- the subscription already exists without a dead-letter policy in place
|
|
207
|
+
|
|
208
|
+
If a dead-letter topic exists and the message handler returns `MessageResult.Fail` the message will be published to the dead-letter topic and `ack()` will be called on the message, removing it from the subscription.
|
|
209
|
+
|
|
210
|
+
There is a possible race condition between publishing the dead-letter message and acknowledging the message causing the message to be re-delivered. This can result in the message ending up in the dead-letter topic more than once, or possibly a message in the dead-letter topic and also successfully handled. This race condition only occurs when `@palmetto/pubsub` is publishing to the dead-letter topic. It should not happen when using the gcp-pubsub dead-letter policy.
|
|
211
|
+
|
|
212
|
+
Note: be sure the dead-letter topic is configured correctly. gcp-pubsub has some strict requirements on how to configure it.
|
|
213
|
+
You can visit the subscription in the Google Cloud console and go to the "Dead lettering" tab to identify and fix any issues.
|
|
214
|
+
The trickiest part might be setting the [IAM roles](https://docs.cloud.google.com/pubsub/docs/dead-letter-topics#grant_forwarding_permissions).
|
|
215
|
+
|
|
216
|
+
Note: When `@palmetto/pubsub` creates the dead-letter topic, it also creates a default subscription ending in `.sub` to ensure dead-letter messages are not lost.
|