foldkit-sync 0.12.4 → 0.13.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 (82) hide show
  1. package/README.md +76 -24
  2. package/dist/diagnostics.d.ts +71 -0
  3. package/dist/diagnostics.d.ts.map +1 -0
  4. package/dist/diagnostics.js +67 -0
  5. package/dist/diagnostics.js.map +1 -0
  6. package/dist/{do.d.mts → do.d.ts} +12 -2
  7. package/dist/do.d.ts.map +1 -0
  8. package/dist/{do.mjs → do.js} +15 -9
  9. package/dist/do.js.map +1 -0
  10. package/dist/{entity.d.mts → entity.d.ts} +1 -1
  11. package/dist/entity.d.ts.map +1 -0
  12. package/dist/{entity.mjs → entity.js} +1 -1
  13. package/dist/entity.js.map +1 -0
  14. package/dist/errors.d.ts +91 -0
  15. package/dist/errors.d.ts.map +1 -0
  16. package/dist/errors.js +75 -0
  17. package/dist/errors.js.map +1 -0
  18. package/dist/ids.d.ts +30 -0
  19. package/dist/ids.d.ts.map +1 -0
  20. package/dist/ids.js +28 -0
  21. package/dist/ids.js.map +1 -0
  22. package/dist/index.d.ts +106 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +77 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/indexedDb.d.ts +62 -0
  27. package/dist/indexedDb.d.ts.map +1 -0
  28. package/dist/indexedDb.js +128 -0
  29. package/dist/indexedDb.js.map +1 -0
  30. package/dist/{journal.d.mts → journal.d.ts} +29 -5
  31. package/dist/journal.d.ts.map +1 -0
  32. package/dist/{journal-D5h-jqXE.mjs → journal.js} +43 -32
  33. package/dist/journal.js.map +1 -0
  34. package/dist/lww.d.ts +76 -0
  35. package/dist/lww.d.ts.map +1 -0
  36. package/dist/lww.js +121 -0
  37. package/dist/lww.js.map +1 -0
  38. package/dist/make.d.ts +162 -0
  39. package/dist/make.d.ts.map +1 -0
  40. package/dist/make.js +153 -0
  41. package/dist/make.js.map +1 -0
  42. package/dist/mount.d.ts +138 -0
  43. package/dist/mount.d.ts.map +1 -0
  44. package/dist/mount.js +344 -0
  45. package/dist/mount.js.map +1 -0
  46. package/dist/presence.d.ts +116 -0
  47. package/dist/presence.d.ts.map +1 -0
  48. package/dist/presence.js +277 -0
  49. package/dist/presence.js.map +1 -0
  50. package/dist/{remote.d.mts → remote.d.ts} +2 -2
  51. package/dist/remote.d.ts.map +1 -0
  52. package/dist/{remote.mjs → remote.js} +1 -1
  53. package/dist/remote.js.map +1 -0
  54. package/dist/revalidate.d.ts +6 -0
  55. package/dist/revalidate.d.ts.map +1 -0
  56. package/dist/revalidate.js +10 -0
  57. package/dist/revalidate.js.map +1 -0
  58. package/dist/sync.d.ts +276 -0
  59. package/dist/sync.d.ts.map +1 -0
  60. package/dist/sync.js +512 -0
  61. package/dist/sync.js.map +1 -0
  62. package/dist/transport.d.ts +151 -0
  63. package/dist/transport.d.ts.map +1 -0
  64. package/dist/{transport-BZ6utYmB.mjs → transport.js} +20 -30
  65. package/dist/transport.js.map +1 -0
  66. package/package.json +24 -24
  67. package/dist/do.d.mts.map +0 -1
  68. package/dist/do.mjs.map +0 -1
  69. package/dist/entity.d.mts.map +0 -1
  70. package/dist/entity.mjs.map +0 -1
  71. package/dist/index.d.mts +0 -397
  72. package/dist/index.d.mts.map +0 -1
  73. package/dist/index.mjs +0 -1613
  74. package/dist/index.mjs.map +0 -1
  75. package/dist/journal-D5h-jqXE.mjs.map +0 -1
  76. package/dist/journal.d.mts.map +0 -1
  77. package/dist/journal.mjs +0 -1
  78. package/dist/make-DJ0Q1SSc.d.mts +0 -702
  79. package/dist/make-DJ0Q1SSc.d.mts.map +0 -1
  80. package/dist/remote.d.mts.map +0 -1
  81. package/dist/remote.mjs.map +0 -1
  82. package/dist/transport-BZ6utYmB.mjs.map +0 -1
@@ -1,5 +1,9 @@
1
- import { E as TransportClient, M as SocketLike, n as AuthorizeDecision, v as Operation, w as Sync } from "./make-DJ0Q1SSc.mjs";
2
1
  import { Cause, Duration, Effect, Layer, Option, Result, Schema } from "effect";
2
+ import { Diagnostic, ReportDiagnostic } from "foldkit-surface";
3
+ import { HostDefect, HostStage } from "./diagnostics.js";
4
+ import { SocketLike } from "./transport.js";
5
+ import { AuthorizeDecision } from "./make.js";
6
+ import { Operation, Sync, TransportClient } from "./sync.js";
3
7
  import { Journal } from "foldkit-durable/core";
4
8
  import { RemoteUnauthenticated } from "foldkit-remote";
