foldkit-sync 0.16.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +160 -27
- package/dist/diagnostics.d.ts +29 -2
- package/dist/diagnostics.d.ts.map +1 -1
- package/dist/diagnostics.js +33 -4
- package/dist/diagnostics.js.map +1 -1
- package/dist/do.d.ts +11 -8
- package/dist/do.d.ts.map +1 -1
- package/dist/do.js +3 -4
- package/dist/do.js.map +1 -1
- package/dist/errors.d.ts +16 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -3
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +9 -7
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/journal.d.ts +15 -9
- package/dist/journal.d.ts.map +1 -1
- package/dist/journal.js +48 -19
- package/dist/journal.js.map +1 -1
- package/dist/make.d.ts +40 -6
- package/dist/make.d.ts.map +1 -1
- package/dist/make.js +35 -3
- package/dist/make.js.map +1 -1
- package/dist/mount.d.ts.map +1 -1
- package/dist/mount.js +27 -2
- package/dist/mount.js.map +1 -1
- package/dist/refusal.d.ts +10 -2
- package/dist/refusal.d.ts.map +1 -1
- package/dist/refusal.js +10 -4
- package/dist/refusal.js.map +1 -1
- package/dist/serverJournal.d.ts +6 -1
- package/dist/serverJournal.d.ts.map +1 -1
- package/dist/serverJournal.js +1 -1
- package/dist/serverJournal.js.map +1 -1
- package/dist/sync.d.ts +48 -7
- package/dist/sync.d.ts.map +1 -1
- package/dist/sync.js +28 -8
- package/dist/sync.js.map +1 -1
- package/dist/transport.d.ts +35 -8
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +41 -8
- package/dist/transport.js.map +1 -1
- package/package.json +12 -12
package/dist/journal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.js","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 {\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 JournalError,\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 { fitWords, SyncRefusal } from './refusal.js'\nimport type { Operation, Sync, TransportClient, WrittenOperation } from './sync.js'\nimport {\n ServerOnlyMessageError,\n UnreadableHistoryError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n} from './errors.js'\nimport { checkRevalidate } from './revalidate.js'\nimport {\n hostDefect,\n listenerFailed,\n reportTo,\n serverOnlySubmitted,\n type HostStage,\n type SyncDiagnostic,\n} from './diagnostics.js'\nimport { serveSocket, type SocketLike } from './transport.js'\nimport type { ServerJournal } from './serverJournal.js'\n\nexport type { HostDefect, HostStage } from './diagnostics.js'\nexport {\n reaction,\n serverJournal,\n type Parked,\n type Reaction,\n type ReactionOptions,\n type Requires,\n type ServerJournal,\n type ServerJournalOptions,\n type Trigger,\n} from './serverJournal.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, WrittenOperation>\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 * Where a `ServerOnlySubmitted` goes: a replica sent a Message only the\n * server appends. The reporter in context when not given, by default the log.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n}\n\nconst encodeRefusal = Schema.encodeSync(SyncRefusal)\n/** A refusal in the server's own words, which name no Entity's invariant. */\nconst invalidAs = (message: string): SyncRefusal =>\n SyncRefusal.Invalid({ entity: Option.none(), rule: Option.none(), message, path: [] })\n\n/** The version an entry claims, read before anything else of it, so a newer one is told from a malformed one. */\nconst claimedVersion = Schema.decodeUnknownOption(\n Schema.Struct({ messageVersion: Schema.optionalKey(Schema.Number) }),\n)\n\n/**\n * What the replica is told: a socket sends an error's message, and the\n * operation's id and version are another replica's. They stay on the error,\n * for the server's own logs.\n */\nconst HISTORY_UNREADABLE = 'This server cannot read the history of this document'\n\n/**\n * A stored row that will not read, as the journal reports it: a\n * `JournalError` whose cause is the codec's own error, never told by its words.\n */\nconst unreadableHistory = (\n documentId: string,\n cause: unknown,\n): Option.Option<UnreadableHistoryError> => {\n if (cause instanceof UnreadableMessageError)\n return Option.some(\n new UnreadableHistoryError({\n documentId,\n opId: cause.opId,\n version: cause.version,\n message: HISTORY_UNREADABLE,\n }),\n )\n if (cause instanceof UnsupportedMessageVersionError)\n return Option.some(\n new UnreadableHistoryError({\n documentId,\n opId: cause.opId,\n version: cause.found,\n message: HISTORY_UNREADABLE,\n }),\n )\n return Option.none()\n}\n\n/** What a replica that sent a server-only Message is told. */\nconst SERVER_ONLY_REASON = 'Only the server makes this change'\n\n/** The replica id an entry claims, for a diagnostic: read without trusting the rest of it. */\nconst replicaOf = (input: unknown): string =>\n Option.match(Schema.decodeUnknownOption(Schema.Struct({ replicaId: Schema.String }))(input), {\n onNone: () => '?',\n onSome: ({ replicaId }) => fitWords(replicaId),\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, as received, and acknowledged once committed, or already\n * committed. Every hook (`admit`, and the journal's `validate`, `authorize`,\n * `reduce` and `stamp`) sees its Message upcast to the current version. One\n * is rejected by its id when its message does not decode, it names another\n * document, the journal refuses it (`authorize`, `validate`), or it was\n * written at an older version no step reads (`Unreadable`); the replica drops\n * it, or keeps an unreadable one in `refused`, rather than send it again. An\n * entry written at a version newer than this server's fails the exchange\n * before anything is appended, so its replica waits with its outbox whole; so\n * do an entry with no id at all, a cursor ahead of the journal's, a\n * connection `opens` refuses, `admit` or the journal failing, and a stored\n * operation that will not read (`UnreadableHistoryError`). 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 contract = sync.journalContract()\n const supported = sync.codec.messageVersion\n /**\n * An entry as written, with what it means: its Message upcast to the current\n * version. Older and unread by any step is told apart, as `Unreadable`, and\n * a Message only the server appends, as `Forbidden`; anything else that\n * fails is not an operation this server accepts.\n */\n const operationOf = (\n input: unknown,\n ): Result.Result<\n { readonly written: WrittenOperation; readonly operation: Operation },\n UnreadableMessageError | ServerOnlyMessageError | 'invalid'\n > => {\n try {\n const written = sync.codec.writtenFrom(input, sync.documentId)\n return Result.succeed({ written, operation: sync.codec.normalizeOperation(written) })\n } catch (cause) {\n return Result.fail(\n cause instanceof UnreadableMessageError || cause instanceof ServerOnlyMessageError\n ? cause\n : 'invalid',\n )\n }\n }\n /** As the replica reads it: written at this server's version, with its order and actor. */\n const committedOf = (committed: Committed<Operation>) => {\n const written = {\n ...contract.operation.encode(committed.operation),\n serverSequence: committed.sequence,\n actorId: committed.actorId,\n }\n // Checked as the replica will check it: a row of another document is the server's fault.\n sync.codec.committedFrom(written, sync.documentId)\n return written\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 // A replica ahead of this server waits, its outbox whole: refused before\n // anything is appended, since a rejection would lose the edit.\n for (const input of pending) {\n const found = Option.flatMapNullishOr(claimedVersion(input), probe => probe.messageVersion)\n if (Option.isSome(found) && found.value > supported)\n return yield* Option.match(idOf(input), {\n onNone: () => Effect.fail(new Error('A pending entry names no operation')),\n onSome: opId =>\n Effect.fail(\n new UnsupportedMessageVersionError({\n opId,\n found: found.value,\n supported,\n message: `The replica writes Message version ${found.value}; this server reads up to ${supported}`,\n }),\n ),\n })\n }\n const rejected: Array<string> = []\n const refusals: Array<{ readonly opId: string; readonly refusal: unknown }> = []\n // Deprecated: the words alone, for a replica that reads `reason`.\n const reasons: Array<{ readonly opId: string; readonly reason: string }> = []\n // Words reach the person whose edit came back: a policy's own, or a fixed\n // sentence, never an error's message, which may carry internals.\n const reject = (opId: string, refusal: SyncRefusal, reason: string) => {\n rejected.push(opId)\n refusals.push({ opId, refusal: encodeRefusal(refusal) })\n reasons.push({ opId, reason })\n }\n const forbid = (opId: string, reason: string | undefined, otherwise: string) => {\n const fitted = reason === undefined ? undefined : fitWords(reason)\n reject(\n opId,\n SyncRefusal.Forbidden({ reason: Option.fromUndefinedOr(fitted) }),\n fitted ?? otherwise,\n )\n }\n const invalid = (opId: string, message: string) => reject(opId, invalidAs(message), message)\n const acknowledged: Array<string> = []\n for (const input of pending) {\n const decoded = operationOf(input)\n if (Result.isFailure(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 const failure = decoded.failure\n if (failure === 'invalid') invalid(id.value, 'Not an operation this server accepts')\n else if (failure instanceof UnreadableMessageError)\n reject(\n id.value,\n SyncRefusal.Unreadable({ version: failure.version }),\n 'Written by a version of the app this server cannot read',\n )\n else {\n forbid(id.value, SERVER_ONLY_REASON, SERVER_ONLY_REASON)\n yield* reportTo(\n options.diagnostics,\n serverOnlySubmitted(sync.documentId, id.value, replicaOf(input)),\n )\n }\n continue\n }\n const { written, operation } = decoded.success\n const admitted = options.admit === undefined ? true : options.admit(operation)\n const decision = Effect.isEffect(admitted) ? yield* admitted : admitted\n if (decision !== true) {\n forbid(\n operation.opId,\n decision === false ? undefined : decision.reason,\n 'This connection may not make changes',\n )\n continue\n }\n // As received: the journal compares a retransmission by what was sent.\n yield* journal.append(key, written, 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(() => forbid(error.opId, error.reason, 'Refused by the server')),\n InvalidOperationError: () =>\n Effect.sync(() => invalid(operation.opId, 'Not a valid operation')),\n IdentityConflictError: () =>\n Effect.sync(() => invalid(operation.opId, 'Its id was already used for another')),\n }),\n )\n }\n if (options.settle !== undefined) yield* options.settle\n // Sent only when something was refused: a replica built before `refusals`\n // decodes the reply strictly and fails on the key, so it fails only then.\n const refused = refusals.length === 0 ? {} : { refusals }\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.try({\n try: () => rows.map(committedOf),\n catch: cause => new Error('Could not read the log', { cause }),\n }).pipe(\n Effect.map(operations => ({\n operations,\n rejected,\n ...refused,\n reasons,\n acknowledged,\n more: rows.length === limit,\n epoch,\n })),\n ),\n onNone: () =>\n Effect.map(journal.load(key), loaded => ({\n operations: [],\n rejected,\n ...refused,\n reasons,\n acknowledged,\n checkpoint: {\n cursor: loaded.cursor,\n model: contract.snapshot.encode(loaded.snapshot),\n },\n epoch,\n })),\n })\n }).pipe(\n // A stored operation that will not read stops the document, typed for the server's logs.\n Effect.mapError(error =>\n error instanceof JournalError\n ? Option.getOrElse(unreadableHistory(sync.documentId, error.cause), () => error)\n : error,\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, WrittenOperation>,\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, Absorbed = never> {\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, WrittenOperation>\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 * Records that the table holds every edit through `through`, as the\n * server: `absorbed(through)` is the server-only Message the replicas drop\n * those edits on hearing, appended under the key `absorbed/<through>`. The\n * log is compacted no further than the server journal's `settledThrough`,\n * so its reactions see every commit first.\n */\n readonly asServer?:\n | {\n readonly journal: ServerJournal<Absorbed, any>\n readonly absorbed: (through: number) => Absorbed\n }\n | undefined\n /**\n * @deprecated Declare the Message `serverOnly` and pass `asServer`; removed\n * in the next release. The server's operation saying the table holds every\n * edit through `through`, sequenced from `cursor`, the journal's, appended\n * as written.\n */\n readonly absorbed?: ((through: number, cursor: number) => WrittenOperation) | undefined\n /** @deprecated With `absorbed`: who the server commits it as. */\n readonly server?: Principal | undefined\n}\n\n/** The stored cursor `editsJournal` keeps: every edit at or before it is in the table. */\nconst EDITS_CURSOR = 'edits'\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 * How far the table holds is a cursor the journal stores (`journal.cursors`),\n * started at the journal's floor, where compaction left it, so a server\n * restarted over a journal that outlived it neither walks the log again nor\n * asks for history that is gone. Intents are keyed by the journal's epoch as\n * well as the operation, so after a reset an operation sent again is applied\n * again, not taken as already run.\n */\nexport const editsJournal = <Shared, Principal, Change, Absorbed = never>(\n options: EditsJournalOptions<Shared, Principal, Change, Absorbed>,\n): {\n readonly settle: Effect.Effect<void, unknown>\n readonly absorb: Effect.Effect<void, unknown>\n} => {\n const { journal, asServer } = options\n if (asServer === undefined && (options.absorbed === undefined || options.server === undefined))\n throw new Error('editsJournal: pass asServer, or absorbed with server')\n const key = JournalDocumentId.make(options.documentId)\n /** The stored cursor in the current epoch, started at the floor the first time. */\n const tracked = Effect.gen(function* () {\n const found = yield* journal.cursors.settled(key, EDITS_CURSOR)\n if (Option.isSome(found)) return found.value\n yield* journal.cursors.track(key, EDITS_CURSOR, { from: 'floor' })\n return Option.getOrThrow(yield* journal.cursors.settled(key, EDITS_CURSOR))\n })\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 const settle = Effect.gen(function* () {\n // The table must not be past the journal: every edit would be skipped.\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 // A new epoch is a new history: the stored cursor reads 0 in it.\n const { epoch, cursor } = yield* tracked\n const through = yield* journal.recover({ key, from: cursor, intents: intents(epoch) })\n if (through > cursor) yield* journal.cursors.advance(key, EDITS_CURSOR, epoch, through)\n })\n // Two absorbs at once need no lock: both name the record by `through`, so\n // the second is the first's retry, answered from history.\n const absorb = Effect.gen(function* () {\n const found = yield* journal.cursors.settled(key, EDITS_CURSOR)\n if (Option.isNone(found) || found.value.cursor === 0) return\n const through = found.value.cursor\n const { snapshot, cursor } = yield* journal.load(key)\n if (!options.holdsThrough(snapshot, through)) return\n const floor = yield* Option.match(Option.fromUndefinedOr(asServer), {\n onSome: ({ journal: server, absorbed }) =>\n Effect.gen(function* () {\n yield* server.appendAsServer(absorbed(through), { key: `absorbed/${through}` })\n return Math.min(through, yield* server.settledThrough)\n }),\n onNone: () =>\n Effect.as(\n journal.append(key, options.absorbed!(through, cursor), options.server!),\n through,\n ),\n })\n // What the log holds through `floor` is in the table and gone from the\n // snapshot; a replica behind it is sent the snapshot instead.\n if (floor > (yield* journal.floor(key))) yield* journal.compact(key, Sequence.make(floor))\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, WrittenOperation>>\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 | ((\n journal: Journal<Operation, Shared, Principal, WrittenOperation>,\n ) => 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":";;;;;;;;;;;;;;;;;;;;AAoHA,MAAM,gBAAgB,OAAO,WAAW,WAAW;;AAEnD,MAAM,aAAa,YACjB,YAAY,QAAQ;CAAE,QAAQ,OAAO,KAAK;CAAG,MAAM,OAAO,KAAK;CAAG;CAAS,MAAM,CAAC;AAAE,CAAC;;AAGvF,MAAM,iBAAiB,OAAO,oBAC5B,OAAO,OAAO,EAAE,gBAAgB,OAAO,YAAY,OAAO,MAAM,EAAE,CAAC,CACrE;;;;;;AAOA,MAAM,qBAAqB;;;;;AAM3B,MAAM,qBACJ,YACA,UAC0C;CAC1C,IAAI,iBAAiB,wBACnB,OAAO,OAAO,KACZ,IAAI,uBAAuB;EACzB;EACA,MAAM,MAAM;EACZ,SAAS,MAAM;EACf,SAAS;CACX,CAAC,CACH;CAC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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"}
|
|
1
|
+
{"version":3,"file":"journal.js","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 {\n Cause,\n Context,\n Duration,\n Effect,\n Exit,\n Fiber,\n Layer,\n Match,\n Option,\n Predicate,\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 JournalError,\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 { fitWords, SyncRefusal } from './refusal.js'\nimport type { Operation, Sync, TransportClient, WrittenOperation } from './sync.js'\nimport {\n ServerOnlyMessageError,\n UnreadableHistoryError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n} from './errors.js'\nimport { checkRevalidate } from './revalidate.js'\nimport {\n answerHostDefect,\n hostDefect,\n listenerFailed,\n reportTo,\n serverOnlySubmitted,\n type HostStage,\n type SyncDiagnostic,\n} from './diagnostics.js'\nimport { ExchangeRefused, serveSocket, type SocketLike } from './transport.js'\nimport type { ServerJournal } from './serverJournal.js'\n\nexport type { HostDefect, HostStage } from './diagnostics.js'\nexport {\n reaction,\n serverJournal,\n type Parked,\n type Reaction,\n type ReactionOptions,\n type Requires,\n type ServerJournal,\n type ServerJournalOptions,\n type Trigger,\n} from './serverJournal.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, WrittenOperation>\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 * Where a `ServerOnlySubmitted` goes: a replica sent a Message only the\n * server appends. The reporter in context when not given, by default the log.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n}\n\nconst encodeRefusal = Schema.encodeSync(SyncRefusal)\n/** A refusal in the server's own words, which name no Entity's invariant. */\nconst invalidAs = (message: string): SyncRefusal =>\n SyncRefusal.Invalid({ entity: Option.none(), rule: Option.none(), message, path: [] })\n\n/** The version an entry claims, read before anything else of it, so a newer one is told from a malformed one. */\nconst claimedVersion = Schema.decodeUnknownOption(\n Schema.Struct({ messageVersion: Schema.optionalKey(Schema.Number) }),\n)\n\n/**\n * What the replica is told, and all of it: the operation's id and version are\n * another replica's. They stay on the error, which a socket reports\n * (`ExchangeDefect`) and does not send.\n */\nconst HISTORY_UNREADABLE = 'This server cannot read the history of this document'\n\n/**\n * A stored row that will not read, as the journal reports it: a\n * `JournalError` whose cause is the codec's own error, never told by its words.\n */\nconst unreadableHistory = (\n documentId: string,\n cause: unknown,\n): Option.Option<UnreadableHistoryError> => {\n if (cause instanceof UnreadableMessageError)\n return Option.some(\n new UnreadableHistoryError({\n documentId,\n opId: cause.opId,\n version: cause.version,\n message: HISTORY_UNREADABLE,\n }),\n )\n if (cause instanceof UnsupportedMessageVersionError)\n return Option.some(\n new UnreadableHistoryError({\n documentId,\n opId: cause.opId,\n version: cause.found,\n message: HISTORY_UNREADABLE,\n }),\n )\n return Option.none()\n}\n\n/** What a replica that sent a server-only Message is told. */\nconst SERVER_ONLY_REASON = 'Only the server makes this change'\n\n/** The replica id an entry claims, for a diagnostic: read without trusting the rest of it. */\nconst replicaOf = (input: unknown): string =>\n Option.match(Schema.decodeUnknownOption(Schema.Struct({ replicaId: Schema.String }))(input), {\n onNone: () => '?',\n onSome: ({ replicaId }) => fitWords(replicaId),\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, as received, and acknowledged once committed, or already\n * committed. Every hook (`admit`, and the journal's `validate`, `authorize`,\n * `reduce` and `stamp`) sees its Message upcast to the current version. One\n * is rejected by its id when its message does not decode, it names another\n * document, the journal refuses it (`authorize`, `validate`), or it was\n * written at an older version no step reads (`Unreadable`); the replica drops\n * it, or keeps an unreadable one in `refused`, rather than send it again. An\n * entry written at a version newer than this server's fails the exchange\n * before anything is appended, so its replica waits with its outbox whole; so\n * do an entry with no id at all, a cursor ahead of the journal's, a\n * connection `opens` refuses, `admit` or the journal failing, and a stored\n * operation that will not read (`UnreadableHistoryError`). 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 contract = sync.journalContract()\n const supported = sync.codec.messageVersion\n /**\n * An entry as written, with what it means: its Message upcast to the current\n * version. Older and unread by any step is told apart, as `Unreadable`, and\n * a Message only the server appends, as `Forbidden`; anything else that\n * fails is not an operation this server accepts.\n */\n const operationOf = (\n input: unknown,\n ): Result.Result<\n { readonly written: WrittenOperation; readonly operation: Operation },\n UnreadableMessageError | ServerOnlyMessageError | 'invalid'\n > => {\n try {\n const written = sync.codec.writtenFrom(input, sync.documentId)\n return Result.succeed({ written, operation: sync.codec.normalizeOperation(written) })\n } catch (cause) {\n return Result.fail(\n cause instanceof UnreadableMessageError || cause instanceof ServerOnlyMessageError\n ? cause\n : 'invalid',\n )\n }\n }\n /** As the replica reads it: written at this server's version, with its order and actor. */\n const committedOf = (committed: Committed<Operation>) => {\n const written = {\n ...contract.operation.encode(committed.operation),\n serverSequence: committed.sequence,\n actorId: committed.actorId,\n }\n // Checked as the replica will check it: a row of another document is the server's fault.\n sync.codec.committedFrom(written, sync.documentId)\n return written\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(\n new ExchangeRefused({ message: 'This connection may not open the document' }),\n )\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(\n new ExchangeRefused({ message: `Cursor ${cursor} is ahead of the server's ${at}` }),\n )\n }\n // A replica ahead of this server waits, its outbox whole: refused before\n // anything is appended, since a rejection would lose the edit.\n for (const input of pending) {\n const found = Option.flatMapNullishOr(claimedVersion(input), probe => probe.messageVersion)\n if (Option.isSome(found) && found.value > supported)\n return yield* Option.match(idOf(input), {\n onNone: () =>\n Effect.fail(new ExchangeRefused({ message: 'A pending entry names no operation' })),\n onSome: opId =>\n Effect.fail(\n new UnsupportedMessageVersionError({\n opId,\n found: found.value,\n supported,\n message: `The replica writes Message version ${found.value}; this server reads up to ${supported}`,\n }),\n ),\n })\n }\n const rejected: Array<string> = []\n const refusals: Array<{ readonly opId: string; readonly refusal: unknown }> = []\n // Deprecated: the words alone, for a replica that reads `reason`.\n const reasons: Array<{ readonly opId: string; readonly reason: string }> = []\n // Words reach the person whose edit came back: a policy's own, or a fixed\n // sentence, never an error's message, which may carry internals.\n const reject = (opId: string, refusal: SyncRefusal, reason: string) => {\n rejected.push(opId)\n refusals.push({ opId, refusal: encodeRefusal(refusal) })\n reasons.push({ opId, reason })\n }\n const forbid = (opId: string, reason: string | undefined, otherwise: string) => {\n const fitted = reason === undefined ? undefined : fitWords(reason)\n reject(\n opId,\n SyncRefusal.Forbidden({ reason: Option.fromUndefinedOr(fitted) }),\n fitted ?? otherwise,\n )\n }\n const invalid = (opId: string, message: string) => reject(opId, invalidAs(message), message)\n const broke = (\n opId: string,\n rule: string,\n reason: string | undefined,\n path: ReadonlyArray<string> | undefined,\n ) => {\n const message = fitWords(reason ?? 'It breaks a law of the document')\n reject(\n opId,\n SyncRefusal.Invalid({\n entity: Option.none(),\n rule: Option.some(fitWords(rule)),\n message,\n path: (path ?? []).slice(0, 16).map(fitWords),\n }),\n message,\n )\n }\n const acknowledged: Array<string> = []\n for (const input of pending) {\n const decoded = operationOf(input)\n if (Result.isFailure(decoded)) {\n const id = idOf(input)\n if (Option.isNone(id))\n return yield* Effect.fail(\n new ExchangeRefused({ message: 'A pending entry names no operation' }),\n )\n const failure = decoded.failure\n if (failure === 'invalid') invalid(id.value, 'Not an operation this server accepts')\n else if (failure instanceof UnreadableMessageError)\n reject(\n id.value,\n SyncRefusal.Unreadable({ version: failure.version }),\n 'Written by a version of the app this server cannot read',\n )\n else {\n forbid(id.value, SERVER_ONLY_REASON, SERVER_ONLY_REASON)\n yield* reportTo(\n options.diagnostics,\n serverOnlySubmitted(sync.documentId, id.value, replicaOf(input)),\n )\n }\n continue\n }\n const { written, operation } = decoded.success\n const admitted = options.admit === undefined ? true : options.admit(operation)\n const decision = Effect.isEffect(admitted) ? yield* admitted : admitted\n if (decision !== true) {\n forbid(\n operation.opId,\n decision === false ? undefined : decision.reason,\n 'This connection may not make changes',\n )\n continue\n }\n // As received: the journal compares a retransmission by what was sent.\n yield* journal.append(key, written, 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 // A rule is a law's id: the snapshot the operation leaves breaks it.\n OperationRejectedError: error =>\n Effect.sync(() =>\n error.rule === undefined\n ? forbid(error.opId, error.reason, 'Refused by the server')\n : broke(error.opId, error.rule, error.reason, error.path),\n ),\n InvalidOperationError: () =>\n Effect.sync(() => invalid(operation.opId, 'Not a valid operation')),\n IdentityConflictError: () =>\n Effect.sync(() => invalid(operation.opId, 'Its id was already used for another')),\n }),\n )\n }\n if (options.settle !== undefined) yield* options.settle\n // Sent only when something was refused: a replica built before `refusals`\n // decodes the reply strictly and fails on the key, so it fails only then.\n const refused = refusals.length === 0 ? {} : { refusals }\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.try({\n try: () => rows.map(committedOf),\n catch: cause => new Error('Could not read the log', { cause }),\n }).pipe(\n Effect.map(operations => ({\n operations,\n rejected,\n ...refused,\n reasons,\n acknowledged,\n more: rows.length === limit,\n epoch,\n })),\n ),\n onNone: () =>\n Effect.map(journal.load(key), loaded => ({\n operations: [],\n rejected,\n ...refused,\n reasons,\n acknowledged,\n checkpoint: {\n cursor: loaded.cursor,\n model: contract.snapshot.encode(loaded.snapshot),\n },\n epoch,\n })),\n })\n }).pipe(\n // A stored operation that will not read stops the document, typed for the server's logs.\n Effect.mapError(error =>\n error instanceof JournalError\n ? Option.getOrElse(unreadableHistory(sync.documentId, error.cause), () => error)\n : error,\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, WrittenOperation>,\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 diagnostics,\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, Absorbed = never> {\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, WrittenOperation>\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 * Records that the table holds every edit through `through`, as the\n * server: `absorbed(through)` is the server-only Message the replicas drop\n * those edits on hearing, appended under the key `absorbed/<through>`. The\n * log is compacted no further than the server journal's `settledThrough`,\n * so its reactions see every commit first.\n */\n readonly asServer?:\n | {\n readonly journal: ServerJournal<Absorbed, any>\n readonly absorbed: (through: number) => Absorbed\n }\n | undefined\n /**\n * @deprecated Declare the Message `serverOnly` and pass `asServer`; removed\n * in the next release. The server's operation saying the table holds every\n * edit through `through`, sequenced from `cursor`, the journal's, appended\n * as written.\n */\n readonly absorbed?: ((through: number, cursor: number) => WrittenOperation) | undefined\n /** @deprecated With `absorbed`: who the server commits it as. */\n readonly server?: Principal | undefined\n}\n\n/** The stored cursor `editsJournal` keeps: every edit at or before it is in the table. */\nconst EDITS_CURSOR = 'edits'\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 * How far the table holds is a cursor the journal stores (`journal.cursors`),\n * started at the journal's floor, where compaction left it, so a server\n * restarted over a journal that outlived it neither walks the log again nor\n * asks for history that is gone. Intents are keyed by the journal's epoch as\n * well as the operation, so after a reset an operation sent again is applied\n * again, not taken as already run.\n */\nexport const editsJournal = <Shared, Principal, Change, Absorbed = never>(\n options: EditsJournalOptions<Shared, Principal, Change, Absorbed>,\n): {\n readonly settle: Effect.Effect<void, unknown>\n readonly absorb: Effect.Effect<void, unknown>\n} => {\n const { journal, asServer } = options\n if (asServer === undefined && (options.absorbed === undefined || options.server === undefined))\n throw new Error('editsJournal: pass asServer, or absorbed with server')\n const key = JournalDocumentId.make(options.documentId)\n /** The stored cursor in the current epoch, started at the floor the first time. */\n const tracked = Effect.gen(function* () {\n const found = yield* journal.cursors.settled(key, EDITS_CURSOR)\n if (Option.isSome(found)) return found.value\n yield* journal.cursors.track(key, EDITS_CURSOR, { from: 'floor' })\n return Option.getOrThrow(yield* journal.cursors.settled(key, EDITS_CURSOR))\n })\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 const settle = Effect.gen(function* () {\n // The table must not be past the journal: every edit would be skipped.\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 // A new epoch is a new history: the stored cursor reads 0 in it.\n const { epoch, cursor } = yield* tracked\n const through = yield* journal.recover({ key, from: cursor, intents: intents(epoch) })\n if (through > cursor) yield* journal.cursors.advance(key, EDITS_CURSOR, epoch, through)\n })\n // Two absorbs at once need no lock: both name the record by `through`, so\n // the second is the first's retry, answered from history.\n const absorb = Effect.gen(function* () {\n const found = yield* journal.cursors.settled(key, EDITS_CURSOR)\n if (Option.isNone(found) || found.value.cursor === 0) return\n const through = found.value.cursor\n const { snapshot, cursor } = yield* journal.load(key)\n if (!options.holdsThrough(snapshot, through)) return\n const floor = yield* Option.match(Option.fromUndefinedOr(asServer), {\n onSome: ({ journal: server, absorbed }) =>\n Effect.gen(function* () {\n yield* server.appendAsServer(absorbed(through), { key: `absorbed/${through}` })\n return Math.min(through, yield* server.settledThrough)\n }),\n onNone: () =>\n Effect.as(\n journal.append(key, options.absorbed!(through, cursor), options.server!),\n through,\n ),\n })\n // What the log holds through `floor` is in the table and gone from the\n // snapshot; a replica behind it is sent the snapshot instead.\n if (floor > (yield* journal.floor(key))) yield* journal.compact(key, Sequence.make(floor))\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, WrittenOperation>>\n /**\n * Who is opening the socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`RemoteServer.unauthenticated(reason?)`) to\n * refuse it: a 401 that says \"Unauthenticated\", or its `reason`, the words\n * written for the caller, when it has one. Its `message` is never sent. A\n * defect, or a failure that is no `RemoteUnauthenticated`, is a 500 that\n * says nothing of it: a session store that is down is no refusal, so let\n * it die (`Effect.orDie`). A browser's `WebSocket` sends no header of the\n * page's: `Origin` and the 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 the reason\n * \"Unauthenticated\", or the refusal's `reason` when it has one (cut to the\n * 123 bytes a close carries), and a principal whose `key` differs from the\n * one it opened with (`Policy.keyOf`) closes it with 1012, which the\n * replica reconnects after, as the new principal; without `key` only a\n * refusal closes it. A resolver that breaks closes it with 1011. Without\n * `revalidate` a socket serves the principal it opened with until it\n * 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 | ((\n journal: Journal<Operation, Shared, Principal, WrittenOperation>,\n ) => 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\n/** What a caller the resolver refused reads when the refusal gives no `reason`. */\nconst UNAUTHENTICATED = 'Unauthenticated'\n\n/**\n * Whether a resolver failed with the refusal its type promises. Asked of the\n * value, since a resolver compiled past its type (a cast, plain JavaScript)\n * can fail with a driver's error, which must not read as \"sign in again\".\n */\nconst isRefusal = (failure: unknown): failure is RemoteUnauthenticated =>\n Predicate.isTagged(failure, 'Unauthenticated')\n\n/** The most UTF-8 bytes a close reason carries; a longer one makes a platform refuse the close. */\nconst CLOSE_REASON_BYTES = 123\n\n/** `words` as a close reason: cut to fit, between characters, and marked where cut. */\nconst fitCloseReason = (words: string): string => {\n const encoder = new TextEncoder()\n if (encoder.encode(words).length <= CLOSE_REASON_BYTES) return words\n let fitted = ''\n let bytes = encoder.encode('…').length\n for (const character of words) {\n bytes += encoder.encode(character).length\n if (bytes > CLOSE_REASON_BYTES) break\n fitted += character\n }\n return `${fitted}…`\n}\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 refuse(await Effect.runPromise(answerHostDefect(reporter, stage, cause)))\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)).pipe(\n // Only a refusal is the caller's to hear of: anything else is this side's.\n Effect.catch(failure => (isRefusal(failure) ? Effect.fail(failure) : Effect.die(failure))),\n )\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(\n // The reason is written for the caller; the message may be anyone's.\n Response.json({ error: resolved.failure.reason ?? UNAUTHENTICATED }, { status: 401 }),\n )\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, fitCloseReason(error.reason ?? UNAUTHENTICATED)] as const),\n })\n try {\n socket.closeWith(code, reason)\n } catch {\n // A close the platform refuses still closes.\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":";;;;;;;;;;;;;;;;;;;;AAsHA,MAAM,gBAAgB,OAAO,WAAW,WAAW;;AAEnD,MAAM,aAAa,YACjB,YAAY,QAAQ;CAAE,QAAQ,OAAO,KAAK;CAAG,MAAM,OAAO,KAAK;C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,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/make.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { Schema } from "effect";
|
|
1
|
+
import { Option, Schema } from "effect";
|
|
2
2
|
import { AppScope, Contract, MergeConstructors, MergeFields, MessageSet, RunnableApplication, Surface, Wiring, WritableProjection } from "foldkit-surface";
|
|
3
3
|
import { Migrations } from "./migrations.js";
|
|
4
|
-
import { CommitStamp, JournalContract, Operation, Sync } from "./sync.js";
|
|
4
|
+
import { CommitStamp, DeclaredLaw, JournalContract, Operation, Sync } from "./sync.js";
|
|
5
5
|
import { DocumentId } from "./ids.js";
|
|
6
6
|
type MessageConstructor<Message> = (...args: never[]) => Message;
|
|
7
7
|
/** The Message union a tuple of constructors produces. */
|
|
@@ -38,6 +38,30 @@ export interface PolicyJournalContract<Operation, Shared, Principal> extends Jou
|
|
|
38
38
|
readonly snapshot: Shared;
|
|
39
39
|
}) => AuthorizeDecision;
|
|
40
40
|
}
|
|
41
|
+
/**
|
|
42
|
+
* One law of a document. `holds` judges the snapshot an operation leaves,
|
|
43
|
+
* with the one before it, and only `true` holds; it sees no principal and no
|
|
44
|
+
* Message. `message` is what the person whose edit broke it is told, and
|
|
45
|
+
* `path` the shared fields it is about.
|
|
46
|
+
*/
|
|
47
|
+
export interface Law<Shared, Key extends string> {
|
|
48
|
+
readonly holds: (states: {
|
|
49
|
+
readonly before: Shared;
|
|
50
|
+
readonly after: Shared;
|
|
51
|
+
}) => boolean;
|
|
52
|
+
readonly message: string;
|
|
53
|
+
readonly path?: ReadonlyArray<Key>;
|
|
54
|
+
}
|
|
55
|
+
/** `make`'s laws, keyed by id: each over the shared fields, and nothing else of the Model. */
|
|
56
|
+
export interface LawsOption<Fields extends Schema.Struct.Fields, LawIds extends string> {
|
|
57
|
+
/**
|
|
58
|
+
* What every snapshot of the document keeps, judged where an operation
|
|
59
|
+
* commits and, as a hint, by a replica's `submit`. An operation whose
|
|
60
|
+
* snapshot breaks one is refused as `SyncRefusal.Invalid` with the law's id
|
|
61
|
+
* as `rule`; the first broken law in the record's order is named.
|
|
62
|
+
*/
|
|
63
|
+
readonly laws?: { readonly [Id in LawIds]: Law<Schema.Struct.Type<Fields>, keyof Fields & string>; };
|
|
64
|
+
}
|
|
41
65
|
/**
|
|
42
66
|
* What a rule decides: allowed, refused, or refused with a reason the server
|
|
43
67
|
* sends to the person whose edit it was. The shape of Durable's own decision.
|
|
@@ -134,7 +158,9 @@ export interface DefinedSync<AppModel, Fields extends Schema.Struct.Fields, Mess
|
|
|
134
158
|
/** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */
|
|
135
159
|
Authorized extends boolean = false,
|
|
136
160
|
/** The server-only constructors, `[]` when `make` was given none. */
|
|
137
|
-
SMs extends readonly unknown[] = []
|
|
161
|
+
SMs extends readonly unknown[] = [],
|
|
162
|
+
/** The ids of `make`'s `laws`; `string` reads any contract's. */
|
|
163
|
+
LawIds extends string = string> extends Sync<Message, Schema.Struct.Type<Fields>, MsgOf<Ms>> {
|
|
138
164
|
readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>;
|
|
139
165
|
readonly projection: WritableProjection<AppModel, Fields>;
|
|
140
166
|
/** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */
|
|
@@ -143,6 +169,14 @@ SMs extends readonly unknown[] = []> extends Sync<Message, Schema.Struct.Type<Fi
|
|
|
143
169
|
readonly messages: Ms;
|
|
144
170
|
/** The server-only constructors: what only the server appends. */
|
|
145
171
|
readonly serverOnlyMessages: SMs;
|
|
172
|
+
/** The declared laws, by id: what `Sync.isInvalidBy` matches a refusal against. */
|
|
173
|
+
readonly laws: { readonly [Id in LawIds]: DeclaredLaw<Id>; };
|
|
174
|
+
/**
|
|
175
|
+
* The first law the step from `before` to `after` breaks, or none: what the
|
|
176
|
+
* journal and `submit` run. Run it over stored snapshots (`judge(s, s)`) to
|
|
177
|
+
* audit them before deploying a new law.
|
|
178
|
+
*/
|
|
179
|
+
readonly judge: (before: Schema.Struct.Type<Fields>, after: Schema.Struct.Type<Fields>) => Option.Option<DeclaredLaw<LawIds>>;
|
|
146
180
|
/** For `Module`: this contract owns the shared projection's paths and records the durable and server-only tags. */
|
|
147
181
|
readonly contract: Contract;
|
|
148
182
|
/**
|
|
@@ -174,10 +208,10 @@ export interface ApplicationSync<AppModel, F extends Schema.Struct.Fields, Cases
|
|
|
174
208
|
*/
|
|
175
209
|
readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(...fragments: Fs) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>;
|
|
176
210
|
readonly make: {
|
|
177
|
-
<Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[], ServerSubset = never, SMs extends readonly MessageConstructor<Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>>[] = []>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> & HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>> & {
|
|
211
|
+
<Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[], ServerSubset = never, SMs extends readonly MessageConstructor<Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>>[] = [], LawIds extends string = never>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> & HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>> & LawsOption<NoInfer<Fields>, LawIds> & {
|
|
178
212
|
readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>;
|
|
179
|
-
}): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true, SMs>;
|
|
180
|
-
<Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[], ServerSubset = never, SMs extends readonly MessageConstructor<Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>>[] = []>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> & HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>>): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, false, SMs>;
|
|
213
|
+
}): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true, SMs, LawIds>;
|
|
214
|
+
<Fields extends Schema.Struct.Fields, Subset, Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[], ServerSubset = never, SMs extends readonly MessageConstructor<Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>>[] = [], LawIds extends string = never>(options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> & HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>> & LawsOption<NoInfer<Fields>, LawIds>): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, false, SMs, LawIds>;
|
|
181
215
|
};
|
|
182
216
|
}
|
|
183
217
|
/**
|
package/dist/make.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make.d.ts","names":[],"sources":["../src/make.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"make.d.ts","names":[],"sources":["../src/make.ts"],"mappings":";;;;;KA+BK,mBAAmB,eAAe,kBAAkB;;YAG7C,MAAM,iCAAiC,wBAAuB,wBAAwB,KAC9F;KAGC,WACH,UACA,UAAU,OAAO,OAAO,QACxB,cAAc,eAAe,OAAO,OAAO,WACzC,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,GAAG,QACxB,IACA,kBAEA,KACA;;;;;;;;;;;qBAuHO,iBACX,UACA,UAAU,OAAO,OAAO,QACxB,cAAc,eAAe,OAAO,OAAO,SAAO,KAE7C,oBAAoB,UAAU,GAAG,gBACrC,gBAAgB,UAAU,GAAG"}
|
package/dist/make.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { Equal, Option, Predicate, Schema } from "effect";
|
|
2
2
|
import { MessageSet, Projection, Surface } from "foldkit-surface";
|
|
3
|
+
import { fitWords } from "./refusal.js";
|
|
3
4
|
import { defineSync } from "./sync.js";
|
|
4
5
|
// src/make.ts
|
|
5
6
|
/**
|
|
@@ -23,7 +24,9 @@ const tagOf = (message) => Predicate.hasProperty(message, "_tag") && typeof mess
|
|
|
23
24
|
* projection. Replay refuses one that returns a Command (a live effect cannot be
|
|
24
25
|
* replayed) or that changes a Model field outside the projection (the change
|
|
25
26
|
* would be silently lost), so a Message that needs either stays local and emits
|
|
26
|
-
* a durable fact once the effect settles.
|
|
27
|
+
* a durable fact once the effect settles. What a Message reads is not visible
|
|
28
|
+
* here, where every other field is `initial`: `Sync.mount` checks it against the
|
|
29
|
+
* live Model.
|
|
27
30
|
*/
|
|
28
31
|
const derivedReplay = (app, shared) => {
|
|
29
32
|
const { initial, update } = app;
|
|
@@ -41,6 +44,29 @@ const derivedReplay = (app, shared) => {
|
|
|
41
44
|
};
|
|
42
45
|
};
|
|
43
46
|
/**
|
|
47
|
+
* The declared laws and their judge. Each id and message must fit a
|
|
48
|
+
* refusal's words, and a path its sixteen fields, or the refusal could not
|
|
49
|
+
* be sent; `make` throws rather than let one fail every exchange.
|
|
50
|
+
*/
|
|
51
|
+
const lawsOf = (declared) => {
|
|
52
|
+
const entries = Object.entries(declared).map(([id, law]) => {
|
|
53
|
+
const path = law.path ?? [];
|
|
54
|
+
if (fitWords(id) !== id || fitWords(law.message) !== law.message || path.length > 16 || path.some((field) => fitWords(field) !== field)) throw new Error(`Sync.make: the law "${fitWords(id)}" does not fit a refusal: an id, a message or a field over 500 characters, or a path over 16 fields`);
|
|
55
|
+
return [{
|
|
56
|
+
id,
|
|
57
|
+
message: law.message,
|
|
58
|
+
path
|
|
59
|
+
}, law.holds];
|
|
60
|
+
});
|
|
61
|
+
return {
|
|
62
|
+
laws: Object.fromEntries(entries.map(([law]) => [law.id, law])),
|
|
63
|
+
judge: (before, after) => Option.fromUndefinedOr(entries.find(([, holds]) => holds({
|
|
64
|
+
before,
|
|
65
|
+
after
|
|
66
|
+
}) !== true)?.[0])
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
44
70
|
* Merges fragments into one. The primitives reject a conflicting field, a
|
|
45
71
|
* duplicate tag, and a subset from another application.
|
|
46
72
|
*/
|
|
@@ -75,11 +101,13 @@ const build = (app) => {
|
|
|
75
101
|
for (const tag of serverTags) if (durableTags.has(tag)) throw new Error(`Sync.make: "${tag}" is both durable and server-only`);
|
|
76
102
|
const sharedCodec = shared.schema;
|
|
77
103
|
const stamps = options.stamp;
|
|
104
|
+
const { laws, judge } = lawsOf(options.laws ?? {});
|
|
78
105
|
const sync = defineSync({
|
|
79
106
|
documentId: options.documentId,
|
|
80
107
|
...migrations === void 0 ? { message: app.Message } : { migrations },
|
|
81
108
|
shared: sharedCodec,
|
|
82
109
|
empty: shared.get(app.initial),
|
|
110
|
+
...options.laws === void 0 ? {} : { judge },
|
|
83
111
|
durable: (message) => Option.exists(tagOf(message), (tag) => durableTags.has(tag)),
|
|
84
112
|
serverOnly: (message) => Option.exists(tagOf(message), (tag) => serverTags.has(tag)),
|
|
85
113
|
replay,
|
|
@@ -117,14 +145,16 @@ const build = (app) => {
|
|
|
117
145
|
model: () => readOnly,
|
|
118
146
|
messages: durable.constructors
|
|
119
147
|
});
|
|
148
|
+
const messages = [...durable.tags, ...serverTags];
|
|
120
149
|
const contract = {
|
|
121
150
|
kind: "sync",
|
|
122
151
|
name: surface.name,
|
|
123
152
|
owner: app.owner,
|
|
124
153
|
owns: shared.dependencies,
|
|
125
154
|
observes: shared.dependencies,
|
|
126
|
-
messages
|
|
127
|
-
metadata: []
|
|
155
|
+
messages,
|
|
156
|
+
metadata: [],
|
|
157
|
+
laws: { model: Object.keys(laws) }
|
|
128
158
|
};
|
|
129
159
|
return {
|
|
130
160
|
...sync,
|
|
@@ -134,6 +164,8 @@ const build = (app) => {
|
|
|
134
164
|
replay,
|
|
135
165
|
messages: durable.constructors,
|
|
136
166
|
serverOnlyMessages: serverOnly?.constructors ?? [],
|
|
167
|
+
laws,
|
|
168
|
+
judge,
|
|
137
169
|
contract,
|
|
138
170
|
wiring: () => ({
|
|
139
171
|
key: `sync:${contract.name}`,
|
package/dist/make.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"make.js","names":[],"sources":["../src/make.ts"],"sourcesContent":["/**\n * The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`\n * compiles an application, a writable projection, and a durable Message subset\n * into the low-level `defineSync` contract, and exposes a read-only Surface over\n * the same projection.\n */\nimport { Equal, Option, Predicate, Schema } from 'effect'\nimport {\n MessageSet,\n Projection,\n Surface,\n type AppScope,\n type Contract,\n type MergeConstructors,\n type MergeFields,\n type RunnableApplication,\n type Wiring,\n type WritableProjection,\n} from 'foldkit-surface'\nimport type { DocumentId } from './ids.js'\nimport type { Migrations } from './migrations.js'\nimport {\n defineSync,\n type CommitStamp,\n type JournalContract,\n type Operation,\n type Sync,\n} from './sync.js'\n\ntype MessageConstructor<Message> = (...args: never[]) => Message\n\n/** The Message union a tuple of constructors produces. */\nexport type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends (...args: never[]) => infer M\n ? M\n : never\n\ntype AppMessage<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>\n\ntype AppMessageEncoded<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = AppScope<AppModel, F, Cases>['Message']['Encoded']\n\n/** `make`'s Message history, typed by the application's own Message. */\nexport interface HistoryOption<Message, Encoded> {\n /**\n * The Schemas the document's durable Messages were stored in, ending at the\n * application's own `Message` (`Sync.migrations(V1).next(App.Message, up)`):\n * operations written at an older version are upcast wherever they are read.\n * Without it, the Message is version 1.\n */\n readonly migrations?: Migrations<Message, Encoded> | undefined\n}\n\n/**\n * The Messages of the server-only constructors: none for `[]`, which\n * `MsgOf` reads as `unknown` (`never` matches its `infer`).\n */\nexport type ServerMsgOf<SMs extends readonly unknown[]> = [SMs[number]] extends [never]\n ? never\n : MsgOf<SMs>\n\n/** Reads the tag off a Foldkit Message constructor without constructing one. */\nconst messageTag = (constructor: unknown): string | undefined => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } }).fields\n ?._tag?.ast?.literal\n return typeof literal === 'string' ? literal : undefined\n}\n\n/** A Message's tag. The application's union is generic here, so its `_tag` is read, not typed. */\nconst tagOf = (message: unknown): Option.Option<string> =>\n Predicate.hasProperty(message, '_tag') && typeof message._tag === 'string'\n ? Option.some(message._tag)\n : Option.none()\n\n/** The `_tag` literal of the Message a constructor produces. */\ntype TagOf<C> = C extends (...args: never[]) => infer M\n ? M extends { readonly _tag: infer T extends string }\n ? T\n : never\n : never\n\n/**\n * A journal contract that also carries the declared authorization policy, in\n * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.\n */\nexport interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<\n Operation,\n Shared\n> {\n readonly authorize?: (request: {\n readonly principal: Principal\n readonly operation: Operation\n readonly snapshot: Shared\n }) => AuthorizeDecision\n}\n\n/**\n * What a rule decides: allowed, refused, or refused with a reason the server\n * sends to the person whose edit it was. The shape of Durable's own decision.\n */\nexport type AuthorizeDecision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a per-variant `authorize` rule sees before the journal commits. */\nexport interface AuthorizeRequest<Principal, Message, Shared> {\n readonly principal: Principal\n readonly message: Message\n readonly shared: Shared\n}\n\n/**\n * Per-variant policy, keyed by durable tag: `message` is that variant exactly,\n * `shared` the authoritative snapshot. A variant without a rule is allowed; the\n * server may still refuse on its own grounds.\n */\nexport type AuthorizePolicy<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> = {\n readonly [K in TagOf<Ms[number]>]?: (\n request: AuthorizeRequest<\n Principal,\n Extract<MsgOf<Ms>, { readonly _tag: K }>,\n Schema.Struct.Type<Fields>\n >,\n ) => AuthorizeDecision\n}\n\n/**\n * Per-variant commit stamps, keyed by durable tag: each writes what the server's commit\n * decided (its sequence, its actor) into that variant, and returns the same variant. A\n * variant without one is committed as sent.\n */\nexport type StampPolicy<Ms extends readonly unknown[]> = {\n readonly [K in TagOf<Ms[number]>]?: (\n message: Extract<MsgOf<Ms>, { readonly _tag: K }>,\n commit: CommitStamp,\n ) => Extract<MsgOf<Ms>, { readonly _tag: K }>\n}\n\ninterface BaseOptions<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n SMs extends readonly unknown[] = [],\n> {\n readonly documentId: DocumentId\n /** Name for the generated `surface`; defaults to the document id. */\n readonly name?: string\n /**\n * Replaces the replay derived from the application's `update`. It is a pure\n * reducer over the shared subset; only durable and server-only Messages reach\n * it, and it runs during admission, replay, and optimistic projection. It is\n * not guarded: the author owns its agreement with `update`.\n */\n readonly replay?: (\n shared: Schema.Struct.Type<NoInfer<Fields>>,\n message: MsgOf<NoInfer<Ms>> | ServerMsgOf<NoInfer<SMs>>,\n ) => Schema.Struct.Type<NoInfer<Fields>>\n /**\n * Authorization the server journal applies before committing, keyed by\n * durable or server-only tag; see `AuthorizePolicy`.\n */\n readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>\n /** What the server's commit writes into a stored Message; see `StampPolicy`. */\n readonly stamp?: StampPolicy<NoInfer<[...Ms, ...SMs]>>\n /**\n * Merges a durable Message into the one submitted before it while that one is unsent,\n * so a burst of edits is one operation. Replaying the result must equal replaying\n * `last` then `next`; undefined keeps them apart.\n */\n readonly coalesce?: (\n last: MsgOf<NoInfer<Ms>>,\n next: MsgOf<NoInfer<Ms>>,\n ) => MsgOf<NoInfer<Ms>> | undefined\n}\n\nexport interface MakeOptions<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n Principal = unknown,\n ServerSubset = never,\n SMs extends readonly MessageConstructor<any>[] = [],\n> extends BaseOptions<Principal, Fields, Ms, SMs> {\n /** The writable projection of the shared fields. */\n readonly shared: WritableProjection<AppModel, Fields>\n /** The Message subset a replica submits, records and replays. */\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n /**\n * The Messages only the server appends (`foldkit-sync/journal`'s\n * `serverJournal`): stored and replayed like durable ones, refused from a\n * replica. A Message in both sets is a type error, and a throw here.\n */\n readonly serverOnly?: MessageSet<AppModel, any, ServerSubset, SMs> | undefined\n}\n\n/**\n * One feature's contribution to a document: the fields it shares and the\n * Messages it records. `compose` merges fragments into one, to spread into\n * `make`; a field declared twice with a different codec or a tag declared twice\n * is rejected there.\n */\nexport interface SyncFragment<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n> {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\ntype SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['shared']\n}\ntype DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['durable']\n}\n/** The merged shared fields of several fragments. */\nexport type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<\n SharedOf<Fs>\n>\n/** The concatenated durable constructors of several fragments. */\nexport type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n MergeConstructors<DurableOf<Fs>>\n\n/** The union of Messages several fragments record. */\nexport type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never\n\n/**\n * The value `make` returns: the low-level `Sync` protocol plus the writable\n * projection, the declared Messages, and a read-only Surface over the\n * projection. Exported so a consumer can name the type.\n */\nexport interface DefinedSync<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n Principal = unknown,\n /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */\n Authorized extends boolean = false,\n /** The server-only constructors, `[]` when `make` was given none. */\n SMs extends readonly unknown[] = [],\n> extends Sync<Message, Schema.Struct.Type<Fields>, MsgOf<Ms>> {\n readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>\n readonly projection: WritableProjection<AppModel, Fields>\n /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */\n readonly replay: (\n shared: Schema.Struct.Type<Fields>,\n message: Message,\n ) => Schema.Struct.Type<Fields>\n /** The durable constructors: what a replica submits. */\n readonly messages: Ms\n /** The server-only constructors: what only the server appends. */\n readonly serverOnlyMessages: SMs\n /** For `Module`: this contract owns the shared projection's paths and records the durable and server-only tags. */\n readonly contract: Contract\n /**\n * How this contract joins an assembly: contract-only, so the Module sees it.\n * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the\n * runtime through `mount` rather than joining it.\n */\n readonly wiring: () => Wiring<AppModel, never>\n /** The durable journal's codecs, reducer, and, when declared, authorization. */\n readonly journalContract: () => Authorized extends true\n ? PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal> &\n Required<\n Pick<PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>, 'authorize'>\n >\n : PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>\n}\n\n/** The sync constructors specialized to one application. */\nexport interface ApplicationSync<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal = unknown,\n> {\n /**\n * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a\n * positional type argument beside an inferred Model, so it is supplied here:\n * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.\n */\n readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>\n /** One feature's shared fields and durable Messages, for `compose`. */\n readonly fragment: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(config: {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n }) => SyncFragment<AppModel, Fields, Subset, Ms>\n /**\n * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.\n * A field declared twice with a different codec, a tag declared twice, or a\n * fragment from another application throws.\n */\n readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(\n ...fragments: Fs\n ) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>\n readonly make: {\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n ServerSubset = never,\n // A server-only constructor makes a Message no durable one does, so a\n // variant in both sets fails here, at `serverOnly`.\n SMs extends readonly MessageConstructor<\n Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>\n >[] = [],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> &\n HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>> & {\n readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>\n },\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, true, SMs>\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n ServerSubset = never,\n SMs extends readonly MessageConstructor<\n Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>\n >[] = [],\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> &\n HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>>,\n ): DefinedSync<AppModel, Fields, AppMessage<AppModel, F, Cases>, Ms, Principal, false, SMs>\n }\n}\n\n/**\n * Replay derived from the application's own `update`: install the shared slice\n * into the initial Model, apply the Message, and read the slice back.\n *\n * A durable Message must be a deterministic, state-only transition of the shared\n * projection. Replay refuses one that returns a Command (a live effect cannot be\n * replayed) or that changes a Model field outside the projection (the change\n * would be silently lost), so a Message that needs either stays local and emits\n * a durable fact once the effect settles.\n */\nconst derivedReplay = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n shared: WritableProjection<AppModel, Fields>,\n): ((\n value: Schema.Struct.Type<Fields>,\n message: AppMessage<AppModel, F, Cases>,\n) => Schema.Struct.Type<Fields>) => {\n const { initial, update } = app\n // Per-field equivalences for the fields the projection does not own outright,\n // built once, so a violation names the fields and replay (which runs per\n // pending operation on every optimistic read) does not re-compare the shared\n // slice against itself. A partially shared field is still compared.\n const owned = new Set(shared.dependencies.filter(path => path.length === 1).map(path => path[0]))\n const fields = Object.entries(app.Model.fields)\n .filter(([key]) => !owned.has(key))\n .map(\n ([key, field]) =>\n [key, Schema.toEquivalence(field as unknown as Schema.Schema<unknown>)] as const,\n )\n return (value, message) => {\n const result = update(shared.set(initial, value), message)\n if (result.commands !== undefined && result.commands.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" returned ${result.commands.length} Command(s); a durable transition is state-only`,\n )\n const next = shared.get(result.model)\n // Writing the projection back into the baseline reproduces `update`'s\n // result exactly when it touched only shared fields.\n const written = shared.set(initial, next) as Record<string, unknown>\n const actual = result.model as Record<string, unknown>\n const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]))\n if (changed.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(', ')}`,\n )\n return next\n }\n}\n\n/**\n * Merges fragments into one. The primitives reject a conflicting field, a\n * duplicate tag, and a subset from another application.\n */\nconst composeFragments = (\n fragments: readonly SyncFragment<any, any, any, any>[],\n): SyncFragment<any, any, any, any> => {\n const compose = Projection.compose as (\n ...projections: readonly WritableProjection<any, any>[]\n ) => WritableProjection<any, any>\n const union = MessageSet.union as (\n ...subsets: readonly MessageSet<any, any, any, any>[]\n ) => MessageSet<any, any, any, any>\n return {\n shared: compose(...fragments.map(fragment => fragment.shared)),\n durable: union(...fragments.map(fragment => fragment.durable)),\n }\n}\n\n/**\n * Specializes the sync constructors to a `Surface.application`, so\n * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the\n * shared codec, the initial snapshot, the durable predicate, and replay from\n * the application, and refuses a subset that belongs to another application.\n * `defineSync` remains the protocol primitive when there is no application to\n * derive from.\n */\nexport const forApplication = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases> => build(app)\n\nconst build = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases, Principal> => {\n type Message = AppMessage<AppModel, F, Cases>\n const decodeMessage = Schema.decodeUnknownSync(\n app.Message as unknown as Schema.Codec<Message, unknown>,\n )\n\n const make = (\n options: MakeOptions<AppModel, any, any, any, Principal, any, any> &\n HistoryOption<Message, unknown>,\n ): DefinedSync<AppModel, any, Message, any, Principal, boolean, any> => {\n type Shared = Record<string, unknown>\n const { shared, durable, migrations, serverOnly } = options\n // A Schema of an older version can equal the current one structurally, so\n // the types cannot tell a history that stops short; identity can.\n if (migrations !== undefined && (migrations.current as unknown) !== app.Message)\n throw new Error(\"Sync.make: the Message history must end at the application's own Message\")\n\n // Two applications can have structurally identical Message unions, so the\n // types cannot separate them; the owner token can.\n if (durable.owner !== app.owner)\n throw new Error('Sync.make: the durable subset belongs to a different application')\n if (serverOnly !== undefined && serverOnly.owner !== app.owner)\n throw new Error('Sync.make: the server-only subset belongs to a different application')\n\n const replay: (value: Shared, message: Message) => Shared =\n options.replay === undefined\n ? derivedReplay(app, shared)\n : // `durable` has already rejected anything outside the declared subset.\n (value, message) => options.replay!(value, message as never)\n const tagsOf = (constructors: readonly unknown[]): ReadonlySet<string> =>\n new Set(constructors.map(messageTag).filter((tag): tag is string => tag !== undefined))\n const durableTags = tagsOf(durable.constructors)\n const serverTags = tagsOf(serverOnly?.constructors ?? [])\n // The types refuse this too; a set built by `MessageSet.union` at run time may not be typed.\n for (const tag of serverTags)\n if (durableTags.has(tag))\n throw new Error(`Sync.make: \"${tag}\" is both durable and server-only`)\n // `AppScope` does not constrain its schemas' services; a Foldkit Message union\n // and a Struct are pure, so the low-level contract's `never` is satisfied.\n const sharedCodec = shared.schema as unknown as Schema.Codec<Shared, unknown>\n const stamps = options.stamp as\n | Record<string, (message: Message, commit: CommitStamp) => Message>\n | undefined\n const sync = defineSync<Message, Shared, unknown, unknown>({\n documentId: options.documentId,\n ...(migrations === undefined\n ? { message: app.Message as unknown as Schema.Codec<Message, unknown> }\n : { migrations }),\n shared: sharedCodec,\n empty: shared.get(app.initial),\n durable: message => Option.exists(tagOf(message), tag => durableTags.has(tag)),\n serverOnly: message => Option.exists(tagOf(message), tag => serverTags.has(tag)),\n replay,\n // `durable` has already rejected anything outside the declared subset.\n coalesce: options.coalesce as\n | ((last: Message, next: Message) => Message | undefined)\n | undefined,\n ...(stamps === undefined\n ? {}\n : {\n stamp: (message: Message, commit: CommitStamp): Message =>\n Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => stamps[tag]),\n {\n onNone: () => message,\n onSome: rule => {\n const stamped = rule(message, commit)\n if (!Equal.equals(tagOf(stamped), tagOf(message)))\n throw new Error('A stamp must return the variant it was given')\n return stamped\n },\n },\n ),\n }),\n })\n\n const rules = options.authorize as\n | Record<string, (request: AuthorizeRequest<Principal, Message, Shared>) => AuthorizeDecision>\n | undefined\n const journalContract = (): PolicyJournalContract<Operation, Shared, Principal> => {\n const base = sync.journalContract()\n if (rules === undefined) return base\n return {\n ...base,\n authorize: ({ principal, operation, snapshot }) => {\n const message = decodeMessage(operation.message)\n return Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => rules[tag]),\n {\n onNone: () => true,\n onSome: rule => rule({ principal, message, shared: snapshot }),\n },\n )\n },\n }\n }\n\n const readOnly: Projection<AppModel, Shared> = Projection.fromReader(sharedCodec, shared.get, {\n dependencies: shared.dependencies,\n })\n const surface = Surface.make(app, options.name ?? String(options.documentId), {\n model: () => readOnly,\n messages: durable.constructors,\n })\n const contract: Contract = {\n kind: 'sync',\n name: surface.name,\n owner: app.owner,\n owns: shared.dependencies,\n observes: shared.dependencies,\n messages: [...durable.tags, ...serverTags],\n metadata: [],\n }\n return {\n ...sync,\n journalContract,\n surface,\n projection: shared,\n replay,\n messages: durable.constructors,\n serverOnlyMessages: serverOnly?.constructors ?? [],\n contract,\n wiring: () => ({ key: `sync:${contract.name}`, handles: [], contract }),\n }\n }\n\n return {\n withPrincipal: <P>() => build<AppModel, F, Cases, P>(app),\n fragment: config => {\n if (config.durable.owner !== app.owner)\n throw new Error('Sync.fragment: the durable subset belongs to a different application')\n return { shared: config.shared, durable: config.durable }\n },\n compose: ((...fragments: readonly SyncFragment<any, any, any, any>[]) =>\n composeFragments(fragments)) as ApplicationSync<AppModel, F, Cases, Principal>['compose'],\n make: make as ApplicationSync<AppModel, F, Cases, Principal>['make'],\n }\n}\n"],"mappings":";;;;;;;;;;;AAoEA,MAAM,cAAc,gBAA6C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,OAAO;GACb,UAAU,OAAO;GACjB,UAAU,CAAC,GAAG,QAAQ,MAAM,GAAG,UAAU;GACzC,UAAU,CAAC;EACb;EACA,OAAO;GACL,GAAG;GACH;GACA;GACA,YAAY;GACZ;GACA,UAAU,QAAQ;GAClB,oBAAoB,YAAY,gBAAgB,CAAC;GACjD;GACA,eAAe;IAAE,KAAK,QAAQ,SAAS;IAAQ,SAAS,CAAC;IAAG;GAAS;EACvE;CACF;CAEA,OAAO;EACL,qBAAwB,MAA6B,GAAG;EACxD,WAAU,WAAU;GAClB,IAAI,OAAO,QAAQ,UAAU,IAAI,OAC/B,MAAM,IAAI,MAAM,sEAAsE;GACxF,OAAO;IAAE,QAAQ,OAAO;IAAQ,SAAS,OAAO;GAAQ;EAC1D;EACA,WAAW,GAAG,cACZ,iBAAiB,SAAS;EACtB;CACR;AACF"}
|
|
1
|
+
{"version":3,"file":"make.js","names":[],"sources":["../src/make.ts"],"sourcesContent":["/**\n * The Foldkit-facing sync layer: `Sync.forApplication(App).make(config)`\n * compiles an application, a writable projection, and a durable Message subset\n * into the low-level `defineSync` contract, and exposes a read-only Surface over\n * the same projection.\n */\nimport { Equal, Option, Predicate, Schema } from 'effect'\nimport {\n MessageSet,\n Projection,\n Surface,\n type AppScope,\n type Contract,\n type MergeConstructors,\n type MergeFields,\n type RunnableApplication,\n type Wiring,\n type WritableProjection,\n} from 'foldkit-surface'\nimport type { DocumentId } from './ids.js'\nimport type { Migrations } from './migrations.js'\nimport { fitWords } from './refusal.js'\nimport {\n defineSync,\n type CommitStamp,\n type DeclaredLaw,\n type JournalContract,\n type Operation,\n type Sync,\n} from './sync.js'\n\ntype MessageConstructor<Message> = (...args: never[]) => Message\n\n/** The Message union a tuple of constructors produces. */\nexport type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends (...args: never[]) => infer M\n ? M\n : never\n\ntype AppMessage<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = Schema.Schema.Type<AppScope<AppModel, F, Cases>['Message']>\n\ntype AppMessageEncoded<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n> = AppScope<AppModel, F, Cases>['Message']['Encoded']\n\n/** `make`'s Message history, typed by the application's own Message. */\nexport interface HistoryOption<Message, Encoded> {\n /**\n * The Schemas the document's durable Messages were stored in, ending at the\n * application's own `Message` (`Sync.migrations(V1).next(App.Message, up)`):\n * operations written at an older version are upcast wherever they are read.\n * Without it, the Message is version 1.\n */\n readonly migrations?: Migrations<Message, Encoded> | undefined\n}\n\n/**\n * The Messages of the server-only constructors: none for `[]`, which\n * `MsgOf` reads as `unknown` (`never` matches its `infer`).\n */\nexport type ServerMsgOf<SMs extends readonly unknown[]> = [SMs[number]] extends [never]\n ? never\n : MsgOf<SMs>\n\n/** Reads the tag off a Foldkit Message constructor without constructing one. */\nconst messageTag = (constructor: unknown): string | undefined => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } }).fields\n ?._tag?.ast?.literal\n return typeof literal === 'string' ? literal : undefined\n}\n\n/** A Message's tag. The application's union is generic here, so its `_tag` is read, not typed. */\nconst tagOf = (message: unknown): Option.Option<string> =>\n Predicate.hasProperty(message, '_tag') && typeof message._tag === 'string'\n ? Option.some(message._tag)\n : Option.none()\n\n/** The `_tag` literal of the Message a constructor produces. */\ntype TagOf<C> = C extends (...args: never[]) => infer M\n ? M extends { readonly _tag: infer T extends string }\n ? T\n : never\n : never\n\n/**\n * A journal contract that also carries the declared authorization policy, in\n * the shape `makeJournal` takes, so `makeJournal({ ...contract })` applies it.\n */\nexport interface PolicyJournalContract<Operation, Shared, Principal> extends JournalContract<\n Operation,\n Shared\n> {\n readonly authorize?: (request: {\n readonly principal: Principal\n readonly operation: Operation\n readonly snapshot: Shared\n }) => AuthorizeDecision\n}\n\n/**\n * One law of a document. `holds` judges the snapshot an operation leaves,\n * with the one before it, and only `true` holds; it sees no principal and no\n * Message. `message` is what the person whose edit broke it is told, and\n * `path` the shared fields it is about.\n */\nexport interface Law<Shared, Key extends string> {\n readonly holds: (states: { readonly before: Shared; readonly after: Shared }) => boolean\n readonly message: string\n readonly path?: ReadonlyArray<Key>\n}\n\n/** `make`'s laws, keyed by id: each over the shared fields, and nothing else of the Model. */\nexport interface LawsOption<Fields extends Schema.Struct.Fields, LawIds extends string> {\n /**\n * What every snapshot of the document keeps, judged where an operation\n * commits and, as a hint, by a replica's `submit`. An operation whose\n * snapshot breaks one is refused as `SyncRefusal.Invalid` with the law's id\n * as `rule`; the first broken law in the record's order is named.\n */\n readonly laws?: {\n readonly [Id in LawIds]: Law<Schema.Struct.Type<Fields>, keyof Fields & string>\n }\n}\n\n/**\n * What a rule decides: allowed, refused, or refused with a reason the server\n * sends to the person whose edit it was. The shape of Durable's own decision.\n */\nexport type AuthorizeDecision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a per-variant `authorize` rule sees before the journal commits. */\nexport interface AuthorizeRequest<Principal, Message, Shared> {\n readonly principal: Principal\n readonly message: Message\n readonly shared: Shared\n}\n\n/**\n * Per-variant policy, keyed by durable tag: `message` is that variant exactly,\n * `shared` the authoritative snapshot. A variant without a rule is allowed; the\n * server may still refuse on its own grounds.\n */\nexport type AuthorizePolicy<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n> = {\n readonly [K in TagOf<Ms[number]>]?: (\n request: AuthorizeRequest<\n Principal,\n Extract<MsgOf<Ms>, { readonly _tag: K }>,\n Schema.Struct.Type<Fields>\n >,\n ) => AuthorizeDecision\n}\n\n/**\n * Per-variant commit stamps, keyed by durable tag: each writes what the server's commit\n * decided (its sequence, its actor) into that variant, and returns the same variant. A\n * variant without one is committed as sent.\n */\nexport type StampPolicy<Ms extends readonly unknown[]> = {\n readonly [K in TagOf<Ms[number]>]?: (\n message: Extract<MsgOf<Ms>, { readonly _tag: K }>,\n commit: CommitStamp,\n ) => Extract<MsgOf<Ms>, { readonly _tag: K }>\n}\n\ninterface BaseOptions<\n Principal,\n Fields extends Schema.Struct.Fields,\n Ms extends readonly unknown[],\n SMs extends readonly unknown[] = [],\n> {\n readonly documentId: DocumentId\n /** Name for the generated `surface`; defaults to the document id. */\n readonly name?: string\n /**\n * Replaces the replay derived from the application's `update`. It is a pure\n * reducer over the shared subset; only durable and server-only Messages reach\n * it, and it runs during admission, replay, and optimistic projection. It is\n * not guarded: the author owns its agreement with `update`.\n */\n readonly replay?: (\n shared: Schema.Struct.Type<NoInfer<Fields>>,\n message: MsgOf<NoInfer<Ms>> | ServerMsgOf<NoInfer<SMs>>,\n ) => Schema.Struct.Type<NoInfer<Fields>>\n /**\n * Authorization the server journal applies before committing, keyed by\n * durable or server-only tag; see `AuthorizePolicy`.\n */\n readonly authorize?: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>\n /** What the server's commit writes into a stored Message; see `StampPolicy`. */\n readonly stamp?: StampPolicy<NoInfer<[...Ms, ...SMs]>>\n /**\n * Merges a durable Message into the one submitted before it while that one is unsent,\n * so a burst of edits is one operation. Replaying the result must equal replaying\n * `last` then `next`; undefined keeps them apart.\n */\n readonly coalesce?: (\n last: MsgOf<NoInfer<Ms>>,\n next: MsgOf<NoInfer<Ms>>,\n ) => MsgOf<NoInfer<Ms>> | undefined\n}\n\nexport interface MakeOptions<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n Principal = unknown,\n ServerSubset = never,\n SMs extends readonly MessageConstructor<any>[] = [],\n> extends BaseOptions<Principal, Fields, Ms, SMs> {\n /** The writable projection of the shared fields. */\n readonly shared: WritableProjection<AppModel, Fields>\n /** The Message subset a replica submits, records and replays. */\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n /**\n * The Messages only the server appends (`foldkit-sync/journal`'s\n * `serverJournal`): stored and replayed like durable ones, refused from a\n * replica. A Message in both sets is a type error, and a throw here.\n */\n readonly serverOnly?: MessageSet<AppModel, any, ServerSubset, SMs> | undefined\n}\n\n/**\n * One feature's contribution to a document: the fields it shares and the\n * Messages it records. `compose` merges fragments into one, to spread into\n * `make`; a field declared twice with a different codec or a tag declared twice\n * is rejected there.\n */\nexport interface SyncFragment<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<any>[],\n> {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n}\n\ntype SharedOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['shared']\n}\ntype DurableOf<Fs extends readonly SyncFragment<any, any, any, any>[]> = {\n readonly [K in keyof Fs]: Fs[K]['durable']\n}\n/** The merged shared fields of several fragments. */\nexport type FragmentFields<Fs extends readonly SyncFragment<any, any, any, any>[]> = MergeFields<\n SharedOf<Fs>\n>\n/** The concatenated durable constructors of several fragments. */\nexport type FragmentConstructors<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n MergeConstructors<DurableOf<Fs>>\n\n/** The union of Messages several fragments record. */\nexport type FragmentMessages<Fs extends readonly SyncFragment<any, any, any, any>[]> =\n Fs[number] extends SyncFragment<any, any, infer V, any> ? V : never\n\n/**\n * The value `make` returns: the low-level `Sync` protocol plus the writable\n * projection, the declared Messages, and a read-only Surface over the\n * projection. Exported so a consumer can name the type.\n */\nexport interface DefinedSync<\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n Principal = unknown,\n /** `true` when `make` was given `authorize`, so the contract's `authorize` is present. */\n Authorized extends boolean = false,\n /** The server-only constructors, `[]` when `make` was given none. */\n SMs extends readonly unknown[] = [],\n /** The ids of `make`'s `laws`; `string` reads any contract's. */\n LawIds extends string = string,\n> extends Sync<Message, Schema.Struct.Type<Fields>, MsgOf<Ms>> {\n readonly surface: Surface<AppModel, Schema.Struct.Type<Fields>, MsgOf<Ms>, void>\n readonly projection: WritableProjection<AppModel, Fields>\n /** The reducer the replica replays durable Messages with: derived from `update`, or `make`'s `replay`. */\n readonly replay: (\n shared: Schema.Struct.Type<Fields>,\n message: Message,\n ) => Schema.Struct.Type<Fields>\n /** The durable constructors: what a replica submits. */\n readonly messages: Ms\n /** The server-only constructors: what only the server appends. */\n readonly serverOnlyMessages: SMs\n /** The declared laws, by id: what `Sync.isInvalidBy` matches a refusal against. */\n readonly laws: { readonly [Id in LawIds]: DeclaredLaw<Id> }\n /**\n * The first law the step from `before` to `after` breaks, or none: what the\n * journal and `submit` run. Run it over stored snapshots (`judge(s, s)`) to\n * audit them before deploying a new law.\n */\n readonly judge: (\n before: Schema.Struct.Type<Fields>,\n after: Schema.Struct.Type<Fields>,\n ) => Option.Option<DeclaredLaw<LawIds>>\n /** For `Module`: this contract owns the shared projection's paths and records the durable and server-only tags. */\n readonly contract: Contract\n /**\n * How this contract joins an assembly: contract-only, so the Module sees it.\n * It routes nothing, runs nothing, and subscribes to nothing; Sync owns the\n * runtime through `mount` rather than joining it.\n */\n readonly wiring: () => Wiring<AppModel, never>\n /** The durable journal's codecs, reducer, and, when declared, authorization. */\n readonly journalContract: () => Authorized extends true\n ? PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal> &\n Required<\n Pick<PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>, 'authorize'>\n >\n : PolicyJournalContract<Operation, Schema.Struct.Type<Fields>, Principal>\n}\n\n/** The sync constructors specialized to one application. */\nexport interface ApplicationSync<\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal = unknown,\n> {\n /**\n * Fixes the `Principal` that `authorize` rules see. A `Principal` cannot be a\n * positional type argument beside an inferred Model, so it is supplied here:\n * `Sync.forApplication(App).withPrincipal<User>()`. Type-only.\n */\n readonly withPrincipal: <P>() => ApplicationSync<AppModel, F, Cases, P>\n /** One feature's shared fields and durable Messages, for `compose`. */\n readonly fragment: <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n >(config: {\n readonly shared: WritableProjection<AppModel, Fields>\n readonly durable: MessageSet<AppModel, any, Subset, Ms>\n }) => SyncFragment<AppModel, Fields, Subset, Ms>\n /**\n * Merges fragments into one: `make({ documentId, ...compose(Todos, Members) })`.\n * A field declared twice with a different codec, a tag declared twice, or a\n * fragment from another application throws.\n */\n readonly compose: <const Fs extends readonly SyncFragment<AppModel, any, any, any>[]>(\n ...fragments: Fs\n ) => SyncFragment<AppModel, FragmentFields<Fs>, FragmentMessages<Fs>, FragmentConstructors<Fs>>\n readonly make: {\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n ServerSubset = never,\n // A server-only constructor makes a Message no durable one does, so a\n // variant in both sets fails here, at `serverOnly`.\n SMs extends readonly MessageConstructor<\n Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>\n >[] = [],\n LawIds extends string = never,\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> &\n HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>> &\n LawsOption<NoInfer<Fields>, LawIds> & {\n readonly authorize: AuthorizePolicy<Principal, NoInfer<Fields>, NoInfer<[...Ms, ...SMs]>>\n },\n ): DefinedSync<\n AppModel,\n Fields,\n AppMessage<AppModel, F, Cases>,\n Ms,\n Principal,\n true,\n SMs,\n LawIds\n >\n <\n Fields extends Schema.Struct.Fields,\n Subset,\n Ms extends readonly MessageConstructor<AppMessage<AppModel, F, Cases>>[],\n ServerSubset = never,\n SMs extends readonly MessageConstructor<\n Exclude<AppMessage<AppModel, F, Cases>, MsgOf<Ms>>\n >[] = [],\n LawIds extends string = never,\n >(\n options: MakeOptions<AppModel, Fields, Subset, Ms, Principal, ServerSubset, SMs> &\n HistoryOption<AppMessage<AppModel, F, Cases>, AppMessageEncoded<AppModel, F, Cases>> &\n LawsOption<NoInfer<Fields>, LawIds>,\n ): DefinedSync<\n AppModel,\n Fields,\n AppMessage<AppModel, F, Cases>,\n Ms,\n Principal,\n false,\n SMs,\n LawIds\n >\n }\n}\n\n/**\n * Replay derived from the application's own `update`: install the shared slice\n * into the initial Model, apply the Message, and read the slice back.\n *\n * A durable Message must be a deterministic, state-only transition of the shared\n * projection. Replay refuses one that returns a Command (a live effect cannot be\n * replayed) or that changes a Model field outside the projection (the change\n * would be silently lost), so a Message that needs either stays local and emits\n * a durable fact once the effect settles. What a Message reads is not visible\n * here, where every other field is `initial`: `Sync.mount` checks it against the\n * live Model.\n */\nconst derivedReplay = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Fields extends Schema.Struct.Fields,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n shared: WritableProjection<AppModel, Fields>,\n): ((\n value: Schema.Struct.Type<Fields>,\n message: AppMessage<AppModel, F, Cases>,\n) => Schema.Struct.Type<Fields>) => {\n const { initial, update } = app\n // Per-field equivalences for the fields the projection does not own outright,\n // built once, so a violation names the fields and replay (which runs per\n // pending operation on every optimistic read) does not re-compare the shared\n // slice against itself. A partially shared field is still compared.\n const owned = new Set(shared.dependencies.filter(path => path.length === 1).map(path => path[0]))\n const fields = Object.entries(app.Model.fields)\n .filter(([key]) => !owned.has(key))\n .map(\n ([key, field]) =>\n [key, Schema.toEquivalence(field as unknown as Schema.Schema<unknown>)] as const,\n )\n return (value, message) => {\n const result = update(shared.set(initial, value), message)\n if (result.commands !== undefined && result.commands.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" returned ${result.commands.length} Command(s); a durable transition is state-only`,\n )\n const next = shared.get(result.model)\n // Writing the projection back into the baseline reproduces `update`'s\n // result exactly when it touched only shared fields.\n const written = shared.set(initial, next) as Record<string, unknown>\n const actual = result.model as Record<string, unknown>\n const changed = fields.filter(([key, equal]) => !equal(actual[key], written[key]))\n if (changed.length > 0)\n throw new Error(\n `Sync.forApplication: durable \"${Option.getOrElse(tagOf(message), () => 'untagged')}\" changed Model fields outside the shared projection: ${changed.map(([key]) => key).join(', ')}`,\n )\n return next\n }\n}\n\n/**\n * The declared laws and their judge. Each id and message must fit a\n * refusal's words, and a path its sixteen fields, or the refusal could not\n * be sent; `make` throws rather than let one fail every exchange.\n */\nconst lawsOf = <Shared>(\n declared: Record<string, Law<Shared, string>>,\n): {\n readonly laws: Record<string, DeclaredLaw>\n readonly judge: (before: Shared, after: Shared) => Option.Option<DeclaredLaw>\n} => {\n const entries = Object.entries(declared).map(([id, law]) => {\n const path = law.path ?? []\n if (\n fitWords(id) !== id ||\n fitWords(law.message) !== law.message ||\n path.length > 16 ||\n path.some(field => fitWords(field) !== field)\n )\n throw new Error(\n `Sync.make: the law \"${fitWords(id)}\" does not fit a refusal: an id, a message or a field over 500 characters, or a path over 16 fields`,\n )\n return [{ id, message: law.message, path }, law.holds] as const\n })\n return {\n laws: Object.fromEntries(entries.map(([law]) => [law.id, law])),\n judge: (before, after) =>\n Option.fromUndefinedOr(entries.find(([, holds]) => holds({ before, after }) !== true)?.[0]),\n }\n}\n\n/**\n * Merges fragments into one. The primitives reject a conflicting field, a\n * duplicate tag, and a subset from another application.\n */\nconst composeFragments = (\n fragments: readonly SyncFragment<any, any, any, any>[],\n): SyncFragment<any, any, any, any> => {\n const compose = Projection.compose as (\n ...projections: readonly WritableProjection<any, any>[]\n ) => WritableProjection<any, any>\n const union = MessageSet.union as (\n ...subsets: readonly MessageSet<any, any, any, any>[]\n ) => MessageSet<any, any, any, any>\n return {\n shared: compose(...fragments.map(fragment => fragment.shared)),\n durable: union(...fragments.map(fragment => fragment.durable)),\n }\n}\n\n/**\n * Specializes the sync constructors to a `Surface.application`, so\n * `Sync.forApplication(App).make({ documentId, shared, durable })` derives the\n * shared codec, the initial snapshot, the durable predicate, and replay from\n * the application, and refuses a subset that belongs to another application.\n * `defineSync` remains the protocol primitive when there is no application to\n * derive from.\n */\nexport const forApplication = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases> => build(app)\n\nconst build = <\n AppModel,\n F extends Schema.Struct.Fields,\n Cases extends Record<string, Schema.Struct.Fields>,\n Principal,\n>(\n app: RunnableApplication<AppModel, F, Cases, any>,\n): ApplicationSync<AppModel, F, Cases, Principal> => {\n type Message = AppMessage<AppModel, F, Cases>\n const decodeMessage = Schema.decodeUnknownSync(\n app.Message as unknown as Schema.Codec<Message, unknown>,\n )\n\n const make = (\n options: MakeOptions<AppModel, any, any, any, Principal, any, any> &\n HistoryOption<Message, unknown> &\n LawsOption<any, string>,\n ): DefinedSync<AppModel, any, Message, any, Principal, boolean, any, string> => {\n type Shared = Record<string, unknown>\n const { shared, durable, migrations, serverOnly } = options\n // A Schema of an older version can equal the current one structurally, so\n // the types cannot tell a history that stops short; identity can.\n if (migrations !== undefined && (migrations.current as unknown) !== app.Message)\n throw new Error(\"Sync.make: the Message history must end at the application's own Message\")\n\n // Two applications can have structurally identical Message unions, so the\n // types cannot separate them; the owner token can.\n if (durable.owner !== app.owner)\n throw new Error('Sync.make: the durable subset belongs to a different application')\n if (serverOnly !== undefined && serverOnly.owner !== app.owner)\n throw new Error('Sync.make: the server-only subset belongs to a different application')\n\n const replay: (value: Shared, message: Message) => Shared =\n options.replay === undefined\n ? derivedReplay(app, shared)\n : // `durable` has already rejected anything outside the declared subset.\n (value, message) => options.replay!(value, message as never)\n const tagsOf = (constructors: readonly unknown[]): ReadonlySet<string> =>\n new Set(constructors.map(messageTag).filter((tag): tag is string => tag !== undefined))\n const durableTags = tagsOf(durable.constructors)\n const serverTags = tagsOf(serverOnly?.constructors ?? [])\n // The types refuse this too; a set built by `MessageSet.union` at run time may not be typed.\n for (const tag of serverTags)\n if (durableTags.has(tag))\n throw new Error(`Sync.make: \"${tag}\" is both durable and server-only`)\n // `AppScope` does not constrain its schemas' services; a Foldkit Message union\n // and a Struct are pure, so the low-level contract's `never` is satisfied.\n const sharedCodec = shared.schema as unknown as Schema.Codec<Shared, unknown>\n const stamps = options.stamp as\n | Record<string, (message: Message, commit: CommitStamp) => Message>\n | undefined\n const { laws, judge } = lawsOf(options.laws ?? {})\n const sync = defineSync<Message, Shared, unknown, unknown>({\n documentId: options.documentId,\n ...(migrations === undefined\n ? { message: app.Message as unknown as Schema.Codec<Message, unknown> }\n : { migrations }),\n shared: sharedCodec,\n empty: shared.get(app.initial),\n ...(options.laws === undefined ? {} : { judge }),\n durable: message => Option.exists(tagOf(message), tag => durableTags.has(tag)),\n serverOnly: message => Option.exists(tagOf(message), tag => serverTags.has(tag)),\n replay,\n // `durable` has already rejected anything outside the declared subset.\n coalesce: options.coalesce as\n | ((last: Message, next: Message) => Message | undefined)\n | undefined,\n ...(stamps === undefined\n ? {}\n : {\n stamp: (message: Message, commit: CommitStamp): Message =>\n Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => stamps[tag]),\n {\n onNone: () => message,\n onSome: rule => {\n const stamped = rule(message, commit)\n if (!Equal.equals(tagOf(stamped), tagOf(message)))\n throw new Error('A stamp must return the variant it was given')\n return stamped\n },\n },\n ),\n }),\n })\n\n const rules = options.authorize as\n | Record<string, (request: AuthorizeRequest<Principal, Message, Shared>) => AuthorizeDecision>\n | undefined\n const journalContract = (): PolicyJournalContract<Operation, Shared, Principal> => {\n const base = sync.journalContract()\n if (rules === undefined) return base\n return {\n ...base,\n authorize: ({ principal, operation, snapshot }) => {\n const message = decodeMessage(operation.message)\n return Option.match(\n Option.flatMapNullishOr(tagOf(message), tag => rules[tag]),\n {\n onNone: () => true,\n onSome: rule => rule({ principal, message, shared: snapshot }),\n },\n )\n },\n }\n }\n\n const readOnly: Projection<AppModel, Shared> = Projection.fromReader(sharedCodec, shared.get, {\n dependencies: shared.dependencies,\n })\n const surface = Surface.make(app, options.name ?? String(options.documentId), {\n model: () => readOnly,\n messages: durable.constructors,\n })\n const messages = [...durable.tags, ...serverTags]\n const contract: Contract = {\n kind: 'sync',\n name: surface.name,\n owner: app.owner,\n owns: shared.dependencies,\n observes: shared.dependencies,\n messages,\n metadata: [],\n // Each law reads the whole slice and each durable or server-only tag writes it, drawn by\n // `Graph.of` when asked.\n laws: { model: Object.keys(laws) },\n }\n return {\n ...sync,\n journalContract,\n surface,\n projection: shared,\n replay,\n messages: durable.constructors,\n serverOnlyMessages: serverOnly?.constructors ?? [],\n laws,\n judge,\n contract,\n wiring: () => ({ key: `sync:${contract.name}`, handles: [], contract }),\n }\n }\n\n return {\n withPrincipal: <P>() => build<AppModel, F, Cases, P>(app),\n fragment: config => {\n if (config.durable.owner !== app.owner)\n throw new Error('Sync.fragment: the durable subset belongs to a different application')\n return { shared: config.shared, durable: config.durable }\n },\n compose: ((...fragments: readonly SyncFragment<any, any, any, any>[]) =>\n composeFragments(fragments)) as ApplicationSync<AppModel, F, Cases, Principal>['compose'],\n make: make as ApplicationSync<AppModel, F, Cases, Principal>['make'],\n }\n}\n"],"mappings":";;;;;;;;;;;;AAsEA,MAAM,cAAc,gBAA6C;CAC/D,MAAM,UAAW,YAAwE,QACrF,MAAM,KAAK;CACf,OAAO,OAAO,YAAY,WAAW,UAAU,KAAA;AACjD;;AAGA,MAAM,SAAS,YACb,UAAU,YAAY,SAAS,MAAM,KAAK,OAAO,QAAQ,SAAS,WAC9D,OAAO,KAAK,QAAQ,IAAI,IACxB,OAAO,KAAK;;;;;;;;;;;;;AAkVlB,MAAM,iBAMJ,KACA,WAIkC;CAClC,MAAM,EAAE,SAAS,WAAW;CAK5B,MAAM,QAAQ,IAAI,IAAI,OAAO,aAAa,QAAO,SAAQ,KAAK,WAAW,CAAC,CAAC,CAAC,KAAI,SAAQ,KAAK,EAAE,CAAC;CAChG,MAAM,SAAS,OAAO,QAAQ,IAAI,MAAM,MAAM,CAAC,CAC5C,QAAQ,CAAC,SAAS,CAAC,MAAM,IAAI,GAAG,CAAC,CAAC,CAClC,KACE,CAAC,K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,EAC5F,cAAc,OAAO,aACvB,CAAC;EACD,MAAM,UAAU,QAAQ,KAAK,KAAK,QAAQ,QAAQ,OAAO,QAAQ,UAAU,GAAG;GAC5E,aAAa;GACb,UAAU,QAAQ;EACpB,CAAC;EACD,MAAM,WAAW,CAAC,GAAG,QAAQ,MAAM,GAAG,UAAU;EAChD,MAAM,WAAqB;GACzB,MAAM;GACN,MAAM,QAAQ;GACd,OAAO,IAAI;GACX,MAAM,OAAO;GACb,UAAU,OAAO;GACjB;GACA,UAAU,CAAC;GAGX,MAAM,EAAE,OAAO,OAAO,KAAK,IAAI,EAAE;EACnC;EACA,OAAO;GACL,GAAG;GACH;GACA;GACA,YAAY;GACZ;GACA,UAAU,QAAQ;GAClB,oBAAoB,YAAY,gBAAgB,CAAC;GACjD;GACA;GACA;GACA,eAAe;IAAE,KAAK,QAAQ,SAAS;IAAQ,SAAS,CAAC;IAAG;GAAS;EACvE;CACF;CAEA,OAAO;EACL,qBAAwB,MAA6B,GAAG;EACxD,WAAU,WAAU;GAClB,IAAI,OAAO,QAAQ,UAAU,IAAI,OAC/B,MAAM,IAAI,MAAM,sEAAsE;GACxF,OAAO;IAAE,QAAQ,OAAO;IAAQ,SAAS,OAAO;GAAQ;EAC1D;EACA,WAAW,GAAG,cACZ,iBAAiB,SAAS;EACtB;CACR;AACF"}
|
package/dist/mount.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mount.d.ts","names":[],"sources":["../src/mount.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"mount.d.ts","names":[],"sources":["../src/mount.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;qBAsEa,OAAQ,SAAO,SACjB;WACG;WAAuB,QAAQ,OAAO,OAAO;;;;;;;;;;iBAqB1C,SAAS,OAAO;WACtB,SAAS,OAAO,OAAO,KAAK,IAAI,QAAQ;WACxC,cAAc,KAAK,IAAI,QAAQ;WAC/B,iBAAiB,S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