foldkit-sync 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { b as SocketLike, f as Sync, m as TransportClient, o as Operation } from "./sync-CP5UGs4r.mjs";
1
+ import { E as TransportClient, M as SocketLike, n as AuthorizeDecision, v as Operation, w as Sync } from "./make-h5yD8STj.mjs";
2
2
  import { Effect, Option, Schema } from "effect";
3
3
  import { Journal } from "foldkit-durable/core";
4
4
  //#region src/journal.d.ts
@@ -22,12 +22,21 @@ export interface JournalExchangeOptions<Message, Shared, Principal> {
22
22
  */
23
23
  readonly settle?: Effect.Effect<void, unknown> | undefined;
24
24
  /**
25
- * Refuses an operation before the journal sees it, by what the transport
26
- * established rather than by the document: a principal that may only read.
27
- * A refused operation is rejected by its id. The journal's own `authorize`
28
- * is where a rule about the document goes.
25
+ * Whether the connection may open the document at all, to read it or to
26
+ * change it: a principal outside its readers. Refused, every exchange fails,
27
+ * and nothing is read or appended.
29
28
  */
30
- readonly refuse?: ((operation: Operation) => boolean) | undefined;
29
+ readonly opens?: Effect.Effect<boolean> | undefined;
30
+ /**
31
+ * Whether an operation may be appended, decided before the journal sees it,
32
+ * by what the transport established rather than by the document: a principal
33
+ * that may only read, or a rule that reads the rows an edit names, which
34
+ * cannot run under the journal's lock (`foldkit-guard/sync`). `true` admits;
35
+ * a refusal is rejected by the operation's id, with its reason when it gives
36
+ * one. One that fails fails the exchange, as the journal failing does. The
37
+ * journal's own `authorize` is where a rule about the document goes.
38
+ */
39
+ readonly admit?: ((operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>) | undefined;
31
40
  /** The most committed operations one reply carries; a replica further behind asks again. Default 500. */
32
41
  readonly limit?: number | undefined;
33
42
  }
@@ -39,7 +48,8 @@ export interface JournalExchangeOptions<Message, Shared, Principal> {
39
48
  * rejected by its id when its message does not decode, it names another
40
49
  * document, or the journal refuses it (`authorize`, `validate`); the replica
41
50
  * drops it rather than send it again. Only an entry with no id at all, a
42
- * cursor ahead of the journal's, or the journal failing fails the exchange. The reply carries what committed
51
+ * cursor ahead of the journal's, a connection `opens` refuses, or `admit` or
52
+ * the journal failing fails the exchange. The reply carries what committed
43
53
  * after the replica's cursor, a checkpoint when that history was compacted,
44
54
  * and the journal's epoch, so a replica of a reset journal starts again.
45
55
  */
@@ -1 +1 @@
1
- {"version":3,"file":"journal.d.mts","names":[],"sources":["../src/journal.ts"],"mappings":";;;;iBAsBiB,uBAAuB,SAAS,QAAQ;;WAE9C,MAAM,KAAK,SAAS;;;;;WAKpB,SAAS,QAAQ,WAAW,QAAQ,WAAW;;;;;WAK/C,WAAW;;;;;;WAMX,SAAS,OAAO;;;;;;;WAOhB,WAAW,WAAW;;WAEtB;;;;;;;;;;;;;;qBAsBE,kBAAmB,SAAS,QAAQ,WAC/C,SAAS,uBAAuB,SAAS,QAAQ,eAChD;;;;;qBA6GU,iBACV,QAAQ,WACP,SAAS,QAAQ,WAAW,QAAQ,WAAW,YAC/C,yBACG;;;;;;qBAgBM,eAAgB,SAAS,QAAQ,WAC5C,QAAQ,YACR,SAAS,uBAAuB,SAAS,QAAQ;;;;;;;;;;;qBAetC,iCAAiC;MAI/B;;iBAKE,oBAAoB,QAAQ,WAAW;;WAE7C;;WAEA,SAAS,QAAQ,WAAW,QAAQ,WAAW;;;;;;WAM/C,UAAU,WAAW,cAAc,OAAO;aACxC,SAAS,cAAc;aACvB,IAAI,OAAO;;;;;;;;;;;;;WAab,QAAQ,QAAQ,QAAQ,eAAe,OAAO;;;;;;;WAO9C,eAAe,OAAO;;WAEtB,eAAe,UAAU,QAAQ;;;;;;WAMjC,WAAW,iBAAiB,mBAAmB;;WAE/C,QAAQ;;;;;;;;;;;;;;qBAeN,eAAgB,QAAQ,WAAW,QAC9C,SAAS,oBAAoB,QAAQ,WAAW;WAEvC,QAAQ,OAAO;WACf,QAAQ,OAAO"}
1
+ {"version":3,"file":"journal.d.mts","names":[],"sources":["../src/journal.ts"],"mappings":";;;;iBAuBiB,uBAAuB,SAAS,QAAQ;;WAE9C,MAAM,KAAK,SAAS;;;;;WAKpB,SAAS,QAAQ,WAAW,QAAQ,WAAW;;;;;WAK/C,WAAW;;;;;;WAMX,SAAS,OAAO;;;;;;WAMhB,QAAQ,OAAO;;;;;;;;;;WAUf,UACH,WAAW,cAAc,oBAAoB,OAAO,OAAO;;WAGxD;;;;;;;;;;;;;;;qBAuBE,kBAAmB,SAAS,QAAQ,WAC/C,SAAS,uBAAuB,SAAS,QAAQ,eAChD;;;;;qBAqHU,iBACV,QAAQ,WACP,SAAS,QAAQ,WAAW,QAAQ,WAAW,YAC/C,yBACG;;;;;;qBAgBM,eAAgB,SAAS,QAAQ,WAC5C,QAAQ,YACR,SAAS,uBAAuB,SAAS,QAAQ;;;;;;;;;;;qBA8BtC,iCAAiC;MAI/B;;iBAKE,oBAAoB,QAAQ,WAAW;;WAE7C;;WAEA,SAAS,QAAQ,WAAW,QAAQ,WAAW;;;;;;WAM/C,UAAU,WAAW,cAAc,OAAO;aACxC,SAAS,cAAc;aACvB,IAAI,OAAO;;;;;;;;;;;;;WAab,QAAQ,QAAQ,QAAQ,eAAe,OAAO;;;;;;;WAO9C,eAAe,OAAO;;WAEtB,eAAe,UAAU,QAAQ;;;;;;WAMjC,WAAW,iBAAiB,mBAAmB;;WAE/C,QAAQ;;;;;;;;;;;;;;qBAeN,eAAgB,QAAQ,WAAW,QAC9C,SAAS,oBAAoB,QAAQ,WAAW;WAEvC,QAAQ,OAAO;WACf,QAAQ,OAAO"}
package/dist/journal.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { c as serveSocket, y as sequence } from "./transport-hlEQpHIv.mjs";
1
+ import { b as sequence, c as serveSocket } from "./transport-DiKXy5zx.mjs";
2
2
  import { Effect, Fiber, Match, Option, Schema, Stream } from "effect";
3
3
  import { Cursor, DocumentId, Sequence } from "foldkit-durable/core";
4
4
  //#region src/journal.ts
@@ -22,7 +22,8 @@ const idOf = (input) => Option.map(Schema.decodeUnknownOption(Schema.Struct({ op
22
22
  * rejected by its id when its message does not decode, it names another
23
23
  * document, or the journal refuses it (`authorize`, `validate`); the replica
24
24
  * drops it rather than send it again. Only an entry with no id at all, a
25
- * cursor ahead of the journal's, or the journal failing fails the exchange. The reply carries what committed
25
+ * cursor ahead of the journal's, a connection `opens` refuses, or `admit` or
26
+ * the journal failing fails the exchange. The reply carries what committed
26
27
  * after the replica's cursor, a checkpoint when that history was compacted,
27
28
  * and the journal's epoch, so a replica of a reset journal starts again.
28
29
  */
@@ -38,6 +39,7 @@ const journalExchange = (options) => {
38
39
  actorId: committed.actorId
39
40
  }, sync.documentId);
40
41
  const exchange = (cursor, pending, seen) => Effect.gen(function* () {
42
+ if (options.opens !== void 0 && !(yield* options.opens)) return yield* Effect.fail(/* @__PURE__ */ new Error("This connection may not open the document"));
41
43
  const epoch = yield* journal.epoch(key);
42
44
  const from = seen !== void 0 && seen !== epoch ? 0 : cursor;
43
45
  const at = yield* journal.cursor(key);
@@ -61,8 +63,10 @@ const journalExchange = (options) => {
61
63
  continue;
62
64
  }
63
65
  const operation = decoded.value;
64
- if (options.refuse?.(operation) === true) {
65
- reject(operation.opId, "This connection may not make changes");
66
+ const admitted = options.admit === void 0 ? true : options.admit(operation);
67
+ const decision = Effect.isEffect(admitted) ? yield* admitted : admitted;
68
+ if (decision !== true) {
69
+ reject(operation.opId, decision === false ? "This connection may not make changes" : decision.reason);
66
70
  continue;
67
71
  }
68
72
  yield* journal.append(key, operation, principal).pipe(Effect.map((appended) => acknowledged.push(Match.valueTags(appended, {
@@ -115,9 +119,13 @@ const journalChanges = (journal, documentId) => (listener) => {
115
119
  */
116
120
  const serveJournal = (socket, options) => {
117
121
  const client = journalExchange(options);
122
+ const notices = journalChanges(options.journal, options.sync.documentId);
123
+ const { opens } = options;
118
124
  return serveSocket(socket, {
119
125
  exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),
120
- changes: journalChanges(options.journal, options.sync.documentId)
126
+ changes: opens === void 0 ? notices : (listener) => notices(() => void Effect.runPromise(opens).then((open) => {
127
+ if (open) listener();
128
+ }, () => {}))
121
129
  });
122
130
  };
123
131
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"journal.mjs","names":["JournalDocumentId"],"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 { Effect, Fiber, Match, Option, Schema, Stream } from 'effect'\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 { Operation, Sync, TransportClient } from './sync.js'\nimport { serveSocket, type SocketLike } from './transport.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 * Refuses an operation before the journal sees it, by what the transport\n * established rather than by the document: a principal that may only read.\n * A refused operation is rejected by its id. The journal's own `authorize`\n * is where a rule about the document goes.\n */\n readonly refuse?: ((operation: Operation) => boolean) | 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, or 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 // 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 if (options.refuse?.(operation) === true) {\n reject(operation.opId, 'This connection may not make changes')\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 */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, Operation>,\n documentId: string,\n ): ((listener: () => void) => () => void) =>\n listener => {\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () => Effect.sync(listener),\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): (() => void) => {\n const client = journalExchange(options)\n return serveSocket(socket, {\n exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),\n changes: journalChanges(options.journal, options.sync.documentId),\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"],"mappings":";;;;;;;;;;;;;;;AAqDA,MAAM,QAAQ,UACZ,OAAO,IACL,OAAO,oBAAoB,OAAO,OAAO,EAAE,MAAM,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC,KAAK,IACvE,EAAE,WAAW,IAChB;;;;;;;;;;;;;AAcF,MAAa,mBACX,YACoB;CACpB,MAAM,EAAE,MAAM,SAAS,cAAc;CACrC,MAAM,QAAQ,QAAQ,SAAS;CAC/B,MAAM,MAAMA,WAAkB,KAAK,K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OAAO;EAAE,QA3BM,OAAO,IAAI,aAAa;GACrC,MAAM,QAAQ,OAAO,QAAQ,MAAM,GAAG;GAEtC,MAAM,OAAO,OAAO,OAAO,MACzB,OAAO,OAAO,UAAS,aAAY,SAAS,UAAU,KAAK,GAC3D;IACE,SAAS,EAAE,aAAa,OAAO,QAAQ,MAAM;IAC7C,cAAc;GAChB,CACF;GACA,MAAM,SAAS,OAAO,QAAQ,QAAQ;IAAE;IAAK;IAAM,SAAS,QAAQ,KAAK;GAAE,CAAC;GAC5E,UAAU,OAAO,KAAK;IAAE;IAAQ;GAAM,CAAC;EACzC,CAec;EAAG,QAZF,OAAO,IAAI,aAAa;GACrC,MAAM,QAAQ,OAAO,QAAQ,MAAM,GAAG;GACtC,MAAM,QAAQ,OAAO,OAAO,UAAS,aAAY,SAAS,UAAU,KAAK;GACzE,IAAI,OAAO,OAAO,KAAK,GAAG;GAC1B,MAAM,UAAU,MAAM,MAAM;GAC5B,MAAM,EAAE,UAAU,WAAW,OAAO,QAAQ,KAAK,GAAG;GACpD,IAAI,CAAC,QAAQ,aAAa,UAAU,OAAO,GAAG;GAC9C,OAAO,QAAQ,OAAO,KAAK,QAAQ,SAAS,SAAS,MAAM,GAAG,QAAQ,MAAM;GAG5E,OAAO,QAAQ,QAAQ,KAAK,SAAS,KAAK,OAAO,CAAC;EACpD,CACsB;CAAE;AAC1B"}
1
+ {"version":3,"file":"journal.mjs","names":["JournalDocumentId"],"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 { Effect, Fiber, Match, Option, Schema, Stream } from 'effect'\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 { serveSocket, type SocketLike } from './transport.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 */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, Operation>,\n documentId: string,\n ): ((listener: () => void) => () => void) =>\n listener => {\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () => Effect.sync(listener),\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): (() => void) => {\n const client = journalExchange(options)\n const notices = journalChanges(options.journal, options.sync.documentId)\n const { opens } = options\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(opens).then(\n open => {\n if (open) listener()\n },\n () => {},\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"],"mappings":";;;;;;;;;;;;;;;AAiEA,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,cAA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AM,GAAG,QAAQ,MAAM;GAG5E,OAAO,QAAQ,QAAQ,KAAK,SAAS,KAAK,OAAO,CAAC;EACpD,CACsB;CAAE;AAC1B"}
@@ -1,4 +1,5 @@
1
1
  import { Config, Context, Duration, Effect, Layer, Metric, Option, Schema, Stream } from "effect";
2
+ import { AppScope, Contract, MergeConstructors, MergeFields, MessageSet, RunnableApplication, Surface, Wiring, WritableProjection } from "foldkit-surface";
2
3
  //#region src/ids.d.ts
3
4
  /** Identifies the replicated document a replica or operation belongs to. */
4
5
  declare const DocumentId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/DocumentId">;
@@ -274,6 +275,14 @@ declare const nativeSocket: (url: string) => SocketLike;
274
275
  declare const portSocket: (port: MessagePort, options?: {
275
276
  readonly signal?: AbortSignal | undefined;
276
277
  }) => SocketLike;
278
+ /**
279
+ * A socket over an existing `WebSocket`: the accepted end of a Cloudflare
280
+ * `WebSocketPair`, or any other socket the platform hands over. Unlike
281
+ * `nativeSocket` it opens nothing — accept the pair first — and unlike
282
+ * `portSocket` there is no signal: the socket closing, erroring, or being
283
+ * closed fires `onClose` once, which is how a host stops serving it.
284
+ */
285
+ declare const workerSocket: (socket: WebSocket) => SocketLike;
277
286
  /**
278
287
  * A WebSocket client transport.
279
288
  *
@@ -543,5 +552,163 @@ interface JournalContract<Operation, Shared> {
543
552
  */
544
553
  declare const defineSync: <Message, Shared, MessageEncoded, SharedEncoded>(definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>) => Sync<Message, Shared>;
545
554
  //#endregion
546
- export { Sequence as $, serveSocket as A, InvalidOutboxError as B, TransportError as C, layerSocket as D, layerLoopback as E, CheckpointRegressionError as F, StorageError as G, ReplayError as H, CommittedOrderError as I, WrongReplicaStorageError as J, UnsupportedClockVersionError as K, ForeignAcknowledgementError as L, OutboxEntry as M, Storage as N, nativeSocket as O, indexedDb as P, ReplicaId as Q, ForeignRejectionError as R, Transport as S, layerFromPromise as T, ReplicaClosedError as U, InvalidReplicaHistoryError as V, ReplicaError as W, LocalSequence as X, DocumentId as Y, OpId as Z, ExchangeFrame as _, JournalContract as a, SocketLike as b, Replica as c, ReplicaStatus as d, documentId as et, Sync as f, syncMetrics as g, defineSync as h, Exchange as i, sequence as it, toPromise as j, portSocket as k, ReplicaSnapshot as l, TransportClient as m, CommitStamp as n, opId as nt, Operation as o, SyncDefinition as p, UnsupportedReplicaVersionError as q, CommittedOperation as r, replicaId as rt, Rejection as s, Checkpoint as t, localSequence as tt, ReplicaState as u, ExchangeReply as v, TransportShape as w, SocketOptions as x, NotifyFrame as y, InvalidExchangeError as z };
547
- //# sourceMappingURL=sync-CP5UGs4r.d.mts.map
555
+ //#region src/make.d.ts
556
+ type MessageConstructor<Message> = (...args: never[]) => Message;
557
+ /** The Message union a tuple of constructors produces. */
558
+ type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends ((...args: never[]) => infer M) ? M : never;
559
+ type AppMessage<AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>;
560
+ /** The `_tag` literal of the Message a constructor produces. */
561
+ type TagOf<C> = C extends ((...args: never[]) => infer M) ? M extends {
562
+ readonly _tag: infer T extends string;
563
+ } ? T : never : never;
564
+ /**
565
+ * A journal contract that also carries the declared authorization policy, in
566
+ * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.
567
+ */
568
+ interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<Operation, Shared> {
569
+ readonly authorize?: (request: {
570
+ readonly principal: Principal;
571
+ readonly operation: Operation;
572
+ readonly snapshot: Shared;
573
+ }) => AuthorizeDecision;
574
+ }
575
+ /**
576
+ * What a rule decides: allowed, refused, or refused with a reason the server
577
+ * sends to the person whose edit it was. The shape of Durable's own decision.
578
+ */
579
+ type AuthorizeDecision = boolean | {
580
+ readonly allowed: false;
581
+ readonly reason: string;
582
+ };
583
+ /** What a per-variant `authorize` rule sees before the journal commits. */
584
+ interface AuthorizeRequest<Principal, Message, Shared> {
585
+ readonly principal: Principal;
586
+ readonly message: Message;
587
+ readonly shared: Shared;
588
+ }
589
+ /**
590
+ * Per-variant policy, keyed by durable tag: `message` is that variant exactly,
591
+ * `shared` the authoritative snapshot. A variant without a rule is allowed; the
592
+ * server may still refuse on its own grounds.
593
+ */
594
+ type AuthorizePolicy<Principal, Fields extends Schema.Struct.Fields, Ms extends readonly unknown[]> = { readonly [K in TagOf<Ms[number]>]?: (request: AuthorizeRequest<Principal, Extract<MsgOf<Ms>, {
595
+ readonly _tag: K;
596
+ }>, Schema.Struct.Type<Fields>>) => AuthorizeDecision; };
597
+ /**
598
+ * Per-variant commit stamps, keyed by durable tag: each writes what the server's commit
599
+ * decided (its sequence, its actor) into that variant, and returns the same variant. A
600
+ * variant without one is committed as sent.
601
+ */
602
+ type StampPolicy<Ms extends readonly unknown[]> = { readonly [K in TagOf<Ms[number]>]?: (message: Extract<MsgOf<Ms>, {
603
+ readonly _tag: K;
604
+ }>, commit: CommitStamp) => Extract<MsgOf<Ms>, {
605
+ readonly _tag: K;
606
+ }>; };
607
+ interface BaseOptions<Principal, Fields extends Schema.Struct.Fields, Ms extends readonly unknown[]> {
608
+ readonly documentId: DocumentId;
609
+ /** Name for the generated `surface`; defaults to the document id. */
610
+ readonly name?: string;
611
+ /**
612
+ * Replaces the replay derived from the application's `update`. It is a pure
613
+ * reducer over the shared subset; only durable Messages reach it, and it runs
614
+ * during admission, replay, and optimistic projection. It is not guarded: the
615
+ * author owns its agreement with `update`.
616
+ */
617
+ readonly replay?: (shared: Schema.Struct.Type<NoInfer<Fields>>, message: MsgOf<NoInfer<Ms>>) => Schema.Struct.Type<NoInfer<Fields>>;
618
+ /** Authorization the server journal applies before committing; see `AuthorizePolicy`. */
619
+ readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>;
620
+ /** What the server's commit writes into a durable Message; see `StampPolicy`. */
621
+ readonly stamp?: StampPolicy<NoInfer<Ms>>;
622
+ /**
623
+ * Merges a durable Message into the one submitted before it while that one is unsent,
624
+ * so a burst of edits is one operation. Replaying the result must equal replaying
625
+ * `last` then `next`; undefined keeps them apart.
626
+ */
627
+ readonly coalesce?: (last: MsgOf<NoInfer<Ms>>, next: MsgOf<NoInfer<Ms>>) => MsgOf<NoInfer<Ms>> | undefined;
628
+ }
629
+ interface MakeOptions<AppModel, Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[], Principal = unknown> extends BaseOptions<Principal, Fields, Ms> {
630
+ /** The writable projection of the shared fields. */
631
+ readonly shared: WritableProjection<AppModel, Fields>;
632
+ /** The Message subset the replica durably records and replays. */
633
+ readonly durable: MessageSet<AppModel, any, Subset, Ms>;
634
+ }
635
+ /**
636
+ * One feature's contribution to a document: the fields it shares and the
637
+ * Messages it records. `compose` merges fragments into one, to spread into
638
+ * `make`; a field declared twice with a different codec or a tag declared twice
639
+ * is rejected there.
640
+ */
641
+ interface SyncFragment<AppModel, Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<any>[]> {
642
+ readonly shared: WritableProjection<AppModel, Fields>;
643
+ readonly durable: MessageSet<AppModel, any, Subset, Ms>;
644
+ }
645
+ type SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = { readonly [K in keyof Fs]: Fs[K]['shared']; };
646
+ type DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = { readonly [K in keyof Fs]: Fs[K]['durable']; };
647
+ /** The merged shared fields of several fragments. */
648
+ type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<SharedOf<Fs>>;
649
+ /** The concatenated durable constructors of several fragments. */
650
+ type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeConstructors<DurableOf<Fs>>;
651
+ /** The union of Messages several fragments record. */
652
+ type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> = Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never;
653
+ /**
654
+ * The value `make` returns: the low-level `Sync` protocol plus the writable
655
+ * projection, the declared Messages, and a read-only Surface over the
656
+ * projection. Exported so a consumer can name the type.
657
+ */
658
+ interface DefinedSync<AppModel, Fields extends Schema.Struct.Fields, Message, Ms extends readonly unknown[], Principal = unknown,
659
+ /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */
660
+ Authorized extends boolean = false> extends Sync<Message, Schema.Struct.Type<Fields>> {
661
+ readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>;
662
+ readonly projection: WritableProjection<AppModel, Fields>;
663
+ /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */
664
+ readonly replay: (shared: Schema.Struct.Type<Fields>, message: Message) => Schema.Struct.Type<Fields>;
665
+ readonly messages: Ms;
666
+ /** For `Module`: this contract owns the shared projection's paths and records the durable tags. */
667
+ readonly contract: Contract;
668
+ /**
669
+ * How this contract joins an assembly: contract-only, so the Module sees it.
670
+ * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the
671
+ * runtime through `mount` rather than joining it.
672
+ */
673
+ readonly wiring: () => Wiring<AppModel, never>;
674
+ /** The durable journal's codecs, reducer, and, when declared, authorization. */
675
+ readonly journalContract: () => Authorized extends true ? PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal> & Required<Pick<PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>, 'authorize'>> : PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>;
676
+ }
677
+ /** The sync constructors specialized to one application. */
678
+ interface ApplicationSync<AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>, Principal = unknown> {
679
+ /**
680
+ * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a
681
+ * positional type argument beside an inferred Model, so it is supplied here:
682
+ * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.
683
+ */
684
+ readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>;
685
+ /** One feature's shared fields and durable Messages, for `compose`. */
686
+ readonly fragment: <Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(config: {
687
+ readonly shared: WritableProjection<AppModel, Fields>;
688
+ readonly durable: MessageSet<AppModel, any, Subset, Ms>;
689
+ }) => SyncFragment<AppModel, Fields, Subset, Ms>;
690
+ /**
691
+ * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.
692
+ * A field declared twice with a different codec, a tag declared twice, or a
693
+ * fragment from another application throws.
694
+ */
695
+ readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(...fragments: Fs) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>;
696
+ readonly make: {
697
+ <Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal> & {
698
+ readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<Ms>>;
699
+ }): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true>;
700
+ <Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[]>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal>): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal>;
701
+ };
702
+ }
703
+ /**
704
+ * Specializes the sync constructors to a `Surface.application`, so
705
+ * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the
706
+ * shared codec, the initial snapshot, the durable predicate, and replay from
707
+ * the application, and refuses a subset that belongs to another application.
708
+ * `defineSync` remains the protocol primitive when there is no application to
709
+ * derive from.
710
+ */
711
+ declare const forApplication: <AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>>(app: RunnableApplication<AppModel, F, Cases, any>) => ApplicationSync<AppModel, F, Cases>;
712
+ //#endregion
713
+ export { InvalidOutboxError as $, ExchangeReply as A, nativeSocket as B, ReplicaStatus as C, defineSync as D, TransportClient as E, TransportError as F, OutboxEntry as G, serveSocket as H, TransportShape as I, CheckpointRegressionError as J, Storage as K, layerFromPromise as L, SocketLike as M, SocketOptions as N, syncMetrics as O, Transport as P, InvalidExchangeError as Q, layerLoopback as R, ReplicaState as S, SyncDefinition as T, toPromise as U, portSocket as V, workerSocket as W, ForeignAcknowledgementError as X, CommittedOrderError as Y, ForeignRejectionError as Z, JournalContract as _, sequence as _t, DefinedSync as a, UnsupportedClockVersionError as at, Replica as b, MsgOf as c, DocumentId as ct, SyncFragment as d, ReplicaId as dt, InvalidReplicaHistoryError as et, forApplication as f, Sequence as ft, Exchange as g, replicaId as gt, CommittedOperation as h, opId as ht, AuthorizeRequest as i, StorageError as it, NotifyFrame as j, ExchangeFrame as k, PolicyJournalContract as l, LocalSequence as lt, CommitStamp as m, localSequence as mt, AuthorizeDecision as n, ReplicaClosedError as nt, FragmentMessages as o, UnsupportedReplicaVersionError as ot, Checkpoint as p, documentId as pt, indexedDb as q, AuthorizePolicy as r, ReplicaError as rt, MakeOptions as s, WrongReplicaStorageError as st, ApplicationSync as t, ReplayError as tt, StampPolicy as u, OpId as ut, Operation as v, Sync as w, ReplicaSnapshot as x, Rejection as y, layerSocket as z };
714
+ //# sourceMappingURL=make-h5yD8STj.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"make-h5yD8STj.d.mts","names":[],"sources":["../src/ids.ts","../src/errors.ts","../src/indexedDb.ts","../src/transport.ts","../src/sync.ts","../src/make.ts"],"mappings":";;;;cAGa,YAAU,OAAA,MAAA,OAAA;KACX,oBAAoB,WAAW;;cAG9B,WAAS,OAAA,MAAA,OAAA;KACV,mBAAmB,UAAU;;cAG5B,MAAI,OAAA,MAAA,OAAA;KACL,cAAc,KAAK;;;;;cAMlB,UAAQ,OAAA,MAAA,OAAA;KAKT,kBAAkB,SAAS;;cAG1B,eAAa,OAAA,MAAA,OA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L,eAAe,OAAO,OAAO,QAC7B,QACA,oBAAoB,mBAAmB,WAAW,UAAU,GAAG,WAE/D,SAAS,YAAY,UAAU,QAAQ,QAAQ,IAAI;eACxC,WAAW,gBAAgB,WAAW,QAAQ,SAAS,QAAQ;QAEzE,YAAY,UAAU,QAAQ,WAAW,UAAU,GAAG,QAAQ,IAAI;KAEnE,eAAe,OAAO,OAAO,QAC7B,QACA,oBAAoB,mBAAmB,WAAW,UAAU,GAAG,WAE/D,SAAS,YAAY,UAAU,QAAQ,QAAQ,IAAI,aAClD,YAAY,UAAU,QAAQ,WAAW,UAAU,GAAG,QAAQ,IAAI;;;;;;;;;;;cAqF5D,iBACX,UACA,UAAU,OAAO,OAAO,QACxB,cAAc,eAAe,OAAO,OAAO,SAE3C,KAAK,oBAAoB,UAAU,GAAG,gBACrC,gBAAgB,UAAU,GAAG"}
@@ -0,0 +1,123 @@
1
+ import { Author } from "./entity.mjs";
2
+ import { Option, Schema } from "effect";
3
+ import { OptimisticOperation, RemoteModel } from "foldkit-remote";
4
+ //#region src/remote.d.ts
5
+ /** What `RemoteEdits.make` uses of a Remote domain: `Remote.make`'s value is one. */
6
+ export interface RemoteOverlays<AppModel> {
7
+ readonly store: {
8
+ get(model: AppModel): RemoteModel;
9
+ };
10
+ overlay(model: AppModel, id: string, optimistic: ReadonlyArray<OptimisticOperation>): AppModel;
11
+ lift(model: AppModel, id: string): AppModel;
12
+ overlays(model: AppModel): ReadonlyArray<string>;
13
+ }
14
+ /** What `RemoteEdits.make` uses of `EditableEntity.make`'s value, over a named Entity. */
15
+ export interface EditsOf<Edit> {
16
+ readonly entity: {
17
+ readonly name: string;
18
+ };
19
+ readonly Edit: Schema.Codec<Edit, unknown>;
20
+ mine(edit: Edit, replica: string): boolean;
21
+ }
22
+ /** The fields every cell edit has, as `EditableEntity`'s `Edit` declares them. */
23
+ interface AnyEdit {
24
+ readonly member: string;
25
+ readonly at: Option.Option<number>;
26
+ readonly by: Option.Option<Author>;
27
+ }
28
+ /** A cell an overlay draws, and whether its edit is still in the slice or only held. */
29
+ export interface ShownEdit<Edit> {
30
+ readonly edit: Edit;
31
+ /** Absorbed from the slice, and shown until a read of its row has it. */
32
+ readonly held: boolean;
33
+ }
34
+ /** What `reconcile` did besides the Model. */
35
+ export interface Reconciled<AppModel, Edit> {
36
+ readonly model: AppModel;
37
+ /**
38
+ * Edits the journal absorbed that a cached row has not been read since. The
39
+ * row is out of date until it is: ask for it again, unless a live stream
40
+ * brings it.
41
+ */
42
+ readonly held: ReadonlyArray<Edit>;
43
+ /**
44
+ * `replica`'s own edits a read of their row reached with another value: the
45
+ * table applies in commit order, so a later edit replaced them. The slice
46
+ * may say whose later, or may not yet; this is the row saying it.
47
+ */
48
+ readonly replaced: ReadonlyArray<Edit>;
49
+ }
50
+ declare const make: <AppModel, Edit extends AnyEdit>(data: RemoteOverlays<AppModel>, edits: EditsOf<Edit>) => {
51
+ /**
52
+ * Brings Remote's overlays in line with `slice`: each edit its row has not
53
+ * reached is shown, and each overlay whose edit has left the slice is
54
+ * lifted, unless its row is cached below it, in which case it is held
55
+ * until a read of the row reaches it. This replica's edit the row has
56
+ * reached with its own value is kept, landed, until the slice drops it, so
57
+ * a later edit reaching the row live is seen replacing it. Call it from
58
+ * `Sync.mount`'s `afterUpdate`: a read can land in any Remote Message, and
59
+ * a replayed durable Message may not touch Remote. With nothing to change,
60
+ * the Model comes back as it was given.
61
+ *
62
+ * Only a committed edit can be held: its `at` says which revision has it.
63
+ * One that leaves the slice straight from pending, committed and absorbed
64
+ * before this page installed the commit, is lifted, and its row shows the
65
+ * cached read until it is read again.
66
+ */
67
+ reconcile: (model: AppModel, slice: ReadonlyArray<Edit>, replica: string) => Reconciled<AppModel, Edit>;
68
+ /**
69
+ * The edits the overlays show over their rows now, in the order they are
70
+ * drawn: for a cell's mark. One the row has reached, kept only to see a
71
+ * later edit replace it, is not among them.
72
+ */
73
+ shown: (model: AppModel) => ReadonlyArray<ShownEdit<Edit>>;
74
+ /**
75
+ * Lifts every overlay this bridge shows: for a server reset, after which
76
+ * the rows' revisions count a history that is gone.
77
+ */
78
+ clear: (model: AppModel) => AppModel;
79
+ };
80
+ export declare const RemoteEdits: {
81
+ /**
82
+ * The bridge between a slice of `EditableEntity` edits and a Remote domain
83
+ * that reads the same Entity, with its `revision`.
84
+ *
85
+ * ```ts
86
+ * const Shown = RemoteEdits.make(Data, ProductEdits)
87
+ * const { model: next } = Shown.reconcile(model, model.edits, model.replica)
88
+ * ```
89
+ */
90
+ make: <AppModel, Edit extends AnyEdit>(data: RemoteOverlays<AppModel>, edits: EditsOf<Edit>) => {
91
+ /**
92
+ * Brings Remote's overlays in line with `slice`: each edit its row has not
93
+ * reached is shown, and each overlay whose edit has left the slice is
94
+ * lifted, unless its row is cached below it, in which case it is held
95
+ * until a read of the row reaches it. This replica's edit the row has
96
+ * reached with its own value is kept, landed, until the slice drops it, so
97
+ * a later edit reaching the row live is seen replacing it. Call it from
98
+ * `Sync.mount`'s `afterUpdate`: a read can land in any Remote Message, and
99
+ * a replayed durable Message may not touch Remote. With nothing to change,
100
+ * the Model comes back as it was given.
101
+ *
102
+ * Only a committed edit can be held: its `at` says which revision has it.
103
+ * One that leaves the slice straight from pending, committed and absorbed
104
+ * before this page installed the commit, is lifted, and its row shows the
105
+ * cached read until it is read again.
106
+ */
107
+ reconcile: (model: AppModel, slice: ReadonlyArray<Edit>, replica: string) => Reconciled<AppModel, Edit>;
108
+ /**
109
+ * The edits the overlays show over their rows now, in the order they are
110
+ * drawn: for a cell's mark. One the row has reached, kept only to see a
111
+ * later edit replace it, is not among them.
112
+ */
113
+ shown: (model: AppModel) => ReadonlyArray<ShownEdit<Edit>>;
114
+ /**
115
+ * Lifts every overlay this bridge shows: for a server reset, after which
116
+ * the rows' revisions count a history that is gone.
117
+ */
118
+ clear: (model: AppModel) => AppModel;
119
+ };
120
+ };
121
+ export type RemoteEdits<AppModel, Edit extends AnyEdit> = ReturnType<typeof make<AppModel, Edit>>;
122
+ //#endregion
123
+ //# sourceMappingURL=remote.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"remote.d.mts","names":[],"sources":["../src/remote.ts"],"mappings":";;;;;iBAyBiB,eAAe;WACrB;IAAS,IAAI,OAAO,WAAW;;EACxC,QAAQ,OAAO,UAAU,YAAY,YAAY,cAAc,uBAAuB;EACtF,KAAK,OAAO,UAAU,aAAa;EACnC,SAAS,OAAO,WAAW;;;iBAIZ,QAAQ;WACd;aAAmB;;WACnB,MAAM,OAAO,MAAM;EAC5B,KAAK,MAAM,MAAM;;;UAIT;WACC;WACA,IAAI,OAAO;WACX,IAAI,OAAO,OAAO;;;iBAWZ,UAAU;WAChB,MAAM;;WAEN;;;iBAIM,WAAW,UAAU;WAC3B,OAAO;;;;;;WAMP,MAAM,cAAc;;;;;;WAMpB,UAAU,cAAc;;cAG7B,OAAQ,UAAU,aAAa,SACnC,MAAM,eAAe,WACrB,OAAO,QAAQ;;;;;;;;;;;;;;;;;EA8EJ,YAAA,OAAA,UAAQ,OACR,cAAc,OAAK,oBAEzB,WAAW,UAAU;;;;;;EA8DT,QAAA,OAAA,aAAW,cAAc,UAAU;;;;;EAWnC,QAAA,OAAA,aAAW;;qBAKjB;;;;;;;;;;EAjKC,OAAA,UAAU,aAAa,SAAO,MACpC,eAAe,WAAS,OACvB,QAAQ;;;;;;;;;;;;;;;;;IA8EJ,YAAA,OAAA,UAAQ,OACR,cAAc,OAAK,oBAEzB,WAAW,UAAU;;;;;;IA8DT,QAAA,OAAA,aAAW,cAAc,UAAU;;;;;IAWnC,QAAA,OAAA,aAAW;;;YAiBlB,YAAY,UAAU,aAAa,WAAW,kBAAkB,KAAK,UAAU"}