@swirls/looms 0.22.1 → 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.
@@ -1,9 +1,8 @@
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';
1
+ import { Effect } from 'effect';
2
+ import { encodeLoomsEvent, isJsonObject, readAttributes } from '@swirls/looms/core';
5
3
  import { ReplicaGapError } from '@swirls/looms/projectors';
6
- import { eventSubject, isValidSubjectPrefix, runSubjectFilter, streamSubject } from './subjects.js';
4
+ import { anyAttributeTokens, attributeTokens, attributeTokensOf, eventSubject, isValidSubjectPrefix, runSubjectFilter, streamSubject, } from './subjects.js';
5
+ import { NatsProjectorError, SERVER_BATCH_LIMIT, natsConnectionTransport, } from './transport.js';
7
6
  /** Headers on every message, so consumers can route without decoding the body. */
8
7
  export const LoomsHeaders = {
9
8
  runId: 'Looms-Run-Id',
@@ -13,37 +12,6 @@ export const LoomsHeaders = {
13
12
  threadId: 'Looms-Thread-Id',
14
13
  ephemeral: 'Looms-Ephemeral',
15
14
  };
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
15
  function groupByRun(events) {
48
16
  const groups = new Map();
49
17
  for (const event of events) {
@@ -76,178 +44,105 @@ function unpublished(runId, tail, events) {
76
44
  }
77
45
  return Effect.succeed(pending);
78
46
  }
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);
47
+ /** The run's attribute tokens from its started event, when the batch holds it. */
48
+ function startedScope(names, events) {
49
+ const started = events.find((event) => event.type === 'runtime.run.started' && !event.ephemeral);
50
+ if (!started) {
51
+ return undefined;
52
+ }
53
+ const payload = isJsonObject(started.payload) ? started.payload : {};
54
+ return attributeTokens(names, readAttributes(payload.attributes));
55
+ }
56
+ function outgoing(prefix, runId, scope, event) {
57
+ const headers = [
58
+ [LoomsHeaders.runId, runId],
59
+ [LoomsHeaders.seq, String(event.seq)],
60
+ [LoomsHeaders.eventId, event.id],
61
+ [LoomsHeaders.type, event.type],
62
+ ];
89
63
  if (event.threadId) {
90
- header.set(LoomsHeaders.threadId, event.threadId);
64
+ headers.push([LoomsHeaders.threadId, event.threadId]);
91
65
  }
92
66
  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');
67
+ headers.push([LoomsHeaders.ephemeral, 'true']);
101
68
  }
102
69
  return {
103
- subject: eventSubject(prefix, runId, event.type),
104
- payload: encoder.encode(JSON.stringify(encodeLoomsEvent(event))),
105
- headers: header,
70
+ subject: eventSubject(prefix, runId, event.type, scope),
71
+ payload: JSON.stringify(encodeLoomsEvent(event)),
72
+ headers: Object.fromEntries(headers),
106
73
  };
107
74
  }
108
75
  /**
109
76
  * Replicates committed events to a NATS JetStream stream, one subject per event:
110
- * `<prefix>.run.<runId>.<type tokens>`. The body is the JSON envelope.
77
+ * `<prefix>.run.<runId>.<type tokens>`, with the run's `subjectAttributes` before the run id
78
+ * when they are set. The body is the JSON envelope.
111
79
  *
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.
80
+ * Each batch lands whole or not at all, and expects the run's last stream sequence, so a
81
+ * concurrent writer or a hole in the run is refused instead of reordering the copy. `position`
82
+ * reads the run's last message, so durable delivery rewinds and catches up when the stream is
83
+ * behind its cursor.
116
84
  *
117
- * Requires nats-server 2.12 or newer (atomic batch publish).
85
+ * Pass a NATS connection, or a `transport` when the host reaches the stream some other way.
86
+ * Over a connection it requires nats-server 2.12 or newer (atomic batch publish).
118
87
  */
