foldkit-sync 0.14.0 → 0.16.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.
Files changed (49) hide show
  1. package/README.md +558 -40
  2. package/dist/diagnostics.d.ts +74 -3
  3. package/dist/diagnostics.d.ts.map +1 -1
  4. package/dist/diagnostics.js +60 -4
  5. package/dist/diagnostics.js.map +1 -1
  6. package/dist/do.d.ts +49 -7
  7. package/dist/do.d.ts.map +1 -1
  8. package/dist/do.js +91 -8
  9. package/dist/do.js.map +1 -1
  10. package/dist/errors.d.ts +92 -1
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +87 -1
  13. package/dist/errors.js.map +1 -1
  14. package/dist/index.d.ts +9 -5
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +6 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/journal.d.ts +52 -27
  19. package/dist/journal.d.ts.map +1 -1
  20. package/dist/journal.js +176 -64
  21. package/dist/journal.js.map +1 -1
  22. package/dist/make.d.ts +48 -17
  23. package/dist/make.d.ts.map +1 -1
  24. package/dist/make.js +11 -4
  25. package/dist/make.js.map +1 -1
  26. package/dist/migrations.d.ts +37 -0
  27. package/dist/migrations.d.ts.map +1 -0
  28. package/dist/migrations.js +56 -0
  29. package/dist/migrations.js.map +1 -0
  30. package/dist/mount.d.ts +1 -1
  31. package/dist/mount.d.ts.map +1 -1
  32. package/dist/mount.js +12 -6
  33. package/dist/mount.js.map +1 -1
  34. package/dist/refusal.d.ts +33 -0
  35. package/dist/refusal.d.ts.map +1 -0
  36. package/dist/refusal.js +47 -0
  37. package/dist/refusal.js.map +1 -0
  38. package/dist/serverJournal.d.ts +143 -0
  39. package/dist/serverJournal.d.ts.map +1 -0
  40. package/dist/serverJournal.js +503 -0
  41. package/dist/serverJournal.js.map +1 -0
  42. package/dist/sync.d.ts +132 -11
  43. package/dist/sync.d.ts.map +1 -1
  44. package/dist/sync.js +273 -64
  45. package/dist/sync.js.map +1 -1
  46. package/dist/transport.d.ts +5 -5
  47. package/dist/transport.d.ts.map +1 -1
  48. package/dist/transport.js.map +1 -1
  49. package/package.json +11 -8
