@dudousxd/nestjs-durable-transport-sqs 0.1.0 → 0.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/LICENSE +21 -0
- package/dist/index.cjs +310 -0
- package/dist/index.cjs.map +1 -0
- package/dist/{sqs-transport.d.ts → index.d.cts} +44 -9
- package/dist/index.d.ts +128 -2
- package/dist/index.js +282 -15
- package/dist/index.js.map +1 -1
- package/package.json +32 -7
- package/dist/index.d.ts.map +0 -1
- package/dist/sqs-transport.d.ts.map +0 -1
- package/dist/sqs-transport.js +0 -191
- package/dist/sqs-transport.js.map +0 -1
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Davide Carvalho
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/index.ts
|
|
22
|
+
var index_exports = {};
|
|
23
|
+
__export(index_exports, {
|
|
24
|
+
SqsTransport: () => SqsTransport
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(index_exports);
|
|
27
|
+
|
|
28
|
+
// src/sqs-transport.ts
|
|
29
|
+
var import_client_sqs = require("@aws-sdk/client-sqs");
|
|
30
|
+
var import_nestjs_durable_core = require("@dudousxd/nestjs-durable-core");
|
|
31
|
+
var RESULT_VISIBILITY_SEC = 30;
|
|
32
|
+
var SqsTransport = class {
|
|
33
|
+
static {
|
|
34
|
+
__name(this, "SqsTransport");
|
|
35
|
+
}
|
|
36
|
+
client;
|
|
37
|
+
ownsClient;
|
|
38
|
+
group;
|
|
39
|
+
prefix;
|
|
40
|
+
autoCreate;
|
|
41
|
+
marker;
|
|
42
|
+
waitTimeSeconds;
|
|
43
|
+
visibilityTimeoutSec;
|
|
44
|
+
taskQueueUrlResolver;
|
|
45
|
+
resultsQueueUrlOption;
|
|
46
|
+
onError;
|
|
47
|
+
handlers = /* @__PURE__ */ new Map();
|
|
48
|
+
urlCache = /* @__PURE__ */ new Map();
|
|
49
|
+
/** `taskQueueUrl` resolutions per group (the promise, so concurrent dispatches share one call). */
|
|
50
|
+
groupUrlCache = /* @__PURE__ */ new Map();
|
|
51
|
+
running = true;
|
|
52
|
+
abort = new AbortController();
|
|
53
|
+
taskLoop;
|
|
54
|
+
resultLoop;
|
|
55
|
+
constructor(options) {
|
|
56
|
+
this.client = options.client ?? new import_client_sqs.SQSClient(options.clientConfig ?? {});
|
|
57
|
+
this.ownsClient = !options.client;
|
|
58
|
+
this.group = options.group;
|
|
59
|
+
this.prefix = options.prefix ?? "durable";
|
|
60
|
+
this.autoCreate = options.autoCreate ?? false;
|
|
61
|
+
this.marker = options.marker;
|
|
62
|
+
this.waitTimeSeconds = options.waitTimeSeconds ?? 20;
|
|
63
|
+
this.visibilityTimeoutSec = options.visibilityTimeoutSec ?? 60;
|
|
64
|
+
this.taskQueueUrlResolver = options.taskQueueUrl;
|
|
65
|
+
this.resultsQueueUrlOption = options.resultsQueueUrl;
|
|
66
|
+
this.onError = options.onError ?? ((err) => console.error("[SqsTransport]", err));
|
|
67
|
+
}
|
|
68
|
+
// ── queue resolution ───────────────────────────────────────────────────────────────────────
|
|
69
|
+
async resolveByName(name) {
|
|
70
|
+
const cached = this.urlCache.get(name);
|
|
71
|
+
if (cached) return cached;
|
|
72
|
+
let url;
|
|
73
|
+
try {
|
|
74
|
+
const out = await this.client.send(new import_client_sqs.GetQueueUrlCommand({
|
|
75
|
+
QueueName: name
|
|
76
|
+
}));
|
|
77
|
+
url = out.QueueUrl;
|
|
78
|
+
} catch (err) {
|
|
79
|
+
if (this.autoCreate) {
|
|
80
|
+
const created = await this.client.send(new import_client_sqs.CreateQueueCommand({
|
|
81
|
+
QueueName: name
|
|
82
|
+
}));
|
|
83
|
+
url = created.QueueUrl;
|
|
84
|
+
} else {
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
this.urlCache.set(name, url);
|
|
89
|
+
return url;
|
|
90
|
+
}
|
|
91
|
+
async tasksUrl(group) {
|
|
92
|
+
const resolver = this.taskQueueUrlResolver;
|
|
93
|
+
if (!resolver) return this.resolveByName(`${this.prefix}-tasks-${group}`);
|
|
94
|
+
let url = this.groupUrlCache.get(group);
|
|
95
|
+
if (!url) {
|
|
96
|
+
url = Promise.resolve().then(() => resolver(group)).catch((err) => {
|
|
97
|
+
this.groupUrlCache.delete(group);
|
|
98
|
+
throw err;
|
|
99
|
+
});
|
|
100
|
+
this.groupUrlCache.set(group, url);
|
|
101
|
+
}
|
|
102
|
+
return url;
|
|
103
|
+
}
|
|
104
|
+
async resultsUrl() {
|
|
105
|
+
const opt = this.resultsQueueUrlOption;
|
|
106
|
+
if (typeof opt === "string") return opt;
|
|
107
|
+
if (typeof opt === "function") return opt();
|
|
108
|
+
return this.resolveByName(`${this.prefix}-results`);
|
|
109
|
+
}
|
|
110
|
+
// ── engine → worker ────────────────────────────────────────────────────────────────────────
|
|
111
|
+
async dispatch(task) {
|
|
112
|
+
const QueueUrl = await this.tasksUrl(task.group);
|
|
113
|
+
await this.client.send(new import_client_sqs.SendMessageCommand({
|
|
114
|
+
QueueUrl,
|
|
115
|
+
MessageBody: JSON.stringify(task),
|
|
116
|
+
MessageAttributes: this.marker ? {
|
|
117
|
+
[this.marker]: {
|
|
118
|
+
DataType: "String",
|
|
119
|
+
StringValue: "1"
|
|
120
|
+
}
|
|
121
|
+
} : void 0
|
|
122
|
+
}));
|
|
123
|
+
}
|
|
124
|
+
// ── worker → engine ────────────────────────────────────────────────────────────────────────
|
|
125
|
+
/** Register a step handler (worker side). Starts the group's task consumer on first call. */
|
|
126
|
+
handle(name, fn) {
|
|
127
|
+
if (!this.group) throw new Error("SqsTransport needs a `group` to register handlers");
|
|
128
|
+
this.handlers.set(name, fn);
|
|
129
|
+
if (!this.taskLoop) this.taskLoop = this.pollTasks(this.group);
|
|
130
|
+
}
|
|
131
|
+
onResult(handler) {
|
|
132
|
+
if (!this.resultLoop) this.resultLoop = this.pollResults(handler);
|
|
133
|
+
}
|
|
134
|
+
onHeartbeat(_handler) {
|
|
135
|
+
}
|
|
136
|
+
// ── polling loops ──────────────────────────────────────────────────────────────────────────
|
|
137
|
+
/**
|
|
138
|
+
* Receive a batch and hand each message to `each`, one at a time, never letting a failure escape:
|
|
139
|
+
* a throw is reported through `onError` and its message is left on the queue (SQS redelivers it
|
|
140
|
+
* after the visibility timeout; a redrive policy DLQs one that keeps failing). Every message of the
|
|
141
|
+
* batch is kept invisible until it is handled (see {@link holdVisible}), so the ones waiting behind a
|
|
142
|
+
* slow handler are never redelivered to another consumer meanwhile.
|
|
143
|
+
*/
|
|
144
|
+
async pollLoop(queueUrl, visibilitySec, each) {
|
|
145
|
+
while (this.running) {
|
|
146
|
+
let QueueUrl;
|
|
147
|
+
try {
|
|
148
|
+
QueueUrl = await queueUrl();
|
|
149
|
+
} catch (err) {
|
|
150
|
+
if (!this.running) return;
|
|
151
|
+
this.onError(err);
|
|
152
|
+
await this.backoff();
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const messages = await this.receive(QueueUrl, visibilitySec);
|
|
156
|
+
const pending = new Set(messages);
|
|
157
|
+
const stopHolding = this.holdVisible(QueueUrl, pending, visibilitySec);
|
|
158
|
+
try {
|
|
159
|
+
for (const msg of messages) {
|
|
160
|
+
if (!this.running) break;
|
|
161
|
+
try {
|
|
162
|
+
if (this.shouldSkip(msg)) {
|
|
163
|
+
pending.delete(msg);
|
|
164
|
+
await this.release(QueueUrl, msg.ReceiptHandle);
|
|
165
|
+
continue;
|
|
166
|
+
}
|
|
167
|
+
await each(QueueUrl, msg);
|
|
168
|
+
} catch (err) {
|
|
169
|
+
this.onError(err);
|
|
170
|
+
} finally {
|
|
171
|
+
pending.delete(msg);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
} finally {
|
|
175
|
+
stopHolding();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Keep `messages` invisible while they wait or run: every third of the visibility timeout, extend
|
|
181
|
+
* each one still in the set back to the full timeout. Returns the stop function.
|
|
182
|
+
*/
|
|
183
|
+
holdVisible(QueueUrl, messages, visibilitySec) {
|
|
184
|
+
if (messages.size === 0) return () => {
|
|
185
|
+
};
|
|
186
|
+
const intervalMs = Math.max(200, Math.floor(visibilitySec * 1e3 / 3));
|
|
187
|
+
let round;
|
|
188
|
+
const timer = setInterval(() => {
|
|
189
|
+
if (round) return;
|
|
190
|
+
round = Promise.all([
|
|
191
|
+
...messages
|
|
192
|
+
].map((msg) => msg.ReceiptHandle ? this.client.send(new import_client_sqs.ChangeMessageVisibilityCommand({
|
|
193
|
+
QueueUrl,
|
|
194
|
+
ReceiptHandle: msg.ReceiptHandle,
|
|
195
|
+
VisibilityTimeout: visibilitySec
|
|
196
|
+
})).then(() => void 0).catch((err) => {
|
|
197
|
+
if (this.running) this.onError(err);
|
|
198
|
+
}) : void 0)).then(() => {
|
|
199
|
+
round = void 0;
|
|
200
|
+
});
|
|
201
|
+
}, intervalMs);
|
|
202
|
+
timer.unref?.();
|
|
203
|
+
return () => clearInterval(timer);
|
|
204
|
+
}
|
|
205
|
+
parse(msg) {
|
|
206
|
+
try {
|
|
207
|
+
return JSON.parse(msg.Body ?? "");
|
|
208
|
+
} catch {
|
|
209
|
+
throw new Error(`[SqsTransport] message ${msg.MessageId ?? "?"} has a non-JSON body; leaving it for the queue's redrive policy`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
pollTasks(group) {
|
|
213
|
+
return this.pollLoop(() => this.tasksUrl(group), this.visibilityTimeoutSec, async (QueueUrl, msg) => {
|
|
214
|
+
const task = this.parse(msg);
|
|
215
|
+
const result = await (0, import_nestjs_durable_core.runStepHandler)(task, this.handlers.get(task.name));
|
|
216
|
+
await this.client.send(new import_client_sqs.SendMessageCommand({
|
|
217
|
+
QueueUrl: await this.resultsUrl(),
|
|
218
|
+
MessageBody: JSON.stringify(result),
|
|
219
|
+
MessageAttributes: this.marker ? {
|
|
220
|
+
[this.marker]: {
|
|
221
|
+
DataType: "String",
|
|
222
|
+
StringValue: "1"
|
|
223
|
+
}
|
|
224
|
+
} : void 0
|
|
225
|
+
}));
|
|
226
|
+
await this.del(QueueUrl, msg.ReceiptHandle);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
pollResults(handler) {
|
|
230
|
+
return this.pollLoop(() => this.resultsUrl(), RESULT_VISIBILITY_SEC, async (QueueUrl, msg) => {
|
|
231
|
+
await handler(this.parse(msg));
|
|
232
|
+
await this.del(QueueUrl, msg.ReceiptHandle);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
/** Wait 1s, or until `close()` aborts. The abort listener is removed when the timer fires, so
|
|
236
|
+
* sustained failures never accumulate listeners on the shared signal. */
|
|
237
|
+
backoff() {
|
|
238
|
+
return new Promise((resolve) => {
|
|
239
|
+
const signal = this.abort.signal;
|
|
240
|
+
if (signal.aborted) return resolve();
|
|
241
|
+
const onAbort = /* @__PURE__ */ __name(() => {
|
|
242
|
+
clearTimeout(timer);
|
|
243
|
+
resolve();
|
|
244
|
+
}, "onAbort");
|
|
245
|
+
const timer = setTimeout(() => {
|
|
246
|
+
signal.removeEventListener("abort", onAbort);
|
|
247
|
+
resolve();
|
|
248
|
+
}, 1e3);
|
|
249
|
+
signal.addEventListener("abort", onAbort, {
|
|
250
|
+
once: true
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
/** One long-poll receive. Swallows the abort thrown on `close()`; logs and backs off otherwise. */
|
|
255
|
+
async receive(QueueUrl, visibility) {
|
|
256
|
+
try {
|
|
257
|
+
const out = await this.client.send(new import_client_sqs.ReceiveMessageCommand({
|
|
258
|
+
QueueUrl,
|
|
259
|
+
MaxNumberOfMessages: 10,
|
|
260
|
+
WaitTimeSeconds: this.waitTimeSeconds,
|
|
261
|
+
VisibilityTimeout: visibility,
|
|
262
|
+
MessageAttributeNames: this.marker ? [
|
|
263
|
+
"All"
|
|
264
|
+
] : void 0
|
|
265
|
+
}), {
|
|
266
|
+
abortSignal: this.abort.signal
|
|
267
|
+
});
|
|
268
|
+
return out.Messages ?? [];
|
|
269
|
+
} catch (err) {
|
|
270
|
+
if (!this.running) return [];
|
|
271
|
+
this.onError(err);
|
|
272
|
+
await this.backoff();
|
|
273
|
+
return [];
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
shouldSkip(msg) {
|
|
277
|
+
return !!this.marker && !msg.MessageAttributes?.[this.marker];
|
|
278
|
+
}
|
|
279
|
+
async del(QueueUrl, ReceiptHandle) {
|
|
280
|
+
if (!ReceiptHandle) return;
|
|
281
|
+
await this.client.send(new import_client_sqs.DeleteMessageCommand({
|
|
282
|
+
QueueUrl,
|
|
283
|
+
ReceiptHandle
|
|
284
|
+
}));
|
|
285
|
+
}
|
|
286
|
+
async release(QueueUrl, ReceiptHandle) {
|
|
287
|
+
if (!ReceiptHandle) return;
|
|
288
|
+
await this.client.send(new import_client_sqs.ChangeMessageVisibilityCommand({
|
|
289
|
+
QueueUrl,
|
|
290
|
+
ReceiptHandle,
|
|
291
|
+
VisibilityTimeout: 0
|
|
292
|
+
})).catch(() => {
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
/** Stop the pollers and (if we created it) destroy the SQS client so the process can exit. */
|
|
296
|
+
async close() {
|
|
297
|
+
this.running = false;
|
|
298
|
+
this.abort.abort();
|
|
299
|
+
await Promise.allSettled([
|
|
300
|
+
this.taskLoop,
|
|
301
|
+
this.resultLoop
|
|
302
|
+
]);
|
|
303
|
+
if (this.ownsClient) this.client.destroy();
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
307
|
+
0 && (module.exports = {
|
|
308
|
+
SqsTransport
|
|
309
|
+
});
|
|
310
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/sqs-transport.ts"],"sourcesContent":["export * from './sqs-transport';\n","import {\n ChangeMessageVisibilityCommand,\n CreateQueueCommand,\n DeleteMessageCommand,\n GetQueueUrlCommand,\n ReceiveMessageCommand,\n SQSClient,\n type SQSClientConfig,\n SendMessageCommand,\n} from '@aws-sdk/client-sqs';\nimport {\n type Heartbeat,\n type RemoteTask,\n type StepHandler,\n type StepResult,\n type Transport,\n runStepHandler,\n} from '@dudousxd/nestjs-durable-core';\n\n/** Resolve a group's tasks queue URL. Sync or async; resolved once per group and cached (a rejected\n * resolution is not cached — the next call asks again). */\nexport type QueueUrlResolver = (group: string) => string | Promise<string>;\n\nexport interface SqsTransportOptions {\n /**\n * Reuse an existing SQS client (recommended — share the app's). When omitted, one is built\n * from `clientConfig` and destroyed on `close()`.\n */\n client?: SQSClient;\n /** Used only when `client` is omitted — e.g. `{ region, endpoint, credentials }` for ElasticMQ. */\n clientConfig?: SQSClientConfig;\n\n /** The worker group this instance serves. Required to register `handle()` consumers. */\n group?: string;\n\n /**\n * Map a group → an **existing** tasks queue URL. This is the seam for reusing queues you already\n * have (e.g. `extraction`, `ingestion`) instead of letting the transport mint its own. When\n * omitted, the transport resolves `${prefix}-tasks-${group}` by name (and creates it if\n * `autoCreate`). Return value is awaited and cached per group.\n */\n taskQueueUrl?: QueueUrlResolver;\n /**\n * The results queue URL (worker → engine). A literal URL or a resolver. When omitted, the\n * transport resolves `${prefix}-results` by name (and creates it if `autoCreate`).\n */\n resultsQueueUrl?: string | (() => string | Promise<string>);\n\n /** Prefix for the fallback `${prefix}-tasks-*` / `${prefix}-results` names. Default `durable`. */\n prefix?: string;\n /**\n * Create the fallback-named queues on first use if they don't exist (handy for ElasticMQ / dev).\n * Ignored for queues you supply via `taskQueueUrl` / `resultsQueueUrl` — those must already exist.\n */\n autoCreate?: boolean;\n\n /**\n * When set, durable messages carry this SQS message attribute and pollers **skip** messages\n * that lack it (releasing them for a co-resident legacy consumer). Enables sharing one physical\n * queue with a non-durable consumer — but only if that consumer likewise ignores tagged messages.\n * Leave unset for the clean case: a queue dedicated to durable traffic.\n */\n marker?: string;\n\n /** SQS receive long-poll seconds (0–20). Default 20. */\n waitTimeSeconds?: number;\n /**\n * Visibility timeout for a received task, in seconds. Default 60. Every message this instance has\n * received — the one running and the ones of the same batch waiting behind it — is kept invisible by\n * re-extending it (`ChangeMessageVisibility`) every third of this, so a step may run longer; only a\n * crashed instance's messages reappear, after at most this long.\n */\n visibilityTimeoutSec?: number;\n /**\n * Where a transport failure is reported: a failing receive, a result handler that throws, a result\n * send that fails, a message whose body isn't JSON. The message involved is NOT deleted: SQS\n * redelivers it after its visibility timeout, and a queue redrive policy (`maxReceiveCount` → DLQ)\n * moves one that keeps failing aside. Default `console.error`.\n */\n onError?: (err: unknown) => void;\n}\n\n/** A received message, as the poll loops use it. */\ninterface Received {\n Body?: string | undefined;\n ReceiptHandle?: string | undefined;\n MessageId?: string | undefined;\n MessageAttributes?: Record<string, unknown> | undefined;\n}\n\n/** The results queue's visibility timeout (seconds). */\nconst RESULT_VISIBILITY_SEC = 30;\n\n/**\n * An SQS-backed `Transport` — dispatch remote steps over Amazon SQS (or ElasticMQ). Unlike the\n * BullMQ transport, it does **not** mint its own queue names: pass `taskQueueUrl` / `resultsQueueUrl`\n * to ride the queues you already operate. The wire payload is the documented `RemoteTask` /\n * `StepResult` JSON, so non-Node workers on the same queues interoperate.\n *\n * Run one instance engine-side (calls `onResult`, dispatches tasks) and one per worker process\n * (calls `handle()` for its group). SQS is at-least-once: a task whose process crashes before the\n * result is sent reappears after the visibility timeout (durable retry); a duplicate `StepResult`\n * is harmless because the engine resolves a step's `pending` exactly once by `stepId`.\n */\nexport class SqsTransport implements Transport {\n private readonly client: SQSClient;\n private readonly ownsClient: boolean;\n private readonly group?: string | undefined;\n private readonly prefix: string;\n private readonly autoCreate: boolean;\n private readonly marker?: string | undefined;\n private readonly waitTimeSeconds: number;\n private readonly visibilityTimeoutSec: number;\n private readonly taskQueueUrlResolver?: QueueUrlResolver | undefined;\n private readonly resultsQueueUrlOption?: string | (() => string | Promise<string>) | undefined;\n private readonly onError: (err: unknown) => void;\n\n private readonly handlers = new Map<string, StepHandler>();\n private readonly urlCache = new Map<string, string>();\n /** `taskQueueUrl` resolutions per group (the promise, so concurrent dispatches share one call). */\n private readonly groupUrlCache = new Map<string, Promise<string>>();\n private running = true;\n private readonly abort = new AbortController();\n private taskLoop?: Promise<void>;\n private resultLoop?: Promise<void>;\n\n constructor(options: SqsTransportOptions) {\n this.client = options.client ?? new SQSClient(options.clientConfig ?? {});\n this.ownsClient = !options.client;\n this.group = options.group;\n this.prefix = options.prefix ?? 'durable';\n this.autoCreate = options.autoCreate ?? false;\n this.marker = options.marker;\n this.waitTimeSeconds = options.waitTimeSeconds ?? 20;\n this.visibilityTimeoutSec = options.visibilityTimeoutSec ?? 60;\n this.taskQueueUrlResolver = options.taskQueueUrl;\n this.resultsQueueUrlOption = options.resultsQueueUrl;\n this.onError = options.onError ?? ((err) => console.error('[SqsTransport]', err));\n }\n\n // ── queue resolution ───────────────────────────────────────────────────────────────────────\n\n private async resolveByName(name: string): Promise<string> {\n const cached = this.urlCache.get(name);\n if (cached) return cached;\n let url: string;\n try {\n const out = await this.client.send(new GetQueueUrlCommand({ QueueName: name }));\n url = out.QueueUrl as string;\n } catch (err) {\n if (this.autoCreate) {\n const created = await this.client.send(new CreateQueueCommand({ QueueName: name }));\n url = created.QueueUrl as string;\n } else {\n throw err;\n }\n }\n this.urlCache.set(name, url);\n return url;\n }\n\n private async tasksUrl(group: string): Promise<string> {\n const resolver = this.taskQueueUrlResolver;\n if (!resolver) return this.resolveByName(`${this.prefix}-tasks-${group}`);\n let url = this.groupUrlCache.get(group);\n if (!url) {\n url = Promise.resolve()\n .then(() => resolver(group))\n .catch((err) => {\n this.groupUrlCache.delete(group);\n throw err;\n });\n this.groupUrlCache.set(group, url);\n }\n return url;\n }\n\n private async resultsUrl(): Promise<string> {\n const opt = this.resultsQueueUrlOption;\n if (typeof opt === 'string') return opt;\n if (typeof opt === 'function') return opt();\n return this.resolveByName(`${this.prefix}-results`);\n }\n\n // ── engine → worker ────────────────────────────────────────────────────────────────────────\n\n async dispatch(task: RemoteTask): Promise<void> {\n const QueueUrl = await this.tasksUrl(task.group);\n await this.client.send(\n new SendMessageCommand({\n QueueUrl,\n MessageBody: JSON.stringify(task),\n MessageAttributes: this.marker\n ? { [this.marker]: { DataType: 'String', StringValue: '1' } }\n : undefined,\n }),\n );\n }\n\n // ── worker → engine ────────────────────────────────────────────────────────────────────────\n\n /** Register a step handler (worker side). Starts the group's task consumer on first call. */\n handle(name: string, fn: StepHandler): void {\n if (!this.group) throw new Error('SqsTransport needs a `group` to register handlers');\n this.handlers.set(name, fn);\n if (!this.taskLoop) this.taskLoop = this.pollTasks(this.group);\n }\n\n onResult(handler: (result: StepResult) => Promise<void>): void {\n if (!this.resultLoop) this.resultLoop = this.pollResults(handler);\n }\n\n onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void {\n // Not modelled over SQS; the queue's visibility-timeout redelivery is the liveness mechanism.\n }\n\n // ── polling loops ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Receive a batch and hand each message to `each`, one at a time, never letting a failure escape:\n * a throw is reported through `onError` and its message is left on the queue (SQS redelivers it\n * after the visibility timeout; a redrive policy DLQs one that keeps failing). Every message of the\n * batch is kept invisible until it is handled (see {@link holdVisible}), so the ones waiting behind a\n * slow handler are never redelivered to another consumer meanwhile.\n */\n private async pollLoop(\n queueUrl: () => Promise<string>,\n visibilitySec: number,\n each: (QueueUrl: string, msg: Received) => Promise<void>,\n ): Promise<void> {\n while (this.running) {\n let QueueUrl: string;\n try {\n QueueUrl = await queueUrl();\n } catch (err) {\n if (!this.running) return;\n this.onError(err);\n await this.backoff();\n continue;\n }\n const messages = await this.receive(QueueUrl, visibilitySec);\n const pending = new Set<Received>(messages);\n const stopHolding = this.holdVisible(QueueUrl, pending, visibilitySec);\n try {\n for (const msg of messages) {\n if (!this.running) break; // close(): what is left reappears after its visibility timeout\n try {\n if (this.shouldSkip(msg)) {\n // Not ours (shared queue): release immediately so the legacy consumer can take it.\n pending.delete(msg);\n await this.release(QueueUrl, msg.ReceiptHandle);\n continue;\n }\n await each(QueueUrl, msg);\n } catch (err) {\n this.onError(err);\n } finally {\n pending.delete(msg);\n }\n }\n } finally {\n stopHolding();\n }\n }\n }\n\n /**\n * Keep `messages` invisible while they wait or run: every third of the visibility timeout, extend\n * each one still in the set back to the full timeout. Returns the stop function.\n */\n private holdVisible(\n QueueUrl: string,\n messages: Set<Received>,\n visibilitySec: number,\n ): () => void {\n if (messages.size === 0) return () => {};\n const intervalMs = Math.max(200, Math.floor((visibilitySec * 1000) / 3));\n let round: Promise<void> | undefined;\n const timer = setInterval(() => {\n if (round) return;\n round = Promise.all(\n [...messages].map((msg) =>\n msg.ReceiptHandle\n ? this.client\n .send(\n new ChangeMessageVisibilityCommand({\n QueueUrl,\n ReceiptHandle: msg.ReceiptHandle,\n VisibilityTimeout: visibilitySec,\n }),\n )\n .then(() => undefined)\n .catch((err) => {\n if (this.running) this.onError(err);\n })\n : undefined,\n ),\n ).then(() => {\n round = undefined;\n });\n }, intervalMs);\n timer.unref?.();\n return () => clearInterval(timer);\n }\n\n private parse<T>(msg: Received): T {\n try {\n return JSON.parse(msg.Body ?? '') as T;\n } catch {\n throw new Error(\n `[SqsTransport] message ${msg.MessageId ?? '?'} has a non-JSON body; leaving it for the queue's redrive policy`,\n );\n }\n }\n\n private pollTasks(group: string): Promise<void> {\n return this.pollLoop(\n () => this.tasksUrl(group),\n this.visibilityTimeoutSec,\n async (QueueUrl, msg) => {\n const task = this.parse<RemoteTask>(msg);\n const result = await runStepHandler(task, this.handlers.get(task.name));\n await this.client.send(\n new SendMessageCommand({\n QueueUrl: await this.resultsUrl(),\n MessageBody: JSON.stringify(result),\n MessageAttributes: this.marker\n ? { [this.marker]: { DataType: 'String', StringValue: '1' } }\n : undefined,\n }),\n );\n await this.del(QueueUrl, msg.ReceiptHandle);\n },\n );\n }\n\n private pollResults(handler: (result: StepResult) => Promise<void>): Promise<void> {\n return this.pollLoop(\n () => this.resultsUrl(),\n RESULT_VISIBILITY_SEC,\n async (QueueUrl, msg) => {\n await handler(this.parse<StepResult>(msg));\n await this.del(QueueUrl, msg.ReceiptHandle);\n },\n );\n }\n\n /** Wait 1s, or until `close()` aborts. The abort listener is removed when the timer fires, so\n * sustained failures never accumulate listeners on the shared signal. */\n private backoff(): Promise<void> {\n return new Promise((resolve) => {\n const signal = this.abort.signal;\n if (signal.aborted) return resolve();\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, 1000);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /** One long-poll receive. Swallows the abort thrown on `close()`; logs and backs off otherwise. */\n private async receive(QueueUrl: string, visibility: number): Promise<Received[]> {\n try {\n const out = await this.client.send(\n new ReceiveMessageCommand({\n QueueUrl,\n MaxNumberOfMessages: 10,\n WaitTimeSeconds: this.waitTimeSeconds,\n VisibilityTimeout: visibility,\n MessageAttributeNames: this.marker ? ['All'] : undefined,\n }),\n { abortSignal: this.abort.signal },\n );\n return out.Messages ?? [];\n } catch (err) {\n if (!this.running) return [];\n this.onError(err);\n await this.backoff();\n return [];\n }\n }\n\n private shouldSkip(msg: { MessageAttributes?: Record<string, unknown> | undefined }): boolean {\n return !!this.marker && !msg.MessageAttributes?.[this.marker];\n }\n\n private async del(QueueUrl: string, ReceiptHandle?: string): Promise<void> {\n if (!ReceiptHandle) return;\n await this.client.send(new DeleteMessageCommand({ QueueUrl, ReceiptHandle }));\n }\n\n private async release(QueueUrl: string, ReceiptHandle?: string): Promise<void> {\n if (!ReceiptHandle) return;\n await this.client\n .send(new ChangeMessageVisibilityCommand({ QueueUrl, ReceiptHandle, VisibilityTimeout: 0 }))\n .catch(() => {});\n }\n\n /** Stop the pollers and (if we created it) destroy the SQS client so the process can exit. */\n async close(): Promise<void> {\n this.running = false;\n this.abort.abort();\n await Promise.allSettled([this.taskLoop, this.resultLoop]);\n if (this.ownsClient) this.client.destroy();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;ACAA,wBASO;AACP,iCAOO;AA0EP,IAAMA,wBAAwB;AAavB,IAAMC,eAAN,MAAMA;EAxGb,OAwGaA;;;EACMC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EAEAC,WAAW,oBAAIC,IAAAA;EACfC,WAAW,oBAAID,IAAAA;;EAEfE,gBAAgB,oBAAIF,IAAAA;EAC7BG,UAAU;EACDC,QAAQ,IAAIC,gBAAAA;EACrBC;EACAC;EAER,YAAYC,SAA8B;AACxC,SAAKpB,SAASoB,QAAQpB,UAAU,IAAIqB,4BAAUD,QAAQE,gBAAgB,CAAC,CAAA;AACvE,SAAKrB,aAAa,CAACmB,QAAQpB;AAC3B,SAAKE,QAAQkB,QAAQlB;AACrB,SAAKC,SAASiB,QAAQjB,UAAU;AAChC,SAAKC,aAAagB,QAAQhB,cAAc;AACxC,SAAKC,SAASe,QAAQf;AACtB,SAAKC,kBAAkBc,QAAQd,mBAAmB;AAClD,SAAKC,uBAAuBa,QAAQb,wBAAwB;AAC5D,SAAKC,uBAAuBY,QAAQG;AACpC,SAAKd,wBAAwBW,QAAQI;AACrC,SAAKd,UAAUU,QAAQV,YAAY,CAACe,QAAQC,QAAQC,MAAM,kBAAkBF,GAAAA;EAC9E;;EAIA,MAAcG,cAAcC,MAA+B;AACzD,U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AAEnC,aAAOvE,IAAIqF,YAAY,CAAA;IACzB,SAAS7F,KAAK;AACZ,UAAI,CAAC,KAAKV,QAAS,QAAO,CAAA;AAC1B,WAAKL,QAAQe,GAAAA;AACb,YAAM,KAAKgD,QAAO;AAClB,aAAO,CAAA;IACT;EACF;EAEQQ,WAAWD,KAA2E;AAC5F,WAAO,CAAC,CAAC,KAAK3E,UAAU,CAAC2E,IAAIxB,oBAAoB,KAAKnD,MAAM;EAC9D;EAEA,MAAckG,IAAIlE,UAAkB8C,eAAuC;AACzE,QAAI,CAACA,cAAe;AACpB,UAAM,KAAKnF,OAAOkC,KAAK,IAAIqF,uCAAqB;MAAElF;MAAU8C;IAAc,CAAA,CAAA;EAC5E;EAEA,MAAcD,QAAQ7C,UAAkB8C,eAAuC;AAC7E,QAAI,CAACA,cAAe;AACpB,UAAM,KAAKnF,OACRkC,KAAK,IAAI4D,iDAA+B;MAAEzD;MAAU8C;MAAeY,mBAAmB;IAAE,CAAA,CAAA,EACxFjD,MAAM,MAAA;IAAO,CAAA;EAClB;;EAGA,MAAM0E,QAAuB;AAC3B,SAAKzG,UAAU;AACf,SAAKC,MAAMA,MAAK;AAChB,UAAM2B,QAAQ8E,WAAW;MAAC,KAAKvG;MAAU,KAAKC;KAAW;AACzD,QAAI,KAAKlB,WAAY,MAAKD,OAAO0H,QAAO;EAC1C;AACF;","names":["RESULT_VISIBILITY_SEC","SqsTransport","client","ownsClient","group","prefix","autoCreate","marker","waitTimeSeconds","visibilityTimeoutSec","taskQueueUrlResolver","resultsQueueUrlOption","onError","handlers","Map","urlCache","groupUrlCache","running","abort","AbortController","taskLoop","resultLoop","options","SQSClient","clientConfig","taskQueueUrl","resultsQueueUrl","err","console","error","resolveByName","name","cached","get","url","out","send","GetQueueUrlCommand","QueueName","QueueUrl","created","CreateQueueCommand","set","tasksUrl","resolver","Promise","resolve","then","catch","delete","resultsUrl","opt","dispatch","task","SendMessageCommand","MessageBody","JSON","stringify","MessageAttributes","DataType","StringValue","undefined","handle","fn","Error","pollTasks","onResult","handler","pollResults","onHeartbeat","_handler","pollLoop","queueUrl","visibilitySec","each","backoff","messages","receive","pending","Set","stopHolding","holdVisible","msg","shouldSkip","release","ReceiptHandle","size","intervalMs","Math","max","floor","round","timer","setInterval","all","map","ChangeMessageVisibilityCommand","VisibilityTimeout","unref","clearInterval","parse","Body","MessageId","result","runStepHandler","del","signal","aborted","onAbort","clearTimeout","setTimeout","removeEventListener","addEventListener","once","visibility","ReceiveMessageCommand","MaxNumberOfMessages","WaitTimeSeconds","MessageAttributeNames","abortSignal","Messages","DeleteMessageCommand","close","allSettled","destroy"]}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import { SQSClient,
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
1
|
+
import { SQSClient, SQSClientConfig } from '@aws-sdk/client-sqs';
|
|
2
|
+
import { Transport, RemoteTask, StepHandler, StepResult, Heartbeat } from '@dudousxd/nestjs-durable-core';
|
|
3
|
+
|
|
4
|
+
/** Resolve a group's tasks queue URL. Sync or async; resolved once per group and cached (a rejected
|
|
5
|
+
* resolution is not cached — the next call asks again). */
|
|
6
|
+
type QueueUrlResolver = (group: string) => string | Promise<string>;
|
|
7
|
+
interface SqsTransportOptions {
|
|
6
8
|
/**
|
|
7
9
|
* Reuse an existing SQS client (recommended — share the app's). When omitted, one is built
|
|
8
10
|
* from `clientConfig` and destroyed on `close()`.
|
|
@@ -16,7 +18,7 @@ export interface SqsTransportOptions {
|
|
|
16
18
|
* Map a group → an **existing** tasks queue URL. This is the seam for reusing queues you already
|
|
17
19
|
* have (e.g. `extraction`, `ingestion`) instead of letting the transport mint its own. When
|
|
18
20
|
* omitted, the transport resolves `${prefix}-tasks-${group}` by name (and creates it if
|
|
19
|
-
* `autoCreate`). Return value is awaited and cached.
|
|
21
|
+
* `autoCreate`). Return value is awaited and cached per group.
|
|
20
22
|
*/
|
|
21
23
|
taskQueueUrl?: QueueUrlResolver;
|
|
22
24
|
/**
|
|
@@ -40,8 +42,20 @@ export interface SqsTransportOptions {
|
|
|
40
42
|
marker?: string;
|
|
41
43
|
/** SQS receive long-poll seconds (0–20). Default 20. */
|
|
42
44
|
waitTimeSeconds?: number;
|
|
43
|
-
/**
|
|
45
|
+
/**
|
|
46
|
+
* Visibility timeout for a received task, in seconds. Default 60. Every message this instance has
|
|
47
|
+
* received — the one running and the ones of the same batch waiting behind it — is kept invisible by
|
|
48
|
+
* re-extending it (`ChangeMessageVisibility`) every third of this, so a step may run longer; only a
|
|
49
|
+
* crashed instance's messages reappear, after at most this long.
|
|
50
|
+
*/
|
|
44
51
|
visibilityTimeoutSec?: number;
|
|
52
|
+
/**
|
|
53
|
+
* Where a transport failure is reported: a failing receive, a result handler that throws, a result
|
|
54
|
+
* send that fails, a message whose body isn't JSON. The message involved is NOT deleted: SQS
|
|
55
|
+
* redelivers it after its visibility timeout, and a queue redrive policy (`maxReceiveCount` → DLQ)
|
|
56
|
+
* moves one that keeps failing aside. Default `console.error`.
|
|
57
|
+
*/
|
|
58
|
+
onError?: (err: unknown) => void;
|
|
45
59
|
}
|
|
46
60
|
/**
|
|
47
61
|
* An SQS-backed `Transport` — dispatch remote steps over Amazon SQS (or ElasticMQ). Unlike the
|
|
@@ -54,7 +68,7 @@ export interface SqsTransportOptions {
|
|
|
54
68
|
* result is sent reappears after the visibility timeout (durable retry); a duplicate `StepResult`
|
|
55
69
|
* is harmless because the engine resolves a step's `pending` exactly once by `stepId`.
|
|
56
70
|
*/
|
|
57
|
-
|
|
71
|
+
declare class SqsTransport implements Transport {
|
|
58
72
|
private readonly client;
|
|
59
73
|
private readonly ownsClient;
|
|
60
74
|
private readonly group?;
|
|
@@ -65,8 +79,11 @@ export declare class SqsTransport implements Transport {
|
|
|
65
79
|
private readonly visibilityTimeoutSec;
|
|
66
80
|
private readonly taskQueueUrlResolver?;
|
|
67
81
|
private readonly resultsQueueUrlOption?;
|
|
82
|
+
private readonly onError;
|
|
68
83
|
private readonly handlers;
|
|
69
84
|
private readonly urlCache;
|
|
85
|
+
/** `taskQueueUrl` resolutions per group (the promise, so concurrent dispatches share one call). */
|
|
86
|
+
private readonly groupUrlCache;
|
|
70
87
|
private running;
|
|
71
88
|
private readonly abort;
|
|
72
89
|
private taskLoop?;
|
|
@@ -80,8 +97,25 @@ export declare class SqsTransport implements Transport {
|
|
|
80
97
|
handle(name: string, fn: StepHandler): void;
|
|
81
98
|
onResult(handler: (result: StepResult) => Promise<void>): void;
|
|
82
99
|
onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void;
|
|
100
|
+
/**
|
|
101
|
+
* Receive a batch and hand each message to `each`, one at a time, never letting a failure escape:
|
|
102
|
+
* a throw is reported through `onError` and its message is left on the queue (SQS redelivers it
|
|
103
|
+
* after the visibility timeout; a redrive policy DLQs one that keeps failing). Every message of the
|
|
104
|
+
* batch is kept invisible until it is handled (see {@link holdVisible}), so the ones waiting behind a
|
|
105
|
+
* slow handler are never redelivered to another consumer meanwhile.
|
|
106
|
+
*/
|
|
107
|
+
private pollLoop;
|
|
108
|
+
/**
|
|
109
|
+
* Keep `messages` invisible while they wait or run: every third of the visibility timeout, extend
|
|
110
|
+
* each one still in the set back to the full timeout. Returns the stop function.
|
|
111
|
+
*/
|
|
112
|
+
private holdVisible;
|
|
113
|
+
private parse;
|
|
83
114
|
private pollTasks;
|
|
84
115
|
private pollResults;
|
|
116
|
+
/** Wait 1s, or until `close()` aborts. The abort listener is removed when the timer fires, so
|
|
117
|
+
* sustained failures never accumulate listeners on the shared signal. */
|
|
118
|
+
private backoff;
|
|
85
119
|
/** One long-poll receive. Swallows the abort thrown on `close()`; logs and backs off otherwise. */
|
|
86
120
|
private receive;
|
|
87
121
|
private shouldSkip;
|
|
@@ -90,4 +124,5 @@ export declare class SqsTransport implements Transport {
|
|
|
90
124
|
/** Stop the pollers and (if we created it) destroy the SQS client so the process can exit. */
|
|
91
125
|
close(): Promise<void>;
|
|
92
126
|
}
|
|
93
|
-
|
|
127
|
+
|
|
128
|
+
export { type QueueUrlResolver, SqsTransport, type SqsTransportOptions };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,2 +1,128 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { SQSClient, SQSClientConfig } from '@aws-sdk/client-sqs';
|
|
2
|
+
import { Transport, RemoteTask, StepHandler, StepResult, Heartbeat } from '@dudousxd/nestjs-durable-core';
|
|
3
|
+
|
|
4
|
+
/** Resolve a group's tasks queue URL. Sync or async; resolved once per group and cached (a rejected
|
|
5
|
+
* resolution is not cached — the next call asks again). */
|
|
6
|
+
type QueueUrlResolver = (group: string) => string | Promise<string>;
|
|
7
|
+
interface SqsTransportOptions {
|
|
8
|
+
/**
|
|
9
|
+
* Reuse an existing SQS client (recommended — share the app's). When omitted, one is built
|
|
10
|
+
* from `clientConfig` and destroyed on `close()`.
|
|
11
|
+
*/
|
|
12
|
+
client?: SQSClient;
|
|
13
|
+
/** Used only when `client` is omitted — e.g. `{ region, endpoint, credentials }` for ElasticMQ. */
|
|
14
|
+
clientConfig?: SQSClientConfig;
|
|
15
|
+
/** The worker group this instance serves. Required to register `handle()` consumers. */
|
|
16
|
+
group?: string;
|
|
17
|
+
/**
|
|
18
|
+
* Map a group → an **existing** tasks queue URL. This is the seam for reusing queues you already
|
|
19
|
+
* have (e.g. `extraction`, `ingestion`) instead of letting the transport mint its own. When
|
|
20
|
+
* omitted, the transport resolves `${prefix}-tasks-${group}` by name (and creates it if
|
|
21
|
+
* `autoCreate`). Return value is awaited and cached per group.
|
|
22
|
+
*/
|
|
23
|
+
taskQueueUrl?: QueueUrlResolver;
|
|
24
|
+
/**
|
|
25
|
+
* The results queue URL (worker → engine). A literal URL or a resolver. When omitted, the
|
|
26
|
+
* transport resolves `${prefix}-results` by name (and creates it if `autoCreate`).
|
|
27
|
+
*/
|
|
28
|
+
resultsQueueUrl?: string | (() => string | Promise<string>);
|
|
29
|
+
/** Prefix for the fallback `${prefix}-tasks-*` / `${prefix}-results` names. Default `durable`. */
|
|
30
|
+
prefix?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Create the fallback-named queues on first use if they don't exist (handy for ElasticMQ / dev).
|
|
33
|
+
* Ignored for queues you supply via `taskQueueUrl` / `resultsQueueUrl` — those must already exist.
|
|
34
|
+
*/
|
|
35
|
+
autoCreate?: boolean;
|
|
36
|
+
/**
|
|
37
|
+
* When set, durable messages carry this SQS message attribute and pollers **skip** messages
|
|
38
|
+
* that lack it (releasing them for a co-resident legacy consumer). Enables sharing one physical
|
|
39
|
+
* queue with a non-durable consumer — but only if that consumer likewise ignores tagged messages.
|
|
40
|
+
* Leave unset for the clean case: a queue dedicated to durable traffic.
|
|
41
|
+
*/
|
|
42
|
+
marker?: string;
|
|
43
|
+
/** SQS receive long-poll seconds (0–20). Default 20. */
|
|
44
|
+
waitTimeSeconds?: number;
|
|
45
|
+
/**
|
|
46
|
+
* Visibility timeout for a received task, in seconds. Default 60. Every message this instance has
|
|
47
|
+
* received — the one running and the ones of the same batch waiting behind it — is kept invisible by
|
|
48
|
+
* re-extending it (`ChangeMessageVisibility`) every third of this, so a step may run longer; only a
|
|
49
|
+
* crashed instance's messages reappear, after at most this long.
|
|
50
|
+
*/
|
|
51
|
+
visibilityTimeoutSec?: number;
|
|
52
|
+
/**
|
|
53
|
+
* Where a transport failure is reported: a failing receive, a result handler that throws, a result
|
|
54
|
+
* send that fails, a message whose body isn't JSON. The message involved is NOT deleted: SQS
|
|
55
|
+
* redelivers it after its visibility timeout, and a queue redrive policy (`maxReceiveCount` → DLQ)
|
|
56
|
+
* moves one that keeps failing aside. Default `console.error`.
|
|
57
|
+
*/
|
|
58
|
+
onError?: (err: unknown) => void;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* An SQS-backed `Transport` — dispatch remote steps over Amazon SQS (or ElasticMQ). Unlike the
|
|
62
|
+
* BullMQ transport, it does **not** mint its own queue names: pass `taskQueueUrl` / `resultsQueueUrl`
|
|
63
|
+
* to ride the queues you already operate. The wire payload is the documented `RemoteTask` /
|
|
64
|
+
* `StepResult` JSON, so non-Node workers on the same queues interoperate.
|
|
65
|
+
*
|
|
66
|
+
* Run one instance engine-side (calls `onResult`, dispatches tasks) and one per worker process
|
|
67
|
+
* (calls `handle()` for its group). SQS is at-least-once: a task whose process crashes before the
|
|
68
|
+
* result is sent reappears after the visibility timeout (durable retry); a duplicate `StepResult`
|
|
69
|
+
* is harmless because the engine resolves a step's `pending` exactly once by `stepId`.
|
|
70
|
+
*/
|
|
71
|
+
declare class SqsTransport implements Transport {
|
|
72
|
+
private readonly client;
|
|
73
|
+
private readonly ownsClient;
|
|
74
|
+
private readonly group?;
|
|
75
|
+
private readonly prefix;
|
|
76
|
+
private readonly autoCreate;
|
|
77
|
+
private readonly marker?;
|
|
78
|
+
private readonly waitTimeSeconds;
|
|
79
|
+
private readonly visibilityTimeoutSec;
|
|
80
|
+
private readonly taskQueueUrlResolver?;
|
|
81
|
+
private readonly resultsQueueUrlOption?;
|
|
82
|
+
private readonly onError;
|
|
83
|
+
private readonly handlers;
|
|
84
|
+
private readonly urlCache;
|
|
85
|
+
/** `taskQueueUrl` resolutions per group (the promise, so concurrent dispatches share one call). */
|
|
86
|
+
private readonly groupUrlCache;
|
|
87
|
+
private running;
|
|
88
|
+
private readonly abort;
|
|
89
|
+
private taskLoop?;
|
|
90
|
+
private resultLoop?;
|
|
91
|
+
constructor(options: SqsTransportOptions);
|
|
92
|
+
private resolveByName;
|
|
93
|
+
private tasksUrl;
|
|
94
|
+
private resultsUrl;
|
|
95
|
+
dispatch(task: RemoteTask): Promise<void>;
|
|
96
|
+
/** Register a step handler (worker side). Starts the group's task consumer on first call. */
|
|
97
|
+
handle(name: string, fn: StepHandler): void;
|
|
98
|
+
onResult(handler: (result: StepResult) => Promise<void>): void;
|
|
99
|
+
onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void;
|
|
100
|
+
/**
|
|
101
|
+
* Receive a batch and hand each message to `each`, one at a time, never letting a failure escape:
|
|
102
|
+
* a throw is reported through `onError` and its message is left on the queue (SQS redelivers it
|
|
103
|
+
* after the visibility timeout; a redrive policy DLQs one that keeps failing). Every message of the
|
|
104
|
+
* batch is kept invisible until it is handled (see {@link holdVisible}), so the ones waiting behind a
|
|
105
|
+
* slow handler are never redelivered to another consumer meanwhile.
|
|
106
|
+
*/
|
|
107
|
+
private pollLoop;
|
|
108
|
+
/**
|
|
109
|
+
* Keep `messages` invisible while they wait or run: every third of the visibility timeout, extend
|
|
110
|
+
* each one still in the set back to the full timeout. Returns the stop function.
|
|
111
|
+
*/
|
|
112
|
+
private holdVisible;
|
|
113
|
+
private parse;
|
|
114
|
+
private pollTasks;
|
|
115
|
+
private pollResults;
|
|
116
|
+
/** Wait 1s, or until `close()` aborts. The abort listener is removed when the timer fires, so
|
|
117
|
+
* sustained failures never accumulate listeners on the shared signal. */
|
|
118
|
+
private backoff;
|
|
119
|
+
/** One long-poll receive. Swallows the abort thrown on `close()`; logs and backs off otherwise. */
|
|
120
|
+
private receive;
|
|
121
|
+
private shouldSkip;
|
|
122
|
+
private del;
|
|
123
|
+
private release;
|
|
124
|
+
/** Stop the pollers and (if we created it) destroy the SQS client so the process can exit. */
|
|
125
|
+
close(): Promise<void>;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export { type QueueUrlResolver, SqsTransport, type SqsTransportOptions };
|
package/dist/index.js
CHANGED
|
@@ -1,18 +1,285 @@
|
|
|
1
|
-
|
|
2
|
-
var
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
3
|
+
|
|
4
|
+
// src/sqs-transport.ts
|
|
5
|
+
import { ChangeMessageVisibilityCommand, CreateQueueCommand, DeleteMessageCommand, GetQueueUrlCommand, ReceiveMessageCommand, SQSClient, SendMessageCommand } from "@aws-sdk/client-sqs";
|
|
6
|
+
import { runStepHandler } from "@dudousxd/nestjs-durable-core";
|
|
7
|
+
var RESULT_VISIBILITY_SEC = 30;
|
|
8
|
+
var SqsTransport = class {
|
|
9
|
+
static {
|
|
10
|
+
__name(this, "SqsTransport");
|
|
11
|
+
}
|
|
12
|
+
client;
|
|
13
|
+
ownsClient;
|
|
14
|
+
group;
|
|
15
|
+
prefix;
|
|
16
|
+
autoCreate;
|
|
17
|
+
marker;
|
|
18
|
+
waitTimeSeconds;
|
|
19
|
+
visibilityTimeoutSec;
|
|
20
|
+
taskQueueUrlResolver;
|
|
21
|
+
resultsQueueUrlOption;
|
|
22
|
+
onError;
|
|
23
|
+
handlers = /* @__PURE__ */ new Map();
|
|
24
|
+
urlCache = /* @__PURE__ */ new Map();
|
|
25
|
+
/** `taskQueueUrl` resolutions per group (the promise, so concurrent dispatches share one call). */
|
|
26
|
+
groupUrlCache = /* @__PURE__ */ new Map();
|
|
27
|
+
running = true;
|
|
28
|
+
abort = new AbortController();
|
|
29
|
+
taskLoop;
|
|
30
|
+
resultLoop;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.client = options.client ?? new SQSClient(options.clientConfig ?? {});
|
|
33
|
+
this.ownsClient = !options.client;
|
|
34
|
+
this.group = options.group;
|
|
35
|
+
this.prefix = options.prefix ?? "durable";
|
|
36
|
+
this.autoCreate = options.autoCreate ?? false;
|
|
37
|
+
this.marker = options.marker;
|
|
38
|
+
this.waitTimeSeconds = options.waitTimeSeconds ?? 20;
|
|
39
|
+
this.visibilityTimeoutSec = options.visibilityTimeoutSec ?? 60;
|
|
40
|
+
this.taskQueueUrlResolver = options.taskQueueUrl;
|
|
41
|
+
this.resultsQueueUrlOption = options.resultsQueueUrl;
|
|
42
|
+
this.onError = options.onError ?? ((err) => console.error("[SqsTransport]", err));
|
|
43
|
+
}
|
|
44
|
+
// ── queue resolution ───────────────────────────────────────────────────────────────────────
|
|
45
|
+
async resolveByName(name) {
|
|
46
|
+
const cached = this.urlCache.get(name);
|
|
47
|
+
if (cached) return cached;
|
|
48
|
+
let url;
|
|
49
|
+
try {
|
|
50
|
+
const out = await this.client.send(new GetQueueUrlCommand({
|
|
51
|
+
QueueName: name
|
|
52
|
+
}));
|
|
53
|
+
url = out.QueueUrl;
|
|
54
|
+
} catch (err) {
|
|
55
|
+
if (this.autoCreate) {
|
|
56
|
+
const created = await this.client.send(new CreateQueueCommand({
|
|
57
|
+
QueueName: name
|
|
58
|
+
}));
|
|
59
|
+
url = created.QueueUrl;
|
|
60
|
+
} else {
|
|
61
|
+
throw err;
|
|
62
|
+
}
|
|
7
63
|
}
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
64
|
+
this.urlCache.set(name, url);
|
|
65
|
+
return url;
|
|
66
|
+
}
|
|
67
|
+
async tasksUrl(group) {
|
|
68
|
+
const resolver = this.taskQueueUrlResolver;
|
|
69
|
+
if (!resolver) return this.resolveByName(`${this.prefix}-tasks-${group}`);
|
|
70
|
+
let url = this.groupUrlCache.get(group);
|
|
71
|
+
if (!url) {
|
|
72
|
+
url = Promise.resolve().then(() => resolver(group)).catch((err) => {
|
|
73
|
+
this.groupUrlCache.delete(group);
|
|
74
|
+
throw err;
|
|
75
|
+
});
|
|
76
|
+
this.groupUrlCache.set(group, url);
|
|
77
|
+
}
|
|
78
|
+
return url;
|
|
79
|
+
}
|
|
80
|
+
async resultsUrl() {
|
|
81
|
+
const opt = this.resultsQueueUrlOption;
|
|
82
|
+
if (typeof opt === "string") return opt;
|
|
83
|
+
if (typeof opt === "function") return opt();
|
|
84
|
+
return this.resolveByName(`${this.prefix}-results`);
|
|
85
|
+
}
|
|
86
|
+
// ── engine → worker ────────────────────────────────────────────────────────────────────────
|
|
87
|
+
async dispatch(task) {
|
|
88
|
+
const QueueUrl = await this.tasksUrl(task.group);
|
|
89
|
+
await this.client.send(new SendMessageCommand({
|
|
90
|
+
QueueUrl,
|
|
91
|
+
MessageBody: JSON.stringify(task),
|
|
92
|
+
MessageAttributes: this.marker ? {
|
|
93
|
+
[this.marker]: {
|
|
94
|
+
DataType: "String",
|
|
95
|
+
StringValue: "1"
|
|
96
|
+
}
|
|
97
|
+
} : void 0
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
// ── worker → engine ────────────────────────────────────────────────────────────────────────
|
|
101
|
+
/** Register a step handler (worker side). Starts the group's task consumer on first call. */
|
|
102
|
+
handle(name, fn) {
|
|
103
|
+
if (!this.group) throw new Error("SqsTransport needs a `group` to register handlers");
|
|
104
|
+
this.handlers.set(name, fn);
|
|
105
|
+
if (!this.taskLoop) this.taskLoop = this.pollTasks(this.group);
|
|
106
|
+
}
|
|
107
|
+
onResult(handler) {
|
|
108
|
+
if (!this.resultLoop) this.resultLoop = this.pollResults(handler);
|
|
109
|
+
}
|
|
110
|
+
onHeartbeat(_handler) {
|
|
111
|
+
}
|
|
112
|
+
// ── polling loops ──────────────────────────────────────────────────────────────────────────
|
|
113
|
+
/**
|
|
114
|
+
* Receive a batch and hand each message to `each`, one at a time, never letting a failure escape:
|
|
115
|
+
* a throw is reported through `onError` and its message is left on the queue (SQS redelivers it
|
|
116
|
+
* after the visibility timeout; a redrive policy DLQs one that keeps failing). Every message of the
|
|
117
|
+
* batch is kept invisible until it is handled (see {@link holdVisible}), so the ones waiting behind a
|
|
118
|
+
* slow handler are never redelivered to another consumer meanwhile.
|
|
119
|
+
*/
|
|
120
|
+
async pollLoop(queueUrl, visibilitySec, each) {
|
|
121
|
+
while (this.running) {
|
|
122
|
+
let QueueUrl;
|
|
123
|
+
try {
|
|
124
|
+
QueueUrl = await queueUrl();
|
|
125
|
+
} catch (err) {
|
|
126
|
+
if (!this.running) return;
|
|
127
|
+
this.onError(err);
|
|
128
|
+
await this.backoff();
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const messages = await this.receive(QueueUrl, visibilitySec);
|
|
132
|
+
const pending = new Set(messages);
|
|
133
|
+
const stopHolding = this.holdVisible(QueueUrl, pending, visibilitySec);
|
|
134
|
+
try {
|
|
135
|
+
for (const msg of messages) {
|
|
136
|
+
if (!this.running) break;
|
|
137
|
+
try {
|
|
138
|
+
if (this.shouldSkip(msg)) {
|
|
139
|
+
pending.delete(msg);
|
|
140
|
+
await this.release(QueueUrl, msg.ReceiptHandle);
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
await each(QueueUrl, msg);
|
|
144
|
+
} catch (err) {
|
|
145
|
+
this.onError(err);
|
|
146
|
+
} finally {
|
|
147
|
+
pending.delete(msg);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
} finally {
|
|
151
|
+
stopHolding();
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Keep `messages` invisible while they wait or run: every third of the visibility timeout, extend
|
|
157
|
+
* each one still in the set back to the full timeout. Returns the stop function.
|
|
158
|
+
*/
|
|
159
|
+
holdVisible(QueueUrl, messages, visibilitySec) {
|
|
160
|
+
if (messages.size === 0) return () => {
|
|
161
|
+
};
|
|
162
|
+
const intervalMs = Math.max(200, Math.floor(visibilitySec * 1e3 / 3));
|
|
163
|
+
let round;
|
|
164
|
+
const timer = setInterval(() => {
|
|
165
|
+
if (round) return;
|
|
166
|
+
round = Promise.all([
|
|
167
|
+
...messages
|
|
168
|
+
].map((msg) => msg.ReceiptHandle ? this.client.send(new ChangeMessageVisibilityCommand({
|
|
169
|
+
QueueUrl,
|
|
170
|
+
ReceiptHandle: msg.ReceiptHandle,
|
|
171
|
+
VisibilityTimeout: visibilitySec
|
|
172
|
+
})).then(() => void 0).catch((err) => {
|
|
173
|
+
if (this.running) this.onError(err);
|
|
174
|
+
}) : void 0)).then(() => {
|
|
175
|
+
round = void 0;
|
|
176
|
+
});
|
|
177
|
+
}, intervalMs);
|
|
178
|
+
timer.unref?.();
|
|
179
|
+
return () => clearInterval(timer);
|
|
180
|
+
}
|
|
181
|
+
parse(msg) {
|
|
182
|
+
try {
|
|
183
|
+
return JSON.parse(msg.Body ?? "");
|
|
184
|
+
} catch {
|
|
185
|
+
throw new Error(`[SqsTransport] message ${msg.MessageId ?? "?"} has a non-JSON body; leaving it for the queue's redrive policy`);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
pollTasks(group) {
|
|
189
|
+
return this.pollLoop(() => this.tasksUrl(group), this.visibilityTimeoutSec, async (QueueUrl, msg) => {
|
|
190
|
+
const task = this.parse(msg);
|
|
191
|
+
const result = await runStepHandler(task, this.handlers.get(task.name));
|
|
192
|
+
await this.client.send(new SendMessageCommand({
|
|
193
|
+
QueueUrl: await this.resultsUrl(),
|
|
194
|
+
MessageBody: JSON.stringify(result),
|
|
195
|
+
MessageAttributes: this.marker ? {
|
|
196
|
+
[this.marker]: {
|
|
197
|
+
DataType: "String",
|
|
198
|
+
StringValue: "1"
|
|
199
|
+
}
|
|
200
|
+
} : void 0
|
|
201
|
+
}));
|
|
202
|
+
await this.del(QueueUrl, msg.ReceiptHandle);
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
pollResults(handler) {
|
|
206
|
+
return this.pollLoop(() => this.resultsUrl(), RESULT_VISIBILITY_SEC, async (QueueUrl, msg) => {
|
|
207
|
+
await handler(this.parse(msg));
|
|
208
|
+
await this.del(QueueUrl, msg.ReceiptHandle);
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
/** Wait 1s, or until `close()` aborts. The abort listener is removed when the timer fires, so
|
|
212
|
+
* sustained failures never accumulate listeners on the shared signal. */
|
|
213
|
+
backoff() {
|
|
214
|
+
return new Promise((resolve) => {
|
|
215
|
+
const signal = this.abort.signal;
|
|
216
|
+
if (signal.aborted) return resolve();
|
|
217
|
+
const onAbort = /* @__PURE__ */ __name(() => {
|
|
218
|
+
clearTimeout(timer);
|
|
219
|
+
resolve();
|
|
220
|
+
}, "onAbort");
|
|
221
|
+
const timer = setTimeout(() => {
|
|
222
|
+
signal.removeEventListener("abort", onAbort);
|
|
223
|
+
resolve();
|
|
224
|
+
}, 1e3);
|
|
225
|
+
signal.addEventListener("abort", onAbort, {
|
|
226
|
+
once: true
|
|
227
|
+
});
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
/** One long-poll receive. Swallows the abort thrown on `close()`; logs and backs off otherwise. */
|
|
231
|
+
async receive(QueueUrl, visibility) {
|
|
232
|
+
try {
|
|
233
|
+
const out = await this.client.send(new ReceiveMessageCommand({
|
|
234
|
+
QueueUrl,
|
|
235
|
+
MaxNumberOfMessages: 10,
|
|
236
|
+
WaitTimeSeconds: this.waitTimeSeconds,
|
|
237
|
+
VisibilityTimeout: visibility,
|
|
238
|
+
MessageAttributeNames: this.marker ? [
|
|
239
|
+
"All"
|
|
240
|
+
] : void 0
|
|
241
|
+
}), {
|
|
242
|
+
abortSignal: this.abort.signal
|
|
243
|
+
});
|
|
244
|
+
return out.Messages ?? [];
|
|
245
|
+
} catch (err) {
|
|
246
|
+
if (!this.running) return [];
|
|
247
|
+
this.onError(err);
|
|
248
|
+
await this.backoff();
|
|
249
|
+
return [];
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
shouldSkip(msg) {
|
|
253
|
+
return !!this.marker && !msg.MessageAttributes?.[this.marker];
|
|
254
|
+
}
|
|
255
|
+
async del(QueueUrl, ReceiptHandle) {
|
|
256
|
+
if (!ReceiptHandle) return;
|
|
257
|
+
await this.client.send(new DeleteMessageCommand({
|
|
258
|
+
QueueUrl,
|
|
259
|
+
ReceiptHandle
|
|
260
|
+
}));
|
|
261
|
+
}
|
|
262
|
+
async release(QueueUrl, ReceiptHandle) {
|
|
263
|
+
if (!ReceiptHandle) return;
|
|
264
|
+
await this.client.send(new ChangeMessageVisibilityCommand({
|
|
265
|
+
QueueUrl,
|
|
266
|
+
ReceiptHandle,
|
|
267
|
+
VisibilityTimeout: 0
|
|
268
|
+
})).catch(() => {
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
/** Stop the pollers and (if we created it) destroy the SQS client so the process can exit. */
|
|
272
|
+
async close() {
|
|
273
|
+
this.running = false;
|
|
274
|
+
this.abort.abort();
|
|
275
|
+
await Promise.allSettled([
|
|
276
|
+
this.taskLoop,
|
|
277
|
+
this.resultLoop
|
|
278
|
+
]);
|
|
279
|
+
if (this.ownsClient) this.client.destroy();
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
export {
|
|
283
|
+
SqsTransport
|
|
15
284
|
};
|
|
16
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./sqs-transport"), exports);
|
|
18
285
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,kDAAgC"}
|
|
1
|
+
{"version":3,"sources":["../src/sqs-transport.ts"],"sourcesContent":["import {\n ChangeMessageVisibilityCommand,\n CreateQueueCommand,\n DeleteMessageCommand,\n GetQueueUrlCommand,\n ReceiveMessageCommand,\n SQSClient,\n type SQSClientConfig,\n SendMessageCommand,\n} from '@aws-sdk/client-sqs';\nimport {\n type Heartbeat,\n type RemoteTask,\n type StepHandler,\n type StepResult,\n type Transport,\n runStepHandler,\n} from '@dudousxd/nestjs-durable-core';\n\n/** Resolve a group's tasks queue URL. Sync or async; resolved once per group and cached (a rejected\n * resolution is not cached — the next call asks again). */\nexport type QueueUrlResolver = (group: string) => string | Promise<string>;\n\nexport interface SqsTransportOptions {\n /**\n * Reuse an existing SQS client (recommended — share the app's). When omitted, one is built\n * from `clientConfig` and destroyed on `close()`.\n */\n client?: SQSClient;\n /** Used only when `client` is omitted — e.g. `{ region, endpoint, credentials }` for ElasticMQ. */\n clientConfig?: SQSClientConfig;\n\n /** The worker group this instance serves. Required to register `handle()` consumers. */\n group?: string;\n\n /**\n * Map a group → an **existing** tasks queue URL. This is the seam for reusing queues you already\n * have (e.g. `extraction`, `ingestion`) instead of letting the transport mint its own. When\n * omitted, the transport resolves `${prefix}-tasks-${group}` by name (and creates it if\n * `autoCreate`). Return value is awaited and cached per group.\n */\n taskQueueUrl?: QueueUrlResolver;\n /**\n * The results queue URL (worker → engine). A literal URL or a resolver. When omitted, the\n * transport resolves `${prefix}-results` by name (and creates it if `autoCreate`).\n */\n resultsQueueUrl?: string | (() => string | Promise<string>);\n\n /** Prefix for the fallback `${prefix}-tasks-*` / `${prefix}-results` names. Default `durable`. */\n prefix?: string;\n /**\n * Create the fallback-named queues on first use if they don't exist (handy for ElasticMQ / dev).\n * Ignored for queues you supply via `taskQueueUrl` / `resultsQueueUrl` — those must already exist.\n */\n autoCreate?: boolean;\n\n /**\n * When set, durable messages carry this SQS message attribute and pollers **skip** messages\n * that lack it (releasing them for a co-resident legacy consumer). Enables sharing one physical\n * queue with a non-durable consumer — but only if that consumer likewise ignores tagged messages.\n * Leave unset for the clean case: a queue dedicated to durable traffic.\n */\n marker?: string;\n\n /** SQS receive long-poll seconds (0–20). Default 20. */\n waitTimeSeconds?: number;\n /**\n * Visibility timeout for a received task, in seconds. Default 60. Every message this instance has\n * received — the one running and the ones of the same batch waiting behind it — is kept invisible by\n * re-extending it (`ChangeMessageVisibility`) every third of this, so a step may run longer; only a\n * crashed instance's messages reappear, after at most this long.\n */\n visibilityTimeoutSec?: number;\n /**\n * Where a transport failure is reported: a failing receive, a result handler that throws, a result\n * send that fails, a message whose body isn't JSON. The message involved is NOT deleted: SQS\n * redelivers it after its visibility timeout, and a queue redrive policy (`maxReceiveCount` → DLQ)\n * moves one that keeps failing aside. Default `console.error`.\n */\n onError?: (err: unknown) => void;\n}\n\n/** A received message, as the poll loops use it. */\ninterface Received {\n Body?: string | undefined;\n ReceiptHandle?: string | undefined;\n MessageId?: string | undefined;\n MessageAttributes?: Record<string, unknown> | undefined;\n}\n\n/** The results queue's visibility timeout (seconds). */\nconst RESULT_VISIBILITY_SEC = 30;\n\n/**\n * An SQS-backed `Transport` — dispatch remote steps over Amazon SQS (or ElasticMQ). Unlike the\n * BullMQ transport, it does **not** mint its own queue names: pass `taskQueueUrl` / `resultsQueueUrl`\n * to ride the queues you already operate. The wire payload is the documented `RemoteTask` /\n * `StepResult` JSON, so non-Node workers on the same queues interoperate.\n *\n * Run one instance engine-side (calls `onResult`, dispatches tasks) and one per worker process\n * (calls `handle()` for its group). SQS is at-least-once: a task whose process crashes before the\n * result is sent reappears after the visibility timeout (durable retry); a duplicate `StepResult`\n * is harmless because the engine resolves a step's `pending` exactly once by `stepId`.\n */\nexport class SqsTransport implements Transport {\n private readonly client: SQSClient;\n private readonly ownsClient: boolean;\n private readonly group?: string | undefined;\n private readonly prefix: string;\n private readonly autoCreate: boolean;\n private readonly marker?: string | undefined;\n private readonly waitTimeSeconds: number;\n private readonly visibilityTimeoutSec: number;\n private readonly taskQueueUrlResolver?: QueueUrlResolver | undefined;\n private readonly resultsQueueUrlOption?: string | (() => string | Promise<string>) | undefined;\n private readonly onError: (err: unknown) => void;\n\n private readonly handlers = new Map<string, StepHandler>();\n private readonly urlCache = new Map<string, string>();\n /** `taskQueueUrl` resolutions per group (the promise, so concurrent dispatches share one call). */\n private readonly groupUrlCache = new Map<string, Promise<string>>();\n private running = true;\n private readonly abort = new AbortController();\n private taskLoop?: Promise<void>;\n private resultLoop?: Promise<void>;\n\n constructor(options: SqsTransportOptions) {\n this.client = options.client ?? new SQSClient(options.clientConfig ?? {});\n this.ownsClient = !options.client;\n this.group = options.group;\n this.prefix = options.prefix ?? 'durable';\n this.autoCreate = options.autoCreate ?? false;\n this.marker = options.marker;\n this.waitTimeSeconds = options.waitTimeSeconds ?? 20;\n this.visibilityTimeoutSec = options.visibilityTimeoutSec ?? 60;\n this.taskQueueUrlResolver = options.taskQueueUrl;\n this.resultsQueueUrlOption = options.resultsQueueUrl;\n this.onError = options.onError ?? ((err) => console.error('[SqsTransport]', err));\n }\n\n // ── queue resolution ───────────────────────────────────────────────────────────────────────\n\n private async resolveByName(name: string): Promise<string> {\n const cached = this.urlCache.get(name);\n if (cached) return cached;\n let url: string;\n try {\n const out = await this.client.send(new GetQueueUrlCommand({ QueueName: name }));\n url = out.QueueUrl as string;\n } catch (err) {\n if (this.autoCreate) {\n const created = await this.client.send(new CreateQueueCommand({ QueueName: name }));\n url = created.QueueUrl as string;\n } else {\n throw err;\n }\n }\n this.urlCache.set(name, url);\n return url;\n }\n\n private async tasksUrl(group: string): Promise<string> {\n const resolver = this.taskQueueUrlResolver;\n if (!resolver) return this.resolveByName(`${this.prefix}-tasks-${group}`);\n let url = this.groupUrlCache.get(group);\n if (!url) {\n url = Promise.resolve()\n .then(() => resolver(group))\n .catch((err) => {\n this.groupUrlCache.delete(group);\n throw err;\n });\n this.groupUrlCache.set(group, url);\n }\n return url;\n }\n\n private async resultsUrl(): Promise<string> {\n const opt = this.resultsQueueUrlOption;\n if (typeof opt === 'string') return opt;\n if (typeof opt === 'function') return opt();\n return this.resolveByName(`${this.prefix}-results`);\n }\n\n // ── engine → worker ────────────────────────────────────────────────────────────────────────\n\n async dispatch(task: RemoteTask): Promise<void> {\n const QueueUrl = await this.tasksUrl(task.group);\n await this.client.send(\n new SendMessageCommand({\n QueueUrl,\n MessageBody: JSON.stringify(task),\n MessageAttributes: this.marker\n ? { [this.marker]: { DataType: 'String', StringValue: '1' } }\n : undefined,\n }),\n );\n }\n\n // ── worker → engine ────────────────────────────────────────────────────────────────────────\n\n /** Register a step handler (worker side). Starts the group's task consumer on first call. */\n handle(name: string, fn: StepHandler): void {\n if (!this.group) throw new Error('SqsTransport needs a `group` to register handlers');\n this.handlers.set(name, fn);\n if (!this.taskLoop) this.taskLoop = this.pollTasks(this.group);\n }\n\n onResult(handler: (result: StepResult) => Promise<void>): void {\n if (!this.resultLoop) this.resultLoop = this.pollResults(handler);\n }\n\n onHeartbeat(_handler: (beat: Heartbeat) => Promise<void>): void {\n // Not modelled over SQS; the queue's visibility-timeout redelivery is the liveness mechanism.\n }\n\n // ── polling loops ──────────────────────────────────────────────────────────────────────────\n\n /**\n * Receive a batch and hand each message to `each`, one at a time, never letting a failure escape:\n * a throw is reported through `onError` and its message is left on the queue (SQS redelivers it\n * after the visibility timeout; a redrive policy DLQs one that keeps failing). Every message of the\n * batch is kept invisible until it is handled (see {@link holdVisible}), so the ones waiting behind a\n * slow handler are never redelivered to another consumer meanwhile.\n */\n private async pollLoop(\n queueUrl: () => Promise<string>,\n visibilitySec: number,\n each: (QueueUrl: string, msg: Received) => Promise<void>,\n ): Promise<void> {\n while (this.running) {\n let QueueUrl: string;\n try {\n QueueUrl = await queueUrl();\n } catch (err) {\n if (!this.running) return;\n this.onError(err);\n await this.backoff();\n continue;\n }\n const messages = await this.receive(QueueUrl, visibilitySec);\n const pending = new Set<Received>(messages);\n const stopHolding = this.holdVisible(QueueUrl, pending, visibilitySec);\n try {\n for (const msg of messages) {\n if (!this.running) break; // close(): what is left reappears after its visibility timeout\n try {\n if (this.shouldSkip(msg)) {\n // Not ours (shared queue): release immediately so the legacy consumer can take it.\n pending.delete(msg);\n await this.release(QueueUrl, msg.ReceiptHandle);\n continue;\n }\n await each(QueueUrl, msg);\n } catch (err) {\n this.onError(err);\n } finally {\n pending.delete(msg);\n }\n }\n } finally {\n stopHolding();\n }\n }\n }\n\n /**\n * Keep `messages` invisible while they wait or run: every third of the visibility timeout, extend\n * each one still in the set back to the full timeout. Returns the stop function.\n */\n private holdVisible(\n QueueUrl: string,\n messages: Set<Received>,\n visibilitySec: number,\n ): () => void {\n if (messages.size === 0) return () => {};\n const intervalMs = Math.max(200, Math.floor((visibilitySec * 1000) / 3));\n let round: Promise<void> | undefined;\n const timer = setInterval(() => {\n if (round) return;\n round = Promise.all(\n [...messages].map((msg) =>\n msg.ReceiptHandle\n ? this.client\n .send(\n new ChangeMessageVisibilityCommand({\n QueueUrl,\n ReceiptHandle: msg.ReceiptHandle,\n VisibilityTimeout: visibilitySec,\n }),\n )\n .then(() => undefined)\n .catch((err) => {\n if (this.running) this.onError(err);\n })\n : undefined,\n ),\n ).then(() => {\n round = undefined;\n });\n }, intervalMs);\n timer.unref?.();\n return () => clearInterval(timer);\n }\n\n private parse<T>(msg: Received): T {\n try {\n return JSON.parse(msg.Body ?? '') as T;\n } catch {\n throw new Error(\n `[SqsTransport] message ${msg.MessageId ?? '?'} has a non-JSON body; leaving it for the queue's redrive policy`,\n );\n }\n }\n\n private pollTasks(group: string): Promise<void> {\n return this.pollLoop(\n () => this.tasksUrl(group),\n this.visibilityTimeoutSec,\n async (QueueUrl, msg) => {\n const task = this.parse<RemoteTask>(msg);\n const result = await runStepHandler(task, this.handlers.get(task.name));\n await this.client.send(\n new SendMessageCommand({\n QueueUrl: await this.resultsUrl(),\n MessageBody: JSON.stringify(result),\n MessageAttributes: this.marker\n ? { [this.marker]: { DataType: 'String', StringValue: '1' } }\n : undefined,\n }),\n );\n await this.del(QueueUrl, msg.ReceiptHandle);\n },\n );\n }\n\n private pollResults(handler: (result: StepResult) => Promise<void>): Promise<void> {\n return this.pollLoop(\n () => this.resultsUrl(),\n RESULT_VISIBILITY_SEC,\n async (QueueUrl, msg) => {\n await handler(this.parse<StepResult>(msg));\n await this.del(QueueUrl, msg.ReceiptHandle);\n },\n );\n }\n\n /** Wait 1s, or until `close()` aborts. The abort listener is removed when the timer fires, so\n * sustained failures never accumulate listeners on the shared signal. */\n private backoff(): Promise<void> {\n return new Promise((resolve) => {\n const signal = this.abort.signal;\n if (signal.aborted) return resolve();\n const onAbort = () => {\n clearTimeout(timer);\n resolve();\n };\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, 1000);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n /** One long-poll receive. Swallows the abort thrown on `close()`; logs and backs off otherwise. */\n private async receive(QueueUrl: string, visibility: number): Promise<Received[]> {\n try {\n const out = await this.client.send(\n new ReceiveMessageCommand({\n QueueUrl,\n MaxNumberOfMessages: 10,\n WaitTimeSeconds: this.waitTimeSeconds,\n VisibilityTimeout: visibility,\n MessageAttributeNames: this.marker ? ['All'] : undefined,\n }),\n { abortSignal: this.abort.signal },\n );\n return out.Messages ?? [];\n } catch (err) {\n if (!this.running) return [];\n this.onError(err);\n await this.backoff();\n return [];\n }\n }\n\n private shouldSkip(msg: { MessageAttributes?: Record<string, unknown> | undefined }): boolean {\n return !!this.marker && !msg.MessageAttributes?.[this.marker];\n }\n\n private async del(QueueUrl: string, ReceiptHandle?: string): Promise<void> {\n if (!ReceiptHandle) return;\n await this.client.send(new DeleteMessageCommand({ QueueUrl, ReceiptHandle }));\n }\n\n private async release(QueueUrl: string, ReceiptHandle?: string): Promise<void> {\n if (!ReceiptHandle) return;\n await this.client\n .send(new ChangeMessageVisibilityCommand({ QueueUrl, ReceiptHandle, VisibilityTimeout: 0 }))\n .catch(() => {});\n }\n\n /** Stop the pollers and (if we created it) destroy the SQS client so the process can exit. */\n async close(): Promise<void> {\n this.running = false;\n this.abort.abort();\n await Promise.allSettled([this.taskLoop, this.resultLoop]);\n if (this.ownsClient) this.client.destroy();\n }\n}\n"],"mappings":";;;;AAAA,SACEA,gCACAC,oBACAC,sBACAC,oBACAC,uBACAC,WAEAC,0BACK;AACP,SAMEC,sBACK;AA0EP,IAAMC,wBAAwB;AAavB,IAAMC,eAAN,MAAMA;EAxGb,OAwGaA;;;EACMC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EACAC;EAEAC,WAAW,oBAAIC,IAAAA;EACfC,WAAW,oBAAID,IAAAA;;EAEfE,gBAAgB,oBAAIF,IAAAA;EAC7BG,UAAU;EACDC,QAAQ,IAAIC,gBAAAA;EACrBC;EACAC;EAER,YAAYC,SAA8B;AACxC,SAAKpB,SAASoB,QAAQpB,UAAU,IAAIqB,UAAUD,QAAQE,gBAAgB,CAAC,CAAA;AACvE,SAAKrB,aAAa,CAACmB,QAAQpB;AAC3B,SAAKE,QAAQkB,QAAQlB;AACrB,SAAKC,SAASiB,QAAQjB,UAAU;AAChC,SAAKC,aAAagB,QAAQhB,cAAc;AACx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AcpC,QAAQtC,UAAkB2E,YAAyC;AAC/E,QAAI;AACF,YAAM/E,MAAM,MAAM,KAAKjC,OAAOkC,KAC5B,IAAI+E,sBAAsB;QACxB5E;QACA6E,qBAAqB;QACrBC,iBAAiB,KAAK7G;QACtByF,mBAAmBiB;QACnBI,uBAAuB,KAAK/G,SAAS;UAAC;YAASsD;MACjD,CAAA,GACA;QAAE0D,aAAa,KAAKrG,MAAMwF;MAAO,CAAA;AAEnC,aAAOvE,IAAIqF,YAAY,CAAA;IACzB,SAAS7F,KAAK;AACZ,UAAI,CAAC,KAAKV,QAAS,QAAO,CAAA;AAC1B,WAAKL,QAAQe,GAAAA;AACb,YAAM,KAAKgD,QAAO;AAClB,aAAO,CAAA;IACT;EACF;EAEQQ,WAAWD,KAA2E;AAC5F,WAAO,CAAC,CAAC,KAAK3E,UAAU,CAAC2E,IAAIxB,oBAAoB,KAAKnD,MAAM;EAC9D;EAEA,MAAckG,IAAIlE,UAAkB8C,eAAuC;AACzE,QAAI,CAACA,cAAe;AACpB,UAAM,KAAKnF,OAAOkC,KAAK,IAAIqF,qBAAqB;MAAElF;MAAU8C;IAAc,CAAA,CAAA;EAC5E;EAEA,MAAcD,QAAQ7C,UAAkB8C,eAAuC;AAC7E,QAAI,CAACA,cAAe;AACpB,UAAM,KAAKnF,OACRkC,KAAK,IAAI4D,+BAA+B;MAAEzD;MAAU8C;MAAeY,mBAAmB;IAAE,CAAA,CAAA,EACxFjD,MAAM,MAAA;IAAO,CAAA;EAClB;;EAGA,MAAM0E,QAAuB;AAC3B,SAAKzG,UAAU;AACf,SAAKC,MAAMA,MAAK;AAChB,UAAM2B,QAAQ8E,WAAW;MAAC,KAAKvG;MAAU,KAAKC;KAAW;AACzD,QAAI,KAAKlB,WAAY,MAAKD,OAAO0H,QAAO;EAC1C;AACF;","names":["ChangeMessageVisibilityCommand","CreateQueueCommand","DeleteMessageCommand","GetQueueUrlCommand","ReceiveMessageCommand","SQSClient","SendMessageCommand","runStepHandler","RESULT_VISIBILITY_SEC","SqsTransport","client","ownsClient","group","prefix","autoCreate","marker","waitTimeSeconds","visibilityTimeoutSec","taskQueueUrlResolver","resultsQueueUrlOption","onError","handlers","Map","urlCache","groupUrlCache","running","abort","AbortController","taskLoop","resultLoop","options","SQSClient","clientConfig","taskQueueUrl","resultsQueueUrl","err","console","error","resolveByName","name","cached","get","url","out","send","GetQueueUrlCommand","QueueName","QueueUrl","created","CreateQueueCommand","set","tasksUrl","resolver","Promise","resolve","then","catch","delete","resultsUrl","opt","dispatch","task","SendMessageCommand","MessageBody","JSON","stringify","MessageAttributes","DataType","StringValue","undefined","handle","fn","Error","pollTasks","onResult","handler","pollResults","onHeartbeat","_handler","pollLoop","queueUrl","visibilitySec","each","backoff","messages","receive","pending","Set","stopHolding","holdVisible","msg","shouldSkip","release","ReceiptHandle","size","intervalMs","Math","max","floor","round","timer","setInterval","all","map","ChangeMessageVisibilityCommand","VisibilityTimeout","unref","clearInterval","parse","Body","MessageId","result","runStepHandler","del","signal","aborted","onAbort","clearTimeout","setTimeout","removeEventListener","addEventListener","once","visibility","ReceiveMessageCommand","MaxNumberOfMessages","WaitTimeSeconds","MessageAttributeNames","abortSignal","Messages","DeleteMessageCommand","close","allSettled","destroy"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dudousxd/nestjs-durable-transport-sqs",
|
|
3
|
-
"version": "0.1
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Amazon SQS Transport for nestjs-durable — dispatch remote steps over existing SQS queues (ElasticMQ-compatible)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Davide Carvalho",
|
|
@@ -9,9 +9,19 @@
|
|
|
9
9
|
"url": "https://github.com/DavideCarvalho/nestjs-durable.git",
|
|
10
10
|
"directory": "packages/transport-sqs"
|
|
11
11
|
},
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
|
|
12
|
+
"homepage": "https://davidecarvalho.github.io/aviary/docs/durable",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/DavideCarvalho/nestjs-durable/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"nestjs",
|
|
18
|
+
"durable",
|
|
19
|
+
"transport",
|
|
20
|
+
"sqs"
|
|
21
|
+
],
|
|
22
|
+
"type": "module",
|
|
23
|
+
"main": "./dist/index.cjs",
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
15
25
|
"files": [
|
|
16
26
|
"dist"
|
|
17
27
|
],
|
|
@@ -20,13 +30,28 @@
|
|
|
20
30
|
"@dudousxd/nestjs-durable-core": ">=0.1.0 <1.0.0"
|
|
21
31
|
},
|
|
22
32
|
"devDependencies": {
|
|
23
|
-
"@aws-sdk/client-sqs": "3.
|
|
33
|
+
"@aws-sdk/client-sqs": "3.1130.0",
|
|
34
|
+
"testcontainers": "10.28.0",
|
|
24
35
|
"typescript": "5.9.3",
|
|
25
36
|
"zod": "3.25.76",
|
|
26
|
-
"
|
|
37
|
+
"tsup": "8.3.5",
|
|
38
|
+
"@dudousxd/nestjs-durable-core": "^0.80.0"
|
|
39
|
+
},
|
|
40
|
+
"module": "./dist/index.js",
|
|
41
|
+
"exports": {
|
|
42
|
+
".": {
|
|
43
|
+
"import": {
|
|
44
|
+
"types": "./dist/index.d.ts",
|
|
45
|
+
"default": "./dist/index.js"
|
|
46
|
+
},
|
|
47
|
+
"require": {
|
|
48
|
+
"types": "./dist/index.d.cts",
|
|
49
|
+
"default": "./dist/index.cjs"
|
|
50
|
+
}
|
|
51
|
+
}
|
|
27
52
|
},
|
|
28
53
|
"scripts": {
|
|
29
|
-
"build": "
|
|
54
|
+
"build": "tsup",
|
|
30
55
|
"typecheck": "tsc -p tsconfig.json --noEmit"
|
|
31
56
|
}
|
|
32
57
|
}
|
package/dist/index.d.ts.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sqs-transport.d.ts","sourceRoot":"","sources":["../src/sqs-transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAOL,SAAS,EACT,KAAK,eAAe,EACrB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,KAAK,SAAS,EACd,KAAK,UAAU,EACf,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,SAAS,EAEf,MAAM,+BAA+B,CAAC;AAEvC,kFAAkF;AAClF,MAAM,MAAM,gBAAgB,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;AAE3E,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,MAAM,CAAC,EAAE,SAAS,CAAC;IACnB,mGAAmG;IACnG,YAAY,CAAC,EAAE,eAAe,CAAC;IAE/B,wFAAwF;IACxF,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf;;;;;OAKG;IACH,YAAY,CAAC,EAAE,gBAAgB,CAAC;IAChC;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,GAAG,CAAC,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC;IAE5D,kGAAkG;IAClG,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,UAAU,CAAC,EAAE,OAAO,CAAC;IAErB;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAEhB,wDAAwD;IACxD,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,wGAAwG;IACxG,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC/B;AAED;;;;;;;;;;GAUG;AACH,qBAAa,YAAa,YAAW,SAAS;IAC5C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAY;IACnC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAU;IACrC,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.js
DELETED
|
@@ -1,191 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SqsTransport = void 0;
|
|
4
|
-
const client_sqs_1 = require("@aws-sdk/client-sqs");
|
|
5
|
-
const nestjs_durable_core_1 = require("@dudousxd/nestjs-durable-core");
|
|
6
|
-
/**
|
|
7
|
-
* An SQS-backed `Transport` — dispatch remote steps over Amazon SQS (or ElasticMQ). Unlike the
|
|
8
|
-
* BullMQ transport, it does **not** mint its own queue names: pass `taskQueueUrl` / `resultsQueueUrl`
|
|
9
|
-
* to ride the queues you already operate. The wire payload is the documented `RemoteTask` /
|
|
10
|
-
* `StepResult` JSON, so non-Node workers on the same queues interoperate.
|
|
11
|
-
*
|
|
12
|
-
* Run one instance engine-side (calls `onResult`, dispatches tasks) and one per worker process
|
|
13
|
-
* (calls `handle()` for its group). SQS is at-least-once: a task whose process crashes before the
|
|
14
|
-
* result is sent reappears after the visibility timeout (durable retry); a duplicate `StepResult`
|
|
15
|
-
* is harmless because the engine resolves a step's `pending` exactly once by `stepId`.
|
|
16
|
-
*/
|
|
17
|
-
class SqsTransport {
|
|
18
|
-
client;
|
|
19
|
-
ownsClient;
|
|
20
|
-
group;
|
|
21
|
-
prefix;
|
|
22
|
-
autoCreate;
|
|
23
|
-
marker;
|
|
24
|
-
waitTimeSeconds;
|
|
25
|
-
visibilityTimeoutSec;
|
|
26
|
-
taskQueueUrlResolver;
|
|
27
|
-
resultsQueueUrlOption;
|
|
28
|
-
handlers = new Map();
|
|
29
|
-
urlCache = new Map();
|
|
30
|
-
running = true;
|
|
31
|
-
abort = new AbortController();
|
|
32
|
-
taskLoop;
|
|
33
|
-
resultLoop;
|
|
34
|
-
constructor(options) {
|
|
35
|
-
this.client = options.client ?? new client_sqs_1.SQSClient(options.clientConfig ?? {});
|
|
36
|
-
this.ownsClient = !options.client;
|
|
37
|
-
this.group = options.group;
|
|
38
|
-
this.prefix = options.prefix ?? 'durable';
|
|
39
|
-
this.autoCreate = options.autoCreate ?? false;
|
|
40
|
-
this.marker = options.marker;
|
|
41
|
-
this.waitTimeSeconds = options.waitTimeSeconds ?? 20;
|
|
42
|
-
this.visibilityTimeoutSec = options.visibilityTimeoutSec ?? 60;
|
|
43
|
-
this.taskQueueUrlResolver = options.taskQueueUrl;
|
|
44
|
-
this.resultsQueueUrlOption = options.resultsQueueUrl;
|
|
45
|
-
}
|
|
46
|
-
// ── queue resolution ───────────────────────────────────────────────────────────────────────
|
|
47
|
-
async resolveByName(name) {
|
|
48
|
-
const cached = this.urlCache.get(name);
|
|
49
|
-
if (cached)
|
|
50
|
-
return cached;
|
|
51
|
-
let url;
|
|
52
|
-
try {
|
|
53
|
-
const out = await this.client.send(new client_sqs_1.GetQueueUrlCommand({ QueueName: name }));
|
|
54
|
-
url = out.QueueUrl;
|
|
55
|
-
}
|
|
56
|
-
catch (err) {
|
|
57
|
-
if (this.autoCreate) {
|
|
58
|
-
const created = await this.client.send(new client_sqs_1.CreateQueueCommand({ QueueName: name }));
|
|
59
|
-
url = created.QueueUrl;
|
|
60
|
-
}
|
|
61
|
-
else {
|
|
62
|
-
throw err;
|
|
63
|
-
}
|
|
64
|
-
}
|
|
65
|
-
this.urlCache.set(name, url);
|
|
66
|
-
return url;
|
|
67
|
-
}
|
|
68
|
-
async tasksUrl(group) {
|
|
69
|
-
if (this.taskQueueUrlResolver)
|
|
70
|
-
return this.taskQueueUrlResolver(group);
|
|
71
|
-
return this.resolveByName(`${this.prefix}-tasks-${group}`);
|
|
72
|
-
}
|
|
73
|
-
async resultsUrl() {
|
|
74
|
-
const opt = this.resultsQueueUrlOption;
|
|
75
|
-
if (typeof opt === 'string')
|
|
76
|
-
return opt;
|
|
77
|
-
if (typeof opt === 'function')
|
|
78
|
-
return opt();
|
|
79
|
-
return this.resolveByName(`${this.prefix}-results`);
|
|
80
|
-
}
|
|
81
|
-
// ── engine → worker ────────────────────────────────────────────────────────────────────────
|
|
82
|
-
async dispatch(task) {
|
|
83
|
-
const QueueUrl = await this.tasksUrl(task.group);
|
|
84
|
-
await this.client.send(new client_sqs_1.SendMessageCommand({
|
|
85
|
-
QueueUrl,
|
|
86
|
-
MessageBody: JSON.stringify(task),
|
|
87
|
-
MessageAttributes: this.marker
|
|
88
|
-
? { [this.marker]: { DataType: 'String', StringValue: '1' } }
|
|
89
|
-
: undefined,
|
|
90
|
-
}));
|
|
91
|
-
}
|
|
92
|
-
// ── worker → engine ────────────────────────────────────────────────────────────────────────
|
|
93
|
-
/** Register a step handler (worker side). Starts the group's task consumer on first call. */
|
|
94
|
-
handle(name, fn) {
|
|
95
|
-
if (!this.group)
|
|
96
|
-
throw new Error('SqsTransport needs a `group` to register handlers');
|
|
97
|
-
this.handlers.set(name, fn);
|
|
98
|
-
if (!this.taskLoop)
|
|
99
|
-
this.taskLoop = this.pollTasks(this.group);
|
|
100
|
-
}
|
|
101
|
-
onResult(handler) {
|
|
102
|
-
if (!this.resultLoop)
|
|
103
|
-
this.resultLoop = this.pollResults(handler);
|
|
104
|
-
}
|
|
105
|
-
onHeartbeat(_handler) {
|
|
106
|
-
// Not modelled over SQS; the queue's visibility-timeout redelivery is the liveness mechanism.
|
|
107
|
-
}
|
|
108
|
-
// ── polling loops ──────────────────────────────────────────────────────────────────────────
|
|
109
|
-
async pollTasks(group) {
|
|
110
|
-
const QueueUrl = await this.tasksUrl(group);
|
|
111
|
-
while (this.running) {
|
|
112
|
-
const messages = await this.receive(QueueUrl, this.visibilityTimeoutSec);
|
|
113
|
-
for (const msg of messages) {
|
|
114
|
-
if (this.shouldSkip(msg)) {
|
|
115
|
-
// Not ours (shared queue): release immediately so the legacy consumer can take it.
|
|
116
|
-
await this.release(QueueUrl, msg.ReceiptHandle);
|
|
117
|
-
continue;
|
|
118
|
-
}
|
|
119
|
-
const task = JSON.parse(msg.Body ?? '{}');
|
|
120
|
-
const result = await (0, nestjs_durable_core_1.runStepHandler)(task, this.handlers.get(task.name));
|
|
121
|
-
await this.client.send(new client_sqs_1.SendMessageCommand({
|
|
122
|
-
QueueUrl: await this.resultsUrl(),
|
|
123
|
-
MessageBody: JSON.stringify(result),
|
|
124
|
-
MessageAttributes: this.marker
|
|
125
|
-
? { [this.marker]: { DataType: 'String', StringValue: '1' } }
|
|
126
|
-
: undefined,
|
|
127
|
-
}));
|
|
128
|
-
await this.del(QueueUrl, msg.ReceiptHandle);
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
}
|
|
132
|
-
async pollResults(handler) {
|
|
133
|
-
const QueueUrl = await this.resultsUrl();
|
|
134
|
-
while (this.running) {
|
|
135
|
-
const messages = await this.receive(QueueUrl, 30);
|
|
136
|
-
for (const msg of messages) {
|
|
137
|
-
if (this.shouldSkip(msg)) {
|
|
138
|
-
await this.release(QueueUrl, msg.ReceiptHandle);
|
|
139
|
-
continue;
|
|
140
|
-
}
|
|
141
|
-
await handler(JSON.parse(msg.Body ?? '{}'));
|
|
142
|
-
await this.del(QueueUrl, msg.ReceiptHandle);
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
/** One long-poll receive. Swallows the abort thrown on `close()`; logs and backs off otherwise. */
|
|
147
|
-
async receive(QueueUrl, visibility) {
|
|
148
|
-
try {
|
|
149
|
-
const out = await this.client.send(new client_sqs_1.ReceiveMessageCommand({
|
|
150
|
-
QueueUrl,
|
|
151
|
-
MaxNumberOfMessages: 10,
|
|
152
|
-
WaitTimeSeconds: this.waitTimeSeconds,
|
|
153
|
-
VisibilityTimeout: visibility,
|
|
154
|
-
MessageAttributeNames: this.marker ? ['All'] : undefined,
|
|
155
|
-
}), { abortSignal: this.abort.signal });
|
|
156
|
-
return out.Messages ?? [];
|
|
157
|
-
}
|
|
158
|
-
catch (err) {
|
|
159
|
-
if (!this.running)
|
|
160
|
-
return [];
|
|
161
|
-
console.error('[SqsTransport] receive failed', err);
|
|
162
|
-
await new Promise((r) => setTimeout(r, 1000));
|
|
163
|
-
return [];
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
shouldSkip(msg) {
|
|
167
|
-
return !!this.marker && !msg.MessageAttributes?.[this.marker];
|
|
168
|
-
}
|
|
169
|
-
async del(QueueUrl, ReceiptHandle) {
|
|
170
|
-
if (!ReceiptHandle)
|
|
171
|
-
return;
|
|
172
|
-
await this.client.send(new client_sqs_1.DeleteMessageCommand({ QueueUrl, ReceiptHandle }));
|
|
173
|
-
}
|
|
174
|
-
async release(QueueUrl, ReceiptHandle) {
|
|
175
|
-
if (!ReceiptHandle)
|
|
176
|
-
return;
|
|
177
|
-
await this.client
|
|
178
|
-
.send(new client_sqs_1.ChangeMessageVisibilityCommand({ QueueUrl, ReceiptHandle, VisibilityTimeout: 0 }))
|
|
179
|
-
.catch(() => { });
|
|
180
|
-
}
|
|
181
|
-
/** Stop the pollers and (if we created it) destroy the SQS client so the process can exit. */
|
|
182
|
-
async close() {
|
|
183
|
-
this.running = false;
|
|
184
|
-
this.abort.abort();
|
|
185
|
-
await Promise.allSettled([this.taskLoop, this.resultLoop]);
|
|
186
|
-
if (this.ownsClient)
|
|
187
|
-
this.client.destroy();
|
|
188
|
-
}
|
|
189
|
-
}
|
|
190
|
-
exports.SqsTransport = SqsTransport;
|
|
191
|
-
//# sourceMappingURL=sqs-transport.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sqs-transport.js","sourceRoot":"","sources":["../src/sqs-transport.ts"],"names":[],"mappings":";;;AAAA,oDAS6B;AAC7B,uEAOuC;AAoDvC;;;;;;;;;;GAUG;AACH,MAAa,YAAY;IACN,MAAM,CAAY;IAClB,UAAU,CAAU;IACpB,KAAK,CAAU;IACf,MAAM,CAAS;IACf,UAAU,CAAU;IACpB,MAAM,CAAU;IAChB,eAAe,CAAS;IACxB,oBAAoB,CAAS;IAC7B,oBAAoB,CAAoB;IACxC,qBAAqB,CAA6C;IAElE,QAAQ,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC1C,QAAQ,GAAG,I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