@swirls/looms 0.20.0 → 0.21.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/CHANGELOG.md +6 -0
- package/dist/nats/index.d.ts +2 -0
- package/dist/nats/index.js +2 -0
- package/dist/nats/projector.d.ts +69 -0
- package/dist/nats/projector.js +278 -0
- package/dist/nats/subjects.d.ts +14 -0
- package/dist/nats/subjects.js +44 -0
- package/dist/schedule/effects.d.ts +18 -18
- package/package.json +8 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @swirls/looms
|
|
2
2
|
|
|
3
|
+
## 0.21.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- cc734ac: Add `@swirls/looms/nats`, a projector that replicates committed events to a NATS JetStream stream. Each event goes to `<prefix>.run.<runId>.<type>` with the JSON envelope as the body and `Looms-*` headers. Batches are JetStream atomic batches fenced on the run's last stream sequence, so a batch lands whole or not at all, redelivery is a no-op, and `position` lets durable delivery rewind and refill a stream that fell behind. Requires nats-server 2.12 or newer.
|
|
8
|
+
|
|
3
9
|
## 0.20.0
|
|
4
10
|
|
|
5
11
|
### Minor Changes
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import type { StreamConfig } from '@nats-io/jetstream';
|
|
2
|
+
import type { NatsConnection } from '@nats-io/nats-core';
|
|
3
|
+
import { type Projector } from '@swirls/looms/projectors';
|
|
4
|
+
/** Headers on every message, so consumers can route without decoding the body. */
|
|
5
|
+
export declare const LoomsHeaders: {
|
|
6
|
+
readonly runId: 'Looms-Run-Id';
|
|
7
|
+
readonly seq: 'Looms-Seq';
|
|
8
|
+
readonly eventId: 'Looms-Event-Id';
|
|
9
|
+
readonly type: 'Looms-Type';
|
|
10
|
+
readonly threadId: 'Looms-Thread-Id';
|
|
11
|
+
readonly ephemeral: 'Looms-Ephemeral';
|
|
12
|
+
};
|
|
13
|
+
declare const NatsProjectorError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
14
|
+
readonly _tag: "NatsProjectorError";
|
|
15
|
+
} & Readonly<A>;
|
|
16
|
+
export declare class NatsProjectorError extends NatsProjectorError_base<{
|
|
17
|
+
readonly message: string;
|
|
18
|
+
readonly cause?: unknown;
|
|
19
|
+
/** JetStream `err_code` when the server rejected the request. */
|
|
20
|
+
readonly errCode?: number;
|
|
21
|
+
}> {
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Where the projector gets its connection. Use whichever transport fits the runtime:
|
|
25
|
+
* `@nats-io/transport-node`, `wsconnect`, and so on.
|
|
26
|
+
*/
|
|
27
|
+
export type NatsConnectionSource = {
|
|
28
|
+
/** A connection the caller owns. The projector never closes it. */
|
|
29
|
+
readonly connection: NatsConnection;
|
|
30
|
+
readonly connect?: never;
|
|
31
|
+
} | {
|
|
32
|
+
/**
|
|
33
|
+
* Opens a connection the projector owns: called on first use, called again after the
|
|
34
|
+
* connection closes, and drained on `dispose`.
|
|
35
|
+
*/
|
|
36
|
+
readonly connect: () => PromiseLike<NatsConnection>;
|
|
37
|
+
readonly connection?: never;
|
|
38
|
+
};
|
|
39
|
+
export type NatsProjectorOptions = NatsConnectionSource & NatsProjectorSettings;
|
|
40
|
+
export interface NatsProjectorSettings {
|
|
41
|
+
/** JetStream stream name. Defaults to `LOOMS`. */
|
|
42
|
+
readonly stream?: string;
|
|
43
|
+
/** Subject prefix; events go to `<prefix>.run.<runId>.<type>`. Defaults to `looms`. */
|
|
44
|
+
readonly subjectPrefix?: string;
|
|
45
|
+
/**
|
|
46
|
+
* Stream config used when `init` finds no stream. `name`, `subjects` and `allow_atomic` are
|
|
47
|
+
* always set by the projector. Pass `false` when the stream is managed elsewhere.
|
|
48
|
+
*/
|
|
49
|
+
readonly createStream?: Partial<StreamConfig> | false;
|
|
50
|
+
/** Events per atomic batch (at most 1000). Defaults to 1000. */
|
|
51
|
+
readonly maxBatch?: number;
|
|
52
|
+
/** Milliseconds to wait for a batch commit. Defaults to 5000. */
|
|
53
|
+
readonly timeoutMs?: number;
|
|
54
|
+
/** Projector name for delivery cursors and diagnostics. Defaults to `nats`. */
|
|
55
|
+
readonly name?: string;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Replicates committed events to a NATS JetStream stream, one subject per event:
|
|
59
|
+
* `<prefix>.run.<runId>.<type tokens>`. The body is the JSON envelope.
|
|
60
|
+
*
|
|
61
|
+
* Each batch is a JetStream atomic batch whose first message expects the run's last stream
|
|
62
|
+
* sequence, so a batch lands whole or not at all, and a concurrent writer or a hole in the run
|
|
63
|
+
* is refused by the server instead of reordering the copy. `position` reads the run's last
|
|
64
|
+
* message, so durable delivery rewinds and catches up when the stream is behind its cursor.
|
|
65
|
+
*
|
|
66
|
+
* Requires nats-server 2.12 or newer (atomic batch publish).
|
|
67
|
+
*/
|
|
68
|
+
export declare function natsProjector(options: NatsProjectorOptions): Projector;
|
|
69
|
+
export {};
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { JetStreamApiCodes, JetStreamApiError, jetstreamManager } from '@nats-io/jetstream';
|
|
2
|
+
import { headers, nuid } from '@nats-io/nats-core';
|
|
3
|
+
import { Data, Effect, Schema } from 'effect';
|
|
4
|
+
import { encodeLoomsEvent } from '@swirls/looms/core';
|
|
5
|
+
import { ReplicaGapError } from '@swirls/looms/projectors';
|
|
6
|
+
import { eventSubject, isValidSubjectPrefix, runSubjectFilter, streamSubject } from './subjects.js';
|
|
7
|
+
/** Headers on every message, so consumers can route without decoding the body. */
|
|
8
|
+
export const LoomsHeaders = {
|
|
9
|
+
runId: 'Looms-Run-Id',
|
|
10
|
+
seq: 'Looms-Seq',
|
|
11
|
+
eventId: 'Looms-Event-Id',
|
|
12
|
+
type: 'Looms-Type',
|
|
13
|
+
threadId: 'Looms-Thread-Id',
|
|
14
|
+
ephemeral: 'Looms-Ephemeral',
|
|
15
|
+
};
|
|
16
|
+
/** The server refuses atomic batches over 1000 messages. */
|
|
17
|
+
const SERVER_BATCH_LIMIT = 1000;
|
|
18
|
+
/** JetStream `err_code` for a failed `Nats-Expected-Last-Subject-Sequence` check. */
|
|
19
|
+
const WRONG_LAST_SEQUENCE = 10071;
|
|
20
|
+
export class NatsProjectorError extends Data.TaggedError('NatsProjectorError') {
|
|
21
|
+
}
|
|
22
|
+
const CommitResponse = Schema.Union([
|
|
23
|
+
Schema.Struct({
|
|
24
|
+
error: Schema.Struct({
|
|
25
|
+
code: Schema.Finite,
|
|
26
|
+
err_code: Schema.optional(Schema.Finite),
|
|
27
|
+
description: Schema.String,
|
|
28
|
+
}),
|
|
29
|
+
}),
|
|
30
|
+
Schema.Struct({
|
|
31
|
+
stream: Schema.String,
|
|
32
|
+
seq: Schema.Finite,
|
|
33
|
+
}),
|
|
34
|
+
]);
|
|
35
|
+
const decodeCommitResponse = Schema.decodeUnknownEffect(Schema.fromJsonString(CommitResponse));
|
|
36
|
+
const encoder = new TextEncoder();
|
|
37
|
+
function natsFailure(message) {
|
|
38
|
+
return (cause) => new NatsProjectorError({
|
|
39
|
+
message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,
|
|
40
|
+
cause,
|
|
41
|
+
errCode: cause instanceof JetStreamApiError ? cause.code : undefined,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
function attempt(message, operation) {
|
|
45
|
+
return Effect.tryPromise({ try: () => Promise.resolve(operation()), catch: natsFailure(message) });
|
|
46
|
+
}
|
|
47
|
+
function groupByRun(events) {
|
|
48
|
+
const groups = new Map();
|
|
49
|
+
for (const event of events) {
|
|
50
|
+
const batch = groups.get(event.runId) ?? [];
|
|
51
|
+
batch.push(event);
|
|
52
|
+
groups.set(event.runId, batch);
|
|
53
|
+
}
|
|
54
|
+
return groups;
|
|
55
|
+
}
|
|
56
|
+
function chunk(items, size) {
|
|
57
|
+
const chunks = [];
|
|
58
|
+
for (let index = 0; index < items.length; index += size) {
|
|
59
|
+
chunks.push(items.slice(index, index + size));
|
|
60
|
+
}
|
|
61
|
+
return chunks;
|
|
62
|
+
}
|
|
63
|
+
/** Events after `tail.loomsSeq`, refusing the batch if one is missing in front of them. */
|
|
64
|
+
function unpublished(runId, tail, events) {
|
|
65
|
+
const pending = [];
|
|
66
|
+
let cursor = tail.loomsSeq;
|
|
67
|
+
for (const event of events) {
|
|
68
|
+
if (event.seq <= cursor) {
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (event.seq !== cursor + 1) {
|
|
72
|
+
return Effect.fail(new ReplicaGapError({ runId, replicatedSeq: tail.loomsSeq, batchFrom: event.seq }));
|
|
73
|
+
}
|
|
74
|
+
pending.push(event);
|
|
75
|
+
cursor = event.seq;
|
|
76
|
+
}
|
|
77
|
+
return Effect.succeed(pending);
|
|
78
|
+
}
|
|
79
|
+
function batchMessage(prefix, runId, event, batch) {
|
|
80
|
+
const header = headers();
|
|
81
|
+
header.set('Nats-Batch-Id', batch.batchId);
|
|
82
|
+
header.set('Nats-Batch-Sequence', String(batch.position));
|
|
83
|
+
// No Nats-Msg-Id: the run-sequence expectation already refuses duplicates, and message ids
|
|
84
|
+
// outlive a purge inside the dedup window, which would block refilling a reset stream.
|
|
85
|
+
header.set(LoomsHeaders.runId, runId);
|
|
86
|
+
header.set(LoomsHeaders.seq, String(event.seq));
|
|
87
|
+
header.set(LoomsHeaders.eventId, event.id);
|
|
88
|
+
header.set(LoomsHeaders.type, event.type);
|
|
89
|
+
if (event.threadId) {
|
|
90
|
+
header.set(LoomsHeaders.threadId, event.threadId);
|
|
91
|
+
}
|
|
92
|
+
if (event.ephemeral) {
|
|
93
|
+
header.set(LoomsHeaders.ephemeral, 'true');
|
|
94
|
+
}
|
|
95
|
+
if (batch.expected !== undefined) {
|
|
96
|
+
header.set('Nats-Expected-Last-Subject-Sequence', String(batch.expected));
|
|
97
|
+
header.set('Nats-Expected-Last-Subject-Sequence-Subject', runSubjectFilter(prefix, runId));
|
|
98
|
+
}
|
|
99
|
+
if (batch.commit) {
|
|
100
|
+
header.set('Nats-Batch-Commit', '1');
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
subject: eventSubject(prefix, runId, event.type),
|
|
104
|
+
payload: encoder.encode(JSON.stringify(encodeLoomsEvent(event))),
|
|
105
|
+
headers: header,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* Replicates committed events to a NATS JetStream stream, one subject per event:
|
|
110
|
+
* `<prefix>.run.<runId>.<type tokens>`. The body is the JSON envelope.
|
|
111
|
+
*
|
|
112
|
+
* Each batch is a JetStream atomic batch whose first message expects the run's last stream
|
|
113
|
+
* sequence, so a batch lands whole or not at all, and a concurrent writer or a hole in the run
|
|
114
|
+
* is refused by the server instead of reordering the copy. `position` reads the run's last
|
|
115
|
+
* message, so durable delivery rewinds and catches up when the stream is behind its cursor.
|
|
116
|
+
*
|
|
117
|
+
* Requires nats-server 2.12 or newer (atomic batch publish).
|
|
118
|
+
*/
|
|
119
|
+
export function natsProjector(options) {
|
|
120
|
+
const stream = options.stream ?? 'LOOMS';
|
|
121
|
+
const prefix = options.subjectPrefix ?? 'looms';
|
|
122
|
+
const maxBatch = Math.min(options.maxBatch ?? SERVER_BATCH_LIMIT, SERVER_BATCH_LIMIT);
|
|
123
|
+
const timeout = options.timeoutMs ?? 5_000;
|
|
124
|
+
const name = options.name ?? 'nats';
|
|
125
|
+
if (!isValidSubjectPrefix(prefix)) {
|
|
126
|
+
throw new NatsProjectorError({
|
|
127
|
+
message: `Subject prefix "${prefix}" must be dot-separated [A-Za-z0-9_-] tokens`,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
if (!Number.isInteger(maxBatch) || maxBatch < 1) {
|
|
131
|
+
throw new NatsProjectorError({ message: 'maxBatch must be a positive integer' });
|
|
132
|
+
}
|
|
133
|
+
const open = options.connect;
|
|
134
|
+
const borrowed = options.connection;
|
|
135
|
+
let opened;
|
|
136
|
+
let live;
|
|
137
|
+
let manager;
|
|
138
|
+
let ready;
|
|
139
|
+
const connection = Effect.suspend(() => {
|
|
140
|
+
if (!open) {
|
|
141
|
+
return borrowed
|
|
142
|
+
? Effect.succeed(borrowed)
|
|
143
|
+
: Effect.fail(new NatsProjectorError({ message: 'Pass `connection` or `connect`' }));
|
|
144
|
+
}
|
|
145
|
+
return attempt('NATS connect failed', () => {
|
|
146
|
+
if (live?.isClosed()) {
|
|
147
|
+
live = undefined;
|
|
148
|
+
opened = undefined;
|
|
149
|
+
}
|
|
150
|
+
opened ??= Promise.resolve(open()).then((nc) => {
|
|
151
|
+
live = nc;
|
|
152
|
+
return nc;
|
|
153
|
+
}, (cause) => {
|
|
154
|
+
opened = undefined;
|
|
155
|
+
throw cause;
|
|
156
|
+
});
|
|
157
|
+
return opened;
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
const jsm = connection.pipe(Effect.flatMap((nc) => {
|
|
161
|
+
if (manager?.connection === nc) {
|
|
162
|
+
return Effect.succeed(manager.jsm);
|
|
163
|
+
}
|
|
164
|
+
return attempt('JetStream unavailable', () => jetstreamManager(nc)).pipe(Effect.tap((created) => Effect.sync(() => {
|
|
165
|
+
manager = { connection: nc, jsm: created };
|
|
166
|
+
})));
|
|
167
|
+
}));
|
|
168
|
+
const ensureStream = Effect.gen(function* () {
|
|
169
|
+
const streams = (yield* jsm).streams;
|
|
170
|
+
const info = yield* attempt(`Reading stream ${stream} failed`, () => streams.info(stream)).pipe(Effect.catchIf((error) => error.errCode === JetStreamApiCodes.StreamNotFound, () => Effect.succeed(null)));
|
|
171
|
+
if (info?.config.allow_atomic === true) {
|
|
172
|
+
return info;
|
|
173
|
+
}
|
|
174
|
+
if (info) {
|
|
175
|
+
return yield* new NatsProjectorError({
|
|
176
|
+
message: `Stream ${stream} must set allow_atomic: true for the Looms NATS projector`,
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
if (options.createStream === false) {
|
|
180
|
+
return yield* new NatsProjectorError({ message: `Stream ${stream} does not exist` });
|
|
181
|
+
}
|
|
182
|
+
return yield* attempt(`Creating stream ${stream} failed`, () => streams.add({
|
|
183
|
+
...options.createStream,
|
|
184
|
+
name: stream,
|
|
185
|
+
subjects: [streamSubject(prefix)],
|
|
186
|
+
allow_atomic: true,
|
|
187
|
+
}));
|
|
188
|
+
});
|
|
189
|
+
const init = () => {
|
|
190
|
+
ready ??= Effect.runPromise(Effect.asVoid(ensureStream)).catch((cause) => {
|
|
191
|
+
ready = undefined;
|
|
192
|
+
throw cause;
|
|
193
|
+
});
|
|
194
|
+
return ready;
|
|
195
|
+
};
|
|
196
|
+
const readTail = (runId) => Effect.gen(function* () {
|
|
197
|
+
const streams = (yield* jsm).streams;
|
|
198
|
+
const last = yield* attempt(`Reading the last message of ${runId} failed`, () => streams.getMessage(stream, { last_by_subj: runSubjectFilter(prefix, runId) }));
|
|
199
|
+
if (!last) {
|
|
200
|
+
return { loomsSeq: 0, streamSeq: 0 };
|
|
201
|
+
}
|
|
202
|
+
const loomsSeq = Number(last.header?.get(LoomsHeaders.seq));
|
|
203
|
+
if (!Number.isSafeInteger(loomsSeq) || loomsSeq < 1) {
|
|
204
|
+
return yield* new NatsProjectorError({
|
|
205
|
+
message: `Message ${last.seq} on ${last.subject} has no ${LoomsHeaders.seq} header`,
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
return { loomsSeq, streamSeq: last.seq };
|
|
209
|
+
});
|
|
210
|
+
const publishBatch = (runId, batch, expected) => Effect.gen(function* () {
|
|
211
|
+
const nc = yield* connection;
|
|
212
|
+
const batchId = nuid.next();
|
|
213
|
+
const commit = yield* Effect.try({
|
|
214
|
+
try: () => {
|
|
215
|
+
const messages = batch.map((event, index) => batchMessage(prefix, runId, event, {
|
|
216
|
+
batchId,
|
|
217
|
+
position: index + 1,
|
|
218
|
+
expected: index === 0 ? expected : undefined,
|
|
219
|
+
commit: index === batch.length - 1,
|
|
220
|
+
}));
|
|
221
|
+
for (const message of messages.slice(0, -1)) {
|
|
222
|
+
nc.publish(message.subject, message.payload, { headers: message.headers });
|
|
223
|
+
}
|
|
224
|
+
return messages.at(-1);
|
|
225
|
+
},
|
|
226
|
+
catch: natsFailure(`Publishing ${runId} failed`),
|
|
227
|
+
});
|
|
228
|
+
if (!commit) {
|
|
229
|
+
return expected;
|
|
230
|
+
}
|
|
231
|
+
const reply = yield* attempt(`Committing ${runId} batch failed`, () => nc.request(commit.subject, commit.payload, { headers: commit.headers, timeout }));
|
|
232
|
+
const response = yield* decodeCommitResponse(reply.string()).pipe(Effect.mapError(natsFailure(`Unreadable commit reply for ${runId}`)));
|
|
233
|
+
if ('error' in response) {
|
|
234
|
+
const errCode = response.error.err_code;
|
|
235
|
+
const conflict = errCode === WRONG_LAST_SEQUENCE;
|
|
236
|
+
return yield* new NatsProjectorError({
|
|
237
|
+
message: conflict
|
|
238
|
+
? `Another writer published to ${runId} first (${response.error.description})`
|
|
239
|
+
: `JetStream refused the ${runId} batch: ${response.error.description}`,
|
|
240
|
+
errCode,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
return response.seq;
|
|
244
|
+
});
|
|
245
|
+
const projectRun = (runId, events) => Effect.gen(function* () {
|
|
246
|
+
const tail = yield* readTail(runId);
|
|
247
|
+
const pending = yield* unpublished(runId, tail, events);
|
|
248
|
+
let expected = tail.streamSeq;
|
|
249
|
+
for (const batch of chunk(pending, maxBatch)) {
|
|
250
|
+
expected = yield* publishBatch(runId, batch, expected);
|
|
251
|
+
}
|
|
252
|
+
});
|
|
253
|
+
return {
|
|
254
|
+
name,
|
|
255
|
+
version: '1',
|
|
256
|
+
init,
|
|
257
|
+
position: (runId) => init().then(() => Effect.runPromise(readTail(runId).pipe(Effect.map((tail) => tail.loomsSeq)))),
|
|
258
|
+
project: (events) => {
|
|
259
|
+
if (events.length === 0) {
|
|
260
|
+
return Promise.resolve();
|
|
261
|
+
}
|
|
262
|
+
return init().then(() => Effect.runPromise(Effect.forEach(groupByRun(events), ([runId, batch]) => projectRun(runId, batch), {
|
|
263
|
+
discard: true,
|
|
264
|
+
})));
|
|
265
|
+
},
|
|
266
|
+
dispose: () => {
|
|
267
|
+
const owned = opened;
|
|
268
|
+
opened = undefined;
|
|
269
|
+
live = undefined;
|
|
270
|
+
manager = undefined;
|
|
271
|
+
ready = undefined;
|
|
272
|
+
if (!owned) {
|
|
273
|
+
return Promise.resolve();
|
|
274
|
+
}
|
|
275
|
+
return owned.then((nc) => (nc.isClosed() ? undefined : nc.drain()), () => undefined);
|
|
276
|
+
},
|
|
277
|
+
};
|
|
278
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Encode one subject token. Characters outside `[A-Za-z0-9_-]` become `~HH` per UTF-8 byte,
|
|
3
|
+
* and the empty string becomes `~`. Raw tokens never contain `~`, so two different inputs
|
|
4
|
+
* never share a token: a run's subjects can't collide with another run's.
|
|
5
|
+
*/
|
|
6
|
+
export declare function encodeSubjectToken(value: string): string;
|
|
7
|
+
/** Each dot-separated part of an event type becomes its own token, so `>` and `*` filter by type. */
|
|
8
|
+
export declare function encodeEventType(type: string): string;
|
|
9
|
+
export declare function isValidSubjectPrefix(prefix: string): boolean;
|
|
10
|
+
/** `<prefix>.run.>`: everything this projector publishes. */
|
|
11
|
+
export declare function streamSubject(prefix: string): string;
|
|
12
|
+
/** `<prefix>.run.<runId>.>`: one run's events, in the order they were published. */
|
|
13
|
+
export declare function runSubjectFilter(prefix: string, runId: string): string;
|
|
14
|
+
export declare function eventSubject(prefix: string, runId: string, type: string): string;
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
const SAFE_TOKEN = /^[A-Za-z0-9_-]+$/;
|
|
2
|
+
const encoder = new TextEncoder();
|
|
3
|
+
/**
|
|
4
|
+
* Encode one subject token. Characters outside `[A-Za-z0-9_-]` become `~HH` per UTF-8 byte,
|
|
5
|
+
* and the empty string becomes `~`. Raw tokens never contain `~`, so two different inputs
|
|
6
|
+
* never share a token: a run's subjects can't collide with another run's.
|
|
7
|
+
*/
|
|
8
|
+
export function encodeSubjectToken(value) {
|
|
9
|
+
if (value.length === 0) {
|
|
10
|
+
return '~';
|
|
11
|
+
}
|
|
12
|
+
if (SAFE_TOKEN.test(value)) {
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
let token = '';
|
|
16
|
+
for (const char of value) {
|
|
17
|
+
if (SAFE_TOKEN.test(char)) {
|
|
18
|
+
token += char;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
for (const byte of encoder.encode(char)) {
|
|
22
|
+
token += `~${byte.toString(16).toUpperCase().padStart(2, '0')}`;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return token;
|
|
26
|
+
}
|
|
27
|
+
/** Each dot-separated part of an event type becomes its own token, so `>` and `*` filter by type. */
|
|
28
|
+
export function encodeEventType(type) {
|
|
29
|
+
return type.split('.').map(encodeSubjectToken).join('.');
|
|
30
|
+
}
|
|
31
|
+
export function isValidSubjectPrefix(prefix) {
|
|
32
|
+
return prefix.split('.').every((token) => SAFE_TOKEN.test(token));
|
|
33
|
+
}
|
|
34
|
+
/** `<prefix>.run.>`: everything this projector publishes. */
|
|
35
|
+
export function streamSubject(prefix) {
|
|
36
|
+
return `${prefix}.run.>`;
|
|
37
|
+
}
|
|
38
|
+
/** `<prefix>.run.<runId>.>`: one run's events, in the order they were published. */
|
|
39
|
+
export function runSubjectFilter(prefix, runId) {
|
|
40
|
+
return `${prefix}.run.${encodeSubjectToken(runId)}.>`;
|
|
41
|
+
}
|
|
42
|
+
export function eventSubject(prefix, runId, type) {
|
|
43
|
+
return `${prefix}.run.${encodeSubjectToken(runId)}.${encodeEventType(type)}`;
|
|
44
|
+
}
|
|
@@ -332,6 +332,15 @@ export declare const planEffect: NoInfer<import("@swirls/looms/core").LocalEffec
|
|
|
332
332
|
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
333
333
|
readonly type: "schedule.paused";
|
|
334
334
|
readonly payload: {};
|
|
335
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
336
|
+
readonly type: "schedule.resumed";
|
|
337
|
+
readonly payload: {};
|
|
338
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
339
|
+
readonly type: "schedule.retired";
|
|
340
|
+
readonly payload: {};
|
|
341
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
342
|
+
readonly type: "schedule.triggered";
|
|
343
|
+
readonly payload: {};
|
|
335
344
|
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
336
345
|
readonly type: "schedule.planned";
|
|
337
346
|
readonly payload: {
|
|
@@ -355,12 +364,6 @@ export declare const planEffect: NoInfer<import("@swirls/looms/core").LocalEffec
|
|
|
355
364
|
readonly payload: {
|
|
356
365
|
readonly reason: string;
|
|
357
366
|
};
|
|
358
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
359
|
-
readonly type: "schedule.resumed";
|
|
360
|
-
readonly payload: {};
|
|
361
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
362
|
-
readonly type: "schedule.retired";
|
|
363
|
-
readonly payload: {};
|
|
364
367
|
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
365
368
|
readonly type: "schedule.skipped";
|
|
366
369
|
readonly payload: {
|
|
@@ -371,9 +374,6 @@ export declare const planEffect: NoInfer<import("@swirls/looms/core").LocalEffec
|
|
|
371
374
|
readonly manual: boolean;
|
|
372
375
|
readonly triggerId?: string | undefined;
|
|
373
376
|
};
|
|
374
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
375
|
-
readonly type: "schedule.triggered";
|
|
376
|
-
readonly payload: {};
|
|
377
377
|
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
378
378
|
readonly type: "schedule.updated";
|
|
379
379
|
readonly payload: {
|
|
@@ -683,6 +683,15 @@ export declare const fireEffect: NoInfer<import("@swirls/looms/core").LocalEffec
|
|
|
683
683
|
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
684
684
|
readonly type: "schedule.paused";
|
|
685
685
|
readonly payload: {};
|
|
686
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
687
|
+
readonly type: "schedule.resumed";
|
|
688
|
+
readonly payload: {};
|
|
689
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
690
|
+
readonly type: "schedule.retired";
|
|
691
|
+
readonly payload: {};
|
|
692
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
693
|
+
readonly type: "schedule.triggered";
|
|
694
|
+
readonly payload: {};
|
|
686
695
|
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
687
696
|
readonly type: "schedule.planned";
|
|
688
697
|
readonly payload: {
|
|
@@ -706,12 +715,6 @@ export declare const fireEffect: NoInfer<import("@swirls/looms/core").LocalEffec
|
|
|
706
715
|
readonly payload: {
|
|
707
716
|
readonly reason: string;
|
|
708
717
|
};
|
|
709
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
710
|
-
readonly type: "schedule.resumed";
|
|
711
|
-
readonly payload: {};
|
|
712
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
713
|
-
readonly type: "schedule.retired";
|
|
714
|
-
readonly payload: {};
|
|
715
718
|
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
716
719
|
readonly type: "schedule.skipped";
|
|
717
720
|
readonly payload: {
|
|
@@ -722,9 +725,6 @@ export declare const fireEffect: NoInfer<import("@swirls/looms/core").LocalEffec
|
|
|
722
725
|
readonly manual: boolean;
|
|
723
726
|
readonly triggerId?: string | undefined;
|
|
724
727
|
};
|
|
725
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
726
|
-
readonly type: "schedule.triggered";
|
|
727
|
-
readonly payload: {};
|
|
728
728
|
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
729
729
|
readonly type: "schedule.updated";
|
|
730
730
|
readonly payload: {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@swirls/looms",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.21.0",
|
|
4
4
|
"description": "Pluggable event-sourced runtime for durable agents and workflows",
|
|
5
5
|
"homepage": "https://github.com/ByteSliceHQ/looms#readme",
|
|
6
6
|
"bugs": {
|
|
@@ -85,6 +85,10 @@
|
|
|
85
85
|
"types": "./dist/evaluator/index.d.ts",
|
|
86
86
|
"import": "./dist/evaluator/index.js"
|
|
87
87
|
},
|
|
88
|
+
"./nats": {
|
|
89
|
+
"types": "./dist/nats/index.d.ts",
|
|
90
|
+
"import": "./dist/nats/index.js"
|
|
91
|
+
},
|
|
88
92
|
"./projectors": {
|
|
89
93
|
"types": "./dist/projectors/index.d.ts",
|
|
90
94
|
"import": "./dist/projectors/index.js"
|
|
@@ -194,6 +198,8 @@
|
|
|
194
198
|
},
|
|
195
199
|
"dependencies": {
|
|
196
200
|
"@effect/platform-bun": "^4.1.4",
|
|
201
|
+
"@nats-io/jetstream": "3.4.0",
|
|
202
|
+
"@nats-io/nats-core": "3.4.0",
|
|
197
203
|
"@noble/hashes": "^2.0.1",
|
|
198
204
|
"@s2-dev/streamstore": "^0.23.0",
|
|
199
205
|
"@standard-schema/spec": "^1.1.0",
|
|
@@ -218,6 +224,7 @@
|
|
|
218
224
|
"@looms/debugger": "workspace:*",
|
|
219
225
|
"@looms/debugger-app": "workspace:*",
|
|
220
226
|
"@looms/evaluator": "workspace:*",
|
|
227
|
+
"@looms/nats": "workspace:*",
|
|
221
228
|
"@looms/projectors": "workspace:*",
|
|
222
229
|
"@looms/react": "workspace:*",
|
|
223
230
|
"@looms/runtime": "workspace:*",
|