@@ -0,0 +1,503 @@
1
+ import { Cause, Clock, Duration, Effect, Option, Predicate, Queue, Result, Schema, Semaphore, Stream } from "effect";
2
+ import { Cursor, DocumentId, InvalidOperationError, JournalError, OpId } from "foldkit-durable/core";
3
+ import { reactionFailed, reactionParked, reactionSkipped, reportTo } from "./diagnostics.js";
4
+ import { SERVER_REPLICA_PREFIX, writtenEnvelope } from "./sync.js";
5
+ import { AmbiguousMessageError, ServerKeyReusedError, StaleParkedRunError, UnreadableMessageError, UnsupportedMessageVersionError } from "./errors.js";
6
+ // src/serverJournal.ts
7
+ /**
8
+ * The server's own side of a document: Messages only it appends, and
9
+ * reactions, the work that runs after a commit. Both commit through the
10
+ * journal's `append` as the server's principal, so the journal's `validate`
11
+ * and `authorize` judge them like any operation.
12
+ *
13
+ * A reaction's cursor and its parked runs live in `foldkit-durable`
14
+ * (`journal.cursors`), beside the effect ledger, which records each run's
15
+ * answer and whether its appends finished. The cursor is a lower bound over
16
+ * the ledger: set back (to the floor, say), it costs ledger reads, never a
17
+ * second external call. A cursor row that is lost altogether is not that:
18
+ * `react` reports it and does nothing until `serverJournal` registers the
19
+ * reaction again, at the journal's cursor then, skipping what came between.
20
+ * An external call still runs at least once, never exactly once: a crash
21
+ * between the call and the ledger's write runs it again, with the same key.
22
+ */
23
+ /** The longest key `appendAsServer` takes. */
24
+ const MAX_KEY = 200;
25
+ /** The most Messages one run may append. */
26
+ const MAX_APPENDS = 16;
27
+ /** How many committed operations a reaction reads at once. */
28
+ const PAGE = 100;
29
+ /** A failing reaction waits from this, doubling, up to the cap, in ms. */
30
+ const BACKOFF_BASE = 500;
31
+ const BACKOFF_MAX = 3e4;
32
+ /** How long a pass waits after the journal itself failed, which counts toward no bound. */
33
+ const JOURNAL_RETRY = Duration.seconds(5);
34
+ const REACTION_NAME = /^[A-Za-z0-9_-]{1,64}$/;
35
+ /** Each reaction's handler and bounds, kept off the value so nothing else can call it. */
36
+ const handlers = /* @__PURE__ */ new WeakMap();
37
+ const tagOf = (message) => Predicate.hasProperty(message, "_tag") && typeof message._tag === "string" ? Option.some(message._tag) : Option.none();
38
+ const tagsOf = (constructors) => new Set(constructors.flatMap((constructor) => {
39
+ const literal = constructor.fields?._tag?.ast?.literal;
40
+ return typeof literal === "string" ? [literal] : [];
41
+ }));
42
+ /**
43
+ * Declares a reaction of a contract from `Sync.forApplication(App).make`:
44
+ * after each committed Message in `on`, in journal order, `run` is called
45
+ * once at least, and what it answers is appended as the server. A handler
46
+ * that keeps failing is parked after `attempts` failures over `parkAfter`;
47
+ * one whose answer can never commit is parked at once. Throws for a name
48
+ * that is not one, or a set of another application or outside the contract.
49
+ */
50
+ const reaction = (sync, options) => {
51
+ const { name } = options;
52
+ if (!REACTION_NAME.test(name)) throw new Error(`Sync.reaction: "${name}" is not a reaction name (letters, digits, _ and -, at most 64)`);
53
+ const owner = sync.contract.owner;
54
+ if (options.on.owner !== owner || options.appends !== void 0 && options.appends.owner !== owner) throw new Error(`Sync.reaction: ${name} names Messages of another application`);
55
+ const durable = tagsOf(sync.messages);
56
+ const server = tagsOf(sync.serverOnlyMessages);
57
+ const on = tagsOf(options.on.constructors);
58
+ const appends = tagsOf(options.appends?.constructors ?? []);
59
+ for (const tag of on) if (!durable.has(tag) && !server.has(tag)) throw new Error(`Sync.reaction: ${name} runs on "${tag}", which never commits`);
60
+ for (const tag of appends) if (!server.has(tag)) throw new Error(`Sync.reaction: ${name} appends "${tag}", which is not server-only`);
61
+ const attempts = options.attempts ?? 8;
62
+ if (!Number.isSafeInteger(attempts) || attempts < 1) throw new Error(`Sync.reaction: ${name}'s attempts must be a positive integer`);
63
+ const made = {
64
+ sync,
65
+ name,
66
+ on,
67
+ appends
68
+ };
69
+ handlers.set(made, {
70
+ run: options.run,
71
+ timeout: Duration.fromInputUnsafe(options.timeout ?? "10 seconds"),
72
+ attempts,
73
+ parkAfter: Duration.fromInputUnsafe(options.parkAfter ?? "1 hour")
74
+ });
75
+ return made;
76
+ };
77
+ /** Canonical JSON with sorted object keys: what two Messages are compared by. */
78
+ const canonical = (value) => JSON.stringify(value, (_, inner) => inner !== null && typeof inner === "object" && !Array.isArray(inner) ? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : inner);
79
+ const sha256 = (text) => Effect.promise(() => crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))).pipe(Effect.map((digest) => Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")));
80
+ /** Why a run failed: its answer can never commit, or it may on another try. */
81
+ var RunFailed = class extends Schema.TaggedError()("SyncRunFailed", {
82
+ permanent: Schema.Boolean,
83
+ reason: Schema.String
84
+ }) {
85
+ get message() {
86
+ return this.reason;
87
+ }
88
+ };
89
+ const cut = (words) => words.length <= 500 ? words : `${words.slice(0, 499)}…`;
90
+ /** A handler's own failure, defect or interruption, in words: a run that may succeed again. */
91
+ const handlerFailed = (cause) => new RunFailed({
92
+ permanent: false,
93
+ reason: cut(Option.match(Cause.findErrorOption(cause), {
94
+ onSome: (error) => Cause.isTimeoutError(error) ? "The handler timed out" : error instanceof Error ? error.message : String(error),
95
+ onNone: () => Cause.pretty(cause).split("\n")[0] ?? "The handler failed"
96
+ }))
97
+ });
98
+ /**
99
+ * An append the journal refused: the same refusal every time, except a
100
+ * Message written at a version newer than this build, which a deploy fixes.
101
+ */
102
+ const appendFailed = (error) => new RunFailed({
103
+ permanent: !(error._tag === "InvalidOperationError" && error.cause instanceof UnsupportedMessageVersionError),
104
+ reason: cut(error.message)
105
+ });
106
+ const RecordedAnswer = Schema.Struct({
107
+ messageVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),
108
+ messages: Schema.Array(Schema.Unknown)
109
+ });
110
+ const decodeAnswer = Schema.decodeUnknownEffect(RecordedAnswer, { onExcessProperty: "error" });
111
+ const ParkedInput = Schema.Struct({
112
+ operation: Schema.Unknown,
113
+ actorId: Schema.NonEmptyString
114
+ });
115
+ const decodeParkedInput = Schema.decodeUnknownEffect(ParkedInput, { onExcessProperty: "error" });
116
+ /** Each reaction appends what reaction feeds; a cycle among them is refused. */
117
+ const checkAcyclic = (reactions) => {
118
+ const visiting = /* @__PURE__ */ new Set();
119
+ const done = /* @__PURE__ */ new Set();
120
+ const visit = (from) => {
121
+ if (done.has(from)) return;
122
+ if (visiting.has(from)) throw new Error(`Sync.serverJournal: reaction ${from.name} is in a cycle`);
123
+ visiting.add(from);
124
+ for (const to of reactions) if ([...from.appends].some((tag) => to.on.has(tag))) visit(to);
125
+ visiting.delete(from);
126
+ done.add(from);
127
+ };
128
+ for (const each of reactions) visit(each);
129
+ };
130
+ /**
131
+ * The server's side of one document: `appendAsServer`, and the declared
132
+ * reactions with what runs them. Registers each reaction's cursor at the
133
+ * journal's current cursor before it answers, so make it before the journal
134
+ * serves its first exchange: a reaction sees every commit made after this.
135
+ * Throws for a reaction of another contract, two of one name, or a cycle.
136
+ */
137
+ const serverJournal = (options) => {
138
+ const sync = options.sync;
139
+ const { journal, server } = options;
140
+ const reactions = options.reactions ?? [];
141
+ const names = /* @__PURE__ */ new Set();
142
+ for (const each of reactions) {
143
+ if (each.sync !== options.sync) throw new Error(`Sync.serverJournal: reaction ${each.name} was declared for another contract`);
144
+ if (names.has(each.name)) throw new Error(`Sync.serverJournal: two reactions are named ${each.name}`);
145
+ names.add(each.name);
146
+ }
147
+ checkAcyclic(reactions);
148
+ const runsPerPass = options.runsPerPass ?? Number.MAX_SAFE_INTEGER;
149
+ if (!Number.isSafeInteger(runsPerPass) || runsPerPass < 1) throw new Error("Sync.serverJournal: runsPerPass must be a positive integer");
150
+ const documentId = String(sync.documentId);
151
+ const key = DocumentId.make(documentId);
152
+ const contract = sync.journalContract();
153
+ const decodeMessage = Schema.decodeUnknownSync(sync.codec.message, { onExcessProperty: "error" });
154
+ const encodeMessage = Schema.encodeSync(sync.codec.message);
155
+ const report = (diagnostic) => reportTo(options.diagnostics, diagnostic);
156
+ const cursorName = (reaction) => `react/${reaction.name}`;
157
+ const handlerOf = (reaction) => handlers.get(reaction);
158
+ /** An operation of the server's, written at `version`, as only Sync writes one. */
159
+ const envelope = (replicaId, localSequence, baseCursor, message, version) => writtenEnvelope({
160
+ protocolVersion: 1,
161
+ schemaVersion: 1,
162
+ documentId,
163
+ replicaId,
164
+ localSequence,
165
+ opId: `${replicaId}:${localSequence}`,
166
+ baseCursor,
167
+ message,
168
+ ...version === 1 ? {} : { messageVersion: version }
169
+ });
170
+ const invalid = (message, cause) => new InvalidOperationError({
171
+ message,
172
+ ...cause === void 0 ? {} : { cause }
173
+ });
174
+ const appendAsServer = (message, { key: fact }) => Effect.gen(function* () {
175
+ if (fact.length === 0 || fact.length > MAX_KEY) return yield* invalid("A server key is a non-empty string of at most 200 characters");
176
+ if (!sync.serverOnly(message)) return yield* invalid("appendAsServer takes a Message only the server appends");
177
+ const encoded = yield* Effect.try({
178
+ try: () => encodeMessage(message),
179
+ catch: (cause) => invalid("The Message does not encode", cause)
180
+ });
181
+ const replicaId = `${SERVER_REPLICA_PREFIX}k/${yield* sha256(fact)}`;
182
+ const written = envelope(replicaId, 1, 0, encoded, sync.codec.messageVersion);
183
+ const recorded = yield* journal.runEffect(canonical([
184
+ "server",
185
+ documentId,
186
+ fact
187
+ ]), Effect.succeed(written)).pipe(Effect.catchTag("EffectFailedError", (error) => Effect.fail(new JournalError({
188
+ message: error.message,
189
+ cause: error
190
+ }))));
191
+ if (!(canonical(recorded) === canonical(written) || Result.match(Result.try(() => contract.operation.decode(recorded)), {
192
+ onFailure: () => false,
193
+ onSuccess: (operation) => canonical(operation.message) === canonical(encoded)
194
+ }))) return yield* new ServerKeyReusedError({ key: fact });
195
+ const kept = yield* Effect.try({
196
+ try: () => writtenEnvelope(recorded),
197
+ catch: (cause) => new JournalError({
198
+ message: "Could not read a recorded operation",
199
+ cause
200
+ })
201
+ });
202
+ return yield* journal.append(key, kept, server).pipe(Effect.tapErrorTag("OperationRejectedError", () => forget(fact)), Effect.tapErrorTag("InvalidOperationError", () => forget(fact)));
203
+ });
204
+ const forget = (fact) => journal.clearEffect(canonical([
205
+ "server",
206
+ documentId,
207
+ fact
208
+ ])).pipe(Effect.ignore);
209
+ /** The run of one reaction on one committed operation: its answer, then its appends. */
210
+ const runOnce = (reaction, epoch, committed) => Effect.gen(function* () {
211
+ const handler = handlerOf(reaction);
212
+ const { opId, sequence } = committed;
213
+ const services = yield* Effect.context();
214
+ const triggerKey = yield* sha256(canonical([
215
+ "react",
216
+ documentId,
217
+ reaction.name,
218
+ opId
219
+ ]));
220
+ const answer = Effect.suspend(() => handler.run({
221
+ message: committed.message,
222
+ opId,
223
+ sequence,
224
+ actorId: committed.actorId,
225
+ key: triggerKey
226
+ })).pipe(Effect.timeout(handler.timeout), Effect.provideContext(services), Effect.sandbox, Effect.mapError(handlerFailed), Effect.flatMap((returned) => Effect.gen(function* () {
227
+ const messages = returned ?? [];
228
+ if (!Array.isArray(messages)) return yield* new RunFailed({
229
+ permanent: true,
230
+ reason: "The answer is not a list"
231
+ });
232
+ if (messages.length > MAX_APPENDS) return yield* new RunFailed({
233
+ permanent: true,
234
+ reason: `The answer holds ${messages.length} Messages, past ${MAX_APPENDS}`
235
+ });
236
+ const encoded = yield* Effect.forEach(messages, (message) => Option.match(Option.filter(tagOf(message), (tag) => reaction.appends.has(tag)), {
237
+ onNone: () => Effect.fail(new RunFailed({
238
+ permanent: true,
239
+ reason: "The answer holds a Message its appends do not name"
240
+ })),
241
+ onSome: () => Effect.try({
242
+ try: () => encodeMessage(message),
243
+ catch: () => new RunFailed({
244
+ permanent: true,
245
+ reason: "The answer does not encode"
246
+ })
247
+ })
248
+ }));
249
+ return {
250
+ messageVersion: sync.codec.messageVersion,
251
+ messages: encoded
252
+ };
253
+ })));
254
+ const replyOf = `${SERVER_REPLICA_PREFIX}r/${reaction.name}/${yield* sha256(opId)}`;
255
+ const appendAll = Effect.gen(function* () {
256
+ const recorded = yield* journal.runEffect(canonical([
257
+ "react",
258
+ documentId,
259
+ reaction.name,
260
+ opId,
261
+ "answer"
262
+ ]), answer).pipe(Effect.flatMap(decodeAnswer), Effect.mapError(asRunFailure));
263
+ for (const [index, message] of recorded.messages.entries()) yield* journal.append(key, envelope(`${replyOf}/${index}`, 1, sequence, message, recorded.messageVersion), server).pipe(Effect.catchTags({
264
+ InvalidOperationError: (error) => Effect.fail(appendFailed(error)),
265
+ OperationRejectedError: (error) => Effect.fail(appendFailed(error)),
266
+ IdentityConflictError: (error) => Effect.fail(appendFailed(error))
267
+ }));
268
+ });
269
+ yield* journal.runEffect(canonical([
270
+ "react",
271
+ documentId,
272
+ reaction.name,
273
+ opId,
274
+ "finished",
275
+ epoch
276
+ ]), appendAll).pipe(Effect.mapError(asRunFailure));
277
+ });
278
+ /** The pass of one reaction: from its cursor, a page, unless its backoff has not elapsed. */
279
+ const passOf = (reaction, budget) => Effect.gen(function* () {
280
+ const name = cursorName(reaction);
281
+ const handler = handlerOf(reaction);
282
+ const tracked = yield* journal.cursors.settled(key, name);
283
+ if (Option.isNone(tracked)) return yield* Effect.die(/* @__PURE__ */ new Error(`Sync.serverJournal: reaction ${reaction.name} was never registered`));
284
+ const { epoch, cursor, attempts, failedAt, firstFailedAt } = tracked.value;
285
+ const now = yield* Clock.currentTimeMillis;
286
+ const wait = Option.match(failedAt, {
287
+ onNone: () => 0,
288
+ onSome: (at) => at + backoff(attempts) - now
289
+ });
290
+ if (attempts > 0 && wait > 0) return {
291
+ runs: 0,
292
+ next: Option.some(Duration.millis(wait))
293
+ };
294
+ let failed = {
295
+ attempts,
296
+ since: firstFailedAt
297
+ };
298
+ const stall = (runs, cause, at) => Effect.gen(function* () {
299
+ yield* journal.cursors.stalled(key, name, epoch, now);
300
+ yield* report(reactionFailed(documentId, reaction.name, at, cut(cause)));
301
+ return {
302
+ runs,
303
+ next: Option.some(Duration.millis(backoff(failed.attempts + 1)))
304
+ };
305
+ });
306
+ const page = yield* Effect.result(journal.read(key, cursor, { limit: PAGE }));
307
+ if (Result.isFailure(page)) {
308
+ const failure = page.failure;
309
+ if (failure._tag === "CompactedCursorError") {
310
+ yield* report(reactionSkipped(documentId, reaction.name, cursor, failure.floor));
311
+ yield* journal.cursors.advance(key, name, epoch, Cursor.make(failure.floor));
312
+ return {
313
+ runs: 0,
314
+ next: Option.some(Duration.zero)
315
+ };
316
+ }
317
+ if (failure._tag === "JournalError" && !unreadable(failure.cause)) return yield* failure;
318
+ return yield* stall(0, failure.message, Option.none());
319
+ }
320
+ let at = cursor;
321
+ let runs = 0;
322
+ const reach = (sequence) => {
323
+ at = Cursor.make(sequence);
324
+ failed = {
325
+ attempts: 0,
326
+ since: Option.none()
327
+ };
328
+ };
329
+ const moved = () => at > cursor ? journal.cursors.advance(key, name, epoch, at) : Effect.void;
330
+ for (const committed of page.success) {
331
+ const message = decodeMessage(committed.operation.message);
332
+ if (!Option.exists(tagOf(message), (tag) => reaction.on.has(tag))) {
333
+ reach(committed.sequence);
334
+ continue;
335
+ }
336
+ if (runs >= budget) {
337
+ yield* moved();
338
+ return {
339
+ runs,
340
+ next: Option.some(Duration.zero)
341
+ };
342
+ }
343
+ runs += 1;
344
+ const outcome = yield* Effect.result(runOnce(reaction, epoch, {
345
+ opId: committed.opId,
346
+ sequence: committed.sequence,
347
+ actorId: committed.actorId,
348
+ message
349
+ }));
350
+ if (Result.isSuccess(outcome)) {
351
+ reach(committed.sequence);
352
+ continue;
353
+ }
354
+ const failure = outcome.failure;
355
+ if (failure._tag === "JournalError") {
356
+ yield* moved();
357
+ return yield* failure;
358
+ }
359
+ const tried = failed.attempts + 1;
360
+ const since = Option.getOrElse(failed.since, () => now);
361
+ const parks = failure.permanent || tried >= handler.attempts && now - since >= Duration.toMillis(handler.parkAfter);
362
+ const place = {
363
+ opId: committed.opId,
364
+ sequence: committed.sequence
365
+ };
366
+ if (!parks) {
367
+ yield* moved();
368
+ return yield* stall(runs, failure.reason, Option.some(place));
369
+ }
370
+ yield* journal.cursors.park(key, {
371
+ name,
372
+ opId: committed.opId,
373
+ epoch,
374
+ sequence: committed.sequence,
375
+ input: {
376
+ operation: contract.operation.encode(committed.operation),
377
+ actorId: committed.actorId
378
+ },
379
+ error: failure.reason
380
+ });
381
+ yield* report(reactionParked(documentId, reaction.name, committed.opId, committed.sequence, failure.reason));
382
+ reach(committed.sequence);
383
+ }
384
+ yield* moved();
385
+ return {
386
+ runs,
387
+ next: page.success.length === PAGE ? Option.some(Duration.zero) : Option.none()
388
+ };
389
+ });
390
+ const earliest = (a, b) => Option.isNone(a) ? b : Option.isNone(b) ? a : Option.some(Duration.min(a.value, b.value));
391
+ let first = 0;
392
+ const passes = Semaphore.makeUnsafe(1);
393
+ const react = Effect.gen(function* () {
394
+ let budget = runsPerPass;
395
+ let next = Option.none();
396
+ const order = reactions.map((_, at) => reactions[(first + at) % reactions.length]);
397
+ first = reactions.length === 0 ? 0 : (first + 1) % reactions.length;
398
+ for (const [at, each] of order.entries()) {
399
+ const share = Math.ceil(budget / (order.length - at));
400
+ if (share <= 0) return Option.some(Duration.zero);
401
+ const pass = yield* passOf(each, share).pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.failCause(cause) : report(reactionFailed(documentId, each.name, Option.none(), cut(Option.match(Cause.findErrorOption(cause), {
402
+ onSome: (error) => error.message,
403
+ onNone: () => Cause.pretty(cause).split("\n")[0] ?? "The pass broke"
404
+ })))).pipe(Effect.as({
405
+ runs: 0,
406
+ next: Option.some(JOURNAL_RETRY)
407
+ }))));
408
+ budget -= pass.runs;
409
+ next = earliest(next, pass.next);
410
+ }
411
+ return next;
412
+ }).pipe(passes.withPermits(1));
413
+ const follow = Effect.gen(function* () {
414
+ const wake = yield* Queue.sliding(1);
415
+ yield* Effect.forkChild(Stream.runForEach(Stream.filter(journal.subscribe, (changed) => changed === documentId), () => Queue.offer(wake, void 0)), { startImmediately: true });
416
+ while (true) {
417
+ const next = yield* react;
418
+ yield* Option.match(next, {
419
+ onNone: () => Queue.take(wake),
420
+ onSome: (delay) => Effect.raceFirst(Queue.take(wake), Effect.sleep(delay))
421
+ });
422
+ }
423
+ });
424
+ const settledThrough = Effect.gen(function* () {
425
+ let lowest = yield* journal.cursor(key);
426
+ for (const each of reactions) {
427
+ const tracked = yield* journal.cursors.settled(key, cursorName(each));
428
+ const at = Option.match(tracked, {
429
+ onNone: () => Cursor.make(0),
430
+ onSome: (t) => t.cursor
431
+ });
432
+ if (at < lowest) lowest = at;
433
+ }
434
+ return lowest;
435
+ });
436
+ const reactionOf = (name) => Option.fromUndefinedOr(reactions.find((each) => cursorName(each) === name));
437
+ const parked = Effect.gen(function* () {
438
+ const epoch = yield* journal.epoch(key);
439
+ return (yield* journal.cursors.parked(key)).flatMap((row) => row.name.startsWith("react/") ? [{
440
+ reaction: row.name.slice(6),
441
+ opId: row.opId,
442
+ sequence: row.sequence,
443
+ error: row.error,
444
+ stale: row.epoch !== epoch
445
+ }] : []);
446
+ });
447
+ const retry = (which) => Effect.gen(function* () {
448
+ const name = `react/${which.reaction}`;
449
+ const epoch = yield* journal.epoch(key);
450
+ const row = (yield* journal.cursors.parked(key)).find((each) => each.name === name && each.opId === which.opId);
451
+ if (row === void 0) return;
452
+ if (row.epoch !== epoch) return yield* new StaleParkedRunError({
453
+ reaction: which.reaction,
454
+ opId: which.opId
455
+ });
456
+ const declared = reactionOf(name);
457
+ if (Option.isNone(declared)) return yield* Effect.fail(/* @__PURE__ */ new Error(`Reaction ${which.reaction} is not declared on this journal`));
458
+ const trigger = yield* parkedTrigger(row);
459
+ yield* runOnce(declared.value, epoch, trigger);
460
+ yield* journal.cursors.unpark(key, name, row.opId);
461
+ });
462
+ const parkedTrigger = (row) => Effect.gen(function* () {
463
+ const input = yield* decodeParkedInput(row.input);
464
+ const operation = yield* Effect.try({
465
+ try: () => contract.operation.decode(input.operation),
466
+ catch: (cause) => new JournalError({
467
+ message: "Could not read a parked run",
468
+ cause
469
+ })
470
+ });
471
+ return {
472
+ opId: row.opId,
473
+ sequence: row.sequence,
474
+ actorId: input.actorId,
475
+ message: decodeMessage(operation.message)
476
+ };
477
+ });
478
+ const dismiss = (which) => journal.cursors.unpark(key, `react/${which.reaction}`, OpId.make(which.opId));
479
+ return Effect.gen(function* () {
480
+ for (const each of reactions) yield* journal.cursors.track(key, cursorName(each));
481
+ return {
482
+ appendAsServer,
483
+ react,
484
+ follow,
485
+ settledThrough,
486
+ parked,
487
+ retry,
488
+ dismiss
489
+ };
490
+ });
491
+ };
492
+ /** Whether the journal failed because a stored Message will not read, not because the store did. */
493
+ const unreadable = (cause) => cause instanceof UnreadableMessageError || cause instanceof UnsupportedMessageVersionError || cause instanceof AmbiguousMessageError;
494
+ /** How long a reaction that has failed `attempts` times waits: 0.5 s doubling to 30 s. */
495
+ const backoff = (attempts) => attempts === 0 ? 0 : Math.min(BACKOFF_MAX, BACKOFF_BASE * 2 ** Math.min(attempts - 1, 16));
496
+ /** A failure of the ledger's record, or of the answer it holds, as the run's. */
497
+ const asRunFailure = (error) => error instanceof RunFailed || error instanceof JournalError ? error : new RunFailed({
498
+ permanent: false,
499
+ reason: cut(error instanceof Error ? error.message : String(error))
500
+ });
501
+ export { reaction, serverJournal };
502
+
503
+ //# sourceMappingURL=serverJournal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverJournal.js","names":["JournalDocumentId"],"sources":["../src/serverJournal.ts"],"sourcesContent":["/**\n * The server's own side of a document: Messages only it appends, and\n * reactions, the work that runs after a commit. Both commit through the\n * journal's `append` as the server's principal, so the journal's `validate`\n * and `authorize` judge them like any operation.\n *\n * A reaction's cursor and its parked runs live in `foldkit-durable`\n * (`journal.cursors`), beside the effect ledger, which records each run's\n * answer and whether its appends finished. The cursor is a lower bound over\n * the ledger: set back (to the floor, say), it costs ledger reads, never a\n * second external call. A cursor row that is lost altogether is not that:\n * `react` reports it and does nothing until `serverJournal` registers the\n * reaction again, at the journal's cursor then, skipping what came between.\n * An external call still runs at least once, never exactly once: a crash\n * between the call and the ledger's write runs it again, with the same key.\n */\nimport {\n Cause,\n Clock,\n Duration,\n Effect,\n Option,\n Predicate,\n Queue,\n Result,\n Schema,\n Semaphore,\n Stream,\n} from 'effect'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n InvalidOperationError,\n JournalError,\n OpId,\n type AppendError,\n type AppendResult,\n type Journal,\n type ParkedRun,\n} from 'foldkit-durable/core'\nimport type { MessageSet, ReportDiagnostic } from 'foldkit-surface'\nimport {\n reactionFailed,\n reactionParked,\n reactionSkipped,\n reportTo,\n type SyncDiagnostic,\n} from './diagnostics.js'\nimport {\n AmbiguousMessageError,\n ServerKeyReusedError,\n StaleParkedRunError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n} from './errors.js'\nimport type { DefinedSync, MsgOf, ServerMsgOf } from './make.js'\nimport {\n SERVER_REPLICA_PREFIX,\n writtenEnvelope,\n type Operation,\n type WrittenOperation,\n} from './sync.js'\n\n/** The longest key `appendAsServer` takes. */\nconst MAX_KEY = 200\n/** The most Messages one run may append. */\nconst MAX_APPENDS = 16\n/** How many committed operations a reaction reads at once. */\nconst PAGE = 100\n/** A failing reaction waits from this, doubling, up to the cap, in ms. */\nconst BACKOFF_BASE = 500\nconst BACKOFF_MAX = 30_000\n/** How long a pass waits after the journal itself failed, which counts toward no bound. */\nconst JOURNAL_RETRY = Duration.seconds(5)\nconst REACTION_NAME = /^[A-Za-z0-9_-]{1,64}$/\n\n/** A committed operation, as a reaction is given it. */\nexport interface Trigger<Message> {\n /** The Message at the current version, as every hook sees it. */\n readonly message: Message\n readonly opId: string\n readonly sequence: number\n /** Who committed it: a person's actor, or the server's. */\n readonly actorId: string\n /**\n * 64 hex characters naming this run, the same on every retry and across\n * restarts: give it to the provider as its idempotency key.\n */\n readonly key: string\n}\n\n/**\n * One declared reaction of one document: what it runs on, what it may\n * append, and what its handler needs. Made by `reaction`, given to\n * `serverJournal`.\n */\nexport interface Reaction<Document, out R = never> {\n /** The contract it was declared for: `serverJournal` refuses it for another. */\n readonly sync: Document\n readonly name: string\n /** The tags it runs on. */\n readonly on: ReadonlySet<string>\n /** The tags it may append. */\n readonly appends: ReadonlySet<string>\n /** The services its handler needs; never present. */\n readonly requires?: () => R\n}\n\ninterface Handler {\n readonly run: (\n trigger: Trigger<unknown>,\n ) => Effect.Effect<ReadonlyArray<unknown> | void, unknown, unknown>\n readonly timeout: Duration.Duration\n readonly attempts: number\n readonly parkAfter: Duration.Duration\n}\n\n/** Each reaction's handler and bounds, kept off the value so nothing else can call it. */\nconst handlers = new WeakMap<Reaction<unknown, unknown>, Handler>()\n\ntype AnySync = DefinedSync<any, any, any, any, any, any, any>\n\nconst tagOf = (message: unknown): Option.Option<string> =>\n Predicate.hasProperty(message, '_tag') && typeof message._tag === 'string'\n ? Option.some(message._tag)\n : Option.none()\n\nconst tagsOf = (constructors: ReadonlyArray<unknown>): ReadonlySet<string> =>\n new Set(\n constructors.flatMap(constructor => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } })\n .fields?._tag?.ast?.literal\n return typeof literal === 'string' ? [literal] : []\n }),\n )\n\nexport interface ReactionOptions<AppModel, On, Appends, R> {\n /** Part of every run's key, so renaming it is a new reaction. Letters, digits, `_` and `-`, at most 64; unique in the document. */\n readonly name: string\n /** The committed Messages it runs after: a set of the contract's own application. */\n readonly on: MessageSet<AppModel, any, On, any>\n /** The server-only Messages it may append, checked on every answer. Without it, it appends nothing. */\n readonly appends?: MessageSet<AppModel, any, Appends, any>\n /** How long one run may take before it counts as failed. Default 10 seconds. */\n readonly timeout?: Duration.Input\n /** A failing run is parked once it has failed this many times, and for at least `parkAfter`. Default 8. */\n readonly attempts?: number\n /** How long a run must have been failing before it may be parked, so an outage parks nothing. Default one hour. */\n readonly parkAfter?: Duration.Input\n /**\n * One external call, or none, and the Messages to append, at most 16. It may\n * run again with the same trigger: pass `trigger.key` to the provider.\n */\n readonly run: (\n trigger: Trigger<On>,\n ) => Effect.Effect<ReadonlyArray<NoInfer<Appends>> | void, unknown, R>\n}\n\n/**\n * Declares a reaction of a contract from `Sync.forApplication(App).make`:\n * after each committed Message in `on`, in journal order, `run` is called\n * once at least, and what it answers is appended as the server. A handler\n * that keeps failing is parked after `attempts` failures over `parkAfter`;\n * one whose answer can never commit is parked at once. Throws for a name\n * that is not one, or a set of another application or outside the contract.\n */\nexport const reaction = <\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n ContractPrincipal,\n Authorized extends boolean,\n SMs extends readonly unknown[],\n On extends MsgOf<Ms> | ServerMsgOf<SMs>,\n Appends extends ServerMsgOf<SMs> = never,\n R = never,\n>(\n sync: DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n options: ReactionOptions<AppModel, On, Appends, R>,\n): Reaction<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, R> => {\n const { name } = options\n if (!REACTION_NAME.test(name))\n throw new Error(\n `Sync.reaction: \"${name}\" is not a reaction name (letters, digits, _ and -, at most 64)`,\n )\n const owner = sync.contract.owner\n if (\n options.on.owner !== owner ||\n (options.appends !== undefined && options.appends.owner !== owner)\n )\n throw new Error(`Sync.reaction: ${name} names Messages of another application`)\n const durable = tagsOf(sync.messages)\n const server = tagsOf(sync.serverOnlyMessages)\n const on = tagsOf(options.on.constructors)\n const appends = tagsOf(options.appends?.constructors ?? [])\n for (const tag of on)\n if (!durable.has(tag) && !server.has(tag))\n throw new Error(`Sync.reaction: ${name} runs on \"${tag}\", which never commits`)\n for (const tag of appends)\n if (!server.has(tag))\n throw new Error(`Sync.reaction: ${name} appends \"${tag}\", which is not server-only`)\n const attempts = options.attempts ?? 8\n if (!Number.isSafeInteger(attempts) || attempts < 1)\n throw new Error(`Sync.reaction: ${name}'s attempts must be a positive integer`)\n const made: Reaction<\n DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n R\n > = { sync, name, on, appends }\n handlers.set(made, {\n run: options.run as Handler['run'],\n timeout: Duration.fromInputUnsafe(options.timeout ?? '10 seconds'),\n attempts,\n parkAfter: Duration.fromInputUnsafe(options.parkAfter ?? '1 hour'),\n })\n return made\n}\n\n/** A run set aside: it failed for good, or too often. Its reaction went on without it. */\nexport interface Parked {\n readonly reaction: string\n readonly opId: string\n readonly sequence: number\n /** Why, as the last failure said it. */\n readonly error: string\n /** Parked in a history since reset: it can be dismissed, not run again. */\n readonly stale: boolean\n}\n\nexport interface ServerJournal<ServerOnly, R> {\n /**\n * Appends a server-only Message as the server. `key` names the fact (a\n * webhook event's id, `absorbed/<through>`): a repeat with the same key and\n * Message is answered from history, and one with another Message fails with\n * `ServerKeyReusedError`. A key is a non-empty string of at most 200\n * characters; another is an `InvalidOperationError`.\n */\n readonly appendAsServer: (\n message: ServerOnly,\n options: { readonly key: string },\n ) => Effect.Effect<AppendResult<Operation>, AppendError | ServerKeyReusedError>\n /**\n * Runs every reaction from its stored cursor, a page at a time. Never\n * fails: a failed run is reported, and the answer is how long to wait\n * before running again; none when every reaction has caught up. Safe to\n * call at any time, from anywhere in this process: passes of one\n * `serverJournal` run one at a time. Two instances over one store (two\n * isolates over one D1) do not wait for each other.\n */\n readonly react: Effect.Effect<Option.Option<Duration.Duration>, never, R>\n /**\n * Runs `react` now, after every commit to the document this journal\n * instance hears of, and after the delay `react` answers, until\n * interrupted: a long-lived process's loop. Fork it.\n */\n readonly follow: Effect.Effect<never, never, R>\n /** The lowest cursor of the declared reactions: compact no further than this. */\n readonly settledThrough: Effect.Effect<Cursor, JournalError>\n /** The runs set aside, for a person to look at. */\n readonly parked: Effect.Effect<ReadonlyArray<Parked>, JournalError>\n /**\n * Runs a parked run again, out of order; it leaves the list when it\n * succeeds, and stays, failing, when it does not. A recorded answer is\n * reused, so a refused append retried after the rule changed makes no\n * second external call. A stale one fails with `StaleParkedRunError`.\n */\n readonly retry: (parked: Parked) => Effect.Effect<void, unknown, R>\n /** Forgets a parked run: its reaction never happens. */\n readonly dismiss: (parked: Parked) => Effect.Effect<void, JournalError>\n}\n\n/** The services a list of reactions needs: none for none. */\nexport type Requires<Reactions extends ReadonlyArray<Reaction<any, any>>> = [\n Reactions[number],\n] extends [never]\n ? never\n : Reactions[number] extends Reaction<any, infer R>\n ? R\n : never\n\nexport interface ServerJournalOptions<Document, Principal, Shared, Reactions> {\n readonly sync: Document\n readonly journal: Journal<Operation, Shared, Principal, WrittenOperation>\n /**\n * Who the server commits as. Never resolved from a request, and best never\n * changed: the journal binds each `server/` replica id to the first actor\n * that commits from it. After a change of `actorId`, a reaction's append for\n * a new trigger and a new `appendAsServer` key commit as the new actor; a\n * redelivered key is an `IdentityConflictError`, and a run retried after\n * its first append committed under the old actor parks.\n */\n readonly server: Principal\n readonly reactions?: Reactions\n /** The most runs one `react` starts, over every reaction; a host with a time limit sets it low. */\n readonly runsPerPass?: number\n /** Where reactions' failures, parks and skips go; the reporter in context when not given. */\n readonly diagnostics?: ReportDiagnostic | undefined\n}\n\n/** Canonical JSON with sorted object keys: what two Messages are compared by. */\nconst canonical = (value: unknown): string =>\n JSON.stringify(value, (_, inner: unknown) =>\n inner !== null && typeof inner === 'object' && !Array.isArray(inner)\n ? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : inner,\n )\n\nconst sha256 = (text: string): Effect.Effect<string> =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest =>\n Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(''),\n ),\n )\n\n/** Why a run failed: its answer can never commit, or it may on another try. */\nclass RunFailed extends Schema.TaggedError<RunFailed>()('SyncRunFailed', {\n permanent: Schema.Boolean,\n reason: Schema.String,\n}) {\n override get message(): string {\n return this.reason\n }\n}\n\nconst cut = (words: string): string => (words.length <= 500 ? words : `${words.slice(0, 499)}…`)\n\n/** A handler's own failure, defect or interruption, in words: a run that may succeed again. */\nconst handlerFailed = (cause: Cause.Cause<unknown>): RunFailed =>\n new RunFailed({\n permanent: false,\n reason: cut(\n Option.match(Cause.findErrorOption(cause), {\n onSome: error =>\n Cause.isTimeoutError(error)\n ? 'The handler timed out'\n : error instanceof Error\n ? error.message\n : String(error),\n onNone: () => Cause.pretty(cause).split('\\n')[0] ?? 'The handler failed',\n }),\n ),\n })\n\n/**\n * An append the journal refused: the same refusal every time, except a\n * Message written at a version newer than this build, which a deploy fixes.\n */\nconst appendFailed = (error: Exclude<AppendError, JournalError>): RunFailed =>\n new RunFailed({\n permanent: !(\n error._tag === 'InvalidOperationError' &&\n error.cause instanceof UnsupportedMessageVersionError\n ),\n reason: cut(error.message),\n })\n\nconst RecordedAnswer = Schema.Struct({\n messageVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n messages: Schema.Array(Schema.Unknown),\n})\nconst decodeAnswer = Schema.decodeUnknownEffect(RecordedAnswer, { onExcessProperty: 'error' })\nconst ParkedInput = Schema.Struct({ operation: Schema.Unknown, actorId: Schema.NonEmptyString })\nconst decodeParkedInput = Schema.decodeUnknownEffect(ParkedInput, { onExcessProperty: 'error' })\n\n/** Each reaction appends what reaction feeds; a cycle among them is refused. */\nconst checkAcyclic = (reactions: ReadonlyArray<Reaction<unknown, unknown>>): void => {\n const visiting = new Set<Reaction<unknown, unknown>>()\n const done = new Set<Reaction<unknown, unknown>>()\n const visit = (from: Reaction<unknown, unknown>): void => {\n if (done.has(from)) return\n if (visiting.has(from))\n throw new Error(`Sync.serverJournal: reaction ${from.name} is in a cycle`)\n visiting.add(from)\n for (const to of reactions) if ([...from.appends].some(tag => to.on.has(tag))) visit(to)\n visiting.delete(from)\n done.add(from)\n }\n for (const each of reactions) visit(each)\n}\n\n/**\n * The server's side of one document: `appendAsServer`, and the declared\n * reactions with what runs them. Registers each reaction's cursor at the\n * journal's current cursor before it answers, so make it before the journal\n * serves its first exchange: a reaction sees every commit made after this.\n * Throws for a reaction of another contract, two of one name, or a cycle.\n */\nexport const serverJournal = <\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n ContractPrincipal,\n Authorized extends boolean,\n SMs extends readonly unknown[],\n Principal,\n const Reactions extends ReadonlyArray<\n Reaction<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, any>\n > = [],\n>(\n options: ServerJournalOptions<\n DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n Principal,\n Schema.Struct.Type<Fields>,\n Reactions\n >,\n): Effect.Effect<ServerJournal<ServerMsgOf<SMs>, Requires<Reactions>>, JournalError> => {\n type R = Requires<Reactions>\n const sync: AnySync = options.sync\n const { journal, server } = options\n const reactions: ReadonlyArray<Reaction<unknown, unknown>> = options.reactions ?? []\n const names = new Set<string>()\n for (const each of reactions) {\n if (each.sync !== options.sync)\n throw new Error(`Sync.serverJournal: reaction ${each.name} was declared for another contract`)\n if (names.has(each.name))\n throw new Error(`Sync.serverJournal: two reactions are named ${each.name}`)\n names.add(each.name)\n }\n checkAcyclic(reactions)\n const runsPerPass = options.runsPerPass ?? Number.MAX_SAFE_INTEGER\n if (!Number.isSafeInteger(runsPerPass) || runsPerPass < 1)\n throw new Error('Sync.serverJournal: runsPerPass must be a positive integer')\n\n const documentId = String(sync.documentId)\n const key = JournalDocumentId.make(documentId)\n const contract = sync.journalContract()\n const decodeMessage = Schema.decodeUnknownSync(sync.codec.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(sync.codec.message)\n const report = (diagnostic: SyncDiagnostic) => reportTo(options.diagnostics, diagnostic)\n const cursorName = (reaction: Reaction<unknown, unknown>) => `react/${reaction.name}`\n const handlerOf = (reaction: Reaction<unknown, unknown>): Handler => handlers.get(reaction)!\n\n /** An operation of the server's, written at `version`, as only Sync writes one. */\n const envelope = (\n replicaId: string,\n localSequence: number,\n baseCursor: number,\n message: unknown,\n version: number,\n ): WrittenOperation =>\n writtenEnvelope({\n protocolVersion: 1,\n schemaVersion: 1,\n documentId,\n replicaId,\n localSequence,\n opId: `${replicaId}:${localSequence}`,\n baseCursor,\n message,\n ...(version === 1 ? {} : { messageVersion: version }),\n })\n\n const invalid = (message: string, cause?: unknown) =>\n new InvalidOperationError({ message, ...(cause === undefined ? {} : { cause }) })\n\n const appendAsServer = (message: ServerMsgOf<SMs>, { key: fact }: { readonly key: string }) =>\n Effect.gen(function* () {\n if (fact.length === 0 || fact.length > MAX_KEY)\n return yield* invalid('A server key is a non-empty string of at most 200 characters')\n if (!sync.serverOnly(message))\n return yield* invalid('appendAsServer takes a Message only the server appends')\n const encoded = yield* Effect.try({\n try: () => encodeMessage(message),\n catch: cause => invalid('The Message does not encode', cause),\n })\n const replicaId = `${SERVER_REPLICA_PREFIX}k/${yield* sha256(fact)}`\n const written = envelope(replicaId, 1, 0, encoded, sync.codec.messageVersion)\n // Recorded before it is appended, so a repeat after a deploy that added\n // a step appends the bytes first written, which the journal compares.\n const recorded = yield* journal\n .runEffect(canonical(['server', documentId, fact]), Effect.succeed(written))\n .pipe(\n Effect.catchTag('EffectFailedError', error =>\n Effect.fail(new JournalError({ message: error.message, cause: error })),\n ),\n )\n const same =\n canonical(recorded) === canonical(written) ||\n Result.match(\n Result.try(() => contract.operation.decode(recorded)),\n {\n onFailure: () => false,\n onSuccess: operation => canonical(operation.message) === canonical(encoded),\n },\n )\n if (!same) return yield* new ServerKeyReusedError({ key: fact })\n // A record that is no envelope is the store's fault, as a row that will not read is.\n const kept = yield* Effect.try({\n try: () => writtenEnvelope(recorded),\n catch: cause => new JournalError({ message: 'Could not read a recorded operation', cause }),\n })\n return yield* journal.append(key, kept, server).pipe(\n // Refused, nothing committed: the key is free again for a Message the\n // rules take. A conflict keeps it, since the id is taken.\n Effect.tapErrorTag('OperationRejectedError', () => forget(fact)),\n Effect.tapErrorTag('InvalidOperationError', () => forget(fact)),\n )\n })\n\n const forget = (fact: string) =>\n journal.clearEffect(canonical(['server', documentId, fact])).pipe(Effect.ignore)\n\n /** The run of one reaction on one committed operation: its answer, then its appends. */\n const runOnce = (\n reaction: Reaction<unknown, unknown>,\n epoch: string,\n committed: {\n readonly opId: string\n readonly sequence: number\n readonly actorId: string\n readonly message: unknown\n },\n ): Effect.Effect<void, RunFailed | JournalError, unknown> =>\n Effect.gen(function* () {\n const handler = handlerOf(reaction)\n const { opId, sequence } = committed\n // The ledger runs what it is given with no services: the handler's are this run's.\n const services = yield* Effect.context<unknown>()\n const triggerKey = yield* sha256(canonical(['react', documentId, reaction.name, opId]))\n const answer = Effect.suspend(() =>\n handler.run({\n message: committed.message,\n opId,\n sequence,\n actorId: committed.actorId,\n key: triggerKey,\n }),\n ).pipe(\n Effect.timeout(handler.timeout),\n Effect.provideContext(services),\n // A defect or an interruption is a failure the ledger records: its\n // `tapError` sees neither, and the record would stay pending.\n Effect.sandbox,\n Effect.mapError(handlerFailed),\n Effect.flatMap(returned =>\n Effect.gen(function* () {\n const messages: ReadonlyArray<unknown> = returned ?? []\n if (!Array.isArray(messages))\n return yield* new RunFailed({ permanent: true, reason: 'The answer is not a list' })\n if (messages.length > MAX_APPENDS)\n return yield* new RunFailed({\n permanent: true,\n reason: `The answer holds ${messages.length} Messages, past ${MAX_APPENDS}`,\n })\n const encoded = yield* Effect.forEach(messages, message =>\n Option.match(\n Option.filter(tagOf(message), tag => reaction.appends.has(tag)),\n {\n onNone: () =>\n Effect.fail(\n new RunFailed({\n permanent: true,\n reason: 'The answer holds a Message its appends do not name',\n }),\n ),\n onSome: () =>\n Effect.try({\n try: () => encodeMessage(message),\n catch: () =>\n new RunFailed({ permanent: true, reason: 'The answer does not encode' }),\n }),\n },\n ),\n )\n return { messageVersion: sync.codec.messageVersion, messages: encoded }\n }),\n ),\n )\n // Named by the trigger's id, never its place: sequences start again\n // after a reset, and a reaction running on this one's append keys its\n // answer by that append's id.\n const replyOf = `${SERVER_REPLICA_PREFIX}r/${reaction.name}/${yield* sha256(opId)}`\n const appendAll = Effect.gen(function* () {\n const recorded = yield* journal\n .runEffect(canonical(['react', documentId, reaction.name, opId, 'answer']), answer)\n .pipe(Effect.flatMap(decodeAnswer), Effect.mapError(asRunFailure))\n for (const [index, message] of recorded.messages.entries())\n yield* journal\n .append(\n key,\n envelope(`${replyOf}/${index}`, 1, sequence, message, recorded.messageVersion),\n server,\n )\n .pipe(\n Effect.catchTags({\n InvalidOperationError: error => Effect.fail(appendFailed(error)),\n OperationRejectedError: error => Effect.fail(appendFailed(error)),\n IdentityConflictError: error => Effect.fail(appendFailed(error)),\n }),\n )\n })\n // The epoch is in this key and not the answer's: after a reset the\n // appends run again in the new history, and the answer is reused.\n yield* journal\n .runEffect(\n canonical(['react', documentId, reaction.name, opId, 'finished', epoch]),\n appendAll,\n )\n .pipe(Effect.mapError(asRunFailure))\n })\n\n /** The pass of one reaction: from its cursor, a page, unless its backoff has not elapsed. */\n const passOf = (\n reaction: Reaction<unknown, unknown>,\n budget: number,\n ): Effect.Effect<\n { readonly runs: number; readonly next: Option.Option<Duration.Duration> },\n JournalError,\n unknown\n > =>\n Effect.gen(function* () {\n const name = cursorName(reaction)\n const handler = handlerOf(reaction)\n const tracked = yield* journal.cursors.settled(key, name)\n if (Option.isNone(tracked))\n return yield* Effect.die(\n new Error(`Sync.serverJournal: reaction ${reaction.name} was never registered`),\n )\n const { epoch, cursor, attempts, failedAt, firstFailedAt } = tracked.value\n const now = yield* Clock.currentTimeMillis\n const wait = Option.match(failedAt, {\n onNone: () => 0,\n onSome: at => at + backoff(attempts) - now,\n })\n if (attempts > 0 && wait > 0) return { runs: 0, next: Option.some(Duration.millis(wait)) }\n // The stored failures are the commit after the cursor's; once the pass\n // moves past it, a failure further on is that commit's first.\n let failed = { attempts, since: firstFailedAt }\n const stall = (\n runs: number,\n cause: string,\n at: Option.Option<{ opId: string; sequence: number }>,\n ) =>\n Effect.gen(function* () {\n yield* journal.cursors.stalled(key, name, epoch, now)\n yield* report(reactionFailed(documentId, reaction.name, at, cut(cause)))\n return { runs, next: Option.some(Duration.millis(backoff(failed.attempts + 1))) }\n })\n const page = yield* Effect.result(journal.read(key, cursor, { limit: PAGE }))\n if (Result.isFailure(page)) {\n const failure = page.failure\n if (failure._tag === 'CompactedCursorError') {\n yield* report(reactionSkipped(documentId, reaction.name, cursor, failure.floor))\n yield* journal.cursors.advance(key, name, epoch, Cursor.make(failure.floor))\n return { runs: 0, next: Option.some(Duration.zero) }\n }\n // A commit that will not read: no operation can be named, so nothing\n // parks, and the reaction waits on its backoff for a build that reads it.\n if (failure._tag === 'JournalError' && !unreadable(failure.cause)) return yield* failure\n return yield* stall(0, failure.message, Option.none())\n }\n let at = cursor\n let runs = 0\n const reach = (sequence: number) => {\n at = Cursor.make(sequence)\n failed = { attempts: 0, since: Option.none() }\n }\n const moved = () =>\n at > cursor ? journal.cursors.advance(key, name, epoch, at) : Effect.void\n for (const committed of page.success) {\n const message = decodeMessage(committed.operation.message)\n if (!Option.exists(tagOf(message), tag => reaction.on.has(tag))) {\n reach(committed.sequence)\n continue\n }\n if (runs >= budget) {\n yield* moved()\n return { runs, next: Option.some(Duration.zero) }\n }\n runs += 1\n const outcome = yield* Effect.result(\n runOnce(reaction, epoch, {\n opId: committed.opId,\n sequence: committed.sequence,\n actorId: committed.actorId,\n message,\n }),\n )\n if (Result.isSuccess(outcome)) {\n reach(committed.sequence)\n continue\n }\n const failure = outcome.failure\n // The store failing is not the run's fault: it counts toward nothing.\n if (failure._tag === 'JournalError') {\n yield* moved()\n return yield* failure\n }\n const tried = failed.attempts + 1\n const since = Option.getOrElse(failed.since, () => now)\n const parks =\n failure.permanent ||\n (tried >= handler.attempts && now - since >= Duration.toMillis(handler.parkAfter))\n const place = { opId: committed.opId, sequence: committed.sequence }\n if (!parks) {\n yield* moved()\n return yield* stall(runs, failure.reason, Option.some(place))\n }\n // Parked first: a crash before the cursor moves runs it once more,\n // and the second park changes nothing.\n yield* journal.cursors.park(key, {\n name,\n opId: committed.opId,\n epoch,\n sequence: committed.sequence,\n input: {\n operation: contract.operation.encode(committed.operation),\n actorId: committed.actorId,\n },\n error: failure.reason,\n })\n yield* report(\n reactionParked(\n documentId,\n reaction.name,\n committed.opId,\n committed.sequence,\n failure.reason,\n ),\n )\n reach(committed.sequence)\n }\n yield* moved()\n return {\n runs,\n next: page.success.length === PAGE ? Option.some(Duration.zero) : Option.none(),\n }\n })\n\n const earliest = (\n a: Option.Option<Duration.Duration>,\n b: Option.Option<Duration.Duration>,\n ): Option.Option<Duration.Duration> =>\n Option.isNone(a) ? b : Option.isNone(b) ? a : Option.some(Duration.min(a.value, b.value))\n\n // Which reaction a pass starts with, turning each pass, so a share's\n // rounding favours no reaction for good.\n let first = 0\n // One pass at a time: two at once would count each failure twice and reach\n // the attempts bound in half the failures.\n const passes = Semaphore.makeUnsafe(1)\n const react = Effect.gen(function* () {\n let budget = runsPerPass\n let next = Option.none<Duration.Duration>()\n const order = reactions.map((_, at) => reactions[(first + at) % reactions.length]!)\n first = reactions.length === 0 ? 0 : (first + 1) % reactions.length\n for (const [at, each] of order.entries()) {\n // A fair share of what is left, so a busy reaction cannot starve the rest.\n const share = Math.ceil(budget / (order.length - at))\n if (share <= 0) return Option.some(Duration.zero)\n const pass = yield* passOf(each, share).pipe(\n Effect.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : report(\n reactionFailed(\n documentId,\n each.name,\n Option.none(),\n cut(\n Option.match(Cause.findErrorOption(cause), {\n onSome: error => error.message,\n onNone: () => Cause.pretty(cause).split('\\n')[0] ?? 'The pass broke',\n }),\n ),\n ),\n ).pipe(Effect.as({ runs: 0, next: Option.some(JOURNAL_RETRY) })),\n ),\n )\n budget -= pass.runs\n next = earliest(next, pass.next)\n }\n return next\n }).pipe(passes.withPermits(1)) as Effect.Effect<Option.Option<Duration.Duration>, never, R>\n\n const follow = Effect.gen(function* () {\n // One pending wake-up is enough: a pass reads everything after the cursor.\n const wake = yield* Queue.sliding<void>(1)\n yield* Effect.forkChild(\n Stream.runForEach(\n Stream.filter(journal.subscribe, changed => changed === documentId),\n () => Queue.offer(wake, undefined),\n ),\n { startImmediately: true },\n )\n while (true) {\n const next = yield* react\n yield* Option.match(next, {\n onNone: () => Queue.take(wake),\n onSome: delay => Effect.raceFirst(Queue.take(wake), Effect.sleep(delay)),\n })\n }\n }) as Effect.Effect<never, never, R>\n\n const settledThrough = Effect.gen(function* () {\n let lowest = yield* journal.cursor(key)\n for (const each of reactions) {\n const tracked = yield* journal.cursors.settled(key, cursorName(each))\n const at = Option.match(tracked, { onNone: () => Cursor.make(0), onSome: t => t.cursor })\n if (at < lowest) lowest = at\n }\n return lowest\n })\n\n const reactionOf = (name: string): Option.Option<Reaction<unknown, unknown>> =>\n Option.fromUndefinedOr(reactions.find(each => cursorName(each) === name))\n\n const parked = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n const rows = yield* journal.cursors.parked(key)\n return rows.flatMap((row): ReadonlyArray<Parked> =>\n row.name.startsWith('react/')\n ? [\n {\n reaction: row.name.slice('react/'.length),\n opId: row.opId,\n sequence: row.sequence,\n error: row.error,\n stale: row.epoch !== epoch,\n },\n ]\n : [],\n )\n })\n\n const retry = (which: Parked) =>\n Effect.gen(function* () {\n const name = `react/${which.reaction}`\n const epoch = yield* journal.epoch(key)\n const rows = yield* journal.cursors.parked(key)\n const row = rows.find(each => each.name === name && each.opId === which.opId)\n // Already resolved: nothing to do.\n if (row === undefined) return\n if (row.epoch !== epoch)\n return yield* new StaleParkedRunError({ reaction: which.reaction, opId: which.opId })\n const declared = reactionOf(name)\n if (Option.isNone(declared))\n return yield* Effect.fail(\n new Error(`Reaction ${which.reaction} is not declared on this journal`),\n )\n const trigger = yield* parkedTrigger(row)\n yield* runOnce(declared.value, epoch, trigger)\n yield* journal.cursors.unpark(key, name, row.opId)\n }) as Effect.Effect<void, unknown, R>\n\n const parkedTrigger = (row: ParkedRun) =>\n Effect.gen(function* () {\n const input = yield* decodeParkedInput(row.input)\n const operation = yield* Effect.try({\n try: () => contract.operation.decode(input.operation),\n catch: cause => new JournalError({ message: 'Could not read a parked run', cause }),\n })\n return {\n opId: row.opId,\n sequence: row.sequence,\n actorId: input.actorId,\n message: decodeMessage(operation.message),\n }\n })\n\n const dismiss = (which: Parked) =>\n journal.cursors.unpark(key, `react/${which.reaction}`, OpId.make(which.opId))\n\n return Effect.gen(function* () {\n for (const each of reactions) yield* journal.cursors.track(key, cursorName(each))\n return {\n appendAsServer,\n react,\n follow,\n settledThrough,\n parked,\n retry,\n dismiss,\n } satisfies ServerJournal<ServerMsgOf<SMs>, R>\n })\n}\n\n/** Whether the journal failed because a stored Message will not read, not because the store did. */\nconst unreadable = (cause: unknown): boolean =>\n cause instanceof UnreadableMessageError ||\n cause instanceof UnsupportedMessageVersionError ||\n cause instanceof AmbiguousMessageError\n\n/** How long a reaction that has failed `attempts` times waits: 0.5 s doubling to 30 s. */\nconst backoff = (attempts: number): number =>\n attempts === 0 ? 0 : Math.min(BACKOFF_MAX, BACKOFF_BASE * 2 ** Math.min(attempts - 1, 16))\n\n/** A failure of the ledger's record, or of the answer it holds, as the run's. */\nconst asRunFailure = (error: unknown): RunFailed | JournalError =>\n error instanceof RunFailed || error instanceof JournalError\n ? error\n : new RunFailed({\n permanent: false,\n reason: cut(error instanceof Error ? error.message : String(error)),\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,UAAU;;AAEhB,MAAM,cAAc;;AAEpB,MAAM,OAAO;;AAEb,MAAM,eAAe;AACrB,MAAM,cAAc;;AAEpB,MAAM,gBAAgB,SAAS,QAAQ,CAAC;AACxC,MAAM,gBAAgB;;AA4CtB,MAAM,2BAAW,IAAI,QAA6C;AAIlE,MAAM,SAAS,YACb,UAAU,YAAY,SAAS,MAAM,KAAK,OAAO,QAAQ,SAAS,WAC9D,OAAO,KAAK,QAAQ,IAAI,IACxB,OAAO,KAAK;AAElB,MAAM,UAAU,iBACd,IAAI,IACF,aAAa,SAAQ,gBAAe;CAClC,MAAM,UAAW,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