@haatlabs-core/queue 0.0.0-stage → 0.10.0
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 +201 -0
- package/README.md +58 -2
- package/dist/cjs/codes.d.ts +14 -0
- package/dist/cjs/codes.js +38 -0
- package/dist/cjs/consumer.d.ts +79 -0
- package/dist/cjs/consumer.js +200 -0
- package/dist/cjs/index.d.ts +6 -0
- package/dist/cjs/index.js +31 -0
- package/dist/cjs/outbox-relay.d.ts +34 -0
- package/dist/cjs/outbox-relay.js +88 -0
- package/dist/cjs/package.json +8 -0
- package/dist/cjs/poll.d.ts +55 -0
- package/dist/cjs/poll.js +93 -0
- package/dist/cjs/publisher.d.ts +59 -0
- package/dist/cjs/publisher.js +77 -0
- package/dist/cjs/topology.d.ts +40 -0
- package/dist/cjs/topology.js +65 -0
- package/dist/codes.d.ts +14 -0
- package/dist/codes.js +10 -0
- package/dist/codes.js.map +1 -0
- package/dist/consumer.d.ts +79 -0
- package/dist/consumer.js +209 -0
- package/dist/consumer.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/outbox-relay.d.ts +34 -0
- package/dist/outbox-relay.js +65 -0
- package/dist/outbox-relay.js.map +1 -0
- package/dist/poll.d.ts +55 -0
- package/dist/poll.js +84 -0
- package/dist/poll.js.map +1 -0
- package/dist/publisher.d.ts +59 -0
- package/dist/publisher.js +61 -0
- package/dist/publisher.js.map +1 -0
- package/dist/topology.d.ts +40 -0
- package/dist/topology.js +51 -0
- package/dist/topology.js.map +1 -0
- package/package.json +63 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "{}"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Haatlabs
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,59 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @haatlabs-core/queue
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
BullMQ work queues on Redis: the publisher, the retrying consumer (with a priority lane) and
|
|
4
|
+
the outbox relay. A project supplies its topology, meaning its queue names, the routing-key
|
|
5
|
+
prefixes each takes, and its key prefix, through its own `connectQueue`:
|
|
6
|
+
|
|
7
|
+
const route = routeByPrefix<QueueName>({ 'shopify-sync': ['shopify.'], imports: ['import.'] });
|
|
8
|
+
export const connectQueue = (url: string, options: { prefix?: string } = {}) =>
|
|
9
|
+
connect(url, { prefix: options.prefix ?? 'shop:queue', route });
|
|
10
|
+
|
|
11
|
+
ioredis is a peer dependency.
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
pnpm add @haatlabs-core/queue
|
|
16
|
+
|
|
17
|
+
It leaves one package to your app, so the app holds one copy: `ioredis`.
|
|
18
|
+
|
|
19
|
+
## Polling without holding a worker slot
|
|
20
|
+
|
|
21
|
+
A handler that waits on something external (a bulk operation, media processing) calls
|
|
22
|
+
`pollAgain(message, { delayMs, deadlineMs, state, onDeadline })`. The job is put back as a
|
|
23
|
+
delayed job, its worker slot is free meanwhile, it keeps its attempt count and its lane, and
|
|
24
|
+
`message.poll` (`round`, `startedAt`, `deadlineAt`, `state`) is there on the next round.
|
|
25
|
+
|
|
26
|
+
- `delayMs` is 250 ms to 15 min a round. Every poll has a deadline, set on the first round and
|
|
27
|
+
shared by all later rounds and phases; a round can shorten it, never extend it. Once it has
|
|
28
|
+
passed, `onDeadline()` is thrown and the job fails.
|
|
29
|
+
- Each round runs the handler again from the top. The work before `pollAgain` must be
|
|
30
|
+
idempotent, or branch on `message.poll.state`.
|
|
31
|
+
- `state` is JSON of at most 16 KiB; more is a `RangeError`.
|
|
32
|
+
- `onDeadline()`'s error decides what happens next: a transient one fails the attempt and the
|
|
33
|
+
retry starts the flow afresh (the poll is cleared); a permanent one keeps the job as failed. A
|
|
34
|
+
`PollAgain` thrown directly past the deadline fails as `POLL_TIMED_OUT` (`QUEUE_ERRORS`),
|
|
35
|
+
which is transient.
|
|
36
|
+
- `RestartPoll` fails the attempt as transient and clears the poll, so the retry starts afresh.
|
|
37
|
+
- A poll round is logged at debug and its `queue.process` span ends with outcome `poll`, not as
|
|
38
|
+
an error.
|
|
39
|
+
|
|
40
|
+
## Delayed and de-duplicated publishes
|
|
41
|
+
|
|
42
|
+
`publish(key, payload, { delayMs, deduplication: { id } })` delays a message, or coalesces the
|
|
43
|
+
publishes that share an id. The job holds the id until it completes or fails for good:
|
|
44
|
+
|
|
45
|
+
- waiting for its first run (delayed or not), a later publish is dropped: the job has not
|
|
46
|
+
started, so it will see the newer state;
|
|
47
|
+
- running, the newest later publish is kept and queued when it finishes or fails;
|
|
48
|
+
- delayed again, by a `PollAgain` round or a retry's backoff, a later publish is **dropped**,
|
|
49
|
+
though the job has already read the state.
|
|
50
|
+
|
|
51
|
+
So use `deduplication` only for handlers that never poll and recompute from scratch on every
|
|
52
|
+
attempt. The consumer warns, once a poll, when a de-duplicated job polls.
|
|
53
|
+
|
|
54
|
+
Such publishes are direct, never through the outbox: an outbox row carries no `delayMs` and no
|
|
55
|
+
`deduplication`. If the process dies between the commit and the publish, the message is lost.
|
|
56
|
+
A caller that needs it to survive publishes through the outbox, without them, and coalesces in
|
|
57
|
+
the handler instead.
|
|
58
|
+
|
|
59
|
+
Failed jobs are kept 1,000 per queue for 14 days.
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AppError } from '@haatlabs-core/errors';
|
|
2
|
+
/** The code this package throws beyond the core ones: a project spreads it into defineErrors. */
|
|
3
|
+
export declare const QUEUE_ERRORS: {
|
|
4
|
+
readonly POLL_TIMED_OUT: {
|
|
5
|
+
readonly httpStatus: 503;
|
|
6
|
+
readonly transient: true;
|
|
7
|
+
};
|
|
8
|
+
};
|
|
9
|
+
export declare const QueueErrorCode: {
|
|
10
|
+
readonly POLL_TIMED_OUT: "POLL_TIMED_OUT";
|
|
11
|
+
};
|
|
12
|
+
export declare const createQueueError: (code: "POLL_TIMED_OUT", message: string, options?: import("@haatlabs-core/errors").AppErrorOptions) => AppError<"POLL_TIMED_OUT">;
|
|
13
|
+
/** The error this package throws: a project that spreads in QUEUE_ERRORS takes it as its own. */
|
|
14
|
+
export type QueueError = AppError<keyof typeof QUEUE_ERRORS>;
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var codes_exports = {};
|
|
19
|
+
__export(codes_exports, {
|
|
20
|
+
QUEUE_ERRORS: () => QUEUE_ERRORS,
|
|
21
|
+
QueueErrorCode: () => QueueErrorCode,
|
|
22
|
+
createQueueError: () => createQueueError
|
|
23
|
+
});
|
|
24
|
+
module.exports = __toCommonJS(codes_exports);
|
|
25
|
+
var import_errors = require("@haatlabs-core/errors");
|
|
26
|
+
const QUEUE_ERRORS = {
|
|
27
|
+
// A poll that ran past its deadline: a timeout, so the job's retry starts the flow afresh.
|
|
28
|
+
POLL_TIMED_OUT: { httpStatus: 503, transient: true }
|
|
29
|
+
};
|
|
30
|
+
const queue = (0, import_errors.domainErrors)(QUEUE_ERRORS);
|
|
31
|
+
const QueueErrorCode = queue.codes;
|
|
32
|
+
const createQueueError = queue.create;
|
|
33
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
34
|
+
0 && (module.exports = {
|
|
35
|
+
QUEUE_ERRORS,
|
|
36
|
+
QueueErrorCode,
|
|
37
|
+
createQueueError
|
|
38
|
+
});
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import type { PollState } from './poll.js';
|
|
2
|
+
import type { QueueConnection } from './topology.js';
|
|
3
|
+
export interface QueueLogger {
|
|
4
|
+
info(obj: object, msg: string): void;
|
|
5
|
+
warn(obj: object, msg: string): void;
|
|
6
|
+
error(obj: object, msg: string): void;
|
|
7
|
+
/** PollAgain is logged here when the logger has it. */
|
|
8
|
+
debug?(obj: object, msg: string): void;
|
|
9
|
+
}
|
|
10
|
+
export interface ConsumedMessage {
|
|
11
|
+
routingKey: string;
|
|
12
|
+
payload: unknown;
|
|
13
|
+
attempt: number;
|
|
14
|
+
messageId: string | undefined;
|
|
15
|
+
/** The traceparent the message arrived with, if it had a usable one. */
|
|
16
|
+
traceContext?: string | null;
|
|
17
|
+
/** What the last PollAgain left; null when none. Always set by the consumer. */
|
|
18
|
+
poll?: PollState | null;
|
|
19
|
+
}
|
|
20
|
+
export interface ConsumerOptions {
|
|
21
|
+
queue: string;
|
|
22
|
+
/** How many jobs of this queue one worker handles at a time. */
|
|
23
|
+
concurrency: number;
|
|
24
|
+
maxAttempts: number;
|
|
25
|
+
handler(message: ConsumedMessage): Promise<void>;
|
|
26
|
+
logger: QueueLogger;
|
|
27
|
+
/** How long a failed job waits before each further attempt; the last is used from then on. */
|
|
28
|
+
retryDelaysMs?: readonly number[];
|
|
29
|
+
}
|
|
30
|
+
/** A failure worth another attempt, and how long to wait before it. */
|
|
31
|
+
export declare class RetryLater extends Error {
|
|
32
|
+
readonly delayMs: number;
|
|
33
|
+
constructor(message: string, delayMs: number);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* How long a failed attempt waits. Attempt 1 waits the first delay, attempt 2 the second,
|
|
37
|
+
* and attempts beyond the last reuse it. A failure that says how long to wait (a
|
|
38
|
+
* provider's "slow down", our own limit) is never brought back sooner than it asked.
|
|
39
|
+
*/
|
|
40
|
+
export declare function retryDelayMs(error: unknown, attempt: number, delays: readonly number[]): number;
|
|
41
|
+
/** What of a job the handling of it reads. */
|
|
42
|
+
export interface IncomingJob {
|
|
43
|
+
id?: string;
|
|
44
|
+
name: string;
|
|
45
|
+
data: unknown;
|
|
46
|
+
attemptsMade: number;
|
|
47
|
+
/** BullMQ's; a job without them cannot be put back (a test's plain object). */
|
|
48
|
+
updateData?(data: unknown): Promise<void>;
|
|
49
|
+
moveToDelayed?(timestamp: number, token?: string): Promise<void>;
|
|
50
|
+
/** BullMQ's: what it was published with. */
|
|
51
|
+
opts?: {
|
|
52
|
+
deduplication?: {
|
|
53
|
+
id: string;
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Handles one job. Returning means it is done. A failure that may pass throws
|
|
59
|
+
* `RetryLater`; one that will not, or that has been tried often enough, throws
|
|
60
|
+
* `UnrecoverableError`, and the job is kept as failed. Only a safe description of the
|
|
61
|
+
* failure leaves here: what is thrown is stored with the job.
|
|
62
|
+
*/
|
|
63
|
+
export declare function handleJob(job: IncomingJob, options: Omit<ConsumerOptions, 'concurrency'>, token?: string): Promise<void>;
|
|
64
|
+
/** How an attempt at a job ended, as its finished line says. */
|
|
65
|
+
export type JobOutcome = 'ok' | 'poll' | 'retry' | 'failed';
|
|
66
|
+
export interface Consumer {
|
|
67
|
+
/** Takes no more work, and resolves once the work in hand is finished. */
|
|
68
|
+
stop(): Promise<void>;
|
|
69
|
+
/** False once it has stopped taking work, whether asked to or not. */
|
|
70
|
+
running(): boolean;
|
|
71
|
+
}
|
|
72
|
+
export declare function startConsumer(connection: QueueConnection, options: ConsumerOptions): Promise<Consumer>;
|
|
73
|
+
/**
|
|
74
|
+
* Consumes a kind of work from both its lanes: the ordinary one and the one for work that
|
|
75
|
+
* goes first, each with the same handler and its own share of the worker (`concurrency`
|
|
76
|
+
* each). Work that goes first is therefore never behind ordinary work, and ordinary work
|
|
77
|
+
* is never held up until the other lane is empty.
|
|
78
|
+
*/
|
|
79
|
+
export declare function startConsumers(connection: QueueConnection, options: ConsumerOptions): Promise<Consumer>;
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __export = (target, all) => {
|
|
6
|
+
for (var name in all)
|
|
7
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
8
|
+
};
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
18
|
+
var consumer_exports = {};
|
|
19
|
+
__export(consumer_exports, {
|
|
20
|
+
RetryLater: () => RetryLater,
|
|
21
|
+
handleJob: () => handleJob,
|
|
22
|
+
retryDelayMs: () => retryDelayMs,
|
|
23
|
+
startConsumer: () => startConsumer,
|
|
24
|
+
startConsumers: () => startConsumers
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(consumer_exports);
|
|
27
|
+
var import_errors = require("@haatlabs-core/errors");
|
|
28
|
+
var import_observability = require("@haatlabs-core/observability");
|
|
29
|
+
var import_api = require("@opentelemetry/api");
|
|
30
|
+
var import_bullmq = require("bullmq");
|
|
31
|
+
var import_codes = require("./codes.js");
|
|
32
|
+
var import_poll = require("./poll.js");
|
|
33
|
+
var import_topology = require("./topology.js");
|
|
34
|
+
const MAX_ERROR_LENGTH = 500;
|
|
35
|
+
const describeError = import_errors.safeErrorMessage;
|
|
36
|
+
class RetryLater extends Error {
|
|
37
|
+
delayMs;
|
|
38
|
+
constructor(message, delayMs) {
|
|
39
|
+
super(message);
|
|
40
|
+
this.delayMs = delayMs;
|
|
41
|
+
this.name = "RetryLater";
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function retryDelayMs(error, attempt, delays) {
|
|
45
|
+
const byAttempt = delays[Math.min(attempt, delays.length) - 1] ?? 0;
|
|
46
|
+
const asked = error instanceof import_errors.AppError ? error.retryAfterMs ?? 0 : 0;
|
|
47
|
+
return Math.max(byAttempt, asked);
|
|
48
|
+
}
|
|
49
|
+
const isJobData = (data) => typeof data === "object" && data !== null && "payload" in data;
|
|
50
|
+
async function handleJob(job, options, token) {
|
|
51
|
+
const attempt = job.attemptsMade + 1;
|
|
52
|
+
const routingKey = job.name;
|
|
53
|
+
const context = { queue: options.queue, routingKey, attempt, messageId: job.id };
|
|
54
|
+
if (!isJobData(job.data)) {
|
|
55
|
+
options.logger.error(context, "Discarding a job that is not one of ours");
|
|
56
|
+
throw new import_bullmq.UnrecoverableError("unparseable");
|
|
57
|
+
}
|
|
58
|
+
const startedAt = Date.now();
|
|
59
|
+
const lines = { traceId: void 0 };
|
|
60
|
+
let outcome = "failed";
|
|
61
|
+
try {
|
|
62
|
+
await processJob(job, job.data, options, context, lines, token);
|
|
63
|
+
outcome = "ok";
|
|
64
|
+
} catch (error) {
|
|
65
|
+
outcome = error instanceof import_bullmq.DelayedError ? "poll" : error instanceof RetryLater ? "retry" : "failed";
|
|
66
|
+
throw error;
|
|
67
|
+
} finally {
|
|
68
|
+
options.logger.info({
|
|
69
|
+
...context,
|
|
70
|
+
...lines.traceId ? { trace_id: lines.traceId } : {},
|
|
71
|
+
outcome,
|
|
72
|
+
durationMs: Date.now() - startedAt
|
|
73
|
+
}, "Job finished");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
async function processJob(job, data, options, context, lines, token) {
|
|
77
|
+
const { attempt, routingKey } = context;
|
|
78
|
+
const { payload } = data;
|
|
79
|
+
const traceContext = typeof data.traceContext === "string" ? data.traceContext : null;
|
|
80
|
+
const poll = (0, import_poll.pollStateOf)(data);
|
|
81
|
+
const clearPoll = async () => {
|
|
82
|
+
if (!poll || !job.updateData)
|
|
83
|
+
return;
|
|
84
|
+
const rest = { ...data };
|
|
85
|
+
delete rest.poll;
|
|
86
|
+
await job.updateData(rest).catch((error) => {
|
|
87
|
+
options.logger.warn({ ...context, err: describeError(error) }, "Could not clear the poll; the next attempt may still see it");
|
|
88
|
+
});
|
|
89
|
+
};
|
|
90
|
+
let failure;
|
|
91
|
+
try {
|
|
92
|
+
const asked = await (0, import_observability.runWithTraceContext)(traceContext, "queue.process", { routing_key: routingKey, attempt, ...job.id !== void 0 ? { "job.id": job.id } : {} }, async () => {
|
|
93
|
+
lines.traceId = import_api.trace.getActiveSpan()?.spanContext().traceId;
|
|
94
|
+
options.logger.info(context, "Job started");
|
|
95
|
+
try {
|
|
96
|
+
await options.handler({
|
|
97
|
+
routingKey,
|
|
98
|
+
payload,
|
|
99
|
+
attempt,
|
|
100
|
+
messageId: job.id,
|
|
101
|
+
traceContext,
|
|
102
|
+
poll
|
|
103
|
+
});
|
|
104
|
+
return null;
|
|
105
|
+
} catch (error) {
|
|
106
|
+
if (!(error instanceof import_poll.PollAgain))
|
|
107
|
+
throw error;
|
|
108
|
+
import_api.trace.getActiveSpan()?.setAttributes({ outcome: "poll", poll_round: (poll?.round ?? 0) + 1 });
|
|
109
|
+
return error;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
if (!asked)
|
|
113
|
+
return;
|
|
114
|
+
failure = asked;
|
|
115
|
+
} catch (error) {
|
|
116
|
+
failure = error;
|
|
117
|
+
}
|
|
118
|
+
if (failure instanceof import_poll.PollAgain) {
|
|
119
|
+
const deadlineAt = poll ? Math.min(poll.deadlineAt, failure.deadlineAt) : failure.deadlineAt;
|
|
120
|
+
if (Date.now() >= deadlineAt) {
|
|
121
|
+
failure = (0, import_codes.createQueueError)(import_codes.QueueErrorCode.POLL_TIMED_OUT, "The poll took too long");
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
if (failure instanceof import_poll.PollAgain) {
|
|
125
|
+
const next = {
|
|
126
|
+
round: (poll?.round ?? 0) + 1,
|
|
127
|
+
startedAt: poll?.startedAt ?? Date.now(),
|
|
128
|
+
deadlineAt: poll ? Math.min(poll.deadlineAt, failure.deadlineAt) : failure.deadlineAt,
|
|
129
|
+
state: failure.state ?? null
|
|
130
|
+
};
|
|
131
|
+
const deduplicationId = job.opts?.deduplication?.id;
|
|
132
|
+
if (deduplicationId !== void 0 && next.round === 1) {
|
|
133
|
+
options.logger.warn({ ...context, deduplicationId }, "A de-duplicated job is polling: publishes with its id are dropped until it finishes");
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
if (!job.updateData || !job.moveToDelayed)
|
|
137
|
+
throw new Error("This job cannot be put back");
|
|
138
|
+
await job.updateData({ ...data, poll: next });
|
|
139
|
+
await job.moveToDelayed(Date.now() + failure.delayMs, token);
|
|
140
|
+
options.logger.debug?.({ ...context, round: next.round, delayMs: failure.delayMs }, "Waiting; the slot is handed back");
|
|
141
|
+
throw new import_bullmq.DelayedError();
|
|
142
|
+
} catch (error) {
|
|
143
|
+
if (error instanceof import_bullmq.DelayedError)
|
|
144
|
+
throw error;
|
|
145
|
+
failure = error;
|
|
146
|
+
}
|
|
147
|
+
} else if (failure instanceof import_poll.RestartPoll || poll && Date.now() >= poll.deadlineAt) {
|
|
148
|
+
await clearPoll();
|
|
149
|
+
}
|
|
150
|
+
const message = describeError(failure);
|
|
151
|
+
const kept = message.slice(0, MAX_ERROR_LENGTH);
|
|
152
|
+
if ((failure instanceof import_poll.RestartPoll || (0, import_errors.isTransientError)(failure)) && attempt < options.maxAttempts) {
|
|
153
|
+
options.logger.warn({ ...context, err: message }, "Handler failed; scheduling retry");
|
|
154
|
+
throw new RetryLater(kept, retryDelayMs(failure, attempt, options.retryDelaysMs ?? import_topology.DEFAULT_RETRY_DELAYS_MS));
|
|
155
|
+
}
|
|
156
|
+
options.logger.error({ ...context, err: message }, "Handler failed permanently; keeping as failed");
|
|
157
|
+
throw new import_bullmq.UnrecoverableError(kept);
|
|
158
|
+
}
|
|
159
|
+
async function startConsumer(connection, options) {
|
|
160
|
+
if (!Number.isInteger(options.concurrency) || options.concurrency < 1)
|
|
161
|
+
throw new Error("concurrency must be a positive integer");
|
|
162
|
+
const worker = new import_bullmq.Worker(options.queue, (job, token) => handleJob(job, options, token), {
|
|
163
|
+
connection: connection.redis,
|
|
164
|
+
prefix: connection.prefix,
|
|
165
|
+
concurrency: options.concurrency,
|
|
166
|
+
settings: {
|
|
167
|
+
backoffStrategy: (_attemptsMade, _type, error) => error instanceof RetryLater ? error.delayMs : 0
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
worker.on("error", (error) => {
|
|
171
|
+
options.logger.error({ queue: options.queue, err: describeError(error) }, "Queue worker error");
|
|
172
|
+
});
|
|
173
|
+
await worker.waitUntilReady();
|
|
174
|
+
return {
|
|
175
|
+
stop: async () => {
|
|
176
|
+
await worker.close();
|
|
177
|
+
},
|
|
178
|
+
running: () => worker.isRunning()
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
async function startConsumers(connection, options) {
|
|
182
|
+
const lanes = [
|
|
183
|
+
await startConsumer(connection, options),
|
|
184
|
+
await startConsumer(connection, { ...options, queue: (0, import_topology.priorityQueueName)(options.queue) })
|
|
185
|
+
];
|
|
186
|
+
return {
|
|
187
|
+
stop: async () => {
|
|
188
|
+
await Promise.all(lanes.map((lane) => lane.stop()));
|
|
189
|
+
},
|
|
190
|
+
running: () => lanes.every((lane) => lane.running())
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
194
|
+
0 && (module.exports = {
|
|
195
|
+
RetryLater,
|
|
196
|
+
handleJob,
|
|
197
|
+
retryDelayMs,
|
|
198
|
+
startConsumer,
|
|
199
|
+
startConsumers
|
|
200
|
+
});
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
5
|
+
var __copyProps = (to, from, except, desc) => {
|
|
6
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
7
|
+
for (let key of __getOwnPropNames(from))
|
|
8
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
9
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
10
|
+
}
|
|
11
|
+
return to;
|
|
12
|
+
};
|
|
13
|
+
var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
|
|
14
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
15
|
+
var index_exports = {};
|
|
16
|
+
module.exports = __toCommonJS(index_exports);
|
|
17
|
+
__reExport(index_exports, require("./topology.js"), module.exports);
|
|
18
|
+
__reExport(index_exports, require("./publisher.js"), module.exports);
|
|
19
|
+
__reExport(index_exports, require("./consumer.js"), module.exports);
|
|
20
|
+
__reExport(index_exports, require("./outbox-relay.js"), module.exports);
|
|
21
|
+
__reExport(index_exports, require("./poll.js"), module.exports);
|
|
22
|
+
__reExport(index_exports, require("./codes.js"), module.exports);
|
|
23
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
24
|
+
0 && (module.exports = {
|
|
25
|
+
...require("./topology.js"),
|
|
26
|
+
...require("./publisher.js"),
|
|
27
|
+
...require("./consumer.js"),
|
|
28
|
+
...require("./outbox-relay.js"),
|
|
29
|
+
...require("./poll.js"),
|
|
30
|
+
...require("./codes.js")
|
|
31
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { QueueLogger } from './consumer.js';
|
|
2
|
+
import type { Publisher } from './publisher.js';
|
|
3
|
+
/** Structurally identical to a project's `OutboxRepository.processBatch`. */
|
|
4
|
+
export interface OutboxStore {
|
|
5
|
+
processBatch(limit: number, publish: (message: {
|
|
6
|
+
id: string;
|
|
7
|
+
routingKey: string;
|
|
8
|
+
payload: unknown;
|
|
9
|
+
traceContext?: string | null;
|
|
10
|
+
priority?: boolean;
|
|
11
|
+
}) => Promise<void>): Promise<number>;
|
|
12
|
+
}
|
|
13
|
+
export declare class OutboxRelay {
|
|
14
|
+
private readonly store;
|
|
15
|
+
private readonly publisher;
|
|
16
|
+
private readonly logger;
|
|
17
|
+
private running;
|
|
18
|
+
private loop;
|
|
19
|
+
private readonly batchSize;
|
|
20
|
+
private readonly idleDelayMs;
|
|
21
|
+
constructor(store: OutboxStore, publisher: Publisher, logger: QueueLogger, options?: {
|
|
22
|
+
batchSize?: number;
|
|
23
|
+
idleDelayMs?: number;
|
|
24
|
+
});
|
|
25
|
+
/**
|
|
26
|
+
* Publishes one batch. An unroutable message is poison, not an outage: it is logged at error
|
|
27
|
+
* level and treated as handled, so one bad row cannot block the messages behind it. Any other
|
|
28
|
+
* publish error propagates to the store, stops the batch, and is logged here with tick
|
|
29
|
+
* reporting zero so the loop keeps running.
|
|
30
|
+
*/
|
|
31
|
+
tick(): Promise<number>;
|
|
32
|
+
start(): void;
|
|
33
|
+
stop(): Promise<void>;
|
|
34
|
+
}
|