119
88
  export function natsProjector(options) {
120
- const stream = options.stream ?? 'LOOMS';
121
89
  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;
90
+ const names = options.subjectAttributes ?? [];
124
91
  const name = options.name ?? 'nats';
125
92
  if (!isValidSubjectPrefix(prefix)) {
126
93
  throw new NatsProjectorError({
127
94
  message: `Subject prefix "${prefix}" must be dot-separated [A-Za-z0-9_-] tokens`,
128
95
  });
129
96
  }
97
+ const transport = options.transport ?? natsConnectionTransport({ ...options, subjects: [streamSubject(prefix)] });
98
+ const limit = Math.min(transport.maxBatch ?? SERVER_BATCH_LIMIT, SERVER_BATCH_LIMIT);
99
+ const maxBatch = Math.min(options.maxBatch ?? limit, limit);
130
100
  if (!Number.isInteger(maxBatch) || maxBatch < 1) {
131
101
  throw new NatsProjectorError({ message: 'maxBatch must be a positive integer' });
132
102
  }
133
- const open = options.connect;
134
- const borrowed = options.connection;
135
- let opened;
136
- let live;
137
- let manager;
138
103
  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
104
  const init = () => {
190
- ready ??= Effect.runPromise(Effect.asVoid(ensureStream)).catch((cause) => {
105
+ ready ??= Effect.runPromise(transport.init?.() ?? Effect.void).catch((cause) => {
191
106
  ready = undefined;
192
107
  throw cause;
193
108
  });
194
109
  return ready;
195
110
  };
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) }));
111
+ /**
112
+ * The run's last message. `scope` is the run's attribute tokens when the caller knows them;
113
+ * without it the read matches the run under any attributes and learns them from the subject.
114
+ */
115
+ const readTail = (runId, scope) => Effect.gen(function* () {
116
+ const last = yield* transport.last(runSubjectFilter(prefix, runId, scope ?? anyAttributeTokens(names.length)));
199
117
  if (!last) {
200
- return { loomsSeq: 0, streamSeq: 0 };
118
+ return { loomsSeq: 0, streamSeq: 0, scope: undefined };
201
119
  }
202
- const loomsSeq = Number(last.header?.get(LoomsHeaders.seq));
120
+ const loomsSeq = Number(last.headers[LoomsHeaders.seq]);
203
121
  if (!Number.isSafeInteger(loomsSeq) || loomsSeq < 1) {
204
122
  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,
123
+ message: `Message ${last.streamSeq} on ${last.subject} has no ${LoomsHeaders.seq} header`,
241
124
  });
242
125
  }
243
- return response.seq;
126
+ return {
127
+ loomsSeq,
128
+ streamSeq: last.streamSeq,
129
+ scope: attributeTokensOf(last.subject, prefix, names.length),
130
+ };
244
131
  });
245
132
  const projectRun = (runId, events) => Effect.gen(function* () {
246
- const tail = yield* readTail(runId);
133
+ const tail = yield* readTail(runId, startedScope(names, events));
247
134
  const pending = yield* unpublished(runId, tail, events);
135
+ // What the stream already files the run under wins. A run it has never seen is filed by
136
+ // its started event, and by empty tokens when the batch does not hold one.
137
+ const scope = tail.scope ?? startedScope(names, events) ?? attributeTokens(names, undefined);
138
+ const filter = runSubjectFilter(prefix, runId, scope);
248
139
  let expected = tail.streamSeq;
249
140
  for (const batch of chunk(pending, maxBatch)) {
250
- expected = yield* publishBatch(runId, batch, expected);
141
+ expected = yield* transport.commit({
142
+ filter,
143
+ expected,
144
+ messages: batch.map((event) => outgoing(prefix, runId, scope, event)),
145
+ });
251
146
  }
252
147
  });
253
148
  return {
@@ -264,15 +159,8 @@ export function natsProjector(options) {
264
159
  })));
265
160
  },
266
161
  dispose: () => {
267
- const owned = opened;
268
- opened = undefined;
269
- live = undefined;
270
- manager = undefined;
271
162
  ready = undefined;
272
- if (!owned) {
273
- return Promise.resolve();
274
- }
275
- return owned.then((nc) => (nc.isClosed() ? undefined : nc.drain()), () => undefined);
163
+ return Effect.runPromise(transport.dispose?.() ?? Effect.void);
276
164
  },
277
165
  };
278
166
  }
@@ -9,6 +9,27 @@ export declare function encodeEventType(type: string): string;
9
9
  export declare function isValidSubjectPrefix(prefix: string): boolean;
10
10
  /** `<prefix>.run.>`: everything this projector publishes. */