5
9
  export interface JournalExchangeOptions<Message, Shared, Principal> {
@@ -57,14 +61,26 @@ export declare const journalExchange: <Message, Shared, Principal>(options: Jour
57
61
  /**
58
62
  * Calls `listener` each time the document commits, for `Sync.transport.serve`'s
59
63
  * `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.
64
+ * A listener that throws is reported as `ListenerFailed` and called again on
65
+ * the next commit; a commit stream that breaks is reported as `HostDefect`
66
+ * (`Changes`), since no notice follows it.
60
67
  */
61
- export declare const journalChanges: <Shared, Principal>(journal: Journal<Operation, Shared, Principal, Operation>, documentId: string) => ((listener: () => void) => () => void);
68
+ export declare const journalChanges: <Shared, Principal>(journal: Journal<Operation, Shared, Principal, Operation>, documentId: string, options?: {
69
+ /** Where a failure is reported; the default reporter when not given, since this runs outside any context. */
70
+ readonly diagnostics?: ReportDiagnostic | undefined;
71
+ }) => ((listener: () => void) => () => void);
62
72
  /**
63
73
  * Serves one accepted socket over the journal: each exchange frame answered by
64
74
  * `journalExchange` with the connection's principal, and a notice sent after
65
75
  * each commit, so the replica hears of others' edits. Returns the stop.
66
76
  */
67
- export declare const serveJournal: <Message, Shared, Principal>(socket: SocketLike, options: JournalExchangeOptions<Message, Shared, Principal>) => (() => void);
77
+ export declare const serveJournal: <Message, Shared, Principal>(socket: SocketLike, options: JournalExchangeOptions<Message, Shared, Principal> & {
78
+ /**
79
+ * Where an `opens` that failed before a notice, a notice that could not be
80
+ * sent, or a broken commit stream is reported; the reporter in context when not given.
81
+ */
82
+ readonly diagnostics?: ReportDiagnostic | undefined;
83
+ }) => (() => void);
68
84
  declare const TableAheadOfJournalError_base: Schema.Class<TableAheadOfJournalError, Schema.TaggedStruct<"SyncTableAheadOfJournalError", {
69
85
  readonly table: Schema.Number;
70
86
  readonly journal: Schema.Number;
@@ -187,6 +203,14 @@ export interface DocumentHostOptions<Message, Shared, Principal, RP = never> {
187
203
  readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined;
188
204
  /** Whether an operation from `principal` may be appended. See `journalExchange`'s `admit`. */
189
205
  readonly admit?: ((principal: Principal, operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>) | undefined;
206
+ /**
207
+ * Where this upgrade's diagnostics go, with its request: each `HostDefect`,
208
+ * a failure answered "Internal error" (or a socket closed with 1011, or a
209
+ * notice not sent) whose cause the replica is never told. The reporter in
210
+ * the Effect context (`Diagnostics.Reporter`) when not given, by default the
211
+ * log.
212
+ */
213
+ readonly diagnostics?: ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>) | undefined;
190
214
  }
191
215
  /**
192
216
  * What the resolver needs (a session store), required exactly when it
@@ -210,5 +234,5 @@ export type DocumentHostOptionsLayer<RP> = [RP] extends [never] ? {
210
234
  * never will, which releases what the upgrade built.
211
235
  */
212
236
  export declare const documentHost: <Message, Shared, Principal, RP = never>(options: DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>) => ((request: Request) => Promise<Result.Result<Accepted, Response>>);
213
- export {};
214
- //# sourceMappingURL=journal.d.mts.map
237
+ export type { HostDefect, HostStage };
238
+ //# sourceMappingURL=journal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"journal.d.ts","names":[],"sources":["../src/journal.ts"],"mappings":";;;;;;;;iBAiDiB,uBAAuB,SAAS,QAAQ;;WAE9C,MAAM,KAAK,SAAS;;;;;WAKpB,SAAS,QAAQ,WAAW,QAAQ,WAAW;;;;;WAK/C,WAAW;;;;;;WAMX,SAAS,OAAO;;;;;;WAMhB,QAAQ,OAAO;;;;;;;;;;WAUf,UAC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AoB,OAAO,OAAO;;;;;;;;WASlC,gBACH,YAAY,YAAY,SAAS,YAAY,OAAO;;;;;;;;YAehD,yBAAyB,OAAO;WAC7B;;WACA,aAAa,MAAM,MAAM;;;;;;;;;;;;qBAY3B,eAAgB,SAAS,QAAQ,WAAW,YAAU,SACxD,oBAAoB,SAAS,QAAQ,WAAW,MAAM,yBAAyB,UACrF,SAAS,YAAY,QAAQ,OAAO,OAAO,UAAU"}
@@ -1,12 +1,9 @@
1
- import { b as sequence, c as serveSocket } from "./transport-BZ6utYmB.mjs";
2
- import { Cause, Context, Duration, Effect, Exit, Fiber, Layer, Match, Option, Result, Schema, Scope, Stream } from "effect";
3
- import { Cursor, DocumentId, Sequence } from "foldkit-durable/core";
4
- // src/revalidate.ts
5
- /** Shared by `documentHost` and `defineDocumentHost`; not part of either entry's API. */
6
- /** Refuses a revalidation interval that would ask the session store without pause. */
7
- const checkRevalidate = (revalidate, who) => {
8
- if (revalidate !== void 0 && !Duration.isGreaterThan(Duration.fromInputUnsafe(revalidate.every), Duration.zero)) throw new Error(`${who}: revalidate.every must be longer than zero`);
9
- };
1
+ import { Cause, Context, Effect, Exit, Fiber, Layer, Match, Option, Result, Schema, Scope, Stream } from "effect";
2
+ import { checkRevalidate } from "./revalidate.js";
3
+ import { hostDefect, listenerFailed, reportTo } from "./diagnostics.js";
4
+ import { serveSocket } from "./transport.js";
5
+ import { sequence } from "./ids.js";
6
+ import { Cursor, DocumentId as DocumentId$1, Sequence as Sequence$1 } from "foldkit-durable/core";
10
7
  // src/journal.ts
11
8
  /**
12
9
  * `foldkit-sync/journal` — the server's side of an exchange, over a
@@ -36,7 +33,7 @@ const idOf = (input) => Option.map(Schema.decodeUnknownOption(Schema.Struct({ op
36
33
  const journalExchange = (options) => {
37
34
  const { sync, journal, principal } = options;
38
35
  const limit = options.limit ?? 500;
39
- const key = DocumentId.make(sync.documentId);
36
+ const key = DocumentId$1.make(sync.documentId);
40
37
  const snapshot = sync.journalContract().snapshot;
41
38
  const operationOf = Option.liftThrowable((input) => sync.codec.operationFrom(input, sync.documentId));
42
39
  const committedOf = (committed) => sync.codec.committedFrom({
@@ -113,9 +110,13 @@ const journalExchange = (options) => {
113
110
  /**
114
111
  * Calls `listener` each time the document commits, for `Sync.transport.serve`'s
115
112
  * `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.
113
+ * A listener that throws is reported as `ListenerFailed` and called again on
114
+ * the next commit; a commit stream that breaks is reported as `HostDefect`
115
+ * (`Changes`), since no notice follows it.
116
116
  */
117
- const journalChanges = (journal, documentId) => (listener) => {
118
- const fiber = Effect.runFork(Stream.runForEach(Stream.filter(journal.subscribe, (key) => key === documentId), () => Effect.sync(listener)));
117
+ const journalChanges = (journal, documentId, options = {}) => (listener) => {
118
+ const report = (diagnostic) => reportTo(options.diagnostics, diagnostic);
119
+ const fiber = Effect.runFork(Stream.runForEach(Stream.filter(journal.subscribe, (key) => key === documentId), () => Effect.try(listener).pipe(Effect.catch((thrown) => report(listenerFailed("Notice", thrown.cause))))).pipe(Effect.catchCause((cause) => Cause.hasInterruptsOnly(cause) ? Effect.void : report(hostDefect("Changes", cause)))));
119
120
  return () => Effect.runSync(Fiber.interrupt(fiber));
120
121
  };
121
122
  /**
@@ -125,13 +126,14 @@ const journalChanges = (journal, documentId) => (listener) => {
125
126
  */
126
127
  const serveJournal = (socket, options) => {
127
128
  const client = journalExchange(options);
128
- const notices = journalChanges(options.journal, options.sync.documentId);
129
- const { opens } = options;
129
+ const notices = journalChanges(options.journal, options.sync.documentId, { diagnostics: options.diagnostics });
130
+ const { opens, diagnostics } = options;
131
+ const report = (cause) => reportTo(diagnostics, hostDefect("Notice", cause));
130
132
  return serveSocket(socket, {
131
133
  exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),
132
- changes: opens === void 0 ? notices : (listener) => notices(() => void Effect.runPromise(opens).then((open) => {
134
+ changes: opens === void 0 ? notices : (listener) => notices(() => void Effect.runPromise(Effect.catchCause(opens, (cause) => Effect.as(report(cause), false))).then((open) => {
133
135
  if (open) listener();
134
- }, () => {}))
136
+ }))
135
137
  });
136
138
  };
137
139
  /**
@@ -162,7 +164,7 @@ var TableAheadOfJournalError = class extends Schema.TaggedError()("SyncTableAhea
162
164
  */
163
165
  const editsJournal = (options) => {
164
166
  const { journal } = options;
165
- const key = DocumentId.make(options.documentId);
167
+ const key = DocumentId$1.make(options.documentId);
166
168
  let applied = Option.none();
167
169
  const intents = (epoch) => (operation) => Option.match(options.editsOf(operation), {
168
170
  onNone: () => [],
@@ -208,7 +210,7 @@ const editsJournal = (options) => {
208
210
  const { snapshot, cursor } = yield* journal.load(key);
209
211
  if (!options.holdsThrough(snapshot, through)) return;
210
212
  yield* journal.append(key, options.absorbed(through, cursor), options.server);
211
- yield* journal.compact(key, Sequence.make(through));
213
+ yield* journal.compact(key, Sequence$1.make(through));
212
214
  })
213
215
  };
214
216
  };
@@ -234,41 +236,50 @@ const documentHost = (options) => {
234
236
  release();
235
237
  return Result.fail(response);
236
238
  };
239
+ const { diagnostics } = options;
240
+ const reporter = diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request);
241
+ const report = (stage, cause) => reportTo(reporter, hostDefect(stage, cause));
242
+ const defect = async (stage, cause) => {
243
+ await Effect.runPromise(report(stage, cause));
244
+ return refuse(internalError());
245
+ };
237
246
  const { layer } = options;
238
247
  const ask = Effect.suspend(() => options.resolvePrincipal(request));
239
- const opened = await Effect.runPromise(Effect.gen(function* () {
248
+ const opened = await Effect.runPromiseExit(Effect.gen(function* () {
240
249
  const services = layer === void 0 ? Context.empty() : yield* Layer.buildWithScope(layer(), scope);
241
250
  const resolve = Effect.provide(ask, services);
242
251
  return {
243
252
  resolve,
244
253
  resolved: yield* Effect.result(resolve)
245
254
  };
246
- })).catch(() => void 0);
247
- if (opened === void 0) return refuse(internalError());
248
- const { resolve, resolved } = opened;
255
+ }));
256
+ if (Exit.isFailure(opened)) return defect("Resolve", opened.cause);
257
+ const { resolve, resolved } = opened.value;
249
258
  if (Result.isFailure(resolved)) return refuse(Response.json({ error: resolved.failure.message }, { status: 401 }));
250
259
  const principal = resolved.success;
251
- const journal = await Promise.resolve().then(options.journal).catch(() => void 0);
252
- if (journal === void 0) return refuse(internalError());
260
+ const journal = await Promise.resolve().then(options.journal).then((open) => Result.succeed(open), (error) => Result.fail(error));
261
+ if (Result.isFailure(journal)) return defect("Journal", Cause.die(journal.failure));
253
262
  let exchange;
254
263
  try {
255
264
  const { admit, settle, opens } = options;
256
265
  exchange = {
257
266
  sync: options.sync,
258
- journal,
267
+ journal: journal.success,
259
268
  principal,
260
- ...settle === void 0 ? {} : { settle: settle(journal) },
269
+ ...settle === void 0 ? {} : { settle: settle(journal.success) },
261
270
  ...opens === void 0 ? {} : { opens: opens(principal) },
262
271
  ...admit === void 0 ? {} : { admit: (operation) => admit(principal, operation) }
263
272
  };
264
273
  } catch (error) {
265
- console.error("[foldkit-sync] answering an upgrade broke:", error);
266
- return refuse(internalError());
274
+ return defect("Exchange", Cause.die(error));
267
275
  }
268
276
  return Result.succeed({
269
277
  abandon: release,
270
278
  serve: (socket) => {
271
- const stop = serveJournal(socket, exchange);
279
+ const stop = serveJournal(socket, {
280
+ ...exchange,
281
+ diagnostics: reporter
282
+ });
272
283
  const { revalidate } = options;
273
284
  if (revalidate !== void 0) {
274
285
  const { every, key } = revalidate;
@@ -285,7 +296,7 @@ const documentHost = (options) => {
285
296
  } finally {
286
297
  release();
287
298
  }
288
- })));
299
+ }).pipe(Effect.andThen(Option.isNone(Cause.findErrorOption(cause)) && !Cause.hasInterruptsOnly(cause) ? report("Revalidate", cause) : Effect.void))));
289
300
  const fiber = Effect.runFork(checking);
