@swirls/looms 0.19.1 → 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 +14 -0
- package/dist/agent/module.d.ts +727 -727
- package/dist/evaluator/effects.d.ts +33 -33
- package/dist/evaluator/module.d.ts +66 -66
- 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/projectors/event-log.d.ts +7 -3
- package/dist/projectors/event-log.js +42 -9
- package/dist/projectors/replica/columns.d.ts +10 -3
- package/dist/projectors/replica/columns.js +22 -7
- package/dist/projectors/replica/drizzle.d.ts +9 -242
- package/dist/projectors/replica/drizzle.js +19 -6
- package/dist/projectors/replica/migrations.d.ts +8 -1
- package/dist/projectors/replica/migrations.js +26 -2
- package/dist/projectors/replica/postgres.d.ts +3 -2
- package/dist/projectors/replica/postgres.js +1 -1
- package/dist/projectors/replica/sqlite-migrations.js +19 -1
- package/dist/projectors/replica/sqlite.d.ts +3 -2
- package/dist/projectors/replica/sqlite.js +13 -4
- package/package.json +8 -1
|
@@ -7,6 +7,39 @@ export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").LocalE
|
|
|
7
7
|
readonly definitionVersion?: string | undefined;
|
|
8
8
|
readonly input?: Schema.Json | undefined;
|
|
9
9
|
}, EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
10
|
+
readonly type: "evaluator.evaluated";
|
|
11
|
+
readonly payload: {
|
|
12
|
+
readonly evaluationId: string;
|
|
13
|
+
readonly definitionName?: string | undefined;
|
|
14
|
+
readonly answers: {
|
|
15
|
+
readonly [x: string]: {
|
|
16
|
+
readonly type: "boolean";
|
|
17
|
+
readonly value: boolean;
|
|
18
|
+
readonly probability: number;
|
|
19
|
+
} | {
|
|
20
|
+
readonly type: "choice";
|
|
21
|
+
readonly value: string;
|
|
22
|
+
} | {
|
|
23
|
+
readonly type: "score";
|
|
24
|
+
readonly value: number;
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
readonly route: string;
|
|
28
|
+
readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
|
|
29
|
+
readonly usage?: {
|
|
30
|
+
readonly input: number;
|
|
31
|
+
readonly output: number;
|
|
32
|
+
} | undefined;
|
|
33
|
+
};
|
|
34
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
35
|
+
readonly type: "evaluator.requested";
|
|
36
|
+
readonly payload: {
|
|
37
|
+
readonly evaluationId: string;
|
|
38
|
+
readonly definitionName?: string | undefined;
|
|
39
|
+
readonly state: string;
|
|
40
|
+
readonly model?: string | undefined;
|
|
41
|
+
};
|
|
42
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
10
43
|
readonly type: "runtime.child.close.requested";
|
|
11
44
|
readonly payload: {
|
|
12
45
|
readonly policy: "terminate" | "wait";
|
|
@@ -252,37 +285,4 @@ export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").LocalE
|
|
|
252
285
|
readonly payload: Schema.Json;
|
|
253
286
|
};
|
|
254
287
|
};
|
|
255
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
256
|
-
readonly type: "evaluator.evaluated";
|
|
257
|
-
readonly payload: {
|
|
258
|
-
readonly evaluationId: string;
|
|
259
|
-
readonly definitionName?: string | undefined;
|
|
260
|
-
readonly answers: {
|
|
261
|
-
readonly [x: string]: {
|
|
262
|
-
readonly type: "boolean";
|
|
263
|
-
readonly value: boolean;
|
|
264
|
-
readonly probability: number;
|
|
265
|
-
} | {
|
|
266
|
-
readonly type: "choice";
|
|
267
|
-
readonly value: string;
|
|
268
|
-
} | {
|
|
269
|
-
readonly type: "score";
|
|
270
|
-
readonly value: number;
|
|
271
|
-
};
|
|
272
|
-
};
|
|
273
|
-
readonly route: string;
|
|
274
|
-
readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
|
|
275
|
-
readonly usage?: {
|
|
276
|
-
readonly input: number;
|
|
277
|
-
readonly output: number;
|
|
278
|
-
} | undefined;
|
|
279
|
-
};
|
|
280
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
281
|
-
readonly type: "evaluator.requested";
|
|
282
|
-
readonly payload: {
|
|
283
|
-
readonly evaluationId: string;
|
|
284
|
-
readonly definitionName?: string | undefined;
|
|
285
|
-
readonly state: string;
|
|
286
|
-
readonly model?: string | undefined;
|
|
287
|
-
};
|
|
288
288
|
})>>;
|
|
@@ -43,6 +43,39 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
|
|
|
43
43
|
readonly definitionVersion?: string | undefined;
|
|
44
44
|
readonly input?: import("effect/Schema").Json | undefined;
|
|
45
45
|
}, import("./definitions-store").EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
46
|
+
readonly type: "evaluator.evaluated";
|
|
47
|
+
readonly payload: {
|
|
48
|
+
readonly evaluationId: string;
|
|
49
|
+
readonly definitionName?: string | undefined;
|
|
50
|
+
readonly answers: {
|
|
51
|
+
readonly [x: string]: {
|
|
52
|
+
readonly type: "boolean";
|
|
53
|
+
readonly value: boolean;
|
|
54
|
+
readonly probability: number;
|
|
55
|
+
} | {
|
|
56
|
+
readonly type: "choice";
|
|
57
|
+
readonly value: string;
|
|
58
|
+
} | {
|
|
59
|
+
readonly type: "score";
|
|
60
|
+
readonly value: number;
|
|
61
|
+
};
|
|
62
|
+
};
|
|
63
|
+
readonly route: string;
|
|
64
|
+
readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
|
|
65
|
+
readonly usage?: {
|
|
66
|
+
readonly input: number;
|
|
67
|
+
readonly output: number;
|
|
68
|
+
} | undefined;
|
|
69
|
+
};
|
|
70
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
71
|
+
readonly type: "evaluator.requested";
|
|
72
|
+
readonly payload: {
|
|
73
|
+
readonly evaluationId: string;
|
|
74
|
+
readonly definitionName?: string | undefined;
|
|
75
|
+
readonly state: string;
|
|
76
|
+
readonly model?: string | undefined;
|
|
77
|
+
};
|
|
78
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
46
79
|
readonly type: "runtime.child.close.requested";
|
|
47
80
|
readonly payload: {
|
|
48
81
|
readonly policy: "terminate" | "wait";
|
|
@@ -288,39 +321,6 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
|
|
|
288
321
|
readonly payload: import("effect/Schema").Json;
|
|
289
322
|
};
|
|
290
323
|
};
|
|
291
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
292
|
-
readonly type: "evaluator.evaluated";
|
|
293
|
-
readonly payload: {
|
|
294
|
-
readonly evaluationId: string;
|
|
295
|
-
readonly definitionName?: string | undefined;
|
|
296
|
-
readonly answers: {
|
|
297
|
-
readonly [x: string]: {
|
|
298
|
-
readonly type: "boolean";
|
|
299
|
-
readonly value: boolean;
|
|
300
|
-
readonly probability: number;
|
|
301
|
-
} | {
|
|
302
|
-
readonly type: "choice";
|
|
303
|
-
readonly value: string;
|
|
304
|
-
} | {
|
|
305
|
-
readonly type: "score";
|
|
306
|
-
readonly value: number;
|
|
307
|
-
};
|
|
308
|
-
};
|
|
309
|
-
readonly route: string;
|
|
310
|
-
readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
|
|
311
|
-
readonly usage?: {
|
|
312
|
-
readonly input: number;
|
|
313
|
-
readonly output: number;
|
|
314
|
-
} | undefined;
|
|
315
|
-
};
|
|
316
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
317
|
-
readonly type: "evaluator.requested";
|
|
318
|
-
readonly payload: {
|
|
319
|
-
readonly evaluationId: string;
|
|
320
|
-
readonly definitionName?: string | undefined;
|
|
321
|
-
readonly state: string;
|
|
322
|
-
readonly model?: string | undefined;
|
|
323
|
-
};
|
|
324
324
|
})>;
|
|
325
325
|
}, {
|
|
326
326
|
evaluator: import("@swirls/looms/core").ThreadDefinition<{
|
|
@@ -391,6 +391,39 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
|
|
|
391
391
|
readonly definitionVersion?: string | undefined;
|
|
392
392
|
readonly input?: import("effect/Schema").Json | undefined;
|
|
393
393
|
}, import("./definitions-store").EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
394
|
+
readonly type: "evaluator.evaluated";
|
|
395
|
+
readonly payload: {
|
|
396
|
+
readonly evaluationId: string;
|
|
397
|
+
readonly definitionName?: string | undefined;
|
|
398
|
+
readonly answers: {
|
|
399
|
+
readonly [x: string]: {
|
|
400
|
+
readonly type: "boolean";
|
|
401
|
+
readonly value: boolean;
|
|
402
|
+
readonly probability: number;
|
|
403
|
+
} | {
|
|
404
|
+
readonly type: "choice";
|
|
405
|
+
readonly value: string;
|
|
406
|
+
} | {
|
|
407
|
+
readonly type: "score";
|
|
408
|
+
readonly value: number;
|
|
409
|
+
};
|
|
410
|
+
};
|
|
411
|
+
readonly route: string;
|
|
412
|
+
readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
|
|
413
|
+
readonly usage?: {
|
|
414
|
+
readonly input: number;
|
|
415
|
+
readonly output: number;
|
|
416
|
+
} | undefined;
|
|
417
|
+
};
|
|
418
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
419
|
+
readonly type: "evaluator.requested";
|
|
420
|
+
readonly payload: {
|
|
421
|
+
readonly evaluationId: string;
|
|
422
|
+
readonly definitionName?: string | undefined;
|
|
423
|
+
readonly state: string;
|
|
424
|
+
readonly model?: string | undefined;
|
|
425
|
+
};
|
|
426
|
+
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
394
427
|
readonly type: "runtime.child.close.requested";
|
|
395
428
|
readonly payload: {
|
|
396
429
|
readonly policy: "terminate" | "wait";
|
|
@@ -636,39 +669,6 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
|
|
|
636
669
|
readonly payload: import("effect/Schema").Json;
|
|
637
670
|
};
|
|
638
671
|
};
|
|
639
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
640
|
-
readonly type: "evaluator.evaluated";
|
|
641
|
-
readonly payload: {
|
|
642
|
-
readonly evaluationId: string;
|
|
643
|
-
readonly definitionName?: string | undefined;
|
|
644
|
-
readonly answers: {
|
|
645
|
-
readonly [x: string]: {
|
|
646
|
-
readonly type: "boolean";
|
|
647
|
-
readonly value: boolean;
|
|
648
|
-
readonly probability: number;
|
|
649
|
-
} | {
|
|
650
|
-
readonly type: "choice";
|
|
651
|
-
readonly value: string;
|
|
652
|
-
} | {
|
|
653
|
-
readonly type: "score";
|
|
654
|
-
readonly value: number;
|
|
655
|
-
};
|
|
656
|
-
};
|
|
657
|
-
readonly route: string;
|
|
658
|
-
readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
|
|
659
|
-
readonly usage?: {
|
|
660
|
-
readonly input: number;
|
|
661
|
-
readonly output: number;
|
|
662
|
-
} | undefined;
|
|
663
|
-
};
|
|
664
|
-
}) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
|
|
665
|
-
readonly type: "evaluator.requested";
|
|
666
|
-
readonly payload: {
|
|
667
|
-
readonly evaluationId: string;
|
|
668
|
-
readonly definitionName?: string | undefined;
|
|
669
|
-
readonly state: string;
|
|
670
|
-
readonly model?: string | undefined;
|
|
671
|
-
};
|
|
672
672
|
})>;
|
|
673
673
|
};
|
|
674
674
|
readonly threads: {
|
|
@@ -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
|
+
}
|
|
@@ -23,7 +23,7 @@ export type PostgresEventLogOptions = ({
|
|
|
23
23
|
} | {
|
|
24
24
|
sql: Sql;
|
|
25
25
|
}) & {
|
|
26
|
-
/** Declared run attributes. Each one is a `looms_run_index`
|
|
26
|
+
/** Declared run attributes. Each one is a column on `looms_run_index` and on `looms_run_events`. */
|
|
27
27
|
readonly additionalFields?: RunAttributeFields;
|
|
28
28
|
/**
|
|
29
29
|
* Schema ownership on init. Default `auto` applies pending versioned migrations
|
|
@@ -36,5 +36,9 @@ export declare function postgresEventLog(options: PostgresEventLogOptions): Even
|
|
|
36
36
|
export declare function applySqlOps(sql: TransactionSql, ops: readonly EventLogOp[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
|
|
37
37
|
/** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
|
|
38
38
|
export declare function applyRunIndexOps(sql: TransactionSql, ops: readonly EventLogOp[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
|
|
39
|
-
/**
|
|
40
|
-
|
|
39
|
+
/**
|
|
40
|
+
* Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered.
|
|
41
|
+
* Each declared attribute column is filled from the run's attributes: the started event when it is in
|
|
42
|
+
* `events`, otherwise the run's `looms_run_index` row, which an earlier batch wrote.
|
|
43
|
+
*/
|
|
44
|
+
export declare function insertRunEvents(sql: TransactionSql, events: readonly EventEnvelope[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
|