11
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;
12
+ /**
13
+ * The tokens between `run` and the run id: one per name, in order, from the run's attributes.
14
+ * An attribute the run does not have is the empty token, `~`.
15
+ */
16
+ export declare function attributeTokens(names: readonly string[], attributes: {
17
+ readonly [key: string]: string;
18
+ } | undefined): readonly string[];
19
+ /**
20
+ * The attribute tokens of a subject this projector published, given how many it carries.
21
+ * `undefined` when the subject is not one of them.
22
+ */
23
+ export declare function attributeTokensOf(subject: string, prefix: string, count: number): readonly string[] | undefined;
24
+ /** `count` tokens that match any attribute: `*` for each. */
25
+ export declare function anyAttributeTokens(count: number): readonly string[];
26
+ /**
27
+ * One run's events, in the order they were published.
28
+ *
29
+ * `scope` is the run's attribute tokens: `<prefix>.run.<tokens>.<runId>.>`. With
30
+ * `anyAttributeTokens` it finds the run whatever its attributes: `<prefix>.run.*.*.<runId>.>`.
31
+ * With no attributes in the subject it is `<prefix>.run.<runId>.>`.
32
+ */
33
+ export declare function runSubjectFilter(prefix: string, runId: string, scope?: readonly string[]): string;
34
+ /** `<prefix>.run.<attribute tokens>.<runId>.<type tokens>`. */
35
+ export declare function eventSubject(prefix: string, runId: string, type: string, scope?: readonly string[]): string;
@@ -35,10 +35,41 @@ export function isValidSubjectPrefix(prefix) {
35
35
  export function streamSubject(prefix) {
36
36
  return `${prefix}.run.>`;
37
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)}.>`;
38
+ /**
39
+ * The tokens between `run` and the run id: one per name, in order, from the run's attributes.
40
+ * An attribute the run does not have is the empty token, `~`.
41
+ */
42
+ export function attributeTokens(names, attributes) {
43
+ return names.map((name) => encodeSubjectToken(attributes?.[name] ?? ''));
44
+ }
45
+ /**
46
+ * The attribute tokens of a subject this projector published, given how many it carries.
47
+ * `undefined` when the subject is not one of them.
48
+ */
49
+ export function attributeTokensOf(subject, prefix, count) {
50
+ const head = `${prefix}.run.`;
51
+ if (!subject.startsWith(head)) {
52
+ return undefined;
53
+ }
54
+ const tokens = subject.slice(head.length).split('.');
55
+ // The attributes, the run id, and at least one token of the event type.
56
+ return tokens.length >= count + 2 ? tokens.slice(0, count) : undefined;
57
+ }
58
+ /** `count` tokens that match any attribute: `*` for each. */
59
+ export function anyAttributeTokens(count) {
60
+ return Array.from({ length: count }, () => '*');
61
+ }
62
+ /**
63
+ * One run's events, in the order they were published.
64
+ *
65
+ * `scope` is the run's attribute tokens: `<prefix>.run.<tokens>.<runId>.>`. With
66
+ * `anyAttributeTokens` it finds the run whatever its attributes: `<prefix>.run.*.*.<runId>.>`.
67
+ * With no attributes in the subject it is `<prefix>.run.<runId>.>`.
68
+ */
69
+ export function runSubjectFilter(prefix, runId, scope = []) {
70
+ return [prefix, 'run', ...scope, encodeSubjectToken(runId), '>'].join('.');
41
71
  }
42
- export function eventSubject(prefix, runId, type) {
43
- return `${prefix}.run.${encodeSubjectToken(runId)}.${encodeEventType(type)}`;
72
+ /** `<prefix>.run.<attribute tokens>.<runId>.<type tokens>`. */
73
+ export function eventSubject(prefix, runId, type, scope = []) {
74
+ return [prefix, 'run', ...scope, encodeSubjectToken(runId), encodeEventType(type)].join('.');
44
75
  }
@@ -0,0 +1,101 @@
1
+ import type { StreamConfig } from '@nats-io/jetstream';
2
+ import type { NatsConnection } from '@nats-io/nats-core';
3
+ import { Effect } from 'effect';
4
+ /** The server refuses atomic batches over 1000 messages. */
5
+ export declare const SERVER_BATCH_LIMIT = 1000;
6
+ /** JetStream `err_code` for a failed `Nats-Expected-Last-Subject-Sequence` check. */
7
+ export declare const WRONG_LAST_SEQUENCE = 10071;
8
+ 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 & {
9
+ readonly _tag: "NatsProjectorError";
10
+ } & Readonly<A>;
11
+ export declare class NatsProjectorError extends NatsProjectorError_base<{
12
+ readonly message: string;
13
+ readonly cause?: unknown;
14
+ /** JetStream `err_code` when the server rejected the request. */
15
+ readonly errCode?: number;
16
+ }> {
17
+ }
18
+ /** A message the projector wants stored. `payload` is the JSON envelope as text. */
19
+ export interface NatsOutgoingMessage {
20
+ readonly subject: string;
21
+ readonly payload: string;
22
+ readonly headers: {
23
+ readonly [name: string]: string;
24
+ };
25
+ }
26
+ /** A message the stream holds. */
27
+ export interface NatsStoredMessage {
28
+ readonly subject: string;
29
+ /** The message's sequence in the stream. */
30
+ readonly streamSeq: number;
31
+ readonly headers: {
32
+ readonly [name: string]: string;
33
+ };
34
+ }
35
+ /** One run's events, to be stored whole or not at all. */
36
+ export interface NatsCommit {
37
+ /** Matches every subject of the run and no other run's. */
38
+ readonly filter: string;
39
+ /**
40
+ * Stream sequence of the last message on `filter`, 0 when it has none. A stream whose last
41
+ * message on `filter` is any other must refuse the commit with `WRONG_LAST_SEQUENCE`.
42
+ */
43
+ readonly expected: number;
44
+ /** In log order, never more than the transport's `maxBatch`, never empty. */
45
+ readonly messages: readonly NatsOutgoingMessage[];
46
+ }
47
+ /**
48
+ * How the projector reaches a stream. `natsConnectionTransport` speaks to NATS over a
49
+ * connection. A host that can't hold one, such as a Durable Object behind an HTTP bridge,
50
+ * supplies its own: the two operations are all the projector asks of a stream.
51
+ */
52
+ export interface NatsProjectorTransport {
53
+ /** The most messages one `commit` takes. At most 1000, which is also the default. */
54
+ readonly maxBatch?: number;
55
+ /** One-time setup. Runs before the first `last` or `commit`, and again after it fails. */
56
+ readonly init?: () => Effect.Effect<void, NatsProjectorError>;
57
+ /** The last message on `filter`, or `null` when the stream holds none. */
58
+ readonly last: (filter: string) => Effect.Effect<NatsStoredMessage | null, NatsProjectorError>;
59
+ /** Stores the batch atomically and returns the stream sequence of its last message. */
60
+ readonly commit: (batch: NatsCommit) => Effect.Effect<number, NatsProjectorError>;
61
+ readonly dispose?: () => Effect.Effect<void>;
62
+ }
63
+ /**
64
+ * Where the transport gets its connection. Use whichever NATS client fits the runtime:
65
+ * `@nats-io/transport-node`, `wsconnect`, and so on.
66
+ */
67
+ export type NatsConnectionSource = {
68
+ /** A connection the caller owns. The transport never closes it. */
69
+ readonly connection: NatsConnection;
70
+ readonly connect?: never;
71
+ } | {
72
+ /**
73
+ * Opens a connection the transport owns: called on first use, called again after the
74
+ * connection closes, and drained on `dispose`.
75
+ */
76
+ readonly connect: () => PromiseLike<NatsConnection>;
77
+ readonly connection?: never;
78
+ };
79
+ export interface NatsStreamSettings {
80
+ /** JetStream stream name. Defaults to `LOOMS`. */
81
+ readonly stream?: string;
82
+ /**
83
+ * Stream config used when `init` finds no stream. `name`, `subjects` and `allow_atomic` are
84
+ * always set by the transport. Pass `false` when the stream is managed elsewhere.
85
+ */
86
+ readonly createStream?: Partial<StreamConfig> | false;
87
+ /** Milliseconds to wait for a batch commit. Defaults to 5000. */
88
+ readonly timeoutMs?: number;
89
+ }
90
+ export type NatsConnectionTransportOptions = NatsConnectionSource & NatsStreamSettings & {
91
+ /** The subjects a stream made by `init` takes. */
92
+ readonly subjects: readonly string[];
93
+ };
94
+ /**
95
+ * The transport over a NATS connection. A commit is a JetStream atomic batch whose first
96
+ * message expects the run's last stream sequence, so the server refuses a concurrent writer.
97
+ *
98
+ * Requires nats-server 2.12 or newer (atomic batch publish).
99
+ */
100
+ export declare function natsConnectionTransport(options: NatsConnectionTransportOptions): NatsProjectorTransport;
101
+ export {};
@@ -0,0 +1,185 @@
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
+ /** The server refuses atomic batches over 1000 messages. */
5
+ export const SERVER_BATCH_LIMIT = 1000;
6
+ /** JetStream `err_code` for a failed `Nats-Expected-Last-Subject-Sequence` check. */
7
+ export const WRONG_LAST_SEQUENCE = 10071;
8
+ export class NatsProjectorError extends Data.TaggedError('NatsProjectorError') {
9
+ }
10
+ const CommitResponse = Schema.Union([
11
+ Schema.Struct({
12
+ error: Schema.Struct({
13
+ code: Schema.Finite,
14
+ err_code: Schema.optional(Schema.Finite),
15
+ description: Schema.String,
16
+ }),
17
+ }),
18
+ Schema.Struct({
19
+ stream: Schema.String,
20
+ seq: Schema.Finite,
21
+ }),
22
+ ]);
23
+ const decodeCommitResponse = Schema.decodeUnknownEffect(Schema.fromJsonString(CommitResponse));
24
+ const encoder = new TextEncoder();
25
+ function natsFailure(message) {
26
+ return (cause) => new NatsProjectorError({
27
+ message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,
28
+ cause,
29
+ errCode: cause instanceof JetStreamApiError ? cause.code : undefined,
30
+ });
31
+ }
32
+ function attempt(message, operation) {
33
+ return Effect.tryPromise({ try: () => Promise.resolve(operation()), catch: natsFailure(message) });
34
+ }
35
+ function wireMessage(message, batch) {
36
+ const header = headers();
37
+ header.set('Nats-Batch-Id', batch.batchId);
38
+ header.set('Nats-Batch-Sequence', String(batch.position));
39
+ // No Nats-Msg-Id: the run-sequence expectation already refuses duplicates, and message ids
40
+ // outlive a purge inside the dedup window, which would block refilling a reset stream.
41
+ for (const [name, value] of Object.entries(message.headers)) {
42
+ header.set(name, value);
43
+ }
44
+ if (batch.expected) {
45
+ header.set('Nats-Expected-Last-Subject-Sequence', String(batch.expected.sequence));
46
+ header.set('Nats-Expected-Last-Subject-Sequence-Subject', batch.expected.filter);
47
+ }
48
+ if (batch.commit) {
49
+ header.set('Nats-Batch-Commit', '1');
50
+ }
51
+ return { subject: message.subject, payload: encoder.encode(message.payload), headers: header };
52
+ }
53
+ /**
54
+ * The transport over a NATS connection. A commit is a JetStream atomic batch whose first
55
+ * message expects the run's last stream sequence, so the server refuses a concurrent writer.
56
+ *
57
+ * Requires nats-server 2.12 or newer (atomic batch publish).
58
+ */
59
+ export function natsConnectionTransport(options) {
60
+ const stream = options.stream ?? 'LOOMS';
61
+ const timeout = options.timeoutMs ?? 5_000;
62
+ const open = options.connect;
63
+ const borrowed = options.connection;
64
+ let opened;
65
+ let live;
66
+ let manager;
67
+ const connection = Effect.suspend(() => {
68
+ if (!open) {
69
+ return borrowed
70
+ ? Effect.succeed(borrowed)
71
+ : Effect.fail(new NatsProjectorError({ message: 'Pass `connection` or `connect`' }));
72
+ }
73
+ return attempt('NATS connect failed', () => {
74
+ if (live?.isClosed()) {
75
+ live = undefined;
76
+ opened = undefined;
77
+ }
78
+ opened ??= Promise.resolve(open()).then((nc) => {
79
+ live = nc;
80
+ return nc;
81
+ }, (cause) => {
82
+ opened = undefined;
83
+ throw cause;
84
+ });
85
+ return opened;
86
+ });
87
+ });
88
+ const jsm = connection.pipe(Effect.flatMap((nc) => {
89
+ if (manager?.connection === nc) {
90
+ return Effect.succeed(manager.jsm);
91
+ }
92
+ return attempt('JetStream unavailable', () => jetstreamManager(nc)).pipe(Effect.tap((created) => Effect.sync(() => {
93
+ manager = { connection: nc, jsm: created };
94
+ })));
95
+ }));
96
+ const init = Effect.gen(function* () {
97
+ const streams = (yield* jsm).streams;
98
+ const info = yield* attempt(`Reading stream ${stream} failed`, () => streams.info(stream)).pipe(Effect.catchIf((error) => error.errCode === JetStreamApiCodes.StreamNotFound, () => Effect.succeed(null)));
99
+ if (info?.config.allow_atomic === true) {
100
+ return info;
101
+ }
102
+ if (info) {
103
+ return yield* new NatsProjectorError({
104
+ message: `Stream ${stream} must set allow_atomic: true for the Looms NATS projector`,
105
+ });
106
+ }
107
+ if (options.createStream === false) {
108
+ return yield* new NatsProjectorError({ message: `Stream ${stream} does not exist` });
109
+ }
110
+ return yield* attempt(`Creating stream ${stream} failed`, () => streams.add({
111
+ ...options.createStream,
112
+ name: stream,
113
+ subjects: [...options.subjects],
114
+ allow_atomic: true,
115
+ }));
116
+ });
117
+ const last = (filter) => Effect.gen(function* () {
118
+ const streams = (yield* jsm).streams;
119
+ const message = yield* attempt(`Reading the last message on ${filter} failed`, () => streams.getMessage(stream, { last_by_subj: filter }));
120
+ if (!message) {
121
+ return null;
122
+ }
123
+ const stored = {};
124
+ for (const name of message.header.keys()) {
125
+ stored[name] = message.header.get(name);
126
+ }
127
+ return {
128
+ subject: message.subject,
129
+ streamSeq: message.seq,
130
+ headers: stored,
131
+ };
132
+ });
133
+ const commit = (batch) => Effect.gen(function* () {
134
+ const nc = yield* connection;
135
+ const batchId = nuid.next();
136
+ const final = yield* Effect.try({
137
+ try: () => {
138
+ const messages = batch.messages.map((message, index) => wireMessage(message, {
139
+ batchId,
140
+ position: index + 1,
141
+ expected: index === 0 ? { filter: batch.filter, sequence: batch.expected } : undefined,
142
+ commit: index === batch.messages.length - 1,
143
+ }));
144
+ for (const message of messages.slice(0, -1)) {
145
+ nc.publish(message.subject, message.payload, { headers: message.headers });
146
+ }
147
+ return messages.at(-1);
148
+ },
149
+ catch: natsFailure(`Publishing on ${batch.filter} failed`),
150
+ });
151
+ if (!final) {
152
+ return batch.expected;
153
+ }
154
+ const reply = yield* attempt(`Committing the batch on ${batch.filter} failed`, () => nc.request(final.subject, final.payload, { headers: final.headers, timeout }));
155
+ const response = yield* decodeCommitResponse(reply.string()).pipe(Effect.mapError(natsFailure(`Unreadable commit reply on ${batch.filter}`)));
156
+ if ('error' in response) {
157
+ const errCode = response.error.err_code;
158
+ const conflict = errCode === WRONG_LAST_SEQUENCE;
159
+ return yield* new NatsProjectorError({
160
+ message: conflict
161
+ ? `Another writer published on ${batch.filter} first (${response.error.description})`
162
+ : `JetStream refused the batch on ${batch.filter}: ${response.error.description}`,
163
+ errCode,
164
+ });
165
+ }
166
+ return response.seq;
167
+ });
168
+ const dispose = Effect.promise(() => {
169
+ const owned = opened;
170
+ opened = undefined;
171
+ live = undefined;
172
+ manager = undefined;
173
+ if (!owned) {
174
+ return Promise.resolve();
175
+ }
176
+ return owned.then((nc) => (nc.isClosed() ? undefined : nc.drain()), () => undefined);
177
+ });
178
+ return {
179
+ maxBatch: SERVER_BATCH_LIMIT,
180
+ init: () => Effect.asVoid(init),
181
+ last,
182
+ commit,
183
+ dispose: () => dispose,
184
+ };
185
+ }