@skein-js/bullmq 0.0.0-stage → 0.23.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 +202 -0
- package/README.md +48 -2
- package/dist/index.d.ts +106 -0
- package/dist/index.js +253 -0
- package/package.json +46 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,49 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @skein-js/bullmq
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Optional BullMQ access to Skein's native client. External command/outcome queues share the runtime's
|
|
4
|
+
authorization, atomic admission, retained results and outbox. Skein's internal execution and delivery
|
|
5
|
+
queues remain in charge.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { createBullMqTransport } from "@skein-js/bullmq";
|
|
9
|
+
|
|
10
|
+
const access = createBullMqTransport({
|
|
11
|
+
commandQueue: "commands",
|
|
12
|
+
outcomeQueue, // borrowed BullMQ Queue
|
|
13
|
+
connection,
|
|
14
|
+
authenticate: async (job) => ({ authContext: await verifyCaller(job) }),
|
|
15
|
+
});
|
|
16
|
+
// Compose access.wrapDispatcher(existingDispatcher) into ProtocolDeps.webhookDispatcher.
|
|
17
|
+
// Bind access.outcomeTarget on runtime.createNativeClient({sourceId, allowedAssistants, ...}).
|
|
18
|
+
await access.start(nativeClient);
|
|
19
|
+
// ... shutdown:
|
|
20
|
+
await access.stop(); // closes owned workers, preserves borrowed connections/queues
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
BullMQ 5/6 and ioredis 5/6 are supported. Producers send version-1 `BullMqCommand` values and configure
|
|
24
|
+
bounded BullMQ attempts/backoff. Job return values acknowledge admission; durable outcomes carry
|
|
25
|
+
`eventId` equal to the outbox delivery ID. Persist receiver deduplication independently of broker job
|
|
26
|
+
retention. `result.get` and `state.get` support bounded digest-checked chunks; native results stay whole.
|
|
27
|
+
|
|
28
|
+
`projectResult` projects outcomes and `result.get`, not full `run.get` metadata or `state.get` snapshots.
|
|
29
|
+
Reject unwanted raw queries in the host's `authenticate`/`route` callbacks. Redis readers can inspect
|
|
30
|
+
job inputs and return values outside native authorization; configure credentials, ACLs, TLS and job
|
|
31
|
+
retention. Skein deletion does not purge external broker copies.
|
|
32
|
+
|
|
33
|
+
The [runnable approval example](https://github.com/skein-js/skein-js/tree/main/examples/native-transports)
|
|
34
|
+
shows explicit lifecycle, a host-bound principal, projected results, chunk verification and durable
|
|
35
|
+
receiver deduplication. See [security and operations](https://github.com/skein-js/skein-js/blob/main/docs/native-access-security.md).
|
|
36
|
+
|
|
37
|
+
Read [native access and BullMQ](https://github.com/skein-js/skein-js/blob/main/docs/native-access.md)
|
|
38
|
+
for setup, message formats, ownership, errors and reconciliation. Run the external packed consumers
|
|
39
|
+
with `pnpm exec nx run test-support:test-native-consumer`.
|
|
40
|
+
|
|
41
|
+
The package supplies its runtime ioredis dependency, including when BullMQ 6 resolves ioredis through
|
|
42
|
+
its optional peer. The adapter accepts connection options or a borrowed supported ioredis `Redis` or
|
|
43
|
+
`Cluster` client.
|
|
44
|
+
For mixed BullMQ 5/ioredis 6 installs, give upstream BullMQ queues and workers connection options so
|
|
45
|
+
they use BullMQ's own client; the maintained example demonstrates this without application casts.
|
|
46
|
+
The adapter keeps borrowed clients and the outcome queue usable after `stop()`.
|
|
47
|
+
Borrowed outcome queues can come from a different supported BullMQ major than the adapter's worker.
|
|
48
|
+
Use `BullMqTransportOptions<typeof outcomeQueue>` when explicitly annotating options for that queue;
|
|
49
|
+
existing annotations retain the full upstream Queue type by default.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { NativeStartInput, NativeResumeInput, WebhookDispatcher, NativeClient, NativeCallOptions } from '@skein-js/agent-protocol';
|
|
2
|
+
import { Run, RunResult } from '@skein-js/core';
|
|
3
|
+
import { Queue, ConnectionOptions, Job } from 'bullmq';
|
|
4
|
+
import { Redis, Cluster } from 'ioredis';
|
|
5
|
+
|
|
6
|
+
/** The BullMQ adapter's wire format. Authority, destinations and deadlines belong to the host. */
|
|
7
|
+
type BullMqCommand = {
|
|
8
|
+
version: 1;
|
|
9
|
+
commandId: string;
|
|
10
|
+
correlationId?: string;
|
|
11
|
+
} & ({
|
|
12
|
+
operation: "start";
|
|
13
|
+
input: NativeStartInput;
|
|
14
|
+
} | {
|
|
15
|
+
operation: "resume";
|
|
16
|
+
input: NativeResumeInput;
|
|
17
|
+
} | {
|
|
18
|
+
operation: "cancel";
|
|
19
|
+
runId: string;
|
|
20
|
+
action?: "interrupt" | "rollback";
|
|
21
|
+
wait?: boolean;
|
|
22
|
+
} | {
|
|
23
|
+
operation: "run.get";
|
|
24
|
+
runId: string;
|
|
25
|
+
offset?: number;
|
|
26
|
+
digest?: string;
|
|
27
|
+
} | {
|
|
28
|
+
operation: "state.get";
|
|
29
|
+
threadId: string;
|
|
30
|
+
offset?: number;
|
|
31
|
+
digest?: string;
|
|
32
|
+
} | {
|
|
33
|
+
operation: "result.get";
|
|
34
|
+
runId: string;
|
|
35
|
+
offset?: number;
|
|
36
|
+
digest?: string;
|
|
37
|
+
} | {
|
|
38
|
+
operation: "receipt.get";
|
|
39
|
+
idempotencyKey: string;
|
|
40
|
+
});
|
|
41
|
+
/** Durable receiver deduplication uses eventId, including after BullMQ jobs have been removed. */
|
|
42
|
+
interface BullMqOutcome {
|
|
43
|
+
version: 1;
|
|
44
|
+
operation: "run.settled";
|
|
45
|
+
eventId: string;
|
|
46
|
+
commandId: string;
|
|
47
|
+
correlationId?: string;
|
|
48
|
+
runId: string;
|
|
49
|
+
threadId: string;
|
|
50
|
+
status: Run["status"];
|
|
51
|
+
resultRef: {
|
|
52
|
+
runId: string;
|
|
53
|
+
};
|
|
54
|
+
truncated: boolean;
|
|
55
|
+
outcome?: unknown;
|
|
56
|
+
}
|
|
57
|
+
/** Byte offsets address a base64 encoded slice of the serialized whole value. */
|
|
58
|
+
interface BullMqChunk {
|
|
59
|
+
encoding: "base64";
|
|
60
|
+
digest: string;
|
|
61
|
+
offset: number;
|
|
62
|
+
nextOffset: number | null;
|
|
63
|
+
totalBytes: number;
|
|
64
|
+
content: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** The adapter publishes outcomes; the host owns every other queue operation and its lifetime. */
|
|
68
|
+
interface OutcomeQueueTarget {
|
|
69
|
+
readonly name: string;
|
|
70
|
+
readonly opts: {
|
|
71
|
+
readonly prefix?: string;
|
|
72
|
+
};
|
|
73
|
+
add(name: string, outcome: unknown, options: {
|
|
74
|
+
jobId: string;
|
|
75
|
+
}): Promise<unknown>;
|
|
76
|
+
}
|
|
77
|
+
interface BullMqTransportOptions<OutcomeQueue extends OutcomeQueueTarget = Queue> {
|
|
78
|
+
commandQueue: string;
|
|
79
|
+
/** Borrowed queue. The adapter never closes it or its connection. */
|
|
80
|
+
outcomeQueue: OutcomeQueue;
|
|
81
|
+
/** A borrowed supported ioredis connection or BullMQ connection options. */
|
|
82
|
+
connection: ConnectionOptions | Redis | Cluster;
|
|
83
|
+
prefix?: string;
|
|
84
|
+
concurrency?: number;
|
|
85
|
+
maxMessageBytes?: number;
|
|
86
|
+
/** Verify broker credentials/claims here. No authority is accepted from the message itself. */
|
|
87
|
+
authenticate(job: Job): Promise<Omit<NativeCallOptions, "idempotencyKey" | "idempotencyInput" | "correlationId">>;
|
|
88
|
+
/** Host-controlled mapping; the original validated command remains its idempotency identity. */
|
|
89
|
+
route?(command: BullMqCommand): BullMqCommand | Promise<BullMqCommand>;
|
|
90
|
+
projectResult?(result: RunResult, runId: string): unknown | Promise<unknown>;
|
|
91
|
+
logger?: {
|
|
92
|
+
warn(message: string, error?: unknown): void;
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
interface BullMqTransport {
|
|
96
|
+
/** Bind this stable address to the native source's outcomeTarget. */
|
|
97
|
+
readonly outcomeTarget: string;
|
|
98
|
+
wrapDispatcher(inner: WebhookDispatcher): WebhookDispatcher;
|
|
99
|
+
start(client: NativeClient): Promise<void>;
|
|
100
|
+
stop(): Promise<void>;
|
|
101
|
+
}
|
|
102
|
+
/** Optional access transport. Skein's own execution and delivery queues remain in charge. */
|
|
103
|
+
declare function createBullMqTransport<OutcomeQueue extends OutcomeQueueTarget>(options: BullMqTransportOptions<OutcomeQueue>): BullMqTransport;
|
|
104
|
+
declare function createBullMqTransport(options: BullMqTransportOptions): BullMqTransport;
|
|
105
|
+
|
|
106
|
+
export { type BullMqChunk, type BullMqCommand, type BullMqOutcome, type BullMqTransport, type BullMqTransportOptions, createBullMqTransport };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// src/bullmq-transport.ts
|
|
2
|
+
import { createHash } from "crypto";
|
|
3
|
+
import {
|
|
4
|
+
DEFAULT_MAX_PAYLOAD_BYTES
|
|
5
|
+
} from "@skein-js/agent-protocol";
|
|
6
|
+
import {
|
|
7
|
+
isSkeinHttpError,
|
|
8
|
+
serializeWireJson,
|
|
9
|
+
SkeinHttpError
|
|
10
|
+
} from "@skein-js/core";
|
|
11
|
+
import { Worker, UnrecoverableError } from "bullmq";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
var key = z.string().min(1).max(255).regex(/^[\x20-\x7e]+$/);
|
|
14
|
+
var chunkFields = {
|
|
15
|
+
offset: z.number().int().nonnegative().optional(),
|
|
16
|
+
digest: z.string().regex(/^[a-f0-9]{64}$/).optional()
|
|
17
|
+
};
|
|
18
|
+
var base = {
|
|
19
|
+
version: z.literal(1),
|
|
20
|
+
commandId: key,
|
|
21
|
+
correlationId: z.string().max(255).optional()
|
|
22
|
+
};
|
|
23
|
+
var commandSchema = z.discriminatedUnion("operation", [
|
|
24
|
+
z.object({ ...base, operation: z.literal("start"), input: z.record(z.unknown()) }).strict(),
|
|
25
|
+
z.object({ ...base, operation: z.literal("resume"), input: z.record(z.unknown()) }).strict(),
|
|
26
|
+
z.object({
|
|
27
|
+
...base,
|
|
28
|
+
operation: z.literal("cancel"),
|
|
29
|
+
runId: z.string().min(1),
|
|
30
|
+
action: z.enum(["interrupt", "rollback"]).optional(),
|
|
31
|
+
wait: z.boolean().optional()
|
|
32
|
+
}).strict(),
|
|
33
|
+
z.object({ ...base, operation: z.literal("run.get"), runId: z.string().min(1), ...chunkFields }).strict(),
|
|
34
|
+
z.object({
|
|
35
|
+
...base,
|
|
36
|
+
operation: z.literal("state.get"),
|
|
37
|
+
threadId: z.string().min(1),
|
|
38
|
+
...chunkFields
|
|
39
|
+
}).strict(),
|
|
40
|
+
z.object({
|
|
41
|
+
...base,
|
|
42
|
+
operation: z.literal("result.get"),
|
|
43
|
+
runId: z.string().min(1),
|
|
44
|
+
...chunkFields
|
|
45
|
+
}).strict(),
|
|
46
|
+
z.object({ ...base, operation: z.literal("receipt.get"), idempotencyKey: key }).strict()
|
|
47
|
+
]);
|
|
48
|
+
function parseCommand(input, cap) {
|
|
49
|
+
if (Buffer.byteLength(serializeWireJson(input)) > cap)
|
|
50
|
+
throw SkeinHttpError.unprocessable("Broker command exceeds the message limit.", {
|
|
51
|
+
code: "message_too_large"
|
|
52
|
+
});
|
|
53
|
+
const parsed = commandSchema.safeParse(input);
|
|
54
|
+
if (!parsed.success)
|
|
55
|
+
throw SkeinHttpError.badRequest("Invalid BullMQ command.", {
|
|
56
|
+
code: "invalid_bullmq_command",
|
|
57
|
+
details: parsed.error.issues
|
|
58
|
+
});
|
|
59
|
+
return parsed.data;
|
|
60
|
+
}
|
|
61
|
+
function chunk(value, request, cap) {
|
|
62
|
+
const bytes = Buffer.from(serializeWireJson(value));
|
|
63
|
+
const digest = createHash("sha256").update(bytes).digest("hex");
|
|
64
|
+
if (request.digest && request.digest !== digest)
|
|
65
|
+
throw SkeinHttpError.conflict("The requested value changed; restart retrieval.", {
|
|
66
|
+
code: "result_digest_mismatch"
|
|
67
|
+
});
|
|
68
|
+
const offset = request.offset ?? 0;
|
|
69
|
+
if (offset > 0 && !request.digest)
|
|
70
|
+
throw SkeinHttpError.badRequest("Continuation requires its digest.", {
|
|
71
|
+
code: "result_digest_required"
|
|
72
|
+
});
|
|
73
|
+
if (offset > bytes.length)
|
|
74
|
+
throw SkeinHttpError.badRequest("Chunk offset is outside the result.", {
|
|
75
|
+
code: "invalid_chunk_offset"
|
|
76
|
+
});
|
|
77
|
+
const end = Math.min(bytes.length, offset + Math.floor((cap - 512) * 3 / 4));
|
|
78
|
+
const result = {
|
|
79
|
+
encoding: "base64",
|
|
80
|
+
digest,
|
|
81
|
+
offset,
|
|
82
|
+
nextOffset: end < bytes.length ? end : null,
|
|
83
|
+
totalBytes: bytes.length,
|
|
84
|
+
content: bytes.subarray(offset, end).toString("base64")
|
|
85
|
+
};
|
|
86
|
+
if (Buffer.byteLength(serializeWireJson(result)) > cap)
|
|
87
|
+
throw new Error("BullMQ chunk framing exceeded its bound.");
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
var transientCodes = /* @__PURE__ */ new Set([
|
|
91
|
+
"native_state_changed",
|
|
92
|
+
"execution_lease_lost",
|
|
93
|
+
"thread_busy",
|
|
94
|
+
"thread_status_mismatch",
|
|
95
|
+
"idempotency_key_in_flight",
|
|
96
|
+
"run_result_pending"
|
|
97
|
+
]);
|
|
98
|
+
function classify(error) {
|
|
99
|
+
if (isSkeinHttpError(error) && !transientCodes.has(error.code ?? "") && (error.status < 500 || error.status === 501))
|
|
100
|
+
throw new UnrecoverableError(
|
|
101
|
+
JSON.stringify({
|
|
102
|
+
code: error.code ?? "command_rejected",
|
|
103
|
+
message: error.message,
|
|
104
|
+
status: error.status
|
|
105
|
+
})
|
|
106
|
+
);
|
|
107
|
+
throw error;
|
|
108
|
+
}
|
|
109
|
+
function createBullMqTransport(options) {
|
|
110
|
+
const cap = options.maxMessageBytes ?? DEFAULT_MAX_PAYLOAD_BYTES;
|
|
111
|
+
if (!Number.isSafeInteger(cap) || cap < 1024 || cap > DEFAULT_MAX_PAYLOAD_BYTES)
|
|
112
|
+
throw new Error("maxMessageBytes must be between 1024 and the existing payload limit.");
|
|
113
|
+
if (!options.commandQueue) throw new Error("commandQueue is required.");
|
|
114
|
+
const logger = options.logger ?? console;
|
|
115
|
+
const outcomeTarget = `skein-bullmq://outcomes/${encodeURIComponent(options.outcomeQueue.opts.prefix ?? "bull")}/${encodeURIComponent(options.outcomeQueue.name)}`;
|
|
116
|
+
let worker;
|
|
117
|
+
let starting;
|
|
118
|
+
let stopping;
|
|
119
|
+
let running;
|
|
120
|
+
const processCommand = async (client, job) => {
|
|
121
|
+
try {
|
|
122
|
+
const original = parseCommand(job.data, cap);
|
|
123
|
+
const { correlationId: _diagnostic, ...meaning } = JSON.parse(
|
|
124
|
+
serializeWireJson(original)
|
|
125
|
+
);
|
|
126
|
+
const authenticated = await options.authenticate(job);
|
|
127
|
+
const command = options.route ? parseCommand(await options.route(structuredClone(original)), cap) : original;
|
|
128
|
+
const call = {
|
|
129
|
+
...authenticated,
|
|
130
|
+
idempotencyKey: original.commandId,
|
|
131
|
+
idempotencyInput: meaning,
|
|
132
|
+
...original.correlationId ? { correlationId: original.correlationId } : {}
|
|
133
|
+
};
|
|
134
|
+
switch (command.operation) {
|
|
135
|
+
case "start":
|
|
136
|
+
return await client.start(command.input, call);
|
|
137
|
+
case "resume":
|
|
138
|
+
return await client.resume(command.input, call);
|
|
139
|
+
case "cancel":
|
|
140
|
+
return await client.cancel(command.runId, {
|
|
141
|
+
...call,
|
|
142
|
+
action: command.action,
|
|
143
|
+
wait: command.wait
|
|
144
|
+
});
|
|
145
|
+
case "run.get": {
|
|
146
|
+
const run = await client.getRun(command.runId, call);
|
|
147
|
+
return chunk(run, command, cap);
|
|
148
|
+
}
|
|
149
|
+
case "receipt.get":
|
|
150
|
+
return await client.getReceipt(command.idempotencyKey, call);
|
|
151
|
+
case "state.get":
|
|
152
|
+
return chunk(await client.getState(command.threadId, call), command, cap);
|
|
153
|
+
case "result.get": {
|
|
154
|
+
const result = await client.getResult(command.runId, call);
|
|
155
|
+
return chunk(
|
|
156
|
+
options.projectResult ? await options.projectResult(result, command.runId) : result,
|
|
157
|
+
command,
|
|
158
|
+
cap
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
} catch (error) {
|
|
163
|
+
classify(error);
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
return {
|
|
167
|
+
outcomeTarget,
|
|
168
|
+
wrapDispatcher: (inner) => async (url, payload, attempt) => {
|
|
169
|
+
if (url !== outcomeTarget) return inner(url, payload, attempt);
|
|
170
|
+
if (!attempt?.deliveryId)
|
|
171
|
+
throw new Error("BullMQ outcomes require an outbox delivery identity.");
|
|
172
|
+
const body = payload;
|
|
173
|
+
if (typeof body["run_id"] !== "string" || typeof body["thread_id"] !== "string" || typeof body["command_id"] !== "string")
|
|
174
|
+
throw new Error("Invalid native outcome.");
|
|
175
|
+
const event = {
|
|
176
|
+
version: 1,
|
|
177
|
+
operation: "run.settled",
|
|
178
|
+
eventId: attempt.deliveryId,
|
|
179
|
+
commandId: body["command_id"],
|
|
180
|
+
...typeof body["correlation_id"] === "string" ? { correlationId: body["correlation_id"] } : {},
|
|
181
|
+
runId: body["run_id"],
|
|
182
|
+
threadId: body["thread_id"],
|
|
183
|
+
status: body["status"],
|
|
184
|
+
resultRef: { runId: body["run_id"] },
|
|
185
|
+
truncated: body["payload_truncated"] === true,
|
|
186
|
+
outcome: options.projectResult ? body["payload_truncated"] === true || body["result_unavailable"] === true ? void 0 : await options.projectResult(
|
|
187
|
+
{
|
|
188
|
+
values: body["values"],
|
|
189
|
+
...body["interrupts"] ? { interrupts: body["interrupts"] } : {},
|
|
190
|
+
...body["reply"] !== void 0 ? { reply: body["reply"] } : {}
|
|
191
|
+
},
|
|
192
|
+
body["run_id"]
|
|
193
|
+
) : payload
|
|
194
|
+
};
|
|
195
|
+
if (Buffer.byteLength(serializeWireJson(event)) > cap) {
|
|
196
|
+
delete event.outcome;
|
|
197
|
+
event.truncated = true;
|
|
198
|
+
}
|
|
199
|
+
if (Buffer.byteLength(serializeWireJson(event)) > cap)
|
|
200
|
+
throw new Error("BullMQ outcome identity exceeds the message bound.");
|
|
201
|
+
await options.outcomeQueue.add("skein.run.settled.v1", event, { jobId: event.eventId });
|
|
202
|
+
},
|
|
203
|
+
start: async (client) => {
|
|
204
|
+
if (stopping) await stopping;
|
|
205
|
+
if (starting) return starting;
|
|
206
|
+
if (worker) return;
|
|
207
|
+
starting = (async () => {
|
|
208
|
+
const owned = new Worker(options.commandQueue, (job) => processCommand(client, job), {
|
|
209
|
+
// BullMQ 5's type names its own ioredis 5 connector class. Keep borrowed client support
|
|
210
|
+
// across the tested ioredis majors without requiring casts at the application's boundary.
|
|
211
|
+
connection: options.connection,
|
|
212
|
+
...options.prefix ? { prefix: options.prefix } : {},
|
|
213
|
+
concurrency: options.concurrency ?? 1,
|
|
214
|
+
autorun: false
|
|
215
|
+
});
|
|
216
|
+
worker = owned;
|
|
217
|
+
owned.on("error", (error) => logger.warn("BullMQ command worker error", error));
|
|
218
|
+
try {
|
|
219
|
+
await owned.waitUntilReady();
|
|
220
|
+
running = owned.run().catch((error) => logger.warn("BullMQ command worker stopped", error));
|
|
221
|
+
} catch (error) {
|
|
222
|
+
worker = void 0;
|
|
223
|
+
await owned.close();
|
|
224
|
+
throw error;
|
|
225
|
+
}
|
|
226
|
+
})();
|
|
227
|
+
try {
|
|
228
|
+
await starting;
|
|
229
|
+
} finally {
|
|
230
|
+
starting = void 0;
|
|
231
|
+
}
|
|
232
|
+
},
|
|
233
|
+
stop: async () => {
|
|
234
|
+
if (stopping) return stopping;
|
|
235
|
+
stopping = (async () => {
|
|
236
|
+
await starting;
|
|
237
|
+
const owned = worker;
|
|
238
|
+
worker = void 0;
|
|
239
|
+
await owned?.close();
|
|
240
|
+
await running;
|
|
241
|
+
running = void 0;
|
|
242
|
+
})();
|
|
243
|
+
try {
|
|
244
|
+
await stopping;
|
|
245
|
+
} finally {
|
|
246
|
+
stopping = void 0;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
export {
|
|
252
|
+
createBullMqTransport
|
|
253
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@skein-js/bullmq",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.23.0",
|
|
4
|
+
"description": "Optional BullMQ command and outcome transport for Skein agents.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://github.com/skein-js/skein-js/tree/main/packages/bullmq#readme",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/skein-js/skein-js.git",
|
|
10
|
+
"directory": "packages/bullmq"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/skein-js/skein-js/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./dist/index.js",
|
|
17
|
+
"module": "./dist/index.js",
|
|
18
|
+
"types": "./dist/index.d.ts",
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"import": "./dist/index.js",
|
|
23
|
+
"default": "./dist/index.js"
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"LICENSE",
|
|
29
|
+
"README.md"
|
|
30
|
+
],
|
|
31
|
+
"sideEffects": false,
|
|
32
|
+
"engines": {
|
|
33
|
+
"node": ">=20"
|
|
34
|
+
},
|
|
35
|
+
"dependencies": {
|
|
36
|
+
"bullmq": "^5.0.0 || ^6.0.0",
|
|
37
|
+
"zod": "^3.25.76",
|
|
38
|
+
"ioredis": "^5.4.0 || ^6.0.0",
|
|
39
|
+
"@skein-js/agent-protocol": "0.23.0",
|
|
40
|
+
"@skein-js/core": "0.23.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@skein-js/test-support": "0.23.0",
|
|
44
|
+
"@skein-js/storage-memory": "0.23.0"
|
|
45
|
+
},
|
|
46
|
+
"publishConfig": {
|
|
47
|
+
"access": "public"
|
|
48
|
+
}
|
|
6
49
|
}
|