290
301
  socket.onClose(() => void Effect.runFork(Fiber.interrupt(fiber)));
291
302
  }
@@ -294,6 +305,6 @@ const documentHost = (options) => {
294
305
  });
295
306
  };
296
307
  };
297
- export { journalExchange as a, journalChanges as i, documentHost as n, serveJournal as o, editsJournal as r, checkRevalidate as s, TableAheadOfJournalError as t };
308
+ export { TableAheadOfJournalError, documentHost, editsJournal, journalChanges, journalExchange, serveJournal };
298
309
 
299
- //# sourceMappingURL=journal-D5h-jqXE.mjs.map
310
+ //# sourceMappingURL=journal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"journal.js","names":["JournalDocumentId","Sequence"],"sources":["../src/journal.ts"],"sourcesContent":["/**\n * `foldkit-sync/journal` — the server's side of an exchange, over a\n * `foldkit-durable` journal. Every Sync server needs the same loop: append\n * what a replica sends, refuse what cannot be taken, and read back what\n * committed since the replica's cursor. Written by hand three times, it\n * failed the same way: an operation that did not decode failed the whole\n * exchange, so the replica sent it again on every one and the edits behind it\n * never went. Here, refused operations are reported by id, and the replica\n * drops them.\n */\nimport {\n Cause,\n Context,\n Duration,\n Effect,\n Exit,\n Fiber,\n Layer,\n Match,\n Option,\n Result,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport type { Diagnostic, ReportDiagnostic } from 'foldkit-surface'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n Sequence,\n type Committed,\n type Journal,\n} from 'foldkit-durable/core'\nimport { sequence } from './ids.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync, TransportClient } from './sync.js'\nimport { checkRevalidate } from './revalidate.js'\nimport {\n hostDefect,\n listenerFailed,\n reportTo,\n type HostStage,\n type SyncDiagnostic,\n} from './diagnostics.js'\nimport { serveSocket, type SocketLike } from './transport.js'\n\nexport type { HostDefect, HostStage } from './diagnostics.js'\n\nexport interface JournalExchangeOptions<Message, Shared, Principal> {\n /** The document's contract: its codecs, and the snapshot a checkpoint encodes. */\n readonly sync: Sync<Message, Shared>\n /**\n * The journal made from `sync.journalContract()`, which orders and keeps the\n * document. One that takes any input, or only operations, is accepted.\n */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * Who is exchanging, as the transport established it. The journal's\n * `authorize` reads it; a refused operation is reported as rejected.\n */\n readonly principal: Principal\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. It runs on\n * every exchange, so a write that failed is tried again on the next.\n */\n readonly settle?: Effect.Effect<void, unknown> | undefined\n /**\n * Whether the connection may open the document at all, to read it or to\n * change it: a principal outside its readers. Refused, every exchange fails,\n * and nothing is read or appended.\n */\n readonly opens?: Effect.Effect<boolean> | undefined\n /**\n * Whether an operation may be appended, decided before the journal sees it,\n * by what the transport established rather than by the document: a principal\n * that may only read, or a rule that reads the rows an edit names, which\n * cannot run under the journal's lock (`foldkit-guard/sync`). `true` admits;\n * a refusal is rejected by the operation's id, with its reason when it gives\n * one. One that fails fails the exchange, as the journal failing does. The\n * journal's own `authorize` is where a rule about the document goes.\n */\n readonly admit?:\n | ((operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /** The most committed operations one reply carries; a replica further behind asks again. Default 500. */\n readonly limit?: number | undefined\n}\n\n/** The id an entry names, read without trusting the rest of it. */\nconst idOf = (input: unknown): Option.Option<string> =>\n Option.map(\n Schema.decodeUnknownOption(Schema.Struct({ opId: Schema.String }))(input),\n ({ opId }) => opId,\n )\n\n/**\n * One replica's exchanges with the journal, as the replica's transport\n * speaks them (`Sync.transport.fromPromise`, or behind\n * `Sync.transport.serve` on a socket). Each pending operation is appended in\n * order, and acknowledged once committed, or already committed. One is\n * rejected by its id when its message does not decode, it names another\n * document, or the journal refuses it (`authorize`, `validate`); the replica\n * drops it rather than send it again. Only an entry with no id at all, a\n * cursor ahead of the journal's, a connection `opens` refuses, or `admit` or\n * the journal failing fails the exchange. The reply carries what committed\n * after the replica's cursor, a checkpoint when that history was compacted,\n * and the journal's epoch, so a replica of a reset journal starts again.\n */\nexport const journalExchange = <Message, Shared, Principal>(\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): TransportClient => {\n const { sync, journal, principal } = options\n const limit = options.limit ?? 500\n const key = JournalDocumentId.make(sync.documentId)\n const snapshot = sync.journalContract().snapshot\n const operationOf = Option.liftThrowable((input: unknown) =>\n sync.codec.operationFrom(input, sync.documentId),\n )\n const committedOf = (committed: Committed<Operation>) =>\n sync.codec.committedFrom(\n { ...committed.operation, serverSequence: committed.sequence, actorId: committed.actorId },\n sync.documentId,\n )\n\n const exchange = (cursor: number, pending: ReadonlyArray<unknown>, seen?: string) =>\n Effect.gen(function* () {\n if (options.opens !== undefined && !(yield* options.opens)) {\n return yield* Effect.fail(new Error('This connection may not open the document'))\n }\n // A replica that saw another epoch holds a cursor into history this journal\n // lacks (it was reset): it is answered from the start. Otherwise a cursor\n // past the journal's is refused before anything is appended, or the\n // operations would commit and their acknowledgements be lost.\n const epoch = yield* journal.epoch(key)\n const from = seen !== undefined && seen !== epoch ? 0 : cursor\n const at = yield* journal.cursor(key)\n if (from > at) {\n return yield* Effect.fail(new Error(`Cursor ${cursor} is ahead of the server's ${at}`))\n }\n const rejected: Array<string> = []\n const reasons: Array<{ readonly opId: string; readonly reason: string }> = []\n // Each reason is words for the person whose edit came back: a policy's own,\n // or a fixed sentence, never an error's message, which may carry internals.\n const reject = (opId: string, reason: string) => {\n rejected.push(opId)\n reasons.push({ opId, reason })\n }\n const acknowledged: Array<string> = []\n for (const input of pending) {\n const decoded = operationOf(input)\n if (Option.isNone(decoded)) {\n const id = idOf(input)\n if (Option.isNone(id))\n return yield* Effect.fail(new Error('A pending entry names no operation'))\n reject(id.value, 'Not an operation this server accepts')\n continue\n }\n const operation = decoded.value\n const admitted = options.admit === undefined ? true : options.admit(operation)\n const decision = Effect.isEffect(admitted) ? yield* admitted : admitted\n if (decision !== true) {\n reject(\n operation.opId,\n decision === false ? 'This connection may not make changes' : decision.reason,\n )\n continue\n }\n yield* journal.append(key, operation, principal).pipe(\n Effect.map(appended =>\n acknowledged.push(\n Match.valueTags(appended, {\n Committed: ({ committed }): string => committed.operation.opId,\n AlreadyCommitted: ({ opId }): string => opId,\n }),\n ),\n ),\n // A refusal, an operation the journal cannot apply, and an id reused for\n // other content fail the same way on every retry, so they are rejected; a\n // `JournalError` may not, so it still fails the exchange.\n Effect.catchTags({\n OperationRejectedError: error =>\n Effect.sync(() => reject(error.opId, error.reason ?? 'Refused by the server')),\n InvalidOperationError: () =>\n Effect.sync(() => reject(operation.opId, 'Not a valid operation')),\n IdentityConflictError: () =>\n Effect.sync(() => reject(operation.opId, 'Its id was already used for another')),\n }),\n )\n }\n if (options.settle !== undefined) yield* options.settle\n // A cursor below the compacted floor is answered with the snapshot; the\n // read decides that itself, so a compaction cannot slip in between.\n const read = yield* journal.read(key, Cursor.make(from), { limit }).pipe(\n Effect.map(rows => Option.some(rows)),\n Effect.catchTag('CompactedCursorError', () => Effect.succeed(Option.none())),\n )\n return yield* Option.match(read, {\n onSome: rows =>\n Effect.succeed({\n operations: rows.map(committedOf),\n rejected,\n reasons,\n acknowledged,\n more: rows.length === limit,\n epoch,\n }),\n onNone: () =>\n Effect.map(journal.load(key), loaded => ({\n operations: [],\n rejected,\n reasons,\n acknowledged,\n checkpoint: { cursor: loaded.cursor, model: snapshot.encode(loaded.snapshot) },\n epoch,\n })),\n })\n })\n\n return {\n exchange: (cursor, pending, seen) => Effect.runPromise(exchange(cursor, pending, seen)),\n }\n}\n\n/**\n * Calls `listener` each time the document commits, for `Sync.transport.serve`'s\n * `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.\n * A listener that throws is reported as `ListenerFailed` and called again on\n * the next commit; a commit stream that breaks is reported as `HostDefect`\n * (`Changes`), since no notice follows it.\n */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, Operation>,\n documentId: string,\n options: {\n /** Where a failure is reported; the default reporter when not given, since this runs outside any context. */\n readonly diagnostics?: ReportDiagnostic | undefined\n } = {},\n ): ((listener: () => void) => () => void) =>\n listener => {\n const report = (diagnostic: SyncDiagnostic) => reportTo(options.diagnostics, diagnostic)\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () =>\n Effect.try(listener).pipe(\n Effect.catch(thrown => report(listenerFailed('Notice', thrown.cause))),\n ),\n ).pipe(\n // A journal shutting down may end its stream by interrupting it, as it\n // may end it; any other cause ends every later notice unannounced.\n Effect.catchCause(cause =>\n Cause.hasInterruptsOnly(cause) ? Effect.void : report(hostDefect('Changes', cause)),\n ),\n ),\n )\n return () => Effect.runSync(Fiber.interrupt(fiber))\n }\n\n/**\n * Serves one accepted socket over the journal: each exchange frame answered by\n * `journalExchange` with the connection's principal, and a notice sent after\n * each commit, so the replica hears of others' edits. Returns the stop.\n */\nexport const serveJournal = <Message, Shared, Principal>(\n socket: SocketLike,\n options: JournalExchangeOptions<Message, Shared, Principal> & {\n /**\n * Where an `opens` that failed before a notice, a notice that could not be\n * sent, or a broken commit stream is reported; the reporter in context when not given.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): (() => void) => {\n const client = journalExchange(options)\n const notices = journalChanges(options.journal, options.sync.documentId, {\n diagnostics: options.diagnostics,\n })\n const { opens, diagnostics } = options\n const report = (cause: Cause.Cause<unknown>) => reportTo(diagnostics, hostDefect('Notice', cause))\n return serveSocket(socket, {\n exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),\n // A connection that may not open the document is told nothing of its commits.\n changes:\n opens === undefined\n ? notices\n : listener =>\n notices(\n () =>\n void Effect.runPromise(\n // A failed `opens` sends no notice, as a refusal does, and is reported.\n Effect.catchCause(opens, cause => Effect.as(report(cause), false)),\n ).then(open => {\n if (open) listener()\n }),\n ),\n })\n}\n\n/**\n * The table holds revisions past every sequence the journal has: it outlived\n * a reset of the journal, or was built from another. New edits commit at\n * sequences the table already passed, so `apply` would skip every one and\n * the replicas count each absorbed: rebuild the table with the journal.\n */\nexport class TableAheadOfJournalError extends Schema.TaggedError<TableAheadOfJournalError>()(\n 'SyncTableAheadOfJournalError',\n { table: Schema.Number, journal: Schema.Number },\n) {\n override get message(): string {\n return `The table holds revision ${this.table}, past the journal's ${this.journal}: rebuild the table with the journal`\n }\n}\n\nexport interface EditsJournalOptions<Shared, Principal, Change> {\n /** The document whose edits the table reads. */\n readonly documentId: string\n /** The journal the edits commit to. */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * The cells an operation edits, with the sequence its stamp wrote in; none\n * for an operation that edits nothing. An edit committed without a sequence\n * is not this journal's: its intents fail rather than write revision 0.\n */\n readonly editsOf: (operation: Operation) => Option.Option<{\n readonly changes: ReadonlyArray<Change>\n readonly at: Option.Option<number>\n }>\n /**\n * Writes one committed change to the table, with the sequence it committed\n * at. It runs as a recovery intent, so it may run again after a crash: it\n * must never move a row back (`revision <= at`). A failure stops recovery\n * there, and the next settle tries it again.\n *\n * It cannot refuse an edit: the edit has committed. One naming a row the\n * table lacks is refused at commit instead, by the journal's `validate`,\n * so its sender is told; let through, it would change nothing and vanish\n * once absorbed.\n */\n readonly apply: (change: Change, at: number) => Effect.Effect<void, unknown>\n /**\n * The highest revision the table holds. Settling refuses to start while it\n * is past the journal's cursor (`TableAheadOfJournalError`), since every\n * edit would then be skipped and counted absorbed; it asks again on each\n * settle until the two agree.\n */\n readonly tableRevision: Effect.Effect<number, unknown>\n /** Whether the snapshot still keeps an edit committed through `through`: whether to absorb. */\n readonly holdsThrough: (snapshot: Shared, through: number) => boolean\n /**\n * The server's operation saying the table holds every edit through\n * `through`, sequenced from `cursor`, the journal's: the replicas drop those\n * edits on hearing it.\n */\n readonly absorbed: (through: number, cursor: number) => Operation\n /** Who the server commits `absorbed` as; the contract's `authorize` should let only it. */\n readonly server: Principal\n}\n\n/**\n * The table as the journal's read model: `settle` applies each committed\n * edit through `apply`, as a recovery intent, and `absorb` records in the\n * journal what the table holds and compacts the log behind it. For\n * `journalExchange`'s `settle`, and a clock that absorbs.\n *\n * Recovery starts at the journal's floor, where compaction left it, so a\n * server restarted over a journal that outlived it does not ask for history\n * that is gone. Intents are keyed by the journal's epoch as well as the\n * operation, so after a reset an operation sent again is applied again, not\n * taken as already run.\n */\nexport const editsJournal = <Shared, Principal, Change>(\n options: EditsJournalOptions<Shared, Principal, Change>,\n): {\n readonly settle: Effect.Effect<void, unknown>\n readonly absorb: Effect.Effect<void, unknown>\n} => {\n const { journal } = options\n const key = JournalDocumentId.make(options.documentId)\n // Operations at or before `applied.cursor` have every change in the table,\n // in `applied.epoch`: none until a settle has run in this process.\n let applied: Option.Option<{ readonly cursor: Cursor; readonly epoch: string }> = Option.none()\n const intents = (epoch: string) => (operation: Operation) =>\n Option.match(options.editsOf(operation), {\n onNone: () => [],\n onSome: ({ changes, at }) =>\n changes.map((change, index) => ({\n key: `${epoch}:${operation.opId}:${index}`,\n run: Option.match(at, {\n onNone: () =>\n Effect.fail(new Error(`Edit ${operation.opId} committed without its sequence`)),\n onSome: sequence => options.apply(change, sequence),\n }),\n })),\n })\n // Before the first recovery of an epoch: the table must not be past it.\n const checked = Effect.gen(function* () {\n const table = yield* options.tableRevision\n const at = yield* journal.cursor(key)\n if (table > at) return yield* new TableAheadOfJournalError({ table, journal: at })\n return Cursor.make(yield* journal.floor(key))\n })\n const settle = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n // A new epoch is a new history: recovery starts over at its floor.\n const from = yield* Option.match(\n Option.filter(applied, previous => previous.epoch === epoch),\n {\n onSome: ({ cursor }) => Effect.succeed(cursor),\n onNone: () => checked,\n },\n )\n const cursor = yield* journal.recover({ key, from, intents: intents(epoch) })\n applied = Option.some({ cursor, epoch })\n })\n // Two absorbs at once need no lock: both name the record by the journal's\n // cursor, so the second is the first's retry, answered from history.\n const absorb = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n const known = Option.filter(applied, previous => previous.epoch === epoch)\n if (Option.isNone(known)) return\n const through = known.value.cursor\n const { snapshot, cursor } = yield* journal.load(key)\n if (!options.holdsThrough(snapshot, through)) return\n yield* journal.append(key, options.absorbed(through, cursor), options.server)\n // What the log holds through `through` is in the table and gone from\n // the snapshot; a replica behind it is sent the snapshot instead.\n yield* journal.compact(key, Sequence.make(through))\n })\n return { settle, absorb }\n}\n\n/** A server socket a host serves on: Sync's socket, and a close with a code the replica reads. */\nexport interface HostSocket extends SocketLike {\n /** Closes with `code` and `reason`; one already closed stays so. */\n closeWith(code: number, reason: string): void\n}\n\n/**\n * An upgrade `documentHost` accepted. Exactly one of the two must follow:\n * `serve` once the runtime has opened the socket, or `abandon` when it never\n * will (the client left, the runtime refused the handshake), which releases\n * what the upgrade built.\n */\nexport interface Accepted {\n readonly serve: (socket: HostSocket) => void\n readonly abandon: () => void\n}\n\n/** What `documentHost` needs: one document, who may open it, and what they may do. */\nexport interface DocumentHostOptions<Message, Shared, Principal, RP = never> {\n readonly sync: Sync<Message, Shared>\n /**\n * The document's journal, asked on each upgrade a principal passed; keep\n * it open between calls. A rejection answers the upgrade with a 500.\n */\n readonly journal: () => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening the socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`) to refuse it:\n * a 401 carrying its message. A defect is a 500 that says nothing of it.\n * A browser's `WebSocket` sends no header of the page's: `Origin` and the\n * cookie are what it has.\n */\n readonly resolvePrincipal: (\n request: Request,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket serves the\n * principal it opened with until it closes, a revoked session included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** After each exchange's appends, given the journal. See `journalExchange`'s `settle`. */\n readonly settle?:\n | ((journal: Journal<Operation, Shared, Principal, Operation>) => Effect.Effect<void, unknown>)\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /** Whether an operation from `principal` may be appended. See `journalExchange`'s `admit`. */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /**\n * Where this upgrade's diagnostics go, with its request: each `HostDefect`,\n * a failure answered \"Internal error\" (or a socket closed with 1011, or a\n * notice not sent) whose cause the replica is never told. The reporter in\n * the Effect context (`Diagnostics.Reporter`) when not given, by default the\n * log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n}\n\n/** What a revalidation that found another principal fails with. */\nconst changed = Symbol('changed')\n\nconst internalError = () => Response.json({ error: 'Internal error' }, { status: 500 })\n\n/**\n * What the resolver needs (a session store), required exactly when it\n * needs something. Built per upgrade and kept until the socket closes,\n * since `revalidate` asks again while it is open; an upgrade it refuses\n * closes it at once.\n */\nexport type DocumentHostOptionsLayer<RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: () => Layer.Layer<RP> }\n\n/**\n * One document's Sync host, for any runtime that upgrades a request to a\n * socket: a Durable Object (`foldkit-sync/do`), or Node's `ws`. Each\n * upgrade is answered before the socket opens: refused (`Result.fail`, a\n * 401 for a principal refused, a 500 for a resolver or journal that broke),\n * or accepted (`Accepted`): `serve` the socket once the runtime has opened\n * it, against the journal, as the principal it resolved, asking again while\n * it is open when `revalidate` says to; or `abandon` it when the runtime\n * never will, which releases what the upgrade built.\n */\nexport const documentHost = <Message, Shared, Principal, RP = never>(\n options: DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>,\n): ((request: Request) => Promise<Result.Result<Accepted, Response>>) => {\n checkRevalidate(options.revalidate, 'documentHost')\n return async request => {\n // The upgrade's services live as long as its socket.\n const scope = Effect.runSync(Scope.make())\n const release = (): void => void Effect.runFork(Scope.close(scope, Exit.void))\n const refuse = (response: Response) => {\n release()\n return Result.fail(response)\n }\n const { diagnostics } = options\n const reporter: ReportDiagnostic | undefined =\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request)\n const report = (stage: HostStage, cause: Cause.Cause<unknown>) =>\n reportTo(reporter, hostDefect(stage, cause))\n const defect = async (stage: HostStage, cause: Cause.Cause<unknown>) => {\n await Effect.runPromise(report(stage, cause))\n return refuse(internalError())\n }\n const { layer } = options\n // Suspended, so the resolver is called each time this runs (a resolver\n // may decide when called, not when its Effect runs), and one that throws\n // is a 500 like one that dies.\n const ask = Effect.suspend(() => options.resolvePrincipal(request))\n // The layer and the first answer in one run: either breaking is a 500.\n const opened = await Effect.runPromiseExit(\n Effect.gen(function* () {\n const services: Context.Context<RP> =\n layer === undefined\n ? // No layer is a resolver that needs nothing (`DocumentHostLayer`).\n (Context.empty() as Context.Context<RP>)\n : yield* Layer.buildWithScope(layer(), scope)\n const resolve = Effect.provide(ask, services)\n return { resolve, resolved: yield* Effect.result(resolve) }\n }),\n )\n if (Exit.isFailure(opened)) return defect('Resolve', opened.cause)\n const { resolve, resolved } = opened.value\n if (Result.isFailure(resolved))\n return refuse(Response.json({ error: resolved.failure.message }, { status: 401 }))\n const principal = resolved.success\n // A throw is a rejection like any other: a 500.\n const journal = await Promise.resolve()\n .then(options.journal)\n .then(\n open => Result.succeed(open),\n (error: unknown) => Result.fail(error),\n )\n if (Result.isFailure(journal)) return defect('Journal', Cause.die(journal.failure))\n // An application's `opens` or `settle` may throw: a 500, before any socket opens.\n let exchange: JournalExchangeOptions<Message, Shared, Principal>\n try {\n const { admit, settle, opens } = options\n exchange = {\n sync: options.sync,\n journal: journal.success,\n principal,\n ...(settle === undefined ? {} : { settle: settle(journal.success) }),\n ...(opens === undefined ? {} : { opens: opens(principal) }),\n ...(admit === undefined\n ? {}\n : { admit: (operation: Operation) => admit(principal, operation) }),\n }\n } catch (error) {\n return defect('Exchange', Cause.die(error))\n }\n return Result.succeed({\n abandon: release,\n serve: socket => {\n const stop = serveJournal(socket, { ...exchange, diagnostics: reporter })\n const { revalidate } = options\n if (revalidate !== undefined) {\n const { every, key } = revalidate\n const checking = Effect.sleep(every).pipe(\n Effect.andThen(resolve),\n Effect.flatMap(now =>\n key === undefined || key(principal) === key(now) ? Effect.void : Effect.fail(changed),\n ),\n Effect.forever,\n Effect.catchCause(cause =>\n Effect.sync(() => {\n // Before closing: a socket may fire its own close only on the\n // replica's reply, and frames in flight until then would\n // still be appended as the principal just refused.\n stop()\n const [code, reason] = Option.match(Cause.findErrorOption(cause), {\n // A defect: this side broke, and the replica learns that it did.\n onNone: () => [1011, 'Internal error'] as const,\n onSome: error =>\n error === changed\n ? ([1012, 'Who is asking changed'] as const)\n : ([4401, error.message] as const),\n })\n try {\n socket.closeWith(code, reason)\n } catch {\n // A reason the platform refuses (past 123 bytes): the code alone.\n socket.close()\n } finally {\n release()\n }\n }).pipe(\n // The replica reads 1011 and no more: the cause is reported here.\n Effect.andThen(\n Option.isNone(Cause.findErrorOption(cause)) && !Cause.hasInterruptsOnly(cause)\n ? report('Revalidate', cause)\n : Effect.void,\n ),\n ),\n ),\n )\n const fiber = Effect.runFork(checking)\n socket.onClose(() => void Effect.runFork(Fiber.interrupt(fiber)))\n }\n socket.onClose(release)\n },\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2FA,MAAM,QAAQ,UACZ,OAAO,IACL,OAAO,oBAAoB,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,IACvE,EAAE,WAAW,IAChB;;;;;;;;;;;;;;AAeF,MAAa,mBACX,YACoB;CACpB,MAAM,EAAE,MAAM,SAAS,cAAc;CACrC,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,MAAMA,aAAkB,KAAK,KAAK,UAAU;CAClD,MAAM,WAAW,KAAK,gBAAgB,CAAC,CAAC;CACxC,MAAM,cAAc,OAAO,eAAe,UACxC,KAAK,MAAM,cAAc,OAAO,KAAK,UAAU,CACjD;CACA,MAAM,eAAe,cACnB,KAAK,MAAM,cACT;EAAE,GAAG,UAAU;EAA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AAM,WAAW,OAAO,MAAM,KAAK,CAAC,CAAC,KACnC,OAAO,QAAQ,OAAO,GACtB,OAAO,SAAQ,QACb,QAAQ,KAAA,KAAa,IAAI,SAAS,MAAM,IAAI,GAAG,IAAI,OAAO,OAAO,OAAO,KAAK,OAAO,CACtF,GACA,OAAO,SACP,OAAO,YAAW,UAChB,OAAO,WAAW;MAIhB,KAAK;MACL,MAAM,CAAC,MAAM,UAAU,OAAO,MAAM,MAAM,gBAAgB,KAAK,GAAG;OAEhE,cAAc,CAAC,MAAM,gBAAgB;OACrC,SAAQ,UACN,UAAU,UACL,CAAC,MAAM,uBAAuB,IAC9B,CAAC,MAAM,MAAM,OAAO;MAC7B,CAAC;MACD,IAAI;OACF,OAAO,UAAU,MAAM,MAAM;MAC/B,QAAQ;OAEN,OAAO,MAAM;MACf,UAAU;OACR,QAAQ;MACV;KACF,CAAC,CAAC,CAAC,KAED,OAAO,QACL,OAAO,OAAO,MAAM,gBAAgB,KAAK,CAAC,KAAK,CAAC,MAAM,kBAAkB,KAAK,IACzE,OAAO,cAAc,KAAK,IAC1B,OAAO,IACb,CACF,CACF,CACF;KACA,MAAM,QAAQ,OAAO,QAAQ,QAAQ;KACrC,OAAO,cAAc,KAAK,OAAO,QAAQ,MAAM,UAAU,KAAK,CAAC,CAAC;IAClE;IACA,OAAO,QAAQ,OAAO;GACxB;EACF,CAAC;CACH;AACF"}
package/dist/lww.d.ts ADDED
@@ -0,0 +1,76 @@
1
+ import { Effect, Schema } from "effect";
2
+ import { Storage } from "./indexedDb.js";
3
+ import { DocumentId, ReplicaId } from "./ids.js";
4
+ import { StorageError, UnsupportedClockVersionError } from "./errors.js";
5
+ /** A logical write time; replica ids break concurrent ties using UTF-16 order. */
6
+ declare const Stamp: Schema.Struct<{
7
+ readonly counter: Schema.Number;
8
+ readonly replicaId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/ReplicaId">;
9
+ }>;
10
+ declare const ClockState: Schema.Struct<{
11
+ readonly schemaVersion: Schema.Literal<1>;
12
+ readonly documentId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/DocumentId">;
13
+ readonly replicaId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/ReplicaId">;
14
+ readonly revision: Schema.Number;
15
+ }>;
16
+ export type LwwClockState = typeof ClockState.Type;
17
+ export interface LwwClock {
18
+ /** Persists a timestamp beyond the saved counter and supplied observation. */
19
+ next: (observedCounter?: number) => Effect.Effect<typeof Stamp.Type, StorageError>;
20
+ /** Drains accepted allocations, then closes storage. Repeated calls no-op. */
21
+ close: Effect.Effect<void>;
22
+ }
23
+ /**
24
+ * Opens a durable clock over the caller's storage.
25
+ *
26
+ * Allocations are serialized through a `SynchronizedRef` and each persists before
27
+ * its stamp is returned. A crash after the save may skip a timestamp but never
28
+ * reuse one. Storage is owned by the caller; a failed open closes it so a partial
29
+ * initialization does not leak the connection.
30
+ */
31
+ export declare const openLwwClock: (options: {
32
+ readonly documentId: DocumentId;
33
+ readonly replicaId: ReplicaId;
34
+ readonly storage: Storage;
35
+ }) => Effect.Effect<{
36
+ next: (observedCounter?: any) => Effect.Effect<{
37
+ readonly counter: number;
38
+ readonly replicaId: string & import("effect/Brand").Brand<"@foldkit-sync/ReplicaId">;
39
+ }, StorageError, never>;
40
+ close: Effect.Effect<void, never, never>;
41
+ }, StorageError | UnsupportedClockVersionError, never>;
42
+ /**
43
+ * A schema and reducer helper for a last-writer-wins register.
44
+ * Allocate a unique stamp per write before dispatch, and retain it in the Message.
45
+ * Merge is for decoded values; the application's schema validates wire input.
46
+ */
47
+ export declare const lwwRegister: <Value, Encoded, RD, RE>(value: Schema.Codec<Value, Encoded, RD, RE>) => {
48
+ schema: Schema.Struct<{
49
+ readonly stamp: Schema.Struct<{
50
+ readonly counter: Schema.Number;
51
+ readonly replicaId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/ReplicaId">;
52
+ }>;
53
+ readonly value: Schema.Codec<Value, Encoded, RD, RE>;
54
+ }>;
55
+ merge: (left: {
56
+ readonly stamp: {
57
+ readonly counter: number;
58
+ readonly replicaId: string & import("effect/Brand").Brand<"@foldkit-sync/ReplicaId">;
59
+ };
60
+ readonly value: Value;
61
+ }, right: {
62
+ readonly stamp: {
63
+ readonly counter: number;
64
+ readonly replicaId: string & import("effect/Brand").Brand<"@foldkit-sync/ReplicaId">;
65
+ };
66
+ readonly value: Value;
67
+ }) => {
68
+ readonly stamp: {
69
+ readonly counter: number;
70
+ readonly replicaId: string & import("effect/Brand").Brand<"@foldkit-sync/ReplicaId">;
71
+ };
72
+ readonly value: Value;
73
+ };
74
+ };
75
+ export {};
76
+ //# sourceMappingURL=lww.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lww.d.ts","names":[],"sources":["../src/lww.ts"],"mappings":";;;;;cAMM,OAAK,OAAA;;;;cAYL,YAAU,OAAA;;;;;;YAOJ,uBAAuB,WAAW;iBAE7B;;EAEf,OAAO,6BAA6B,OAAO,cAAc,MAAM,MAAM;;EAErE,OAAO,OAAO;;;;;;;;;;qBAuCH,eAAY;WAEA,YAAA;WACD,WAAA;WACF,SAAA;;;;;;;GAgErB,eAAA;;;;;;qBAOY,cAAe,OAAO,SAAS,IAAI,IAAE,OACzC,OAAO,MAAM,OAAO,SAAS,IAAI"}
package/dist/lww.js ADDED
@@ -0,0 +1,121 @@
1
+ import { Effect, Exit, Ref, Schema, SynchronizedRef } from "effect";
2
+ import { DocumentId, ReplicaId } from "./ids.js";
3
+ import { StorageError, UnsupportedClockVersionError } from "./errors.js";
4
+ // src/lww.ts
5
+ /** A logical write time; replica ids break concurrent ties using UTF-16 order. */
6
+ const Stamp = Schema.Struct({
7
+ counter: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER)),
8
+ replicaId: ReplicaId
9
+ });
10
+ /** The persisted clock format. A bump must handle the older value explicitly. */
11
+ const CLOCK_SCHEMA_VERSION = 1;
12
+ const ClockState = Schema.Struct({
13
+ schemaVersion: Schema.Literal(CLOCK_SCHEMA_VERSION),
14
+ documentId: DocumentId,
15
+ replicaId: ReplicaId,
16
+ revision: Stamp.fields.counter
17
+ });
18
+ const decodeClock = Schema.decodeUnknownSync(ClockState, { onExcessProperty: "error" });
19
+ const decodeCounter = Schema.decodeUnknownSync(Stamp.fields.counter);
20
+ const clockError = (message, cause) => new StorageError({
21
+ message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,
22
+ cause
23
+ });
24
+ const VersionProbe = Schema.Struct({ schemaVersion: Schema.optional(Schema.Number) });
25
+ /**
26
+ * Tells a version this build does not understand apart from malformed data, so
27
+ * the caller gets an actionable failure and the stored state is preserved.
28
+ */
29
+ const unsupportedVersion = (input) => {
30
+ let found;
31
+ try {
32
+ found = Schema.decodeUnknownSync(VersionProbe)(input);
33
+ } catch {
34
+ return;
35
+ }
36
+ if (found.schemaVersion === CLOCK_SCHEMA_VERSION) return void 0;
37
+ return new UnsupportedClockVersionError({
38
+ schemaVersion: found.schemaVersion ?? null,
39
+ message: `Stored clock uses schema ${found.schemaVersion ?? "?"}; this build supports ${CLOCK_SCHEMA_VERSION}`
40
+ });
41
+ };
42
+ /**
43
+ * Opens a durable clock over the caller's storage.
44
+ *
45
+ * Allocations are serialized through a `SynchronizedRef` and each persists before
46
+ * its stamp is returned. A crash after the save may skip a timestamp but never
47
+ * reuse one. Storage is owned by the caller; a failed open closes it so a partial
48
+ * initialization does not leak the connection.
49
+ */
50
+ const openLwwClock = Effect.fn("Lww.openClock")(function* (options) {
51
+ const { documentId, replicaId, storage } = options;
52
+ yield* Effect.annotateCurrentSpan({
53
+ documentId,
54
+ replicaId
55
+ });
56
+ const initial = decodeClock({
57
+ schemaVersion: CLOCK_SCHEMA_VERSION,
58
+ documentId,
59
+ replicaId,
60
+ revision: 0
61
+ });
62
+ const saved = yield* storage.load();
63
+ const state = yield* Effect.try({
64
+ try: () => saved === void 0 ? initial : decodeClock(saved),
65
+ catch: (cause) => unsupportedVersion(saved) ?? clockError("Stored clock state is invalid", cause)
66
+ });
67
+ if (state.documentId !== documentId || state.replicaId !== replicaId) return yield* new StorageError({ message: "Wrong clock storage" });
68
+ if (saved === void 0) yield* storage.save(state, null);
69
+ const stateRef = yield* SynchronizedRef.make(state);
70
+ const closed = yield* Ref.make(false);
71
+ return {
72
+ next: Effect.fn("Lww.next")(function* (observedCounter = 0) {
73
+ if (yield* Ref.get(closed)) return yield* new StorageError({ message: "Clock is closed" });
74
+ return yield* SynchronizedRef.modifyEffect(stateRef, (current) => Effect.gen(function* () {
75
+ if (yield* Ref.get(closed)) return yield* new StorageError({ message: "Clock is closed" });
76
+ const allocated = yield* Effect.try({
77
+ try: () => decodeClock({
78
+ ...current,
79
+ revision: Math.max(current.revision, decodeCounter(observedCounter)) + 1
80
+ }),
81
+ catch: (cause) => clockError("Invalid clock allocation", cause)
82
+ });
83
+ yield* storage.save(allocated, current.revision);
84
+ return [{
85
+ counter: allocated.revision,
86
+ replicaId
87
+ }, allocated];
88
+ }));
89
+ }),
90
+ close: Effect.fn("Lww.close")(function* () {
91
+ if (yield* Ref.modify(closed, (current) => [current, true])) return;
92
+ yield* SynchronizedRef.modifyEffect(stateRef, (current) => Effect.succeed([void 0, current]));
93
+ yield* storage.close;
94
+ })()
95
+ };
96
+ }, (effect, options) => effect.pipe(Effect.onExit((exit) => Exit.isSuccess(exit) ? Effect.void : options.storage.close.pipe(Effect.ignore))));
97
+ /**
98
+ * A schema and reducer helper for a last-writer-wins register.
99
+ * Allocate a unique stamp per write before dispatch, and retain it in the Message.
100
+ * Merge is for decoded values; the application's schema validates wire input.
101
+ */
102
+ const lwwRegister = (value) => {
103
+ const schema = Schema.Struct({
104
+ stamp: Stamp,
105
+ value
106
+ });
107
+ const equivalent = Schema.toEquivalence(value);
108
+ const merge = (left, right) => {
109
+ if (left.stamp.counter !== right.stamp.counter) return left.stamp.counter > right.stamp.counter ? left : right;
110
+ if (left.stamp.replicaId !== right.stamp.replicaId) return left.stamp.replicaId > right.stamp.replicaId ? left : right;
111
+ if (!equivalent(left.value, right.value)) throw new Error("Conflicting LWW write identity");
112
+ return left;
113
+ };
114
+ return {
115
+ schema,
116
+ merge
117
+ };
118
+ };
119
+ export { lwwRegister, openLwwClock };
120
+
121
+ //# sourceMappingURL=lww.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lww.js","names":[],"sources":["../src/lww.ts"],"sourcesContent":["import { Effect, Exit, Ref, Schema, SynchronizedRef } from 'effect'\nimport { StorageError, UnsupportedClockVersionError } from './errors.js'\nimport { DocumentId, ReplicaId } from './ids.js'\nimport type { Storage } from './indexedDb.js'\n\n/** A logical write time; replica ids break concurrent ties using UTF-16 order. */\nconst Stamp = Schema.Struct({\n counter: Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n ),\n replicaId: ReplicaId,\n})\n\n/** The persisted clock format. A bump must handle the older value explicitly. */\nconst CLOCK_SCHEMA_VERSION = 1\n\nconst ClockState = Schema.Struct({\n schemaVersion: Schema.Literal(CLOCK_SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n // The high-water counter also serves as the storage's CAS revision.\n revision: Stamp.fields.counter,\n})\nexport type LwwClockState = typeof ClockState.Type\n\nexport interface LwwClock {\n /** Persists a timestamp beyond the saved counter and supplied observation. */\n next: (observedCounter?: number) => Effect.Effect<typeof Stamp.Type, StorageError>\n /** Drains accepted allocations, then closes storage. Repeated calls no-op. */\n close: Effect.Effect<void>\n}\n\nconst decodeClock = Schema.decodeUnknownSync(ClockState, { onExcessProperty: 'error' })\nconst decodeCounter = Schema.decodeUnknownSync(Stamp.fields.counter)\n\nconst clockError = (message: string, cause: unknown): StorageError =>\n new StorageError({\n message: `${message}: ${cause instanceof Error ? cause.message : String(cause)}`,\n cause,\n })\n\nconst VersionProbe = Schema.Struct({ schemaVersion: Schema.optional(Schema.Number) })\n/**\n * Tells a version this build does not understand apart from malformed data, so\n * the caller gets an actionable failure and the stored state is preserved.\n */\nconst unsupportedVersion = (input: unknown): UnsupportedClockVersionError | undefined => {\n let found: { readonly schemaVersion?: number | undefined }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.schemaVersion === CLOCK_SCHEMA_VERSION) return undefined\n return new UnsupportedClockVersionError({\n schemaVersion: found.schemaVersion ?? null,\n message: `Stored clock uses schema ${found.schemaVersion ?? '?'}; this build supports ${CLOCK_SCHEMA_VERSION}`,\n })\n}\n\n/**\n * Opens a durable clock over the caller's storage.\n *\n * Allocations are serialized through a `SynchronizedRef` and each persists before\n * its stamp is returned. A crash after the save may skip a timestamp but never\n * reuse one. Storage is owned by the caller; a failed open closes it so a partial\n * initialization does not leak the connection.\n */\nexport const openLwwClock = Effect.fn('Lww.openClock')(\n function* (options: {\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly storage: Storage\n }) {\n const { documentId, replicaId, storage } = options\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const initial = decodeClock({\n schemaVersion: CLOCK_SCHEMA_VERSION,\n documentId,\n replicaId,\n revision: 0,\n })\n const saved = yield* storage.load()\n const state = yield* Effect.try({\n try: () => (saved === undefined ? initial : decodeClock(saved)),\n catch: cause =>\n unsupportedVersion(saved) ?? clockError('Stored clock state is invalid', cause),\n })\n if (state.documentId !== documentId || state.replicaId !== replicaId)\n return yield* new StorageError({ message: 'Wrong clock storage' })\n if (saved === undefined) yield* storage.save(state, null)\n\n const stateRef = yield* SynchronizedRef.make(state)\n const closed = yield* Ref.make(false)\n\n const next = Effect.fn('Lww.next')(function* (observedCounter = 0) {\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n return yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // Re-check under the lock: a `close` that set the flag while this\n // allocation was queued must not save to a closed connection.\n if (yield* Ref.get(closed)) return yield* new StorageError({ message: 'Clock is closed' })\n const allocated = yield* Effect.try({\n try: () =>\n decodeClock({\n ...current,\n revision: Math.max(current.revision, decodeCounter(observedCounter)) + 1,\n }),\n catch: cause => clockError('Invalid clock allocation', cause),\n })\n yield* storage.save(allocated, current.revision)\n return [{ counter: allocated.revision, replicaId }, allocated] as const\n }),\n )\n })\n\n const close = Effect.fn('Lww.close')(function* () {\n const alreadyClosed = yield* Ref.modify(closed, current => [current, true] as const)\n if (alreadyClosed) return\n // Drains any accepted allocation before releasing the connection.\n yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.succeed([undefined, current] as const),\n )\n yield* storage.close\n })()\n\n return { next, close }\n },\n (effect, options) =>\n // Close a partially initialized storage on any failure, including a defect,\n // so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : options.storage.close.pipe(Effect.ignore),\n ),\n ),\n)\n\n/**\n * A schema and reducer helper for a last-writer-wins register.\n * Allocate a unique stamp per write before dispatch, and retain it in the Message.\n * Merge is for decoded values; the application's schema validates wire input.\n */\nexport const lwwRegister = <Value, Encoded, RD, RE>(\n value: Schema.Codec<Value, Encoded, RD, RE>,\n) => {\n const schema = Schema.Struct({ stamp: Stamp, value })\n type Register = typeof schema.Type\n const equivalent = Schema.toEquivalence(value)\n\n const merge = (left: Register, right: Register): Register => {\n if (left.stamp.counter !== right.stamp.counter)\n return left.stamp.counter > right.stamp.counter ? left : right\n if (left.stamp.replicaId !== right.stamp.replicaId)\n return left.stamp.replicaId > right.stamp.replicaId ? left : right\n // Reusing a write identity for different values would make arrival order win.\n if (!equivalent(left.value, right.value)) throw new Error('Conflicting LWW write identity')\n return left\n }\n\n return { schema, merge }\n}\n"],"mappings":";;;;;AAMA,MAAM,QAAQ,OAAO,OAAO;CAC1B,SAAS,OAAO,OAAO,MACrB,OAAO,MAAM,GACb,OAAO,uBAAuB,CAAC,GAC/B,OAAO,oBAAoB,OAAO,gBAAgB,CACpD;CACA,WAAW;AACb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