foldkit-sync 0.16.0 → 0.17.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 CHANGED
@@ -781,7 +781,10 @@ const serving = Effect.gen(function* () {
781
781
  - A server that hands `foldkit-durable`'s `append` input it did not first read
782
782
  with a `codec` reader gets no server-only check: the journal knows no
783
783
  Message's tag. Read every sent entry with `codec.writtenFrom` before
784
- appending it, as `journalExchange` does.
784
+ appending it, as `journalExchange` does. The types hold you to it: what an
785
+ exchange receives (`Sync.transport.serve`'s `exchange`, a `TransportClient`,
786
+ a `loopback` handler) is `ReadonlyArray<unknown>`, and `append` takes only
787
+ a `WrittenOperation`.
785
788
 
786
789
  ### Work after a commit: reactions
787
790
 
@@ -1031,7 +1034,10 @@ A server that builds an operation itself and appends it (`editsJournal`'s
1031
1034
  `Notes.journalContract().operation.encode(operation)`. The journal takes a
1032
1035
  `WrittenOperation`, which is branded so that only Sync makes one: a decoded
1033
1036
  `Operation` names no version, would read as version 1, and is refused by the
1034
- type. Changing the shared
1037
+ type. An entry from a wire is `unknown` until `codec.writtenFrom` reads it.
1038
+ Nothing read as history writes again: `operation.decode` takes only a
1039
+ `WrittenOperation`, and `encode` refuses what `codec.committedFrom` returns,
1040
+ stripped of its commit or not. Changing the shared
1035
1041
  slice's own Schema is not covered: a stored snapshot or checkpoint of the old
1036
1042
  shape still needs a migration of your own.
1037
1043
 
@@ -1164,7 +1170,9 @@ const inMemory = Effect.gen(function* () {
1164
1170
  Effect.provide(
1165
1171
  Sync.transport.loopback((_cursor, pending) => ({
1166
1172
  operations: [],
1167
- acknowledged: pending.map(operation => operation.opId),
1173
+ acknowledged: pending.map(
1174
+ entry => TodoSync.codec.writtenFrom(entry, TodoSync.documentId).opId,
1175
+ ),
1168
1176
  rejected: [],
1169
1177
  })),
1170
1178
  ),
@@ -462,7 +462,7 @@ const serverJournal = (options) => {
462
462
  const parkedTrigger = (row) => Effect.gen(function* () {
463
463
  const input = yield* decodeParkedInput(row.input);
464
464
  const operation = yield* Effect.try({
465
- try: () => contract.operation.decode(input.operation),
465
+ try: () => contract.operation.decode(writtenEnvelope(input.operation)),
466
466
  catch: (cause) => new JournalError({
467
467
  message: "Could not read a parked run",
468
468
  cause
@@ -1 +1 @@
1
- {"version":3,"file":"serverJournal.js","names":["JournalDocumentId"],"sources":["../src/serverJournal.ts"],"sourcesContent":["/**\n * The server's own side of a document: Messages only it appends, and\n * reactions, the work that runs after a commit. Both commit through the\n * journal's `append` as the server's principal, so the journal's `validate`\n * and `authorize` judge them like any operation.\n *\n * A reaction's cursor and its parked runs live in `foldkit-durable`\n * (`journal.cursors`), beside the effect ledger, which records each run's\n * answer and whether its appends finished. The cursor is a lower bound over\n * the ledger: set back (to the floor, say), it costs ledger reads, never a\n * second external call. A cursor row that is lost altogether is not that:\n * `react` reports it and does nothing until `serverJournal` registers the\n * reaction again, at the journal's cursor then, skipping what came between.\n * An external call still runs at least once, never exactly once: a crash\n * between the call and the ledger's write runs it again, with the same key.\n */\nimport {\n Cause,\n Clock,\n Duration,\n Effect,\n Option,\n Predicate,\n Queue,\n Result,\n Schema,\n Semaphore,\n Stream,\n} from 'effect'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n InvalidOperationError,\n JournalError,\n OpId,\n type AppendError,\n type AppendResult,\n type Journal,\n type ParkedRun,\n} from 'foldkit-durable/core'\nimport type { MessageSet, ReportDiagnostic } from 'foldkit-surface'\nimport {\n reactionFailed,\n reactionParked,\n reactionSkipped,\n reportTo,\n type SyncDiagnostic,\n} from './diagnostics.js'\nimport {\n AmbiguousMessageError,\n ServerKeyReusedError,\n StaleParkedRunError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n} from './errors.js'\nimport type { DefinedSync, MsgOf, ServerMsgOf } from './make.js'\nimport {\n SERVER_REPLICA_PREFIX,\n writtenEnvelope,\n type Operation,\n type WrittenOperation,\n} from './sync.js'\n\n/** The longest key `appendAsServer` takes. */\nconst MAX_KEY = 200\n/** The most Messages one run may append. */\nconst MAX_APPENDS = 16\n/** How many committed operations a reaction reads at once. */\nconst PAGE = 100\n/** A failing reaction waits from this, doubling, up to the cap, in ms. */\nconst BACKOFF_BASE = 500\nconst BACKOFF_MAX = 30_000\n/** How long a pass waits after the journal itself failed, which counts toward no bound. */\nconst JOURNAL_RETRY = Duration.seconds(5)\nconst REACTION_NAME = /^[A-Za-z0-9_-]{1,64}$/\n\n/** A committed operation, as a reaction is given it. */\nexport interface Trigger<Message> {\n /** The Message at the current version, as every hook sees it. */\n readonly message: Message\n readonly opId: string\n readonly sequence: number\n /** Who committed it: a person's actor, or the server's. */\n readonly actorId: string\n /**\n * 64 hex characters naming this run, the same on every retry and across\n * restarts: give it to the provider as its idempotency key.\n */\n readonly key: string\n}\n\n/**\n * One declared reaction of one document: what it runs on, what it may\n * append, and what its handler needs. Made by `reaction`, given to\n * `serverJournal`.\n */\nexport interface Reaction<Document, out R = never> {\n /** The contract it was declared for: `serverJournal` refuses it for another. */\n readonly sync: Document\n readonly name: string\n /** The tags it runs on. */\n readonly on: ReadonlySet<string>\n /** The tags it may append. */\n readonly appends: ReadonlySet<string>\n /** The services its handler needs; never present. */\n readonly requires?: () => R\n}\n\ninterface Handler {\n readonly run: (\n trigger: Trigger<unknown>,\n ) => Effect.Effect<ReadonlyArray<unknown> | void, unknown, unknown>\n readonly timeout: Duration.Duration\n readonly attempts: number\n readonly parkAfter: Duration.Duration\n}\n\n/** Each reaction's handler and bounds, kept off the value so nothing else can call it. */\nconst handlers = new WeakMap<Reaction<unknown, unknown>, Handler>()\n\ntype AnySync = DefinedSync<any, any, any, any, any, any, any>\n\nconst tagOf = (message: unknown): Option.Option<string> =>\n Predicate.hasProperty(message, '_tag') && typeof message._tag === 'string'\n ? Option.some(message._tag)\n : Option.none()\n\nconst tagsOf = (constructors: ReadonlyArray<unknown>): ReadonlySet<string> =>\n new Set(\n constructors.flatMap(constructor => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } })\n .fields?._tag?.ast?.literal\n return typeof literal === 'string' ? [literal] : []\n }),\n )\n\nexport interface ReactionOptions<AppModel, On, Appends, R> {\n /** Part of every run's key, so renaming it is a new reaction. Letters, digits, `_` and `-`, at most 64; unique in the document. */\n readonly name: string\n /** The committed Messages it runs after: a set of the contract's own application. */\n readonly on: MessageSet<AppModel, any, On, any>\n /** The server-only Messages it may append, checked on every answer. Without it, it appends nothing. */\n readonly appends?: MessageSet<AppModel, any, Appends, any>\n /** How long one run may take before it counts as failed. Default 10 seconds. */\n readonly timeout?: Duration.Input\n /** A failing run is parked once it has failed this many times, and for at least `parkAfter`. Default 8. */\n readonly attempts?: number\n /** How long a run must have been failing before it may be parked, so an outage parks nothing. Default one hour. */\n readonly parkAfter?: Duration.Input\n /**\n * One external call, or none, and the Messages to append, at most 16. It may\n * run again with the same trigger: pass `trigger.key` to the provider.\n */\n readonly run: (\n trigger: Trigger<On>,\n ) => Effect.Effect<ReadonlyArray<NoInfer<Appends>> | void, unknown, R>\n}\n\n/**\n * Declares a reaction of a contract from `Sync.forApplication(App).make`:\n * after each committed Message in `on`, in journal order, `run` is called\n * once at least, and what it answers is appended as the server. A handler\n * that keeps failing is parked after `attempts` failures over `parkAfter`;\n * one whose answer can never commit is parked at once. Throws for a name\n * that is not one, or a set of another application or outside the contract.\n */\nexport const reaction = <\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n ContractPrincipal,\n Authorized extends boolean,\n SMs extends readonly unknown[],\n On extends MsgOf<Ms> | ServerMsgOf<SMs>,\n Appends extends ServerMsgOf<SMs> = never,\n R = never,\n>(\n sync: DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n options: ReactionOptions<AppModel, On, Appends, R>,\n): Reaction<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, R> => {\n const { name } = options\n if (!REACTION_NAME.test(name))\n throw new Error(\n `Sync.reaction: \"${name}\" is not a reaction name (letters, digits, _ and -, at most 64)`,\n )\n const owner = sync.contract.owner\n if (\n options.on.owner !== owner ||\n (options.appends !== undefined && options.appends.owner !== owner)\n )\n throw new Error(`Sync.reaction: ${name} names Messages of another application`)\n const durable = tagsOf(sync.messages)\n const server = tagsOf(sync.serverOnlyMessages)\n const on = tagsOf(options.on.constructors)\n const appends = tagsOf(options.appends?.constructors ?? [])\n for (const tag of on)\n if (!durable.has(tag) && !server.has(tag))\n throw new Error(`Sync.reaction: ${name} runs on \"${tag}\", which never commits`)\n for (const tag of appends)\n if (!server.has(tag))\n throw new Error(`Sync.reaction: ${name} appends \"${tag}\", which is not server-only`)\n const attempts = options.attempts ?? 8\n if (!Number.isSafeInteger(attempts) || attempts < 1)\n throw new Error(`Sync.reaction: ${name}'s attempts must be a positive integer`)\n const made: Reaction<\n DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n R\n > = { sync, name, on, appends }\n handlers.set(made, {\n run: options.run as Handler['run'],\n timeout: Duration.fromInputUnsafe(options.timeout ?? '10 seconds'),\n attempts,\n parkAfter: Duration.fromInputUnsafe(options.parkAfter ?? '1 hour'),\n })\n return made\n}\n\n/** A run set aside: it failed for good, or too often. Its reaction went on without it. */\nexport interface Parked {\n readonly reaction: string\n readonly opId: string\n readonly sequence: number\n /** Why, as the last failure said it. */\n readonly error: string\n /** Parked in a history since reset: it can be dismissed, not run again. */\n readonly stale: boolean\n}\n\nexport interface ServerJournal<ServerOnly, R> {\n /**\n * Appends a server-only Message as the server. `key` names the fact (a\n * webhook event's id, `absorbed/<through>`): a repeat with the same key and\n * Message is answered from history, and one with another Message fails with\n * `ServerKeyReusedError`. A key is a non-empty string of at most 200\n * characters; another is an `InvalidOperationError`.\n */\n readonly appendAsServer: (\n message: ServerOnly,\n options: { readonly key: string },\n ) => Effect.Effect<AppendResult<Operation>, AppendError | ServerKeyReusedError>\n /**\n * Runs every reaction from its stored cursor, a page at a time. Never\n * fails: a failed run is reported, and the answer is how long to wait\n * before running again; none when every reaction has caught up. Safe to\n * call at any time, from anywhere in this process: passes of one\n * `serverJournal` run one at a time. Two instances over one store (two\n * isolates over one D1) do not wait for each other.\n */\n readonly react: Effect.Effect<Option.Option<Duration.Duration>, never, R>\n /**\n * Runs `react` now, after every commit to the document this journal\n * instance hears of, and after the delay `react` answers, until\n * interrupted: a long-lived process's loop. Fork it.\n */\n readonly follow: Effect.Effect<never, never, R>\n /** The lowest cursor of the declared reactions: compact no further than this. */\n readonly settledThrough: Effect.Effect<Cursor, JournalError>\n /** The runs set aside, for a person to look at. */\n readonly parked: Effect.Effect<ReadonlyArray<Parked>, JournalError>\n /**\n * Runs a parked run again, out of order; it leaves the list when it\n * succeeds, and stays, failing, when it does not. A recorded answer is\n * reused, so a refused append retried after the rule changed makes no\n * second external call. A stale one fails with `StaleParkedRunError`.\n */\n readonly retry: (parked: Parked) => Effect.Effect<void, unknown, R>\n /** Forgets a parked run: its reaction never happens. */\n readonly dismiss: (parked: Parked) => Effect.Effect<void, JournalError>\n}\n\n/** The services a list of reactions needs: none for none. */\nexport type Requires<Reactions extends ReadonlyArray<Reaction<any, any>>> = [\n Reactions[number],\n] extends [never]\n ? never\n : Reactions[number] extends Reaction<any, infer R>\n ? R\n : never\n\nexport interface ServerJournalOptions<Document, Principal, Shared, Reactions> {\n readonly sync: Document\n readonly journal: Journal<Operation, Shared, Principal, WrittenOperation>\n /**\n * Who the server commits as. Never resolved from a request, and best never\n * changed: the journal binds each `server/` replica id to the first actor\n * that commits from it. After a change of `actorId`, a reaction's append for\n * a new trigger and a new `appendAsServer` key commit as the new actor; a\n * redelivered key is an `IdentityConflictError`, and a run retried after\n * its first append committed under the old actor parks.\n */\n readonly server: Principal\n readonly reactions?: Reactions\n /** The most runs one `react` starts, over every reaction; a host with a time limit sets it low. */\n readonly runsPerPass?: number\n /** Where reactions' failures, parks and skips go; the reporter in context when not given. */\n readonly diagnostics?: ReportDiagnostic | undefined\n}\n\n/** Canonical JSON with sorted object keys: what two Messages are compared by. */\nconst canonical = (value: unknown): string =>\n JSON.stringify(value, (_, inner: unknown) =>\n inner !== null && typeof inner === 'object' && !Array.isArray(inner)\n ? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : inner,\n )\n\nconst sha256 = (text: string): Effect.Effect<string> =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest =>\n Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(''),\n ),\n )\n\n/** Why a run failed: its answer can never commit, or it may on another try. */\nclass RunFailed extends Schema.TaggedError<RunFailed>()('SyncRunFailed', {\n permanent: Schema.Boolean,\n reason: Schema.String,\n}) {\n override get message(): string {\n return this.reason\n }\n}\n\nconst cut = (words: string): string => (words.length <= 500 ? words : `${words.slice(0, 499)}…`)\n\n/** A handler's own failure, defect or interruption, in words: a run that may succeed again. */\nconst handlerFailed = (cause: Cause.Cause<unknown>): RunFailed =>\n new RunFailed({\n permanent: false,\n reason: cut(\n Option.match(Cause.findErrorOption(cause), {\n onSome: error =>\n Cause.isTimeoutError(error)\n ? 'The handler timed out'\n : error instanceof Error\n ? error.message\n : String(error),\n onNone: () => Cause.pretty(cause).split('\\n')[0] ?? 'The handler failed',\n }),\n ),\n })\n\n/**\n * An append the journal refused: the same refusal every time, except a\n * Message written at a version newer than this build, which a deploy fixes.\n */\nconst appendFailed = (error: Exclude<AppendError, JournalError>): RunFailed =>\n new RunFailed({\n permanent: !(\n error._tag === 'InvalidOperationError' &&\n error.cause instanceof UnsupportedMessageVersionError\n ),\n reason: cut(error.message),\n })\n\nconst RecordedAnswer = Schema.Struct({\n messageVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n messages: Schema.Array(Schema.Unknown),\n})\nconst decodeAnswer = Schema.decodeUnknownEffect(RecordedAnswer, { onExcessProperty: 'error' })\nconst ParkedInput = Schema.Struct({ operation: Schema.Unknown, actorId: Schema.NonEmptyString })\nconst decodeParkedInput = Schema.decodeUnknownEffect(ParkedInput, { onExcessProperty: 'error' })\n\n/** Each reaction appends what reaction feeds; a cycle among them is refused. */\nconst checkAcyclic = (reactions: ReadonlyArray<Reaction<unknown, unknown>>): void => {\n const visiting = new Set<Reaction<unknown, unknown>>()\n const done = new Set<Reaction<unknown, unknown>>()\n const visit = (from: Reaction<unknown, unknown>): void => {\n if (done.has(from)) return\n if (visiting.has(from))\n throw new Error(`Sync.serverJournal: reaction ${from.name} is in a cycle`)\n visiting.add(from)\n for (const to of reactions) if ([...from.appends].some(tag => to.on.has(tag))) visit(to)\n visiting.delete(from)\n done.add(from)\n }\n for (const each of reactions) visit(each)\n}\n\n/**\n * The server's side of one document: `appendAsServer`, and the declared\n * reactions with what runs them. Registers each reaction's cursor at the\n * journal's current cursor before it answers, so make it before the journal\n * serves its first exchange: a reaction sees every commit made after this.\n * Throws for a reaction of another contract, two of one name, or a cycle.\n */\nexport const serverJournal = <\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n ContractPrincipal,\n Authorized extends boolean,\n SMs extends readonly unknown[],\n Principal,\n const Reactions extends ReadonlyArray<\n Reaction<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, any>\n > = [],\n>(\n options: ServerJournalOptions<\n DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n Principal,\n Schema.Struct.Type<Fields>,\n Reactions\n >,\n): Effect.Effect<ServerJournal<ServerMsgOf<SMs>, Requires<Reactions>>, JournalError> => {\n type R = Requires<Reactions>\n const sync: AnySync = options.sync\n const { journal, server } = options\n const reactions: ReadonlyArray<Reaction<unknown, unknown>> = options.reactions ?? []\n const names = new Set<string>()\n for (const each of reactions) {\n if (each.sync !== options.sync)\n throw new Error(`Sync.serverJournal: reaction ${each.name} was declared for another contract`)\n if (names.has(each.name))\n throw new Error(`Sync.serverJournal: two reactions are named ${each.name}`)\n names.add(each.name)\n }\n checkAcyclic(reactions)\n const runsPerPass = options.runsPerPass ?? Number.MAX_SAFE_INTEGER\n if (!Number.isSafeInteger(runsPerPass) || runsPerPass < 1)\n throw new Error('Sync.serverJournal: runsPerPass must be a positive integer')\n\n const documentId = String(sync.documentId)\n const key = JournalDocumentId.make(documentId)\n const contract = sync.journalContract()\n const decodeMessage = Schema.decodeUnknownSync(sync.codec.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(sync.codec.message)\n const report = (diagnostic: SyncDiagnostic) => reportTo(options.diagnostics, diagnostic)\n const cursorName = (reaction: Reaction<unknown, unknown>) => `react/${reaction.name}`\n const handlerOf = (reaction: Reaction<unknown, unknown>): Handler => handlers.get(reaction)!\n\n /** An operation of the server's, written at `version`, as only Sync writes one. */\n const envelope = (\n replicaId: string,\n localSequence: number,\n baseCursor: number,\n message: unknown,\n version: number,\n ): WrittenOperation =>\n writtenEnvelope({\n protocolVersion: 1,\n schemaVersion: 1,\n documentId,\n replicaId,\n localSequence,\n opId: `${replicaId}:${localSequence}`,\n baseCursor,\n message,\n ...(version === 1 ? {} : { messageVersion: version }),\n })\n\n const invalid = (message: string, cause?: unknown) =>\n new InvalidOperationError({ message, ...(cause === undefined ? {} : { cause }) })\n\n const appendAsServer = (message: ServerMsgOf<SMs>, { key: fact }: { readonly key: string }) =>\n Effect.gen(function* () {\n if (fact.length === 0 || fact.length > MAX_KEY)\n return yield* invalid('A server key is a non-empty string of at most 200 characters')\n if (!sync.serverOnly(message))\n return yield* invalid('appendAsServer takes a Message only the server appends')\n const encoded = yield* Effect.try({\n try: () => encodeMessage(message),\n catch: cause => invalid('The Message does not encode', cause),\n })\n const replicaId = `${SERVER_REPLICA_PREFIX}k/${yield* sha256(fact)}`\n const written = envelope(replicaId, 1, 0, encoded, sync.codec.messageVersion)\n // Recorded before it is appended, so a repeat after a deploy that added\n // a step appends the bytes first written, which the journal compares.\n const recorded = yield* journal\n .runEffect(canonical(['server', documentId, fact]), Effect.succeed(written))\n .pipe(\n Effect.catchTag('EffectFailedError', error =>\n Effect.fail(new JournalError({ message: error.message, cause: error })),\n ),\n )\n const same =\n canonical(recorded) === canonical(written) ||\n Result.match(\n Result.try(() => contract.operation.decode(recorded)),\n {\n onFailure: () => false,\n onSuccess: operation => canonical(operation.message) === canonical(encoded),\n },\n )\n if (!same) return yield* new ServerKeyReusedError({ key: fact })\n // A record that is no envelope is the store's fault, as a row that will not read is.\n const kept = yield* Effect.try({\n try: () => writtenEnvelope(recorded),\n catch: cause => new JournalError({ message: 'Could not read a recorded operation', cause }),\n })\n return yield* journal.append(key, kept, server).pipe(\n // Refused, nothing committed: the key is free again for a Message the\n // rules take. A conflict keeps it, since the id is taken.\n Effect.tapErrorTag('OperationRejectedError', () => forget(fact)),\n Effect.tapErrorTag('InvalidOperationError', () => forget(fact)),\n )\n })\n\n const forget = (fact: string) =>\n journal.clearEffect(canonical(['server', documentId, fact])).pipe(Effect.ignore)\n\n /** The run of one reaction on one committed operation: its answer, then its appends. */\n const runOnce = (\n reaction: Reaction<unknown, unknown>,\n epoch: string,\n committed: {\n readonly opId: string\n readonly sequence: number\n readonly actorId: string\n readonly message: unknown\n },\n ): Effect.Effect<void, RunFailed | JournalError, unknown> =>\n Effect.gen(function* () {\n const handler = handlerOf(reaction)\n const { opId, sequence } = committed\n // The ledger runs what it is given with no services: the handler's are this run's.\n const services = yield* Effect.context<unknown>()\n const triggerKey = yield* sha256(canonical(['react', documentId, reaction.name, opId]))\n const answer = Effect.suspend(() =>\n handler.run({\n message: committed.message,\n opId,\n sequence,\n actorId: committed.actorId,\n key: triggerKey,\n }),\n ).pipe(\n Effect.timeout(handler.timeout),\n Effect.provideContext(services),\n // A defect or an interruption is a failure the ledger records: its\n // `tapError` sees neither, and the record would stay pending.\n Effect.sandbox,\n Effect.mapError(handlerFailed),\n Effect.flatMap(returned =>\n Effect.gen(function* () {\n const messages: ReadonlyArray<unknown> = returned ?? []\n if (!Array.isArray(messages))\n return yield* new RunFailed({ permanent: true, reason: 'The answer is not a list' })\n if (messages.length > MAX_APPENDS)\n return yield* new RunFailed({\n permanent: true,\n reason: `The answer holds ${messages.length} Messages, past ${MAX_APPENDS}`,\n })\n const encoded = yield* Effect.forEach(messages, message =>\n Option.match(\n Option.filter(tagOf(message), tag => reaction.appends.has(tag)),\n {\n onNone: () =>\n Effect.fail(\n new RunFailed({\n permanent: true,\n reason: 'The answer holds a Message its appends do not name',\n }),\n ),\n onSome: () =>\n Effect.try({\n try: () => encodeMessage(message),\n catch: () =>\n new RunFailed({ permanent: true, reason: 'The answer does not encode' }),\n }),\n },\n ),\n )\n return { messageVersion: sync.codec.messageVersion, messages: encoded }\n }),\n ),\n )\n // Named by the trigger's id, never its place: sequences start again\n // after a reset, and a reaction running on this one's append keys its\n // answer by that append's id.\n const replyOf = `${SERVER_REPLICA_PREFIX}r/${reaction.name}/${yield* sha256(opId)}`\n const appendAll = Effect.gen(function* () {\n const recorded = yield* journal\n .runEffect(canonical(['react', documentId, reaction.name, opId, 'answer']), answer)\n .pipe(Effect.flatMap(decodeAnswer), Effect.mapError(asRunFailure))\n for (const [index, message] of recorded.messages.entries())\n yield* journal\n .append(\n key,\n envelope(`${replyOf}/${index}`, 1, sequence, message, recorded.messageVersion),\n server,\n )\n .pipe(\n Effect.catchTags({\n InvalidOperationError: error => Effect.fail(appendFailed(error)),\n OperationRejectedError: error => Effect.fail(appendFailed(error)),\n IdentityConflictError: error => Effect.fail(appendFailed(error)),\n }),\n )\n })\n // The epoch is in this key and not the answer's: after a reset the\n // appends run again in the new history, and the answer is reused.\n yield* journal\n .runEffect(\n canonical(['react', documentId, reaction.name, opId, 'finished', epoch]),\n appendAll,\n )\n .pipe(Effect.mapError(asRunFailure))\n })\n\n /** The pass of one reaction: from its cursor, a page, unless its backoff has not elapsed. */\n const passOf = (\n reaction: Reaction<unknown, unknown>,\n budget: number,\n ): Effect.Effect<\n { readonly runs: number; readonly next: Option.Option<Duration.Duration> },\n JournalError,\n unknown\n > =>\n Effect.gen(function* () {\n const name = cursorName(reaction)\n const handler = handlerOf(reaction)\n const tracked = yield* journal.cursors.settled(key, name)\n if (Option.isNone(tracked))\n return yield* Effect.die(\n new Error(`Sync.serverJournal: reaction ${reaction.name} was never registered`),\n )\n const { epoch, cursor, attempts, failedAt, firstFailedAt } = tracked.value\n const now = yield* Clock.currentTimeMillis\n const wait = Option.match(failedAt, {\n onNone: () => 0,\n onSome: at => at + backoff(attempts) - now,\n })\n if (attempts > 0 && wait > 0) return { runs: 0, next: Option.some(Duration.millis(wait)) }\n // The stored failures are the commit after the cursor's; once the pass\n // moves past it, a failure further on is that commit's first.\n let failed = { attempts, since: firstFailedAt }\n const stall = (\n runs: number,\n cause: string,\n at: Option.Option<{ opId: string; sequence: number }>,\n ) =>\n Effect.gen(function* () {\n yield* journal.cursors.stalled(key, name, epoch, now)\n yield* report(reactionFailed(documentId, reaction.name, at, cut(cause)))\n return { runs, next: Option.some(Duration.millis(backoff(failed.attempts + 1))) }\n })\n const page = yield* Effect.result(journal.read(key, cursor, { limit: PAGE }))\n if (Result.isFailure(page)) {\n const failure = page.failure\n if (failure._tag === 'CompactedCursorError') {\n yield* report(reactionSkipped(documentId, reaction.name, cursor, failure.floor))\n yield* journal.cursors.advance(key, name, epoch, Cursor.make(failure.floor))\n return { runs: 0, next: Option.some(Duration.zero) }\n }\n // A commit that will not read: no operation can be named, so nothing\n // parks, and the reaction waits on its backoff for a build that reads it.\n if (failure._tag === 'JournalError' && !unreadable(failure.cause)) return yield* failure\n return yield* stall(0, failure.message, Option.none())\n }\n let at = cursor\n let runs = 0\n const reach = (sequence: number) => {\n at = Cursor.make(sequence)\n failed = { attempts: 0, since: Option.none() }\n }\n const moved = () =>\n at > cursor ? journal.cursors.advance(key, name, epoch, at) : Effect.void\n for (const committed of page.success) {\n const message = decodeMessage(committed.operation.message)\n if (!Option.exists(tagOf(message), tag => reaction.on.has(tag))) {\n reach(committed.sequence)\n continue\n }\n if (runs >= budget) {\n yield* moved()\n return { runs, next: Option.some(Duration.zero) }\n }\n runs += 1\n const outcome = yield* Effect.result(\n runOnce(reaction, epoch, {\n opId: committed.opId,\n sequence: committed.sequence,\n actorId: committed.actorId,\n message,\n }),\n )\n if (Result.isSuccess(outcome)) {\n reach(committed.sequence)\n continue\n }\n const failure = outcome.failure\n // The store failing is not the run's fault: it counts toward nothing.\n if (failure._tag === 'JournalError') {\n yield* moved()\n return yield* failure\n }\n const tried = failed.attempts + 1\n const since = Option.getOrElse(failed.since, () => now)\n const parks =\n failure.permanent ||\n (tried >= handler.attempts && now - since >= Duration.toMillis(handler.parkAfter))\n const place = { opId: committed.opId, sequence: committed.sequence }\n if (!parks) {\n yield* moved()\n return yield* stall(runs, failure.reason, Option.some(place))\n }\n // Parked first: a crash before the cursor moves runs it once more,\n // and the second park changes nothing.\n yield* journal.cursors.park(key, {\n name,\n opId: committed.opId,\n epoch,\n sequence: committed.sequence,\n input: {\n operation: contract.operation.encode(committed.operation),\n actorId: committed.actorId,\n },\n error: failure.reason,\n })\n yield* report(\n reactionParked(\n documentId,\n reaction.name,\n committed.opId,\n committed.sequence,\n failure.reason,\n ),\n )\n reach(committed.sequence)\n }\n yield* moved()\n return {\n runs,\n next: page.success.length === PAGE ? Option.some(Duration.zero) : Option.none(),\n }\n })\n\n const earliest = (\n a: Option.Option<Duration.Duration>,\n b: Option.Option<Duration.Duration>,\n ): Option.Option<Duration.Duration> =>\n Option.isNone(a) ? b : Option.isNone(b) ? a : Option.some(Duration.min(a.value, b.value))\n\n // Which reaction a pass starts with, turning each pass, so a share's\n // rounding favours no reaction for good.\n let first = 0\n // One pass at a time: two at once would count each failure twice and reach\n // the attempts bound in half the failures.\n const passes = Semaphore.makeUnsafe(1)\n const react = Effect.gen(function* () {\n let budget = runsPerPass\n let next = Option.none<Duration.Duration>()\n const order = reactions.map((_, at) => reactions[(first + at) % reactions.length]!)\n first = reactions.length === 0 ? 0 : (first + 1) % reactions.length\n for (const [at, each] of order.entries()) {\n // A fair share of what is left, so a busy reaction cannot starve the rest.\n const share = Math.ceil(budget / (order.length - at))\n if (share <= 0) return Option.some(Duration.zero)\n const pass = yield* passOf(each, share).pipe(\n Effect.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : report(\n reactionFailed(\n documentId,\n each.name,\n Option.none(),\n cut(\n Option.match(Cause.findErrorOption(cause), {\n onSome: error => error.message,\n onNone: () => Cause.pretty(cause).split('\\n')[0] ?? 'The pass broke',\n }),\n ),\n ),\n ).pipe(Effect.as({ runs: 0, next: Option.some(JOURNAL_RETRY) })),\n ),\n )\n budget -= pass.runs\n next = earliest(next, pass.next)\n }\n return next\n }).pipe(passes.withPermits(1)) as Effect.Effect<Option.Option<Duration.Duration>, never, R>\n\n const follow = Effect.gen(function* () {\n // One pending wake-up is enough: a pass reads everything after the cursor.\n const wake = yield* Queue.sliding<void>(1)\n yield* Effect.forkChild(\n Stream.runForEach(\n Stream.filter(journal.subscribe, changed => changed === documentId),\n () => Queue.offer(wake, undefined),\n ),\n { startImmediately: true },\n )\n while (true) {\n const next = yield* react\n yield* Option.match(next, {\n onNone: () => Queue.take(wake),\n onSome: delay => Effect.raceFirst(Queue.take(wake), Effect.sleep(delay)),\n })\n }\n }) as Effect.Effect<never, never, R>\n\n const settledThrough = Effect.gen(function* () {\n let lowest = yield* journal.cursor(key)\n for (const each of reactions) {\n const tracked = yield* journal.cursors.settled(key, cursorName(each))\n const at = Option.match(tracked, { onNone: () => Cursor.make(0), onSome: t => t.cursor })\n if (at < lowest) lowest = at\n }\n return lowest\n })\n\n const reactionOf = (name: string): Option.Option<Reaction<unknown, unknown>> =>\n Option.fromUndefinedOr(reactions.find(each => cursorName(each) === name))\n\n const parked = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n const rows = yield* journal.cursors.parked(key)\n return rows.flatMap((row): ReadonlyArray<Parked> =>\n row.name.startsWith('react/')\n ? [\n {\n reaction: row.name.slice('react/'.length),\n opId: row.opId,\n sequence: row.sequence,\n error: row.error,\n stale: row.epoch !== epoch,\n },\n ]\n : [],\n )\n })\n\n const retry = (which: Parked) =>\n Effect.gen(function* () {\n const name = `react/${which.reaction}`\n const epoch = yield* journal.epoch(key)\n const rows = yield* journal.cursors.parked(key)\n const row = rows.find(each => each.name === name && each.opId === which.opId)\n // Already resolved: nothing to do.\n if (row === undefined) return\n if (row.epoch !== epoch)\n return yield* new StaleParkedRunError({ reaction: which.reaction, opId: which.opId })\n const declared = reactionOf(name)\n if (Option.isNone(declared))\n return yield* Effect.fail(\n new Error(`Reaction ${which.reaction} is not declared on this journal`),\n )\n const trigger = yield* parkedTrigger(row)\n yield* runOnce(declared.value, epoch, trigger)\n yield* journal.cursors.unpark(key, name, row.opId)\n }) as Effect.Effect<void, unknown, R>\n\n const parkedTrigger = (row: ParkedRun) =>\n Effect.gen(function* () {\n const input = yield* decodeParkedInput(row.input)\n const operation = yield* Effect.try({\n try: () => contract.operation.decode(input.operation),\n catch: cause => new JournalError({ message: 'Could not read a parked run', cause }),\n })\n return {\n opId: row.opId,\n sequence: row.sequence,\n actorId: input.actorId,\n message: decodeMessage(operation.message),\n }\n })\n\n const dismiss = (which: Parked) =>\n journal.cursors.unpark(key, `react/${which.reaction}`, OpId.make(which.opId))\n\n return Effect.gen(function* () {\n for (const each of reactions) yield* journal.cursors.track(key, cursorName(each))\n return {\n appendAsServer,\n react,\n follow,\n settledThrough,\n parked,\n retry,\n dismiss,\n } satisfies ServerJournal<ServerMsgOf<SMs>, R>\n })\n}\n\n/** Whether the journal failed because a stored Message will not read, not because the store did. */\nconst unreadable = (cause: unknown): boolean =>\n cause instanceof UnreadableMessageError ||\n cause instanceof UnsupportedMessageVersionError ||\n cause instanceof AmbiguousMessageError\n\n/** How long a reaction that has failed `attempts` times waits: 0.5 s doubling to 30 s. */\nconst backoff = (attempts: number): number =>\n attempts === 0 ? 0 : Math.min(BACKOFF_MAX, BACKOFF_BASE * 2 ** Math.min(attempts - 1, 16))\n\n/** A failure of the ledger's record, or of the answer it holds, as the run's. */\nconst asRunFailure = (error: unknown): RunFailed | JournalError =>\n error instanceof RunFailed || error instanceof JournalError\n ? error\n : new RunFailed({\n permanent: false,\n reason: cut(error instanceof Error ? error.message : String(error)),\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,UAAU;;AAEhB,MAAM,cAAc;;AAEpB,MAAM,OAAO;;AAEb,MAAM,eAAe;AACrB,MAAM,cAAc;;AAEpB,MAAM,gBAAgB,SAAS,QAAQ,CAAC;AACxC,MAAM,gBAAgB;;AA4CtB,MAAM,2BAAW,IAAI,QAA6C;AAIlE,MAAM,SAAS,YACb,UAAU,YAAY,SAAS,MAAM,KAAK,OAAO,QAAQ,SAAS,WAC9D,OAAO,KAAK,QAAQ,IAAI,IACxB,OAAO,KAAK;AAElB,MAAM,UAAU,iBACd,IAAI,IACF,aAAa,SAAQ,gBAAe;CAClC,MAAM,UAAW,YACd,QAAQ,MAAM,KAAK;CACtB,OAAO,OAAO,YAAY,WAAW,CAAC,OAAO,IAAI,CAAC;AACpD,CAAC,CACH;;;;;;;;;AAgCF,MAAa,YAYX,MACA,YACgG;CAChG,MAAM,EAAE,SAAS;CACjB,IAAI,CAAC,cAAc,KAAK,IAAI,GAC1B,MAAM,IAAI,MACR,mBAAmB,KAAK,gEAC1B;CACF,MAAM,QAAQ,KAAK,SAAS;CAC5B,IACE,QAAQ,GAAG,UAAU,SACpB,QAAQ,YAAY,KAAA,KAAa,QAAQ,QAAQ,UAAU,OAE5D,MAAM,IAAI,MAAM,kBAAkB,KAAK,uCAAuC;CAChF,MAAM,UAAU,OAAO,KAAK,QAAQ;CACpC,MAAM,SAAS,OAAO,KAAK,kBAAkB;CAC7C,MAAM,KAAK,OAAO,QAAQ,GAAG,YAAY;CACzC,MAAM,UAAU,OAAO,QAAQ,SAAS,gBAAgB,CAAC,CAAC;CAC1D,KAAK,MAAM,OAAO,IAChB,IAAI,CAAC,QAAQ,IAAI,GAAG,KAAK,CAAC,OAA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,UAAU,IAAI;GACd,SAAS,MAAM;GACf,SAAS,cAAc,UAAU,OAAO;EAC1C;CACF,CAAC;CAEH,MAAM,WAAW,UACf,QAAQ,QAAQ,OAAO,KAAK,SAAS,MAAM,YAAY,KAAK,KAAK,MAAM,IAAI,CAAC;CAE9E,OAAO,OAAO,IAAI,aAAa;EAC7B,KAAK,MAAM,QAAQ,WAAW,OAAO,QAAQ,QAAQ,MAAM,KAAK,WAAW,IAAI,CAAC;EAChF,OAAO;GACL;GACA;GACA;GACA;GACA;GACA;GACA;EACF;CACF,CAAC;AACH;;AAGA,MAAM,cAAc,UAClB,iBAAiB,0BACjB,iBAAiB,kCACjB,iBAAiB;;AAGnB,MAAM,WAAW,aACf,aAAa,IAAI,IAAI,KAAK,IAAI,aAAa,eAAe,KAAK,KAAK,IAAI,WAAW,GAAG,EAAE,CAAC;;AAG3F,MAAM,gBAAgB,UACpB,iBAAiB,aAAa,iBAAiB,eAC3C,QACA,IAAI,UAAU;CACZ,WAAW;CACX,QAAQ,IAAI,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AACpE,CAAC"}
1
+ {"version":3,"file":"serverJournal.js","names":["JournalDocumentId"],"sources":["../src/serverJournal.ts"],"sourcesContent":["/**\n * The server's own side of a document: Messages only it appends, and\n * reactions, the work that runs after a commit. Both commit through the\n * journal's `append` as the server's principal, so the journal's `validate`\n * and `authorize` judge them like any operation.\n *\n * A reaction's cursor and its parked runs live in `foldkit-durable`\n * (`journal.cursors`), beside the effect ledger, which records each run's\n * answer and whether its appends finished. The cursor is a lower bound over\n * the ledger: set back (to the floor, say), it costs ledger reads, never a\n * second external call. A cursor row that is lost altogether is not that:\n * `react` reports it and does nothing until `serverJournal` registers the\n * reaction again, at the journal's cursor then, skipping what came between.\n * An external call still runs at least once, never exactly once: a crash\n * between the call and the ledger's write runs it again, with the same key.\n */\nimport {\n Cause,\n Clock,\n Duration,\n Effect,\n Option,\n Predicate,\n Queue,\n Result,\n Schema,\n Semaphore,\n Stream,\n} from 'effect'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n InvalidOperationError,\n JournalError,\n OpId,\n type AppendError,\n type AppendResult,\n type Journal,\n type ParkedRun,\n} from 'foldkit-durable/core'\nimport type { MessageSet, ReportDiagnostic } from 'foldkit-surface'\nimport {\n reactionFailed,\n reactionParked,\n reactionSkipped,\n reportTo,\n type SyncDiagnostic,\n} from './diagnostics.js'\nimport {\n AmbiguousMessageError,\n ServerKeyReusedError,\n StaleParkedRunError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n} from './errors.js'\nimport type { DefinedSync, MsgOf, ServerMsgOf } from './make.js'\nimport {\n SERVER_REPLICA_PREFIX,\n writtenEnvelope,\n type Operation,\n type WrittenOperation,\n} from './sync.js'\n\n/** The longest key `appendAsServer` takes. */\nconst MAX_KEY = 200\n/** The most Messages one run may append. */\nconst MAX_APPENDS = 16\n/** How many committed operations a reaction reads at once. */\nconst PAGE = 100\n/** A failing reaction waits from this, doubling, up to the cap, in ms. */\nconst BACKOFF_BASE = 500\nconst BACKOFF_MAX = 30_000\n/** How long a pass waits after the journal itself failed, which counts toward no bound. */\nconst JOURNAL_RETRY = Duration.seconds(5)\nconst REACTION_NAME = /^[A-Za-z0-9_-]{1,64}$/\n\n/** A committed operation, as a reaction is given it. */\nexport interface Trigger<Message> {\n /** The Message at the current version, as every hook sees it. */\n readonly message: Message\n readonly opId: string\n readonly sequence: number\n /** Who committed it: a person's actor, or the server's. */\n readonly actorId: string\n /**\n * 64 hex characters naming this run, the same on every retry and across\n * restarts: give it to the provider as its idempotency key.\n */\n readonly key: string\n}\n\n/**\n * One declared reaction of one document: what it runs on, what it may\n * append, and what its handler needs. Made by `reaction`, given to\n * `serverJournal`.\n */\nexport interface Reaction<Document, out R = never> {\n /** The contract it was declared for: `serverJournal` refuses it for another. */\n readonly sync: Document\n readonly name: string\n /** The tags it runs on. */\n readonly on: ReadonlySet<string>\n /** The tags it may append. */\n readonly appends: ReadonlySet<string>\n /** The services its handler needs; never present. */\n readonly requires?: () => R\n}\n\ninterface Handler {\n readonly run: (\n trigger: Trigger<unknown>,\n ) => Effect.Effect<ReadonlyArray<unknown> | void, unknown, unknown>\n readonly timeout: Duration.Duration\n readonly attempts: number\n readonly parkAfter: Duration.Duration\n}\n\n/** Each reaction's handler and bounds, kept off the value so nothing else can call it. */\nconst handlers = new WeakMap<Reaction<unknown, unknown>, Handler>()\n\ntype AnySync = DefinedSync<any, any, any, any, any, any, any>\n\nconst tagOf = (message: unknown): Option.Option<string> =>\n Predicate.hasProperty(message, '_tag') && typeof message._tag === 'string'\n ? Option.some(message._tag)\n : Option.none()\n\nconst tagsOf = (constructors: ReadonlyArray<unknown>): ReadonlySet<string> =>\n new Set(\n constructors.flatMap(constructor => {\n const literal = (constructor as { fields?: { _tag?: { ast?: { literal?: unknown } } } })\n .fields?._tag?.ast?.literal\n return typeof literal === 'string' ? [literal] : []\n }),\n )\n\nexport interface ReactionOptions<AppModel, On, Appends, R> {\n /** Part of every run's key, so renaming it is a new reaction. Letters, digits, `_` and `-`, at most 64; unique in the document. */\n readonly name: string\n /** The committed Messages it runs after: a set of the contract's own application. */\n readonly on: MessageSet<AppModel, any, On, any>\n /** The server-only Messages it may append, checked on every answer. Without it, it appends nothing. */\n readonly appends?: MessageSet<AppModel, any, Appends, any>\n /** How long one run may take before it counts as failed. Default 10 seconds. */\n readonly timeout?: Duration.Input\n /** A failing run is parked once it has failed this many times, and for at least `parkAfter`. Default 8. */\n readonly attempts?: number\n /** How long a run must have been failing before it may be parked, so an outage parks nothing. Default one hour. */\n readonly parkAfter?: Duration.Input\n /**\n * One external call, or none, and the Messages to append, at most 16. It may\n * run again with the same trigger: pass `trigger.key` to the provider.\n */\n readonly run: (\n trigger: Trigger<On>,\n ) => Effect.Effect<ReadonlyArray<NoInfer<Appends>> | void, unknown, R>\n}\n\n/**\n * Declares a reaction of a contract from `Sync.forApplication(App).make`:\n * after each committed Message in `on`, in journal order, `run` is called\n * once at least, and what it answers is appended as the server. A handler\n * that keeps failing is parked after `attempts` failures over `parkAfter`;\n * one whose answer can never commit is parked at once. Throws for a name\n * that is not one, or a set of another application or outside the contract.\n */\nexport const reaction = <\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n ContractPrincipal,\n Authorized extends boolean,\n SMs extends readonly unknown[],\n On extends MsgOf<Ms> | ServerMsgOf<SMs>,\n Appends extends ServerMsgOf<SMs> = never,\n R = never,\n>(\n sync: DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n options: ReactionOptions<AppModel, On, Appends, R>,\n): Reaction<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, R> => {\n const { name } = options\n if (!REACTION_NAME.test(name))\n throw new Error(\n `Sync.reaction: \"${name}\" is not a reaction name (letters, digits, _ and -, at most 64)`,\n )\n const owner = sync.contract.owner\n if (\n options.on.owner !== owner ||\n (options.appends !== undefined && options.appends.owner !== owner)\n )\n throw new Error(`Sync.reaction: ${name} names Messages of another application`)\n const durable = tagsOf(sync.messages)\n const server = tagsOf(sync.serverOnlyMessages)\n const on = tagsOf(options.on.constructors)\n const appends = tagsOf(options.appends?.constructors ?? [])\n for (const tag of on)\n if (!durable.has(tag) && !server.has(tag))\n throw new Error(`Sync.reaction: ${name} runs on \"${tag}\", which never commits`)\n for (const tag of appends)\n if (!server.has(tag))\n throw new Error(`Sync.reaction: ${name} appends \"${tag}\", which is not server-only`)\n const attempts = options.attempts ?? 8\n if (!Number.isSafeInteger(attempts) || attempts < 1)\n throw new Error(`Sync.reaction: ${name}'s attempts must be a positive integer`)\n const made: Reaction<\n DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n R\n > = { sync, name, on, appends }\n handlers.set(made, {\n run: options.run as Handler['run'],\n timeout: Duration.fromInputUnsafe(options.timeout ?? '10 seconds'),\n attempts,\n parkAfter: Duration.fromInputUnsafe(options.parkAfter ?? '1 hour'),\n })\n return made\n}\n\n/** A run set aside: it failed for good, or too often. Its reaction went on without it. */\nexport interface Parked {\n readonly reaction: string\n readonly opId: string\n readonly sequence: number\n /** Why, as the last failure said it. */\n readonly error: string\n /** Parked in a history since reset: it can be dismissed, not run again. */\n readonly stale: boolean\n}\n\nexport interface ServerJournal<ServerOnly, R> {\n /**\n * Appends a server-only Message as the server. `key` names the fact (a\n * webhook event's id, `absorbed/<through>`): a repeat with the same key and\n * Message is answered from history, and one with another Message fails with\n * `ServerKeyReusedError`. A key is a non-empty string of at most 200\n * characters; another is an `InvalidOperationError`.\n */\n readonly appendAsServer: (\n message: ServerOnly,\n options: { readonly key: string },\n ) => Effect.Effect<AppendResult<Operation>, AppendError | ServerKeyReusedError>\n /**\n * Runs every reaction from its stored cursor, a page at a time. Never\n * fails: a failed run is reported, and the answer is how long to wait\n * before running again; none when every reaction has caught up. Safe to\n * call at any time, from anywhere in this process: passes of one\n * `serverJournal` run one at a time. Two instances over one store (two\n * isolates over one D1) do not wait for each other.\n */\n readonly react: Effect.Effect<Option.Option<Duration.Duration>, never, R>\n /**\n * Runs `react` now, after every commit to the document this journal\n * instance hears of, and after the delay `react` answers, until\n * interrupted: a long-lived process's loop. Fork it.\n */\n readonly follow: Effect.Effect<never, never, R>\n /** The lowest cursor of the declared reactions: compact no further than this. */\n readonly settledThrough: Effect.Effect<Cursor, JournalError>\n /** The runs set aside, for a person to look at. */\n readonly parked: Effect.Effect<ReadonlyArray<Parked>, JournalError>\n /**\n * Runs a parked run again, out of order; it leaves the list when it\n * succeeds, and stays, failing, when it does not. A recorded answer is\n * reused, so a refused append retried after the rule changed makes no\n * second external call. A stale one fails with `StaleParkedRunError`.\n */\n readonly retry: (parked: Parked) => Effect.Effect<void, unknown, R>\n /** Forgets a parked run: its reaction never happens. */\n readonly dismiss: (parked: Parked) => Effect.Effect<void, JournalError>\n}\n\n/** The services a list of reactions needs: none for none. */\nexport type Requires<Reactions extends ReadonlyArray<Reaction<any, any>>> = [\n Reactions[number],\n] extends [never]\n ? never\n : Reactions[number] extends Reaction<any, infer R>\n ? R\n : never\n\nexport interface ServerJournalOptions<Document, Principal, Shared, Reactions> {\n readonly sync: Document\n readonly journal: Journal<Operation, Shared, Principal, WrittenOperation>\n /**\n * Who the server commits as. Never resolved from a request, and best never\n * changed: the journal binds each `server/` replica id to the first actor\n * that commits from it. After a change of `actorId`, a reaction's append for\n * a new trigger and a new `appendAsServer` key commit as the new actor; a\n * redelivered key is an `IdentityConflictError`, and a run retried after\n * its first append committed under the old actor parks.\n */\n readonly server: Principal\n readonly reactions?: Reactions\n /** The most runs one `react` starts, over every reaction; a host with a time limit sets it low. */\n readonly runsPerPass?: number\n /** Where reactions' failures, parks and skips go; the reporter in context when not given. */\n readonly diagnostics?: ReportDiagnostic | undefined\n}\n\n/** Canonical JSON with sorted object keys: what two Messages are compared by. */\nconst canonical = (value: unknown): string =>\n JSON.stringify(value, (_, inner: unknown) =>\n inner !== null && typeof inner === 'object' && !Array.isArray(inner)\n ? Object.fromEntries(Object.entries(inner).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : inner,\n )\n\nconst sha256 = (text: string): Effect.Effect<string> =>\n Effect.promise(() => crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))).pipe(\n Effect.map(digest =>\n Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(''),\n ),\n )\n\n/** Why a run failed: its answer can never commit, or it may on another try. */\nclass RunFailed extends Schema.TaggedError<RunFailed>()('SyncRunFailed', {\n permanent: Schema.Boolean,\n reason: Schema.String,\n}) {\n override get message(): string {\n return this.reason\n }\n}\n\nconst cut = (words: string): string => (words.length <= 500 ? words : `${words.slice(0, 499)}…`)\n\n/** A handler's own failure, defect or interruption, in words: a run that may succeed again. */\nconst handlerFailed = (cause: Cause.Cause<unknown>): RunFailed =>\n new RunFailed({\n permanent: false,\n reason: cut(\n Option.match(Cause.findErrorOption(cause), {\n onSome: error =>\n Cause.isTimeoutError(error)\n ? 'The handler timed out'\n : error instanceof Error\n ? error.message\n : String(error),\n onNone: () => Cause.pretty(cause).split('\\n')[0] ?? 'The handler failed',\n }),\n ),\n })\n\n/**\n * An append the journal refused: the same refusal every time, except a\n * Message written at a version newer than this build, which a deploy fixes.\n */\nconst appendFailed = (error: Exclude<AppendError, JournalError>): RunFailed =>\n new RunFailed({\n permanent: !(\n error._tag === 'InvalidOperationError' &&\n error.cause instanceof UnsupportedMessageVersionError\n ),\n reason: cut(error.message),\n })\n\nconst RecordedAnswer = Schema.Struct({\n messageVersion: Schema.Int.check(Schema.isGreaterThanOrEqualTo(1)),\n messages: Schema.Array(Schema.Unknown),\n})\nconst decodeAnswer = Schema.decodeUnknownEffect(RecordedAnswer, { onExcessProperty: 'error' })\nconst ParkedInput = Schema.Struct({ operation: Schema.Unknown, actorId: Schema.NonEmptyString })\nconst decodeParkedInput = Schema.decodeUnknownEffect(ParkedInput, { onExcessProperty: 'error' })\n\n/** Each reaction appends what reaction feeds; a cycle among them is refused. */\nconst checkAcyclic = (reactions: ReadonlyArray<Reaction<unknown, unknown>>): void => {\n const visiting = new Set<Reaction<unknown, unknown>>()\n const done = new Set<Reaction<unknown, unknown>>()\n const visit = (from: Reaction<unknown, unknown>): void => {\n if (done.has(from)) return\n if (visiting.has(from))\n throw new Error(`Sync.serverJournal: reaction ${from.name} is in a cycle`)\n visiting.add(from)\n for (const to of reactions) if ([...from.appends].some(tag => to.on.has(tag))) visit(to)\n visiting.delete(from)\n done.add(from)\n }\n for (const each of reactions) visit(each)\n}\n\n/**\n * The server's side of one document: `appendAsServer`, and the declared\n * reactions with what runs them. Registers each reaction's cursor at the\n * journal's current cursor before it answers, so make it before the journal\n * serves its first exchange: a reaction sees every commit made after this.\n * Throws for a reaction of another contract, two of one name, or a cycle.\n */\nexport const serverJournal = <\n AppModel,\n Fields extends Schema.Struct.Fields,\n Message,\n Ms extends readonly unknown[],\n ContractPrincipal,\n Authorized extends boolean,\n SMs extends readonly unknown[],\n Principal,\n const Reactions extends ReadonlyArray<\n Reaction<DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>, any>\n > = [],\n>(\n options: ServerJournalOptions<\n DefinedSync<AppModel, Fields, Message, Ms, ContractPrincipal, Authorized, SMs>,\n Principal,\n Schema.Struct.Type<Fields>,\n Reactions\n >,\n): Effect.Effect<ServerJournal<ServerMsgOf<SMs>, Requires<Reactions>>, JournalError> => {\n type R = Requires<Reactions>\n const sync: AnySync = options.sync\n const { journal, server } = options\n const reactions: ReadonlyArray<Reaction<unknown, unknown>> = options.reactions ?? []\n const names = new Set<string>()\n for (const each of reactions) {\n if (each.sync !== options.sync)\n throw new Error(`Sync.serverJournal: reaction ${each.name} was declared for another contract`)\n if (names.has(each.name))\n throw new Error(`Sync.serverJournal: two reactions are named ${each.name}`)\n names.add(each.name)\n }\n checkAcyclic(reactions)\n const runsPerPass = options.runsPerPass ?? Number.MAX_SAFE_INTEGER\n if (!Number.isSafeInteger(runsPerPass) || runsPerPass < 1)\n throw new Error('Sync.serverJournal: runsPerPass must be a positive integer')\n\n const documentId = String(sync.documentId)\n const key = JournalDocumentId.make(documentId)\n const contract = sync.journalContract()\n const decodeMessage = Schema.decodeUnknownSync(sync.codec.message, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(sync.codec.message)\n const report = (diagnostic: SyncDiagnostic) => reportTo(options.diagnostics, diagnostic)\n const cursorName = (reaction: Reaction<unknown, unknown>) => `react/${reaction.name}`\n const handlerOf = (reaction: Reaction<unknown, unknown>): Handler => handlers.get(reaction)!\n\n /** An operation of the server's, written at `version`, as only Sync writes one. */\n const envelope = (\n replicaId: string,\n localSequence: number,\n baseCursor: number,\n message: unknown,\n version: number,\n ): WrittenOperation =>\n writtenEnvelope({\n protocolVersion: 1,\n schemaVersion: 1,\n documentId,\n replicaId,\n localSequence,\n opId: `${replicaId}:${localSequence}`,\n baseCursor,\n message,\n ...(version === 1 ? {} : { messageVersion: version }),\n })\n\n const invalid = (message: string, cause?: unknown) =>\n new InvalidOperationError({ message, ...(cause === undefined ? {} : { cause }) })\n\n const appendAsServer = (message: ServerMsgOf<SMs>, { key: fact }: { readonly key: string }) =>\n Effect.gen(function* () {\n if (fact.length === 0 || fact.length > MAX_KEY)\n return yield* invalid('A server key is a non-empty string of at most 200 characters')\n if (!sync.serverOnly(message))\n return yield* invalid('appendAsServer takes a Message only the server appends')\n const encoded = yield* Effect.try({\n try: () => encodeMessage(message),\n catch: cause => invalid('The Message does not encode', cause),\n })\n const replicaId = `${SERVER_REPLICA_PREFIX}k/${yield* sha256(fact)}`\n const written = envelope(replicaId, 1, 0, encoded, sync.codec.messageVersion)\n // Recorded before it is appended, so a repeat after a deploy that added\n // a step appends the bytes first written, which the journal compares.\n const recorded = yield* journal\n .runEffect(canonical(['server', documentId, fact]), Effect.succeed(written))\n .pipe(\n Effect.catchTag('EffectFailedError', error =>\n Effect.fail(new JournalError({ message: error.message, cause: error })),\n ),\n )\n const same =\n canonical(recorded) === canonical(written) ||\n Result.match(\n Result.try(() => contract.operation.decode(recorded)),\n {\n onFailure: () => false,\n onSuccess: operation => canonical(operation.message) === canonical(encoded),\n },\n )\n if (!same) return yield* new ServerKeyReusedError({ key: fact })\n // A record that is no envelope is the store's fault, as a row that will not read is.\n const kept = yield* Effect.try({\n try: () => writtenEnvelope(recorded),\n catch: cause => new JournalError({ message: 'Could not read a recorded operation', cause }),\n })\n return yield* journal.append(key, kept, server).pipe(\n // Refused, nothing committed: the key is free again for a Message the\n // rules take. A conflict keeps it, since the id is taken.\n Effect.tapErrorTag('OperationRejectedError', () => forget(fact)),\n Effect.tapErrorTag('InvalidOperationError', () => forget(fact)),\n )\n })\n\n const forget = (fact: string) =>\n journal.clearEffect(canonical(['server', documentId, fact])).pipe(Effect.ignore)\n\n /** The run of one reaction on one committed operation: its answer, then its appends. */\n const runOnce = (\n reaction: Reaction<unknown, unknown>,\n epoch: string,\n committed: {\n readonly opId: string\n readonly sequence: number\n readonly actorId: string\n readonly message: unknown\n },\n ): Effect.Effect<void, RunFailed | JournalError, unknown> =>\n Effect.gen(function* () {\n const handler = handlerOf(reaction)\n const { opId, sequence } = committed\n // The ledger runs what it is given with no services: the handler's are this run's.\n const services = yield* Effect.context<unknown>()\n const triggerKey = yield* sha256(canonical(['react', documentId, reaction.name, opId]))\n const answer = Effect.suspend(() =>\n handler.run({\n message: committed.message,\n opId,\n sequence,\n actorId: committed.actorId,\n key: triggerKey,\n }),\n ).pipe(\n Effect.timeout(handler.timeout),\n Effect.provideContext(services),\n // A defect or an interruption is a failure the ledger records: its\n // `tapError` sees neither, and the record would stay pending.\n Effect.sandbox,\n Effect.mapError(handlerFailed),\n Effect.flatMap(returned =>\n Effect.gen(function* () {\n const messages: ReadonlyArray<unknown> = returned ?? []\n if (!Array.isArray(messages))\n return yield* new RunFailed({ permanent: true, reason: 'The answer is not a list' })\n if (messages.length > MAX_APPENDS)\n return yield* new RunFailed({\n permanent: true,\n reason: `The answer holds ${messages.length} Messages, past ${MAX_APPENDS}`,\n })\n const encoded = yield* Effect.forEach(messages, message =>\n Option.match(\n Option.filter(tagOf(message), tag => reaction.appends.has(tag)),\n {\n onNone: () =>\n Effect.fail(\n new RunFailed({\n permanent: true,\n reason: 'The answer holds a Message its appends do not name',\n }),\n ),\n onSome: () =>\n Effect.try({\n try: () => encodeMessage(message),\n catch: () =>\n new RunFailed({ permanent: true, reason: 'The answer does not encode' }),\n }),\n },\n ),\n )\n return { messageVersion: sync.codec.messageVersion, messages: encoded }\n }),\n ),\n )\n // Named by the trigger's id, never its place: sequences start again\n // after a reset, and a reaction running on this one's append keys its\n // answer by that append's id.\n const replyOf = `${SERVER_REPLICA_PREFIX}r/${reaction.name}/${yield* sha256(opId)}`\n const appendAll = Effect.gen(function* () {\n const recorded = yield* journal\n .runEffect(canonical(['react', documentId, reaction.name, opId, 'answer']), answer)\n .pipe(Effect.flatMap(decodeAnswer), Effect.mapError(asRunFailure))\n for (const [index, message] of recorded.messages.entries())\n yield* journal\n .append(\n key,\n envelope(`${replyOf}/${index}`, 1, sequence, message, recorded.messageVersion),\n server,\n )\n .pipe(\n Effect.catchTags({\n InvalidOperationError: error => Effect.fail(appendFailed(error)),\n OperationRejectedError: error => Effect.fail(appendFailed(error)),\n IdentityConflictError: error => Effect.fail(appendFailed(error)),\n }),\n )\n })\n // The epoch is in this key and not the answer's: after a reset the\n // appends run again in the new history, and the answer is reused.\n yield* journal\n .runEffect(\n canonical(['react', documentId, reaction.name, opId, 'finished', epoch]),\n appendAll,\n )\n .pipe(Effect.mapError(asRunFailure))\n })\n\n /** The pass of one reaction: from its cursor, a page, unless its backoff has not elapsed. */\n const passOf = (\n reaction: Reaction<unknown, unknown>,\n budget: number,\n ): Effect.Effect<\n { readonly runs: number; readonly next: Option.Option<Duration.Duration> },\n JournalError,\n unknown\n > =>\n Effect.gen(function* () {\n const name = cursorName(reaction)\n const handler = handlerOf(reaction)\n const tracked = yield* journal.cursors.settled(key, name)\n if (Option.isNone(tracked))\n return yield* Effect.die(\n new Error(`Sync.serverJournal: reaction ${reaction.name} was never registered`),\n )\n const { epoch, cursor, attempts, failedAt, firstFailedAt } = tracked.value\n const now = yield* Clock.currentTimeMillis\n const wait = Option.match(failedAt, {\n onNone: () => 0,\n onSome: at => at + backoff(attempts) - now,\n })\n if (attempts > 0 && wait > 0) return { runs: 0, next: Option.some(Duration.millis(wait)) }\n // The stored failures are the commit after the cursor's; once the pass\n // moves past it, a failure further on is that commit's first.\n let failed = { attempts, since: firstFailedAt }\n const stall = (\n runs: number,\n cause: string,\n at: Option.Option<{ opId: string; sequence: number }>,\n ) =>\n Effect.gen(function* () {\n yield* journal.cursors.stalled(key, name, epoch, now)\n yield* report(reactionFailed(documentId, reaction.name, at, cut(cause)))\n return { runs, next: Option.some(Duration.millis(backoff(failed.attempts + 1))) }\n })\n const page = yield* Effect.result(journal.read(key, cursor, { limit: PAGE }))\n if (Result.isFailure(page)) {\n const failure = page.failure\n if (failure._tag === 'CompactedCursorError') {\n yield* report(reactionSkipped(documentId, reaction.name, cursor, failure.floor))\n yield* journal.cursors.advance(key, name, epoch, Cursor.make(failure.floor))\n return { runs: 0, next: Option.some(Duration.zero) }\n }\n // A commit that will not read: no operation can be named, so nothing\n // parks, and the reaction waits on its backoff for a build that reads it.\n if (failure._tag === 'JournalError' && !unreadable(failure.cause)) return yield* failure\n return yield* stall(0, failure.message, Option.none())\n }\n let at = cursor\n let runs = 0\n const reach = (sequence: number) => {\n at = Cursor.make(sequence)\n failed = { attempts: 0, since: Option.none() }\n }\n const moved = () =>\n at > cursor ? journal.cursors.advance(key, name, epoch, at) : Effect.void\n for (const committed of page.success) {\n const message = decodeMessage(committed.operation.message)\n if (!Option.exists(tagOf(message), tag => reaction.on.has(tag))) {\n reach(committed.sequence)\n continue\n }\n if (runs >= budget) {\n yield* moved()\n return { runs, next: Option.some(Duration.zero) }\n }\n runs += 1\n const outcome = yield* Effect.result(\n runOnce(reaction, epoch, {\n opId: committed.opId,\n sequence: committed.sequence,\n actorId: committed.actorId,\n message,\n }),\n )\n if (Result.isSuccess(outcome)) {\n reach(committed.sequence)\n continue\n }\n const failure = outcome.failure\n // The store failing is not the run's fault: it counts toward nothing.\n if (failure._tag === 'JournalError') {\n yield* moved()\n return yield* failure\n }\n const tried = failed.attempts + 1\n const since = Option.getOrElse(failed.since, () => now)\n const parks =\n failure.permanent ||\n (tried >= handler.attempts && now - since >= Duration.toMillis(handler.parkAfter))\n const place = { opId: committed.opId, sequence: committed.sequence }\n if (!parks) {\n yield* moved()\n return yield* stall(runs, failure.reason, Option.some(place))\n }\n // Parked first: a crash before the cursor moves runs it once more,\n // and the second park changes nothing.\n yield* journal.cursors.park(key, {\n name,\n opId: committed.opId,\n epoch,\n sequence: committed.sequence,\n input: {\n operation: contract.operation.encode(committed.operation),\n actorId: committed.actorId,\n },\n error: failure.reason,\n })\n yield* report(\n reactionParked(\n documentId,\n reaction.name,\n committed.opId,\n committed.sequence,\n failure.reason,\n ),\n )\n reach(committed.sequence)\n }\n yield* moved()\n return {\n runs,\n next: page.success.length === PAGE ? Option.some(Duration.zero) : Option.none(),\n }\n })\n\n const earliest = (\n a: Option.Option<Duration.Duration>,\n b: Option.Option<Duration.Duration>,\n ): Option.Option<Duration.Duration> =>\n Option.isNone(a) ? b : Option.isNone(b) ? a : Option.some(Duration.min(a.value, b.value))\n\n // Which reaction a pass starts with, turning each pass, so a share's\n // rounding favours no reaction for good.\n let first = 0\n // One pass at a time: two at once would count each failure twice and reach\n // the attempts bound in half the failures.\n const passes = Semaphore.makeUnsafe(1)\n const react = Effect.gen(function* () {\n let budget = runsPerPass\n let next = Option.none<Duration.Duration>()\n const order = reactions.map((_, at) => reactions[(first + at) % reactions.length]!)\n first = reactions.length === 0 ? 0 : (first + 1) % reactions.length\n for (const [at, each] of order.entries()) {\n // A fair share of what is left, so a busy reaction cannot starve the rest.\n const share = Math.ceil(budget / (order.length - at))\n if (share <= 0) return Option.some(Duration.zero)\n const pass = yield* passOf(each, share).pipe(\n Effect.catchCause(cause =>\n Cause.hasInterruptsOnly(cause)\n ? Effect.failCause(cause)\n : report(\n reactionFailed(\n documentId,\n each.name,\n Option.none(),\n cut(\n Option.match(Cause.findErrorOption(cause), {\n onSome: error => error.message,\n onNone: () => Cause.pretty(cause).split('\\n')[0] ?? 'The pass broke',\n }),\n ),\n ),\n ).pipe(Effect.as({ runs: 0, next: Option.some(JOURNAL_RETRY) })),\n ),\n )\n budget -= pass.runs\n next = earliest(next, pass.next)\n }\n return next\n }).pipe(passes.withPermits(1)) as Effect.Effect<Option.Option<Duration.Duration>, never, R>\n\n const follow = Effect.gen(function* () {\n // One pending wake-up is enough: a pass reads everything after the cursor.\n const wake = yield* Queue.sliding<void>(1)\n yield* Effect.forkChild(\n Stream.runForEach(\n Stream.filter(journal.subscribe, changed => changed === documentId),\n () => Queue.offer(wake, undefined),\n ),\n { startImmediately: true },\n )\n while (true) {\n const next = yield* react\n yield* Option.match(next, {\n onNone: () => Queue.take(wake),\n onSome: delay => Effect.raceFirst(Queue.take(wake), Effect.sleep(delay)),\n })\n }\n }) as Effect.Effect<never, never, R>\n\n const settledThrough = Effect.gen(function* () {\n let lowest = yield* journal.cursor(key)\n for (const each of reactions) {\n const tracked = yield* journal.cursors.settled(key, cursorName(each))\n const at = Option.match(tracked, { onNone: () => Cursor.make(0), onSome: t => t.cursor })\n if (at < lowest) lowest = at\n }\n return lowest\n })\n\n const reactionOf = (name: string): Option.Option<Reaction<unknown, unknown>> =>\n Option.fromUndefinedOr(reactions.find(each => cursorName(each) === name))\n\n const parked = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n const rows = yield* journal.cursors.parked(key)\n return rows.flatMap((row): ReadonlyArray<Parked> =>\n row.name.startsWith('react/')\n ? [\n {\n reaction: row.name.slice('react/'.length),\n opId: row.opId,\n sequence: row.sequence,\n error: row.error,\n stale: row.epoch !== epoch,\n },\n ]\n : [],\n )\n })\n\n const retry = (which: Parked) =>\n Effect.gen(function* () {\n const name = `react/${which.reaction}`\n const epoch = yield* journal.epoch(key)\n const rows = yield* journal.cursors.parked(key)\n const row = rows.find(each => each.name === name && each.opId === which.opId)\n // Already resolved: nothing to do.\n if (row === undefined) return\n if (row.epoch !== epoch)\n return yield* new StaleParkedRunError({ reaction: which.reaction, opId: which.opId })\n const declared = reactionOf(name)\n if (Option.isNone(declared))\n return yield* Effect.fail(\n new Error(`Reaction ${which.reaction} is not declared on this journal`),\n )\n const trigger = yield* parkedTrigger(row)\n yield* runOnce(declared.value, epoch, trigger)\n yield* journal.cursors.unpark(key, name, row.opId)\n }) as Effect.Effect<void, unknown, R>\n\n const parkedTrigger = (row: ParkedRun) =>\n Effect.gen(function* () {\n const input = yield* decodeParkedInput(row.input)\n const operation = yield* Effect.try({\n // The server parked these bytes itself, written by `encode`.\n try: () => contract.operation.decode(writtenEnvelope(input.operation)),\n catch: cause => new JournalError({ message: 'Could not read a parked run', cause }),\n })\n return {\n opId: row.opId,\n sequence: row.sequence,\n actorId: input.actorId,\n message: decodeMessage(operation.message),\n }\n })\n\n const dismiss = (which: Parked) =>\n journal.cursors.unpark(key, `react/${which.reaction}`, OpId.make(which.opId))\n\n return Effect.gen(function* () {\n for (const each of reactions) yield* journal.cursors.track(key, cursorName(each))\n return {\n appendAsServer,\n react,\n follow,\n settledThrough,\n parked,\n retry,\n dismiss,\n } satisfies ServerJournal<ServerMsgOf<SMs>, R>\n })\n}\n\n/** Whether the journal failed because a stored Message will not read, not because the store did. */\nconst unreadable = (cause: unknown): boolean =>\n cause instanceof UnreadableMessageError ||\n cause instanceof UnsupportedMessageVersionError ||\n cause instanceof AmbiguousMessageError\n\n/** How long a reaction that has failed `attempts` times waits: 0.5 s doubling to 30 s. */\nconst backoff = (attempts: number): number =>\n attempts === 0 ? 0 : Math.min(BACKOFF_MAX, BACKOFF_BASE * 2 ** Math.min(attempts - 1, 16))\n\n/** A failure of the ledger's record, or of the answer it holds, as the run's. */\nconst asRunFailure = (error: unknown): RunFailed | JournalError =>\n error instanceof RunFailed || error instanceof JournalError\n ? error\n : new RunFailed({\n permanent: false,\n reason: cut(error instanceof Error ? error.message : String(error)),\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgEA,MAAM,UAAU;;AAEhB,MAAM,cAAc;;AAEpB,MAAM,OAAO;;AAEb,MAAM,eAAe;AACrB,MAAM,cAAc;;AAEpB,MAAM,gBAAgB,SAAS,QAAQ,CAAC;AACxC,MAAM,gBAAgB;;AA4CtB,MAAM,2BAAW,IAAI,QAA6C;AAIlE,MAAM,SAAS,YACb,UAAU,YAAY,SAAS,MAAM,KAAK,OAAO,QAAQ,SAAS,WAC9D,OAAO,KAAK,QAAQ,IAAI,IACxB,OAAO,KAAK;AAElB,MAAM,UAAU,iBACd,IAAI,IACF,aAAa,SAAQ,gBAAe;CAClC,MAAM,UAAW,YACd,QAAQ,MAAM,KAAK;CACtB,OAAO,OAAO,YAAY,WAAW,CAAC,OAAO,IAAI,CAAC;AACpD,CAAC,CACH;;;;;;;;;AAgC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,KAAK,CAAC;AACpE,CAAC"}
package/dist/sync.d.ts CHANGED
@@ -62,6 +62,14 @@ declare const CommittedSchema: Schema.Struct<{
62
62
  }>;
63
63
  /** Named to avoid colliding with `foldkit-durable`'s `Committed`. */
64
64
  export type CommittedOperation = typeof CommittedSchema.Type;
65
+ /**
66
+ * A type-only mark on what `codec.committedFrom` returns. It reads its input as
67
+ * history, so it skips the checks of a sent entry, and
68
+ * `journalContract().operation.encode` refuses it, stripped of its commit or not.
69
+ */
70
+ export interface ReadAsHistory {
71
+ readonly '~foldkit-sync/history': true;
72
+ }
65
73
  /**
66
74
  * An envelope as written, checked for its shape and nothing else: for the
67
75
  * server's own operations (`serverJournal`), whose bytes it wrote or recorded.
@@ -134,8 +142,12 @@ export interface ReplicaState<Shared> {
134
142
  * is the primary seam.
135
143
  */
136
144
  export interface TransportClient {
137
- /** `epoch` is the server history the replica's cursor points into, when it knows one. */
138
- exchange(cursor: Sequence, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined): Promise<unknown>;
145
+ /**
146
+ * `epoch` is the server history the replica's cursor points into, when it
147
+ * knows one. `pending` is unread, as on every transport seam: a server reads
148
+ * each entry with `codec.writtenFrom`, which refuses what only it may append.
149
+ */
150
+ exchange(cursor: Sequence, pending: ReadonlyArray<unknown>, epoch?: string | undefined): Promise<unknown>;
139
151
  }
140
152
  /** A redacted view of a replica's state, for a UI to explain and recover. */
141
153
  export interface ReplicaStatus {
@@ -330,7 +342,7 @@ export interface Sync<Message, Shared, Durable = Message> {
330
342
  * be read as version 1. Write one with `journalContract().operation.encode`.
331
343
  */
332
344
  readonly writtenFrom: (input: unknown, documentId: DocumentId) => WrittenOperation;
333
- readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation;
345
+ readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation & ReadAsHistory;
334
346
  readonly decodeExchange: (input: unknown) => Exchange<Shared>;
335
347
  };
336
348
  /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */
@@ -359,19 +371,22 @@ export interface JournalContract<Operation, Shared> {
359
371
  readonly legacyReplicaId: (opId: string) => string;
360
372
  readonly operation: {
361
373
  /** Written at the current version: what the journal stores. */
362
- readonly encode: (operation: Operation) => WrittenOperation;
374
+ readonly encode: (operation: Operation & {
375
+ readonly '~foldkit-sync/history'?: never;
376
+ }) => WrittenOperation;
363
377
  /**
364
378
  * Read from any version the history has, upcast to the current one: stored
365
379
  * history, so the server's own Messages read too. Never the reader of an
366
380
  * entry someone sent (`codec.writtenFrom`).
367
381
  */
368
- readonly decode: (input: unknown) => Operation;
382
+ readonly decode: (input: WrittenOperation) => Operation;
369
383
  /**
370
384
  * What a retransmission is compared by: the operation normalized at the
371
385
  * version it was written at, as the build that wrote it normalized it, so
372
- * an edit committed before a deploy is still recognized after it.
386
+ * an edit committed before a deploy is still recognized after it. Only
387
+ * hashed: never an entry to append.
373
388
  */
374
- readonly compared: (input: unknown) => WrittenOperation;
389
+ readonly compared: (input: unknown) => unknown;
375
390
  };
376
391
  readonly snapshot: {
377
392
  readonly encode: (snapshot: Shared) => unknown;
@@ -1 +1 @@
1
- {"version":3,"file":"sync.d.ts","names":[],"sources":["../src/sync.ts"],"mappings":";;;;;;;;cAgDM;cACA;;;;;;qBAOO;;;;;cAQP,iBAAe,OAAA;;;;;;;;;;YAUT,mBAAmB,gBAAgB;;;;;;;cAoBzC,wBAAsB,OAAA,MAAA,OAAA;;;;;;;;;;;YAChB,0BAA0B,uBAAuB;;cASvD,iBAAe,OAAA;;;;;;;;;;;;;YAET,4BAA4B,gBAAgB;;;;;;qBAe3C,kBAAe,mBAAqB;;qBAoBpC;EACX,WAAS,OAAA;EACT,SAAO,OAAA;EACP,aAAW,OAAA;EACX,iBAAe,OAAA;;iBAKA,WAAW;WACjB,QAAQ;WACR,OAAO;;iBAGD,SAAS;;WAEf,YAAY;WACZ,UAAU,cAAc;;;;;WAKxB,WACL;aAAyB,MAAM;aAAe,gBAAgB,YAAY;;;;;;WAM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WAAW;;WAEvB,kBAAkB;WAClB;;aAEE,SACP,WAAW;eAAuB;UAC/B;;;;;;aAMI,SAAS,OAAO,qBAAqB;;;;;;;aAOrC,WAAW;;WAEb;aACE,SAAS,UAAU;aACnB,SAAS,mBAAmB;;WAE9B,aAAa;WACb,SAAS,UAAU,QAAQ,WAAW,cAAc;;WAEpD,SACP,WAAW,WACX;aAAmB;aAA2B;QAC3C;;;;;;;;;qBAUM,aAAc,SAAS,QAAQ,gBAAgB,eAAa,YAC3D,eAAe,SAAS,QAAQ,gBAAgB,mBAC3D,KAAK,SAAS"}
package/dist/sync.js CHANGED
@@ -276,18 +276,18 @@ const defineSync = (definition) => {
276
276
  /**
277
277
  * Normalized at the version it was written at, with no upcast: what the
278
278
  * build that wrote it hashed. An explicit `messageVersion: 1` is dropped,
279
- * so it and an absent one compare alike.
279
+ * so it and an absent one compare alike. Not branded: it skips the checks
280
+ * of a sent entry, so it must never reach `append`.
280
281
  */
281
282
  const compared = (input) => {
282
283
  const written = decodeWritten(input);
283
284
  const version = versionOf(written);
284
285
  if (version > current) throw newer(written.opId, version);
285
- const envelope = envelopeOf(written);
286
- return vouched({
287
- ...envelope,
286
+ return {
287
+ ...envelopeOf(written),
288
288
  ...version === 1 ? {} : { messageVersion: version },
289
289
  message: history.normalize(version, written.message)
290
- });
290
+ };
291
291
  };
292
292
  const journalContract = () => ({
293
293
  replicaId: (operation) => operation.replicaId,
package/dist/sync.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sync.js","names":[],"sources":["../src/sync.ts"],"sourcesContent":["import {\n Effect,\n Exit,\n Metric,\n Option,\n PubSub,\n Queue,\n Ref,\n Result,\n Schema,\n Stream,\n SynchronizedRef,\n} from 'effect'\nimport {\n AmbiguousMessageError,\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n ServerOnlyMessageError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport { historyOf, migrations, type Migrations } from './migrations.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { exchangeFailed, historyRebuilt, unknownRefusal } from './diagnostics.js'\nimport { fitWords, SyncRefusal } from './refusal.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/**\n * Replica ids the server's own operations use (`foldkit-sync/journal`'s\n * `serverJournal`): a sent entry may not claim one, or it could bind the id to\n * its actor first and have the server's append refused.\n */\nexport const SERVER_REPLICA_PREFIX = 'server/'\n/** The longest replica id a sent entry may name. A stored one is read whatever its length. */\nconst MAX_SENT_REPLICA_ID = 128\n\n/**\n * A client-authored operation envelope. `message` is the application's\n * Message, encoded at the current version of the document's history.\n */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/**\n * An operation as it was written: what a replica keeps in its outbox and\n * sends, with its Message at the version it was written at. `messageVersion`\n * is absent for version 1, so a document with no migrations writes today's\n * envelope byte for byte.\n */\nconst WrittenFields = Schema.Struct({\n ...OperationSchema.fields,\n messageVersion: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))),\n})\n/** The written shape, unbranded: what the codec reads before it vouches for anything. */\ntype WrittenShape = typeof WrittenFields.Type\n/**\n * Branded, so only Sync makes one: decoding an entry, or writing an\n * `Operation` at the current version (`journalContract().operation.encode`).\n * A decoded `Operation` is not one, since its missing `messageVersion` would\n * read as version 1 and be upcast again.\n */\nconst WrittenOperationSchema = WrittenFields.pipe(Schema.brand('foldkit-sync/WrittenOperation'))\nexport type WrittenOperation = typeof WrittenOperationSchema.Type\n/** What the codec has checked or written itself. */\nconst vouched = (operation: WrittenShape): WrittenOperation => operation as WrittenOperation\n\nconst committedFields = {\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n}\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({ ...OperationSchema.fields, ...committedFields })\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = typeof CommittedSchema.Type\n/** A committed operation as the server sends it: written at the server's current version. */\nconst CommittedWrittenSchema = Schema.Struct({\n ...WrittenFields.fields,\n ...committedFields,\n})\n\nconst decodeWritten = Schema.decodeUnknownSync(WrittenOperationSchema, {\n onExcessProperty: 'error',\n})\n/**\n * An envelope as written, checked for its shape and nothing else: for the\n * server's own operations (`serverJournal`), whose bytes it wrote or recorded.\n * Never for an entry someone sent.\n */\nexport const writtenEnvelope = (input: unknown): WrittenOperation => decodeWritten(input)\nconst decodeCommittedWritten = Schema.decodeUnknownSync(CommittedWrittenSchema, {\n onExcessProperty: 'error',\n})\n/** The version an operation was written at: absent is 1. */\nconst versionOf = (operation: WrittenShape): number => operation.messageVersion ?? 1\nconst decodeRefusal = Schema.decodeUnknownResult(SyncRefusal, { onExcessProperty: 'error' })\n\n/**\n * How many committed-operation ids a replica retains for duplicate detection.\n * Committed sequences are contiguous and the server enforces `opId`\n * uniqueness, so this is defence in depth; bounding it keeps replica state from\n * growing without limit on a log that is never checkpointed.\n */\nconst COMMITTED_ID_WINDOW = 1024\n/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */\nconst START_RETRY_BASE = 500\nconst START_RETRY_MAX = 30_000\n\n/** Counters and a histogram an application can scrape. */\nexport const syncMetrics = {\n exchanges: Metric.counter('foldkit_sync_exchanges_total'),\n applied: Metric.counter('foldkit_sync_commits_applied_total'),\n checkpoints: Metric.counter('foldkit_sync_checkpoints_adopted_total'),\n exchangePending: Metric.histogram('foldkit_sync_exchange_pending', {\n boundaries: [1, 4, 16, 64, 256, 1024],\n }),\n}\n\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /**\n * Why some of `rejected` were refused, each an encoded `SyncRefusal`. One\n * without a refusal is still rejected.\n */\n readonly refusals?:\n | ReadonlyArray<{ readonly opId: OpId; readonly refusal: typeof SyncRefusal.Encoded }>\n | undefined\n /**\n * @deprecated Send `refusals`; removed in the next release. Words the server\n * chose for a person, for some of `rejected`.\n */\n readonly reasons?: ReadonlyArray<{ readonly opId: OpId; readonly reason: string }> | undefined\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n /** The server sent only part of what is after the cursor; the replica asks again. */\n readonly more?: boolean | undefined\n /**\n * The identity of the server's history. The replica sends back the one it last saw; a\n * server that finds another answers from the start of its own history, and the replica,\n * seeing a new epoch, rebuilds its committed state from that answer and keeps its outbox.\n */\n readonly epoch?: string | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n /** Operations not yet committed, as written. */\n readonly pending: ReadonlyArray<WrittenOperation>\n /** Operations this build cannot read, kept as written until dismissed; absent when none. */\n readonly refused?: ReadonlyArray<WrittenOperation>\n /** The server history `cursor` points into, once an exchange has named one. */\n readonly epoch?: string\n}\n\n/**\n * What the promise-based edge adapter consumes; the Effect `Transport` service\n * is the primary seam.\n */\nexport interface TransportClient {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first, with its reason when it gave one. */\n readonly rejected: ReadonlyArray<Rejection>\n /**\n * Operations this build cannot read, as written: an older version of the\n * document's Message that no step of its history reads, found in the outbox\n * or refused by the server as `Unreadable`. Never sent; kept, with their\n * payload, until `Replica.dismiss`.\n */\n readonly refused: ReadonlyArray<WrittenOperation>\n /**\n * The server history the cursor points into, once a server named one. A new\n * one means the server was reset: what the replica had committed is gone.\n */\n readonly epoch: Option.Option<string>\n}\n\n/**\n * An operation the server refused, and why, when it said. It carries the\n * operation itself: the replica drops it from the outbox in the same step,\n * so what it changed can be read from here rather than looked up in time.\n */\nexport interface Rejection {\n readonly opId: OpId\n /**\n * Why, typed. None when the server named no refusal (an older or a custom\n * server), or one this build cannot read (reported as `UnknownRefusal`).\n */\n readonly refusal: Option.Option<SyncRefusal>\n /**\n * @deprecated Read `refusal`, through `SyncRefusal.match`; removed in the\n * next release. The server's words from its `reasons`.\n */\n readonly reason: Option.Option<string>\n /** The operation as it was sent: its Message at the version it was written at. */\n readonly operation: WrittenOperation\n /** The operation's Message, encoded at the current version: what to read it by. */\n readonly message: unknown\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n /** The server-confirmed state the optimistic `shared` is built on. */\n readonly committed: Shared\n /**\n * The local sequence the next submitted operation takes. Only a successful\n * submit moves it, so a caller that submits one Message at a time can tell\n * from one snapshot whether `shared` already holds it.\n */\n readonly nextLocalSequence: LocalSequence\n}\n\nexport interface Replica<Message, Shared> {\n /** The id this replica's operations carry, one per tab: what its commits are stamped with. */\n readonly replicaId: ReplicaId\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n /**\n * The server-confirmed state through `cursor`, with no pending operation\n * applied. A pending edit reaches it only once the server commits it, and a\n * rejected one never does.\n */\n readonly committed: Effect.Effect<Shared>\n /** The outbox, as written. */\n readonly pending: Effect.Effect<ReadonlyArray<WrittenOperation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n /** The status, `shared`, `committed` and next local sequence, read from one replica state. */\n readonly snapshot: Effect.Effect<ReplicaSnapshot<Shared>>\n /** Records a durable Message in the outbox and applies it optimistically. */\n // A method, so a replica of the durable subset is still a `Replica` of the\n // application's Messages where one is only passed along (`Sync.mount`).\n submit(message: Message): Effect.Effect<void, ReplicaError>\n /** Reconciles against the server. The `Transport` service must be provided. */\n readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>\n /**\n * The exchange loop: exchanges once, then after every `submit` and every\n * notice on the transport's `changes`, until the replica closes or the fiber\n * is interrupted. A failed exchange is recorded\n * in `status.lastError` and retried on a backoff (from 0.5 s, doubling up to\n * 30 s), or at once on the next `submit`, so the fiber never fails. Fork it\n * with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n /** Forgets a `status.refused` operation, its payload with it. One that is not there changes nothing. */\n dismiss(opId: OpId): Effect.Effect<void, ReplicaError>\n readonly close: Effect.Effect<void>\n}\n\n/**\n * The document's Message: one Schema, at version 1, or its history\n * (`Sync.migrations`), whose current Schema is the Message.\n */\nexport type MessageHistory<Message, MessageEncoded> =\n | {\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly migrations?: undefined\n }\n | {\n /** The Schemas operations may be stored in, and how each becomes the next. */\n readonly migrations: Migrations<Message, MessageEncoded>\n readonly message?: undefined\n }\n\nexport type SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> = SyncDefinitionOptions<\n Message,\n Shared,\n SharedEncoded\n> &\n MessageHistory<Message, MessageEncoded>\n\nexport interface SyncDefinitionOptions<Message, Shared, SharedEncoded> {\n readonly documentId: DocumentId\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n /**\n * Optional. The Messages only the server appends: stored and replayed like\n * durable ones, never accepted from a replica. A Message both predicates\n * accept is refused wherever it is read.\n */\n readonly serverOnly?: ((message: Message) => boolean) | undefined\n readonly replay: (shared: Shared, message: Message) => Shared\n /**\n * Optional. Merges a durable Message into the one submitted before it, while that one\n * has not been sent: one operation instead of two, for a burst of typing. Replaying the\n * result must equal replaying `last` then `next`. Undefined keeps them apart.\n */\n readonly coalesce?: ((last: Message, next: Message) => Message | undefined) | undefined\n /**\n * Optional. Writes what the server's commit decided into a durable Message, on the\n * server only: the journal stores, reduces and sends the stamped Message, so every\n * replica replays the same one in place of what it sent.\n */\n readonly stamp?: ((message: Message, commit: CommitStamp) => Message) | undefined\n}\n\n/**\n * What a commit decided, for `stamp`: the operation's place in the order, who\n * committed it, and from which replica. `actorId` is the principal, shared by\n * every tab a person has open; `replicaId` tells those tabs apart.\n */\nexport interface CommitStamp {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n}\n\n/**\n * A document's protocol. `Durable` is what a replica's `submit` takes: the\n * durable subset for a contract from `Sync.forApplication(App).make`, every\n * Message for one from `Sync.define`, which checks `durable` when called.\n */\nexport interface Sync<Message, Shared, Durable = Message> {\n readonly documentId: DocumentId\n /** Whether a Message is one the replica records and replays. */\n readonly durable: (message: Message) => boolean\n /** Whether a Message is one only the server appends: replicas replay it and never submit it. */\n readonly serverOnly: (message: Message) => boolean\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n /** The current version of the document's Message history: 1 with no migrations. */\n readonly messageVersion: number\n /** The document's Message at its current version: what every hook decodes. */\n readonly message: Schema.Codec<Message, unknown, never, never>\n /**\n * An entry someone sent, read: its Message upcast to the current version.\n * Throws `UnsupportedMessageVersionError` for a newer version,\n * `UnreadableMessageError` for an older one no step reads, and\n * `ServerOnlyMessageError` for a Message only the server appends; it\n * refuses a replica id under `server/` or past 128 characters. Read\n * stored history with `journalContract().operation.decode`, which takes\n * the server's Messages too.\n */\n readonly normalizeOperation: (input: unknown) => Operation\n /** `normalizeOperation`, of this document only. */\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n /**\n * An entry as received, checked as an envelope of this document and read\n * as `normalizeOperation` reads it, and returned as written: what a server\n * appends. A custom server reads every entry with it before appending.\n * Never pass it an `Operation`: that Message is already current and would\n * be read as version 1. Write one with `journalContract().operation.encode`.\n */\n readonly writtenFrom: (input: unknown, documentId: DocumentId) => WrittenOperation\n readonly committedFrom: (input: unknown, documentId: DocumentId) => CommittedOperation\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n /**\n * Opens the replica a store holds. Its id is the store's: read back, or minted\n * when the store is empty, so two stores never share one. In a browser the\n * store is `Sync.tabStorage(name)`, one per tab.\n */\n readonly openReplica: (\n storage: Storage,\n options?: OpenReplicaOptions,\n ) => Effect.Effect<Replica<Durable, Shared>, ReplicaError>\n}\n\nexport interface OpenReplicaOptions {\n /**\n * The id the store must hold, for a test asserting operation ids or a replica\n * a server names. It names one store, never a person: operation ids are\n * `replicaId:localSequence`, so two stores under one id (a person's second\n * browser) reuse ids the journal refuses.\n */\n readonly replicaId?: ReplicaId | undefined\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n /** The replica each operation came from, which Durable binds to its first committer. */\n readonly replicaId: (operation: Operation) => string\n /** Sync's operation id includes the replica, even after Durable compacts its payload. */\n readonly legacyReplicaId: (opId: string) => string\n readonly operation: {\n /** Written at the current version: what the journal stores. */\n readonly encode: (operation: Operation) => WrittenOperation\n /**\n * Read from any version the history has, upcast to the current one: stored\n * history, so the server's own Messages read too. Never the reader of an\n * entry someone sent (`codec.writtenFrom`).\n */\n readonly decode: (input: unknown) => Operation\n /**\n * What a retransmission is compared by: the operation normalized at the\n * version it was written at, as the build that wrote it normalized it, so\n * an edit committed before a deploy is still recognized after it.\n */\n readonly compared: (input: unknown) => WrittenOperation\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n /** Present when the definition stamps: Durable's `stamp`, over the operation's Message. */\n readonly stamp?: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ) => Operation\n}\n\n/**\n * Binds the replicated-state protocol to one application contract.\n *\n * The returned codecs decide what is a valid operation and what the shared\n * projection means; the replica owns the local outbox, optimistic projection,\n * and reconciliation as Effects, and never runs a second reducer.\n */\nexport const defineSync = <Message, Shared, MessageEncoded, SharedEncoded>(\n definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>,\n): Sync<Message, Shared> => {\n const documentId = definition.documentId\n const messages = definition.migrations ?? migrations(definition.message)\n const history = historyOf(messages as Migrations<unknown, unknown>)\n const current = history.version\n const decodeMessage = Schema.decodeUnknownSync(messages.current, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(messages.current)\n const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(WrittenOperationSchema),\n refused: Schema.optionalKey(Schema.Array(WrittenOperationSchema)),\n epoch: Schema.optionalKey(Schema.NonEmptyString),\n })\n const CheckpointSchema = Schema.Struct({ cursor: Sequence, model: definition.shared })\n const ExchangeSchema = Schema.Struct({\n operations: Schema.Array(Schema.Unknown),\n rejected: Schema.Array(OpId),\n // Each refusal is decoded on its own, when the rejection is read: one this\n // build cannot read must not fail the exchange that rejected its operation.\n refusals: Schema.optional(Schema.Array(Schema.Struct({ opId: OpId, refusal: Schema.Unknown }))),\n // A server's words for a person, bounded: a reply is not a place for a document.\n reasons: Schema.optional(\n Schema.Array(\n Schema.Struct({ opId: OpId, reason: Schema.String.check(Schema.isMaxLength(500)) }),\n ),\n ),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n more: Schema.optional(Schema.Boolean),\n epoch: Schema.optional(Schema.NonEmptyString),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const encodeWritten = Schema.encodeSync(WrittenOperationSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\n const decodeExchange = (input: unknown): Exchange<Shared> =>\n Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: 'error' })(\n input,\n ) as Exchange<Shared>\n\n const checkIdentity = (operation: Operation): void => {\n // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\n throw new Error('Invalid operation identity')\n }\n }\n /**\n * An operation's Message, upcast to the current version and decoded. The\n * durable check runs on the current Message, so a step that maps an old\n * variant onto a local-only one is refused as that one is.\n */\n const newer = (opId: string, version: number) =>\n new UnsupportedMessageVersionError({\n opId,\n found: version,\n supported: current,\n message: `Operation ${opId} was written at Message version ${version}; this build reads up to ${current}`,\n })\n const serverOnly = definition.serverOnly ?? (() => false)\n /**\n * `sent` is an entry someone sent, which may carry only what a replica\n * submits; `history` is what the journal stored, the server's Messages too.\n */\n const messageOf = (operation: WrittenShape, kind: 'sent' | 'history'): Message => {\n const version = versionOf(operation)\n if (version > current) throw newer(operation.opId, version)\n let decoded: Message\n if (version === current) decoded = decodeMessage(operation.message)\n else\n try {\n decoded = decodeMessage(history.upcast(version, operation.message))\n } catch (cause) {\n throw new UnreadableMessageError({\n opId: operation.opId,\n version,\n message: `No step of the Message history reads operation ${operation.opId}, written at version ${version}`,\n cause,\n })\n }\n const durable = definition.durable(decoded)\n const server = serverOnly(decoded)\n if (durable && server)\n throw new AmbiguousMessageError({\n opId: operation.opId,\n message: `Operation ${operation.opId} carries a Message both durable and server-only`,\n })\n if (server && kind === 'sent')\n throw new ServerOnlyMessageError({\n opId: operation.opId,\n message: `Operation ${operation.opId} carries a Message only the server appends`,\n })\n if (!durable && !server) throw new Error('Message is local-only')\n return decoded\n }\n /** The envelope alone: the decoded side holds no version, only the current Message. */\n const envelopeOf = <O extends WrittenShape>({\n messageVersion: _,\n ...envelope\n }: O): Omit<O, 'messageVersion'> => envelope\n /** Written at the current version, which an explicit 1 is not. */\n const write = (operation: Operation): WrittenOperation => {\n const envelope = envelopeOf(operation)\n return vouched(current === 1 ? envelope : { ...envelope, messageVersion: current })\n }\n const assertDocument = <O extends WrittenShape>(operation: O, key: DocumentId): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n /** What a sent entry may not name: the server's replica ids, or one past the bound. */\n const checkSentReplica = (operation: WrittenShape): void => {\n if (operation.replicaId.startsWith(SERVER_REPLICA_PREFIX))\n throw new Error('The replica id is reserved for the server')\n if (operation.replicaId.length > MAX_SENT_REPLICA_ID)\n throw new Error('The replica id is too long')\n }\n const read = (written: WrittenShape, kind: 'sent' | 'history'): Operation => {\n checkIdentity(written)\n if (kind === 'sent') checkSentReplica(written)\n return { ...envelopeOf(written), message: encodeMessage(messageOf(written, kind)) }\n }\n const normalizeOperation = (input: unknown): Operation => read(decodeWritten(input), 'sent')\n const operationFrom = (input: unknown, key: DocumentId): Operation =>\n read(assertDocument(decodeWritten(input), key), 'sent')\n const writtenFrom = (input: unknown, key: DocumentId): WrittenOperation => {\n const written = assertDocument(decodeWritten(input), key)\n // Read for its checks and discarded: what is appended is what was sent.\n read(written, 'sent')\n return written\n }\n /** Stored history: the server's Messages read, and a stored replica id of any length. */\n const readStored = (input: unknown): Operation => read(decodeWritten(input), 'history')\n /** An outbox entry this replica wrote: history, since it may predate a deploy that moved its variant. */\n const storedFrom = (input: unknown, key: DocumentId): Operation =>\n read(assertDocument(decodeWritten(input), key), 'history')\n /**\n * A committed operation arrives with its message already encoded, so decode it\n * once for the contract check and hand it to `replay` instead of decoding and\n * re-encoding it on the way.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: DocumentId,\n ): { readonly committed: CommittedOperation; readonly message: Message } => {\n const written = assertDocument(decodeCommittedWritten(input), key)\n checkIdentity(written)\n const message = messageOf(written, 'history')\n return { committed: { ...envelopeOf(written), message: encodeMessage(message) }, message }\n }\n const committedFrom = (input: unknown, key: DocumentId): CommittedOperation =>\n decodeCommittedOperation(input, key).committed\n /**\n * Normalized at the version it was written at, with no upcast: what the\n * build that wrote it hashed. An explicit `messageVersion: 1` is dropped,\n * so it and an absent one compare alike.\n */\n const compared = (input: unknown): WrittenOperation => {\n const written = decodeWritten(input)\n const version = versionOf(written)\n if (version > current) throw newer(written.opId, version)\n const envelope = envelopeOf(written)\n return vouched({\n ...envelope,\n ...(version === 1 ? {} : { messageVersion: version }),\n message: history.normalize(version, written.message),\n })\n }\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n replicaId: operation => operation.replicaId,\n legacyReplicaId: opId => opId.slice(0, opId.lastIndexOf(':')),\n // Stored written at the current version; read from any version the history has.\n operation: { encode: write, decode: readStored, compared },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n ...(definition.stamp === undefined\n ? {}\n : {\n stamp: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ): Operation => ({\n ...operation,\n message: encodeMessage(\n definition.stamp!(decodeMessage(operation.message), {\n ...commit,\n replicaId: operation.replicaId,\n }),\n ),\n }),\n }),\n })\n\n /** `state` with `refused` set; the key is absent when none is, so such a state is as before. */\n const withRefused = (\n { refused: _, ...state }: ReplicaState<Shared>,\n refused: ReadonlyArray<WrittenOperation>,\n ): ReplicaState<Shared> => (refused.length === 0 ? state : { ...state, refused })\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, messageOf(operation, 'history')),\n state.committed,\n )\n\n const openReplica = Effect.fn('Sync.openReplica')(\n function* (storage: Storage, options?: OpenReplicaOptions) {\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId: options?.replicaId ?? ReplicaId.make(crypto.randomUUID()),\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(0),\n committed: definition.empty,\n committedIds: [],\n pending: [],\n }\n const state: ReplicaState<Shared> =\n saved === undefined\n ? initial\n : yield* Effect.try({\n try: () => decodeState(saved),\n catch: cause =>\n unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n const replicaId = state.replicaId\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n if (\n state.documentId !== documentId ||\n (options?.replicaId !== undefined && replicaId !== options.replicaId)\n )\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId: options?.replicaId ?? replicaId,\n message: 'The stored replica belongs to a different document or replica',\n })\n const committedIds = new Set(state.committedIds)\n if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length)\n return yield* new InvalidReplicaHistoryError({ message: 'Invalid replica history' })\n const pendingIds = new Set<string>()\n // Written at an older version no step reads: refused by its id, kept as\n // written, so the rest of the outbox opens and sends.\n const unreadable = new Set<WrittenOperation>()\n for (const pending of state.pending) {\n if (\n pending.replicaId !== replicaId ||\n pending.localSequence >= state.nextLocalSequence ||\n committedIds.has(pending.opId) ||\n pendingIds.has(pending.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(pending.opId)\n try {\n storedFrom(pending, documentId)\n } catch (cause) {\n // A newer build wrote it: nothing is removed, and that build reads it.\n if (cause instanceof UnsupportedMessageVersionError) return yield* cause\n if (cause instanceof UnreadableMessageError) unreadable.add(pending)\n else return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n }\n }\n // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n // The one write an open makes, under the loaded revision: a tab that\n // opened the same store meanwhile fails it as a conflict.\n const opened: ReplicaState<Shared> =\n unreadable.size === 0\n ? state\n : withRefused(\n {\n ...state,\n revision: state.revision + 1,\n pending: state.pending.filter(operation => !unreadable.has(operation)),\n },\n [...(state.refused ?? []), ...unreadable],\n )\n if (opened !== state) yield* store(opened, state.revision)\n\n const stateRef = yield* SynchronizedRef.make(opened)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<Rejection>>([])\n // Operations submitted since opening that no exchange has carried yet. Only these may\n // be coalesced: one that was sent may already be committed as it was.\n const unsent = yield* Ref.make<ReadonlySet<string>>(new Set())\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The current value, then again after every change. Subscribed before the\n // first read, so a change made while a subscriber holds that value, or\n // between the read and the subscription, is still told.\n const following = <A>(read: Effect.Effect<A>): Stream.Stream<A> =>\n Stream.unwrap(\n Effect.map(PubSub.subscribe(statusSignals), signals =>\n Stream.concat(\n Stream.fromEffect(read),\n Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)),\n ),\n ),\n )\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n refused: current.refused ?? [],\n epoch: Option.fromUndefinedOr(current.epoch),\n },\n shared: projected,\n committed: current.committed,\n nextLocalSequence: current.nextLocalSequence,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\n\n // `SynchronizedRef.modifyEffect` installs the returned state itself, so\n // persisting must not also set the ref (that would re-enter the lock).\n const persist = (next: ReplicaState<Shared>, current: ReplicaState<Shared>) =>\n store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n if (serverOnly(message))\n return yield* new InvalidOutboxError({\n message: 'Message is one only the server appends',\n })\n if (!definition.durable(message))\n return yield* new InvalidOutboxError({ message: 'Message is local-only' })\n const last = current.pending[current.pending.length - 1]\n const merged =\n last !== undefined &&\n definition.coalesce !== undefined &&\n (yield* Ref.get(unsent)).has(last.opId)\n ? definition.coalesce(messageOf(last, 'history'), message)\n : undefined\n if (merged !== undefined && !definition.durable(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a local-only Message',\n })\n if (merged !== undefined && serverOnly(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a Message only the server appends',\n })\n // A merged Message takes the place of the last operation, under its identity.\n const operation = yield* Effect.try({\n try: () =>\n write(\n storedFrom(\n write(\n merged === undefined\n ? {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: OpId.make(`${replicaId}:${current.nextLocalSequence}`),\n baseCursor: current.cursor,\n message: encodeMessage(message),\n }\n : { ...envelopeOf(last!), message: encodeMessage(merged) },\n ),\n documentId,\n ),\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n // The sequence moves on a merge too, so every submit is visible in it; a gap\n // in local sequences is harmless.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [\n ...(merged === undefined ? current.pending : current.pending.slice(0, -1)),\n operation,\n ],\n }\n // Only the new operation is written when the storage can append it.\n if (storage.append === undefined) yield* persist(next, current)\n else {\n const encoded = yield* Effect.try({\n try: () => encodeWritten(operation),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the operation',\n cause,\n }),\n })\n yield* storage.append(\n {\n revision: next.revision,\n nextLocalSequence: next.nextLocalSequence,\n localSequence: operation.localSequence,\n operation: encoded,\n },\n current.revision,\n )\n }\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Ref.update(unsent, ids => new Set(ids).add(operation.opId))\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n /** One exchange; whether the server has more to send and this one made progress. */\n const exchangeOnce = Effect.fn('Sync.exchange')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Read under the lock, as a submit writes, so no submit can merge into an operation\n // between its being read here and its being marked sent.\n const sent = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Ref.update(unsent, ids => {\n const left = new Set(ids)\n for (const operation of current.pending) left.delete(operation.opId)\n return left\n }).pipe(Effect.as([current, current] as const)),\n )\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n })\n const { restarted, refusals } = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // A `close` during the exchange must not persist its result.\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Another epoch means the server's history is not the one the cursor points\n // into (it was reset): the answer starts from its beginning, so the committed\n // state is rebuilt from it. The outbox is the user's intent and is kept.\n const restarted =\n response.epoch !== undefined &&\n current.epoch !== undefined &&\n response.epoch !== current.epoch\n if (restarted) yield* Diagnostics.report(historyRebuilt(documentId, replicaId))\n let cursor = restarted ? sequence(0) : current.cursor\n let committed = restarted ? definition.empty : current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it, as it does on a new epoch.\n const ids =\n response.checkpoint === undefined && !restarted\n ? new Set(current.committedIds)\n : new Set<string>()\n if (response.checkpoint !== undefined) {\n if (response.checkpoint.cursor < cursor)\n return yield* new CheckpointRegressionError({\n cursor,\n checkpointCursor: response.checkpoint.cursor,\n message: 'Checkpoint is behind the replica',\n })\n committed = response.checkpoint.model\n cursor = response.checkpoint.cursor\n yield* Metric.update(syncMetrics.checkpoints, 1)\n yield* Effect.logDebug('sync checkpoint adopted', { documentId, replicaId, cursor })\n }\n const acknowledged = new Set(response.acknowledged ?? [])\n const rejected = new Set(response.rejected)\n const sentIds = new Set(sent.pending.map(operation => operation.opId))\n for (const id of acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\n for (const id of rejected) {\n if (!sentIds.has(id))\n return yield* new ForeignRejectionError({\n opId: id,\n message: 'Server rejected an operation that was not sent',\n })\n // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n for (const { opId } of [...(response.refusals ?? []), ...(response.reasons ?? [])])\n if (!rejected.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave a reason for an operation it did not reject',\n })\n // One each, so there are no more to decode than operations it rejected.\n const refusing = new Set<string>()\n for (const { opId } of response.refusals ?? []) {\n if (refusing.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave two refusals for one operation',\n })\n refusing.add(opId)\n }\n const refusals = (response.refusals ?? []).map(\n ({ opId, refusal }) => [opId, decodeRefusal(refusal)] as const,\n )\n // What the server could not read is kept, as this build cannot either\n // once their chains agree: never sent again, never lost.\n const unreadableIds = new Set(\n refusals.flatMap(([opId, refusal]) =>\n Result.match(refusal, {\n onFailure: (): ReadonlyArray<OpId> => [],\n onSuccess: SyncRefusal.match({\n Forbidden: (): ReadonlyArray<OpId> => [],\n Invalid: () => [],\n Unreadable: () => [opId],\n }),\n }),\n ),\n )\n let applied = 0\n for (const raw of response.operations) {\n const { committed: operation, message } = yield* Effect.try({\n try: () => decodeCommittedOperation(raw, documentId),\n catch: cause =>\n cause instanceof UnsupportedMessageVersionError\n ? cause\n : new InvalidReplicaHistoryError({\n message: 'Invalid committed operation',\n cause,\n }),\n })\n if (operation.serverSequence <= cursor) continue\n if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId))\n return yield* new CommittedOrderError({\n expected: cursor + 1,\n actual: operation.serverSequence,\n message: 'Invalid committed order',\n })\n // A throw here would be a defect, which bypasses `lastError` and leaves\n // `start` retrying the same page in silence.\n const replaying = committed\n committed = yield* Effect.try({\n try: () => definition.replay(replaying, message),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const epoch = response.epoch ?? current.epoch\n const next = withRefused(\n {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n ...(epoch === undefined ? {} : { epoch }),\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n // While the server has more to send, an acknowledged operation's committed\n // copy may be on a later page, so it stays in the optimistic view until then.\n // An acknowledged operation the replica is already past (committed before a\n // checkpoint, say) never arrives, so it goes once there is no more to read.\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !(acknowledged.has(operation.opId) && response.more !== true) &&\n !rejected.has(operation.opId),\n ),\n },\n [\n ...(current.refused ?? []),\n // A refusal names only a rejected id (anything else failed the\n // exchange above), so what moves here has left `pending`.\n ...current.pending.filter(operation => unreadableIds.has(operation.opId)),\n ],\n )\n yield* persist(next, current)\n return [{ restarted, refusals }, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0) {\n const reasonOf = new Map(\n (response.reasons ?? []).map(({ opId, reason }) => [opId, reason] as const),\n )\n const refusalOf = new Map<string, SyncRefusal>()\n for (const [opId, decoded] of refusals) {\n if (Result.isSuccess(decoded)) refusalOf.set(opId, decoded.success)\n else\n yield* Diagnostics.report(\n unknownRefusal(documentId, replicaId, opId, fitWords(decoded.failure.message)),\n )\n }\n // Every rejected id was sent: an unknown one failed the exchange above.\n const sentOf = new Map(\n sent.pending.map(operation => [operation.opId, operation] as const),\n )\n // Every pending operation reads: one that did not was refused on open.\n const refused = response.rejected.map((opId): Rejection => {\n const operation = sentOf.get(opId)!\n return {\n opId,\n refusal: Option.fromUndefinedOr(refusalOf.get(opId)),\n reason: Option.fromUndefinedOr(reasonOf.get(opId)),\n operation,\n message: encodeMessage(messageOf(operation, 'history')),\n }\n })\n yield* Ref.update(rejectedOps, previous => [...refused, ...previous].slice(0, 32))\n }\n yield* PubSub.publish(statusSignals, undefined)\n const reached = (yield* SynchronizedRef.get(stateRef)).cursor\n return response.more === true && reached > (restarted ? 0 : sent.cursor)\n })\n\n // A server that pages its answer says there is more, and the replica asks again at\n // once; a round that moves the cursor nowhere ends it.\n const synchronize = Effect.gen(function* () {\n while (yield* exchangeOnce()) {}\n }).pipe(\n Effect.withSpan('Sync.synchronize'),\n // Any failed exchange, a refused response included, is what a UI shows,\n // so it is recorded and announced rather than left for the next submit.\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Diagnostics.report(exchangeFailed(documentId, replicaId, error))\n yield* Ref.set(lastError, error.message)\n yield* PubSub.publish(statusSignals, undefined)\n }),\n ),\n )\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n const transport = yield* Transport\n // A server's notice wakes the loop as a submit does; the fiber ends with this one.\n // It starts at once so it is subscribed before the first exchange, which a\n // notice may arrive during.\n if (transport.changes !== undefined)\n yield* Effect.forkChild(\n Stream.runForEach(transport.changes, () => Queue.offer(wake, undefined)),\n { startImmediately: true },\n )\n let failures = 0\n while (!(yield* Ref.get(closed))) {\n const exit = yield* Effect.exit(synchronize)\n if (yield* Ref.get(closed)) return\n yield* Exit.match(exit, {\n onSuccess: () => {\n failures = 0\n return Queue.take(wake)\n },\n onFailure: () => {\n // Retried on a backoff, or sooner on a submit: an outbox must not\n // wait for the next keystroke to be delivered.\n failures += 1\n const backoff = Math.min(\n START_RETRY_MAX,\n START_RETRY_BASE * 2 ** Math.min(failures - 1, 16),\n )\n return Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff))\n },\n })\n }\n })\n\n const dismiss = Effect.fn('Sync.dismiss')(function* (opId: OpId) {\n const dismissed = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n const refused = current.refused ?? []\n const left = refused.filter(operation => operation.opId !== opId)\n if (left.length === refused.length) return [false, current] as const\n const next = withRefused({ ...current, revision: current.revision + 1 }, left)\n yield* persist(next, current)\n return [true, next] as const\n }),\n )\n if (dismissed) yield* PubSub.publish(statusSignals, undefined)\n })\n\n return {\n replicaId,\n shared,\n snapshot,\n committed: Effect.map(SynchronizedRef.get(stateRef), state => state.committed),\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: following(status),\n changes: following(snapshot),\n submit,\n synchronize,\n start,\n dismiss,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n durable: definition.durable,\n serverOnly,\n codec: {\n messageVersion: current,\n message: messages.current as Schema.Codec<Message, unknown, never, never>,\n normalizeOperation,\n operationFrom,\n writtenFrom,\n committedFrom,\n decodeExchange,\n },\n journalContract,\n openReplica,\n }\n}\n"],"mappings":";;;;;;;;;;AAgDA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;AAOvB,MAAa,wBAAwB;;AAErC,MAAM,sBAAsB;;;;;AAM5B,MAAM,kBAAkB,OAAO,OAAO;CACpC,iBAAiB,OAAO,QAAQ,gBAAgB;CAChD,eAAe,OAAO,QAAQ,cAAc;CAC5C,YAAY;CACZ,WAAW;CACX,eAAe;CACf,MAAM;CACN,YAAY;CACZ,SAAS,OAAO;AAClB,CAAC;;;;;;;AASD,MAAM,gBAAgB,OAAO,OAAO;CAClC,GAAG,gBAAgB;CACnB,gBAAgB,OAAO,YAAY,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,CAAC;AACvF,CAAC;;;;;;;AASD,MAAM,yBAAyB,cAAc,KAAK,OAAO,MAAM,+BAA+B,CAAC;;AAG/F,MAAM,WAAW,cAA8C;AAE/D,MAAM,kBAAkB;CACtB,gBAAgB,SAAS,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC/D,SAAS,OAAO;AAClB;AAEwB,OAAO,OAAO;CAAE,GAAG,gBAAgB;CAAQ,GAAG;AAAgB,CAAC;;AAIvF,MAAM,yBAAyB,OAAO,OAAO;CAC3C,GAAG,cAAc;CACjB,GAAG;AACL,CAAC;AAED,MAAM,gBAAgB,OAAO,kBAAkB,wBAAwB,EACrE,kBAAkB,QACpB,CAAC;;;;;;AAMD,MAAa,mBAAmB,UAAqC,cAAc,KAAK;AACxF,MAAM,yBAAyB,OAAO,kBAAkB,wBAAwB,EAC9E,kBAAkB,QACpB,CAAC;;AAED,MAAM,aAAa,cAAoC,UAAU,kBAAkB;AACnF,MAAM,gBAAgB,OAAO,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;GACA;GACA;GACA,WAAW,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,SAAS;GAC7E,SAAS,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,OAAO;GACzE,QAAQ,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,MAAM;GACvE;GACA,eAAe,UAAU,MAAM;GAC/B,SAAS,UAAU,QAAQ;GAC3B;GACA;GACA;GACA;GACA,OAAO,OAAO,GAAG,YAAY,CAAC,CAAC,aAAa;IAC1C,OAAO,IAAI,IAAI,QAAQ,IAAI;IAE3B,OAAO,MAAM,MAAM,MAAM,KAAA,CAAS;IAClC,OAAO,QAAQ;GACjB,CAAC,CAAC,CAAC;EACL;CACF,IACC,QAAQ,YAGP,OAAO,KACL,OAAO,QAAO,SACZ,KAAK,UAAU,IAAI,IAAI,OAAO,OAAO,QAAQ,MAAM,KAAK,OAAO,MAAM,CACvE,CACF,CACJ;CAEA,OAAO;EACL;EACA,SAAS,WAAW;EACpB;EACA,OAAO;GACL,gBAAgB;GAChB,SAAS,SAAS;GAClB;GACA;GACA;GACA;GACA;EACF;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"sync.js","names":[],"sources":["../src/sync.ts"],"sourcesContent":["import {\n Effect,\n Exit,\n Metric,\n Option,\n PubSub,\n Queue,\n Ref,\n Result,\n Schema,\n Stream,\n SynchronizedRef,\n} from 'effect'\nimport {\n AmbiguousMessageError,\n CheckpointRegressionError,\n CommittedOrderError,\n ForeignAcknowledgementError,\n ForeignRejectionError,\n InvalidExchangeError,\n InvalidOutboxError,\n InvalidReplicaHistoryError,\n ReplayError,\n ReplicaClosedError,\n ServerOnlyMessageError,\n UnreadableMessageError,\n UnsupportedMessageVersionError,\n UnsupportedReplicaVersionError,\n WrongReplicaStorageError,\n type ReplicaError,\n} from './errors.js'\nimport { historyOf, migrations, type Migrations } from './migrations.js'\nimport type { Storage } from './indexedDb.js'\nimport {\n DocumentId,\n LocalSequence,\n OpId,\n ReplicaId,\n Sequence,\n localSequence,\n sequence,\n} from './ids.js'\nimport { Transport, TransportError } from './transport.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { exchangeFailed, historyRebuilt, unknownRefusal } from './diagnostics.js'\nimport { fitWords, SyncRefusal } from './refusal.js'\n\n/** Wire and persisted-format versions. A bump must handle the older value explicitly. */\nconst PROTOCOL_VERSION = 1\nconst SCHEMA_VERSION = 1\n\n/**\n * Replica ids the server's own operations use (`foldkit-sync/journal`'s\n * `serverJournal`): a sent entry may not claim one, or it could bind the id to\n * its actor first and have the server's append refused.\n */\nexport const SERVER_REPLICA_PREFIX = 'server/'\n/** The longest replica id a sent entry may name. A stored one is read whatever its length. */\nconst MAX_SENT_REPLICA_ID = 128\n\n/**\n * A client-authored operation envelope. `message` is the application's\n * Message, encoded at the current version of the document's history.\n */\nconst OperationSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n localSequence: LocalSequence,\n opId: OpId,\n baseCursor: Sequence,\n message: Schema.Unknown,\n})\nexport type Operation = typeof OperationSchema.Type\n\n/**\n * An operation as it was written: what a replica keeps in its outbox and\n * sends, with its Message at the version it was written at. `messageVersion`\n * is absent for version 1, so a document with no migrations writes today's\n * envelope byte for byte.\n */\nconst WrittenFields = Schema.Struct({\n ...OperationSchema.fields,\n messageVersion: Schema.optionalKey(Schema.Int.check(Schema.isGreaterThanOrEqualTo(1))),\n})\n/** The written shape, unbranded: what the codec reads before it vouches for anything. */\ntype WrittenShape = typeof WrittenFields.Type\n/**\n * Branded, so only Sync makes one: decoding an entry, or writing an\n * `Operation` at the current version (`journalContract().operation.encode`).\n * A decoded `Operation` is not one, since its missing `messageVersion` would\n * read as version 1 and be upcast again.\n */\nconst WrittenOperationSchema = WrittenFields.pipe(Schema.brand('foldkit-sync/WrittenOperation'))\nexport type WrittenOperation = typeof WrittenOperationSchema.Type\n/** What the codec has checked or written itself. */\nconst vouched = (operation: WrittenShape): WrittenOperation => operation as WrittenOperation\n\nconst committedFields = {\n serverSequence: Sequence.check(Schema.isGreaterThanOrEqualTo(1)),\n actorId: Schema.NonEmptyString,\n}\n/** An operation the server committed, with its authoritative order and actor. */\nconst CommittedSchema = Schema.Struct({ ...OperationSchema.fields, ...committedFields })\n/** Named to avoid colliding with `foldkit-durable`'s `Committed`. */\nexport type CommittedOperation = typeof CommittedSchema.Type\n/**\n * A type-only mark on what `codec.committedFrom` returns. It reads its input as\n * history, so it skips the checks of a sent entry, and\n * `journalContract().operation.encode` refuses it, stripped of its commit or not.\n */\nexport interface ReadAsHistory {\n readonly '~foldkit-sync/history': true\n}\n/** A committed operation as the server sends it: written at the server's current version. */\nconst CommittedWrittenSchema = Schema.Struct({\n ...WrittenFields.fields,\n ...committedFields,\n})\n\nconst decodeWritten = Schema.decodeUnknownSync(WrittenOperationSchema, {\n onExcessProperty: 'error',\n})\n/**\n * An envelope as written, checked for its shape and nothing else: for the\n * server's own operations (`serverJournal`), whose bytes it wrote or recorded.\n * Never for an entry someone sent.\n */\nexport const writtenEnvelope = (input: unknown): WrittenOperation => decodeWritten(input)\nconst decodeCommittedWritten = Schema.decodeUnknownSync(CommittedWrittenSchema, {\n onExcessProperty: 'error',\n})\n/** The version an operation was written at: absent is 1. */\nconst versionOf = (operation: WrittenShape): number => operation.messageVersion ?? 1\nconst decodeRefusal = Schema.decodeUnknownResult(SyncRefusal, { onExcessProperty: 'error' })\n\n/**\n * How many committed-operation ids a replica retains for duplicate detection.\n * Committed sequences are contiguous and the server enforces `opId`\n * uniqueness, so this is defence in depth; bounding it keeps replica state from\n * growing without limit on a log that is never checkpointed.\n */\nconst COMMITTED_ID_WINDOW = 1024\n/** How long `start` waits after a failed exchange: doubling from the base, up to the cap, in ms. */\nconst START_RETRY_BASE = 500\nconst START_RETRY_MAX = 30_000\n\n/** Counters and a histogram an application can scrape. */\nexport const syncMetrics = {\n exchanges: Metric.counter('foldkit_sync_exchanges_total'),\n applied: Metric.counter('foldkit_sync_commits_applied_total'),\n checkpoints: Metric.counter('foldkit_sync_checkpoints_adopted_total'),\n exchangePending: Metric.histogram('foldkit_sync_exchange_pending', {\n boundaries: [1, 4, 16, 64, 256, 1024],\n }),\n}\n\nexport interface Checkpoint<Shared> {\n readonly cursor: Sequence\n readonly model: Shared\n}\n\nexport interface Exchange<Shared> {\n /** Server-committed operations as they arrived; validated against `CommittedOperation` on adoption. */\n readonly operations: ReadonlyArray<unknown>\n readonly rejected: ReadonlyArray<OpId>\n /**\n * Why some of `rejected` were refused, each an encoded `SyncRefusal`. One\n * without a refusal is still rejected.\n */\n readonly refusals?:\n | ReadonlyArray<{ readonly opId: OpId; readonly refusal: typeof SyncRefusal.Encoded }>\n | undefined\n /**\n * @deprecated Send `refusals`; removed in the next release. Words the server\n * chose for a person, for some of `rejected`.\n */\n readonly reasons?: ReadonlyArray<{ readonly opId: OpId; readonly reason: string }> | undefined\n /** Sends from the request that are durably committed, so the replica can drop them. */\n readonly acknowledged?: ReadonlyArray<OpId> | undefined\n /** The snapshot a replica predating compaction adopts in place of the log. */\n readonly checkpoint?: Checkpoint<Shared> | undefined\n /** The server sent only part of what is after the cursor; the replica asks again. */\n readonly more?: boolean | undefined\n /**\n * The identity of the server's history. The replica sends back the one it last saw; a\n * server that finds another answers from the start of its own history, and the replica,\n * seeing a new epoch, rebuilds its committed state from that answer and keeps its outbox.\n */\n readonly epoch?: string | undefined\n}\n\nexport interface ReplicaState<Shared> {\n readonly protocolVersion: typeof PROTOCOL_VERSION\n readonly schemaVersion: typeof SCHEMA_VERSION\n readonly documentId: DocumentId\n readonly replicaId: ReplicaId\n readonly revision: number\n readonly nextLocalSequence: LocalSequence\n readonly cursor: Sequence\n readonly committed: Shared\n readonly committedIds: ReadonlyArray<string>\n /** Operations not yet committed, as written. */\n readonly pending: ReadonlyArray<WrittenOperation>\n /** Operations this build cannot read, kept as written until dismissed; absent when none. */\n readonly refused?: ReadonlyArray<WrittenOperation>\n /** The server history `cursor` points into, once an exchange has named one. */\n readonly epoch?: string\n}\n\n/**\n * What the promise-based edge adapter consumes; the Effect `Transport` service\n * is the primary seam.\n */\nexport interface TransportClient {\n /**\n * `epoch` is the server history the replica's cursor points into, when it\n * knows one. `pending` is unread, as on every transport seam: a server reads\n * each entry with `codec.writtenFrom`, which refuses what only it may append.\n */\n exchange(\n cursor: Sequence,\n pending: ReadonlyArray<unknown>,\n epoch?: string | undefined,\n ): Promise<unknown>\n}\n\n/** A redacted view of a replica's state, for a UI to explain and recover. */\nexport interface ReplicaStatus {\n readonly pending: number\n readonly cursor: Sequence\n /** The last exchange failure, cleared by a successful exchange. */\n readonly lastError: string | undefined\n /** Operations the server refused, most recent first, with its reason when it gave one. */\n readonly rejected: ReadonlyArray<Rejection>\n /**\n * Operations this build cannot read, as written: an older version of the\n * document's Message that no step of its history reads, found in the outbox\n * or refused by the server as `Unreadable`. Never sent; kept, with their\n * payload, until `Replica.dismiss`.\n */\n readonly refused: ReadonlyArray<WrittenOperation>\n /**\n * The server history the cursor points into, once a server named one. A new\n * one means the server was reset: what the replica had committed is gone.\n */\n readonly epoch: Option.Option<string>\n}\n\n/**\n * An operation the server refused, and why, when it said. It carries the\n * operation itself: the replica drops it from the outbox in the same step,\n * so what it changed can be read from here rather than looked up in time.\n */\nexport interface Rejection {\n readonly opId: OpId\n /**\n * Why, typed. None when the server named no refusal (an older or a custom\n * server), or one this build cannot read (reported as `UnknownRefusal`).\n */\n readonly refusal: Option.Option<SyncRefusal>\n /**\n * @deprecated Read `refusal`, through `SyncRefusal.match`; removed in the\n * next release. The server's words from its `reasons`.\n */\n readonly reason: Option.Option<string>\n /** The operation as it was sent: its Message at the version it was written at. */\n readonly operation: WrittenOperation\n /** The operation's Message, encoded at the current version: what to read it by. */\n readonly message: unknown\n}\n\n/**\n * A consistent status and optimistic-shared pair, read from one replica state.\n * `Replica.changes` emits it so a UI can hold a single subscription.\n */\nexport interface ReplicaSnapshot<Shared> {\n readonly status: ReplicaStatus\n readonly shared: Shared\n /** The server-confirmed state the optimistic `shared` is built on. */\n readonly committed: Shared\n /**\n * The local sequence the next submitted operation takes. Only a successful\n * submit moves it, so a caller that submits one Message at a time can tell\n * from one snapshot whether `shared` already holds it.\n */\n readonly nextLocalSequence: LocalSequence\n}\n\nexport interface Replica<Message, Shared> {\n /** The id this replica's operations carry, one per tab: what its commits are stamped with. */\n readonly replicaId: ReplicaId\n /** The optimistic projection: committed state with pending operations replayed. */\n readonly shared: Effect.Effect<Shared>\n /**\n * The server-confirmed state through `cursor`, with no pending operation\n * applied. A pending edit reaches it only once the server commits it, and a\n * rejected one never does.\n */\n readonly committed: Effect.Effect<Shared>\n /** The outbox, as written. */\n readonly pending: Effect.Effect<ReadonlyArray<WrittenOperation>>\n readonly cursor: Effect.Effect<Sequence>\n /**\n * Waiting/recovery information without exposing Messages or the Model. It is a\n * snapshot; `statusChanges` re-emits it after every submit and exchange.\n */\n readonly status: Effect.Effect<ReplicaStatus>\n /** The status, re-emitted after every submit and exchange. */\n readonly statusChanges: Stream.Stream<ReplicaStatus>\n /**\n * The status and the optimistic shared value together, re-emitted after every\n * submit and exchange, so a UI can subscribe once instead of to both.\n */\n readonly changes: Stream.Stream<ReplicaSnapshot<Shared>>\n /** The status, `shared`, `committed` and next local sequence, read from one replica state. */\n readonly snapshot: Effect.Effect<ReplicaSnapshot<Shared>>\n /** Records a durable Message in the outbox and applies it optimistically. */\n // A method, so a replica of the durable subset is still a `Replica` of the\n // application's Messages where one is only passed along (`Sync.mount`).\n submit(message: Message): Effect.Effect<void, ReplicaError>\n /** Reconciles against the server. The `Transport` service must be provided. */\n readonly synchronize: Effect.Effect<void, ReplicaError | TransportError, Transport>\n /**\n * The exchange loop: exchanges once, then after every `submit` and every\n * notice on the transport's `changes`, until the replica closes or the fiber\n * is interrupted. A failed exchange is recorded\n * in `status.lastError` and retried on a backoff (from 0.5 s, doubling up to\n * 30 s), or at once on the next `submit`, so the fiber never fails. Fork it\n * with `Effect.forkScoped` and provide `Transport`.\n */\n readonly start: Effect.Effect<void, never, Transport>\n /** Forgets a `status.refused` operation, its payload with it. One that is not there changes nothing. */\n dismiss(opId: OpId): Effect.Effect<void, ReplicaError>\n readonly close: Effect.Effect<void>\n}\n\n/**\n * The document's Message: one Schema, at version 1, or its history\n * (`Sync.migrations`), whose current Schema is the Message.\n */\nexport type MessageHistory<Message, MessageEncoded> =\n | {\n readonly message: Schema.Codec<Message, MessageEncoded, never, never>\n readonly migrations?: undefined\n }\n | {\n /** The Schemas operations may be stored in, and how each becomes the next. */\n readonly migrations: Migrations<Message, MessageEncoded>\n readonly message?: undefined\n }\n\nexport type SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded> = SyncDefinitionOptions<\n Message,\n Shared,\n SharedEncoded\n> &\n MessageHistory<Message, MessageEncoded>\n\nexport interface SyncDefinitionOptions<Message, Shared, SharedEncoded> {\n readonly documentId: DocumentId\n readonly shared: Schema.Codec<Shared, SharedEncoded, never, never>\n readonly empty: Shared\n readonly durable: (message: Message) => boolean\n /**\n * Optional. The Messages only the server appends: stored and replayed like\n * durable ones, never accepted from a replica. A Message both predicates\n * accept is refused wherever it is read.\n */\n readonly serverOnly?: ((message: Message) => boolean) | undefined\n readonly replay: (shared: Shared, message: Message) => Shared\n /**\n * Optional. Merges a durable Message into the one submitted before it, while that one\n * has not been sent: one operation instead of two, for a burst of typing. Replaying the\n * result must equal replaying `last` then `next`. Undefined keeps them apart.\n */\n readonly coalesce?: ((last: Message, next: Message) => Message | undefined) | undefined\n /**\n * Optional. Writes what the server's commit decided into a durable Message, on the\n * server only: the journal stores, reduces and sends the stamped Message, so every\n * replica replays the same one in place of what it sent.\n */\n readonly stamp?: ((message: Message, commit: CommitStamp) => Message) | undefined\n}\n\n/**\n * What a commit decided, for `stamp`: the operation's place in the order, who\n * committed it, and from which replica. `actorId` is the principal, shared by\n * every tab a person has open; `replicaId` tells those tabs apart.\n */\nexport interface CommitStamp {\n readonly sequence: number\n readonly actorId: string\n readonly replicaId: string\n}\n\n/**\n * A document's protocol. `Durable` is what a replica's `submit` takes: the\n * durable subset for a contract from `Sync.forApplication(App).make`, every\n * Message for one from `Sync.define`, which checks `durable` when called.\n */\nexport interface Sync<Message, Shared, Durable = Message> {\n readonly documentId: DocumentId\n /** Whether a Message is one the replica records and replays. */\n readonly durable: (message: Message) => boolean\n /** Whether a Message is one only the server appends: replicas replay it and never submit it. */\n readonly serverOnly: (message: Message) => boolean\n /**\n * Low-level wire codecs for adapters and the transport. Most applications use\n * `journalContract` and `openReplica`; these are exposed for a custom\n * transport or a server that must speak the operation envelope directly.\n */\n readonly codec: {\n /** The current version of the document's Message history: 1 with no migrations. */\n readonly messageVersion: number\n /** The document's Message at its current version: what every hook decodes. */\n readonly message: Schema.Codec<Message, unknown, never, never>\n /**\n * An entry someone sent, read: its Message upcast to the current version.\n * Throws `UnsupportedMessageVersionError` for a newer version,\n * `UnreadableMessageError` for an older one no step reads, and\n * `ServerOnlyMessageError` for a Message only the server appends; it\n * refuses a replica id under `server/` or past 128 characters. Read\n * stored history with `journalContract().operation.decode`, which takes\n * the server's Messages too.\n */\n readonly normalizeOperation: (input: unknown) => Operation\n /** `normalizeOperation`, of this document only. */\n readonly operationFrom: (input: unknown, documentId: DocumentId) => Operation\n /**\n * An entry as received, checked as an envelope of this document and read\n * as `normalizeOperation` reads it, and returned as written: what a server\n * appends. A custom server reads every entry with it before appending.\n * Never pass it an `Operation`: that Message is already current and would\n * be read as version 1. Write one with `journalContract().operation.encode`.\n */\n readonly writtenFrom: (input: unknown, documentId: DocumentId) => WrittenOperation\n readonly committedFrom: (\n input: unknown,\n documentId: DocumentId,\n ) => CommittedOperation & ReadAsHistory\n readonly decodeExchange: (input: unknown) => Exchange<Shared>\n }\n /** The codecs and pure reducer `foldkit-durable`'s `makeJournal` consumes. */\n readonly journalContract: () => JournalContract<Operation, Shared>\n /**\n * Opens the replica a store holds. Its id is the store's: read back, or minted\n * when the store is empty, so two stores never share one. In a browser the\n * store is `Sync.tabStorage(name)`, one per tab.\n */\n readonly openReplica: (\n storage: Storage,\n options?: OpenReplicaOptions,\n ) => Effect.Effect<Replica<Durable, Shared>, ReplicaError>\n}\n\nexport interface OpenReplicaOptions {\n /**\n * The id the store must hold, for a test asserting operation ids or a replica\n * a server names. It names one store, never a person: operation ids are\n * `replicaId:localSequence`, so two stores under one id (a person's second\n * browser) reuse ids the journal refuses.\n */\n readonly replicaId?: ReplicaId | undefined\n}\n\n/** Structural match for `foldkit-durable`'s journal options; Sync stays independent. */\nexport interface JournalContract<Operation, Shared> {\n /** The replica each operation came from, which Durable binds to its first committer. */\n readonly replicaId: (operation: Operation) => string\n /** Sync's operation id includes the replica, even after Durable compacts its payload. */\n readonly legacyReplicaId: (opId: string) => string\n readonly operation: {\n /** Written at the current version: what the journal stores. */\n readonly encode: (\n operation: Operation & { readonly '~foldkit-sync/history'?: never },\n ) => WrittenOperation\n /**\n * Read from any version the history has, upcast to the current one: stored\n * history, so the server's own Messages read too. Never the reader of an\n * entry someone sent (`codec.writtenFrom`).\n */\n readonly decode: (input: WrittenOperation) => Operation\n /**\n * What a retransmission is compared by: the operation normalized at the\n * version it was written at, as the build that wrote it normalized it, so\n * an edit committed before a deploy is still recognized after it. Only\n * hashed: never an entry to append.\n */\n readonly compared: (input: unknown) => unknown\n }\n readonly snapshot: {\n readonly encode: (snapshot: Shared) => unknown\n readonly decode: (input: unknown) => Shared\n }\n readonly empty: () => Shared\n readonly reduce: (snapshot: Shared, operation: Operation) => Shared\n /** Present when the definition stamps: Durable's `stamp`, over the operation's Message. */\n readonly stamp?: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ) => Operation\n}\n\n/**\n * Binds the replicated-state protocol to one application contract.\n *\n * The returned codecs decide what is a valid operation and what the shared\n * projection means; the replica owns the local outbox, optimistic projection,\n * and reconciliation as Effects, and never runs a second reducer.\n */\nexport const defineSync = <Message, Shared, MessageEncoded, SharedEncoded>(\n definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>,\n): Sync<Message, Shared> => {\n const documentId = definition.documentId\n const messages = definition.migrations ?? migrations(definition.message)\n const history = historyOf(messages as Migrations<unknown, unknown>)\n const current = history.version\n const decodeMessage = Schema.decodeUnknownSync(messages.current, { onExcessProperty: 'error' })\n const encodeMessage = Schema.encodeSync(messages.current)\n const decodeShared = Schema.decodeUnknownSync(definition.shared, { onExcessProperty: 'error' })\n const encodeShared = Schema.encodeSync(definition.shared)\n\n const ReplicaStateSchema = Schema.Struct({\n protocolVersion: Schema.Literal(PROTOCOL_VERSION),\n schemaVersion: Schema.Literal(SCHEMA_VERSION),\n documentId: DocumentId,\n replicaId: ReplicaId,\n revision: Schema.Number,\n nextLocalSequence: LocalSequence,\n cursor: Sequence,\n committed: definition.shared,\n committedIds: Schema.Array(Schema.String),\n pending: Schema.Array(WrittenOperationSchema),\n refused: Schema.optionalKey(Schema.Array(WrittenOperationSchema)),\n epoch: Schema.optionalKey(Schema.NonEmptyString),\n })\n const CheckpointSchema = Schema.Struct({ cursor: Sequence, model: definition.shared })\n const ExchangeSchema = Schema.Struct({\n operations: Schema.Array(Schema.Unknown),\n rejected: Schema.Array(OpId),\n // Each refusal is decoded on its own, when the rejection is read: one this\n // build cannot read must not fail the exchange that rejected its operation.\n refusals: Schema.optional(Schema.Array(Schema.Struct({ opId: OpId, refusal: Schema.Unknown }))),\n // A server's words for a person, bounded: a reply is not a place for a document.\n reasons: Schema.optional(\n Schema.Array(\n Schema.Struct({ opId: OpId, reason: Schema.String.check(Schema.isMaxLength(500)) }),\n ),\n ),\n acknowledged: Schema.optional(Schema.Array(OpId)),\n checkpoint: Schema.optional(CheckpointSchema),\n more: Schema.optional(Schema.Boolean),\n epoch: Schema.optional(Schema.NonEmptyString),\n })\n const decodeState = Schema.decodeUnknownSync(ReplicaStateSchema, { onExcessProperty: 'error' })\n const encodeState = Schema.encodeSync(ReplicaStateSchema)\n const encodeWritten = Schema.encodeSync(WrittenOperationSchema)\n const VersionProbe = Schema.Struct({\n protocolVersion: Schema.optional(Schema.Number),\n schemaVersion: Schema.optional(Schema.Number),\n })\n /**\n * Tells a version this build does not understand apart from malformed data,\n * so the caller gets an actionable failure and the stored state is preserved.\n */\n const unsupportedVersion = (input: unknown): UnsupportedReplicaVersionError | undefined => {\n let found: {\n readonly protocolVersion?: number | undefined\n readonly schemaVersion?: number | undefined\n }\n try {\n found = Schema.decodeUnknownSync(VersionProbe)(input)\n } catch {\n return undefined\n }\n if (found.protocolVersion === PROTOCOL_VERSION && found.schemaVersion === SCHEMA_VERSION)\n return undefined\n const protocolVersion = found.protocolVersion ?? null\n const schemaVersion = found.schemaVersion ?? null\n return new UnsupportedReplicaVersionError({\n protocolVersion,\n schemaVersion,\n message: `Stored replica uses protocol ${protocolVersion ?? '?'} / schema ${schemaVersion ?? '?'}; this build supports ${PROTOCOL_VERSION}/${SCHEMA_VERSION}`,\n })\n }\n const decodeExchange = (input: unknown): Exchange<Shared> =>\n Schema.decodeUnknownSync(ExchangeSchema, { onExcessProperty: 'error' })(\n input,\n ) as Exchange<Shared>\n\n const checkIdentity = (operation: Operation): void => {\n // `LocalSequence` already rejects a non-positive counter; this checks the\n // derived identity.\n if (operation.opId !== `${operation.replicaId}:${operation.localSequence}`) {\n throw new Error('Invalid operation identity')\n }\n }\n /**\n * An operation's Message, upcast to the current version and decoded. The\n * durable check runs on the current Message, so a step that maps an old\n * variant onto a local-only one is refused as that one is.\n */\n const newer = (opId: string, version: number) =>\n new UnsupportedMessageVersionError({\n opId,\n found: version,\n supported: current,\n message: `Operation ${opId} was written at Message version ${version}; this build reads up to ${current}`,\n })\n const serverOnly = definition.serverOnly ?? (() => false)\n /**\n * `sent` is an entry someone sent, which may carry only what a replica\n * submits; `history` is what the journal stored, the server's Messages too.\n */\n const messageOf = (operation: WrittenShape, kind: 'sent' | 'history'): Message => {\n const version = versionOf(operation)\n if (version > current) throw newer(operation.opId, version)\n let decoded: Message\n if (version === current) decoded = decodeMessage(operation.message)\n else\n try {\n decoded = decodeMessage(history.upcast(version, operation.message))\n } catch (cause) {\n throw new UnreadableMessageError({\n opId: operation.opId,\n version,\n message: `No step of the Message history reads operation ${operation.opId}, written at version ${version}`,\n cause,\n })\n }\n const durable = definition.durable(decoded)\n const server = serverOnly(decoded)\n if (durable && server)\n throw new AmbiguousMessageError({\n opId: operation.opId,\n message: `Operation ${operation.opId} carries a Message both durable and server-only`,\n })\n if (server && kind === 'sent')\n throw new ServerOnlyMessageError({\n opId: operation.opId,\n message: `Operation ${operation.opId} carries a Message only the server appends`,\n })\n if (!durable && !server) throw new Error('Message is local-only')\n return decoded\n }\n /** The envelope alone: the decoded side holds no version, only the current Message. */\n const envelopeOf = <O extends WrittenShape>({\n messageVersion: _,\n ...envelope\n }: O): Omit<O, 'messageVersion'> => envelope\n /** Written at the current version, which an explicit 1 is not. */\n const write = (operation: Operation): WrittenOperation => {\n const envelope = envelopeOf(operation)\n return vouched(current === 1 ? envelope : { ...envelope, messageVersion: current })\n }\n const assertDocument = <O extends WrittenShape>(operation: O, key: DocumentId): O => {\n if (operation.documentId !== key) throw new Error('Wrong document')\n return operation\n }\n /** What a sent entry may not name: the server's replica ids, or one past the bound. */\n const checkSentReplica = (operation: WrittenShape): void => {\n if (operation.replicaId.startsWith(SERVER_REPLICA_PREFIX))\n throw new Error('The replica id is reserved for the server')\n if (operation.replicaId.length > MAX_SENT_REPLICA_ID)\n throw new Error('The replica id is too long')\n }\n const read = (written: WrittenShape, kind: 'sent' | 'history'): Operation => {\n checkIdentity(written)\n if (kind === 'sent') checkSentReplica(written)\n return { ...envelopeOf(written), message: encodeMessage(messageOf(written, kind)) }\n }\n const normalizeOperation = (input: unknown): Operation => read(decodeWritten(input), 'sent')\n const operationFrom = (input: unknown, key: DocumentId): Operation =>\n read(assertDocument(decodeWritten(input), key), 'sent')\n const writtenFrom = (input: unknown, key: DocumentId): WrittenOperation => {\n const written = assertDocument(decodeWritten(input), key)\n // Read for its checks and discarded: what is appended is what was sent.\n read(written, 'sent')\n return written\n }\n /** Stored history: the server's Messages read, and a stored replica id of any length. */\n const readStored = (input: unknown): Operation => read(decodeWritten(input), 'history')\n /** An outbox entry this replica wrote: history, since it may predate a deploy that moved its variant. */\n const storedFrom = (input: unknown, key: DocumentId): Operation =>\n read(assertDocument(decodeWritten(input), key), 'history')\n /**\n * A committed operation arrives with its message already encoded, so decode it\n * once for the contract check and hand it to `replay` instead of decoding and\n * re-encoding it on the way.\n */\n const decodeCommittedOperation = (\n input: unknown,\n key: DocumentId,\n ): { readonly committed: CommittedOperation; readonly message: Message } => {\n const written = assertDocument(decodeCommittedWritten(input), key)\n checkIdentity(written)\n const message = messageOf(written, 'history')\n return { committed: { ...envelopeOf(written), message: encodeMessage(message) }, message }\n }\n const committedFrom = (input: unknown, key: DocumentId): CommittedOperation & ReadAsHistory =>\n decodeCommittedOperation(input, key).committed as CommittedOperation & ReadAsHistory\n /**\n * Normalized at the version it was written at, with no upcast: what the\n * build that wrote it hashed. An explicit `messageVersion: 1` is dropped,\n * so it and an absent one compare alike. Not branded: it skips the checks\n * of a sent entry, so it must never reach `append`.\n */\n const compared = (input: unknown): WrittenShape => {\n const written = decodeWritten(input)\n const version = versionOf(written)\n if (version > current) throw newer(written.opId, version)\n const envelope = envelopeOf(written)\n return {\n ...envelope,\n ...(version === 1 ? {} : { messageVersion: version }),\n message: history.normalize(version, written.message),\n }\n }\n\n const journalContract = (): JournalContract<Operation, Shared> => ({\n replicaId: operation => operation.replicaId,\n legacyReplicaId: opId => opId.slice(0, opId.lastIndexOf(':')),\n // Stored written at the current version; read from any version the history has.\n operation: { encode: write, decode: readStored, compared },\n snapshot: { encode: encodeShared, decode: decodeShared },\n empty: () => definition.empty,\n reduce: (snapshot, operation) => definition.replay(snapshot, decodeMessage(operation.message)),\n ...(definition.stamp === undefined\n ? {}\n : {\n stamp: (\n operation: Operation,\n commit: { readonly sequence: number; readonly actorId: string },\n ): Operation => ({\n ...operation,\n message: encodeMessage(\n definition.stamp!(decodeMessage(operation.message), {\n ...commit,\n replicaId: operation.replicaId,\n }),\n ),\n }),\n }),\n })\n\n /** `state` with `refused` set; the key is absent when none is, so such a state is as before. */\n const withRefused = (\n { refused: _, ...state }: ReplicaState<Shared>,\n refused: ReadonlyArray<WrittenOperation>,\n ): ReplicaState<Shared> => (refused.length === 0 ? state : { ...state, refused })\n\n const optimistic = (state: ReplicaState<Shared>): Shared =>\n state.pending.reduce(\n (model, operation) => definition.replay(model, messageOf(operation, 'history')),\n state.committed,\n )\n\n const openReplica = Effect.fn('Sync.openReplica')(\n function* (storage: Storage, options?: OpenReplicaOptions) {\n const saved = yield* storage.load()\n const initial: ReplicaState<Shared> = {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId: options?.replicaId ?? ReplicaId.make(crypto.randomUUID()),\n revision: 0,\n nextLocalSequence: localSequence(1),\n cursor: sequence(0),\n committed: definition.empty,\n committedIds: [],\n pending: [],\n }\n const state: ReplicaState<Shared> =\n saved === undefined\n ? initial\n : yield* Effect.try({\n try: () => decodeState(saved),\n catch: cause =>\n unsupportedVersion(saved) ??\n new InvalidReplicaHistoryError({\n message: 'Stored replica state is invalid',\n cause,\n }),\n })\n const replicaId = state.replicaId\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n if (\n state.documentId !== documentId ||\n (options?.replicaId !== undefined && replicaId !== options.replicaId)\n )\n return yield* new WrongReplicaStorageError({\n documentId,\n replicaId: options?.replicaId ?? replicaId,\n message: 'The stored replica belongs to a different document or replica',\n })\n const committedIds = new Set(state.committedIds)\n if (state.nextLocalSequence < 1 || committedIds.size !== state.committedIds.length)\n return yield* new InvalidReplicaHistoryError({ message: 'Invalid replica history' })\n const pendingIds = new Set<string>()\n // Written at an older version no step reads: refused by its id, kept as\n // written, so the rest of the outbox opens and sends.\n const unreadable = new Set<WrittenOperation>()\n for (const pending of state.pending) {\n if (\n pending.replicaId !== replicaId ||\n pending.localSequence >= state.nextLocalSequence ||\n committedIds.has(pending.opId) ||\n pendingIds.has(pending.opId)\n )\n return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n pendingIds.add(pending.opId)\n try {\n storedFrom(pending, documentId)\n } catch (cause) {\n // A newer build wrote it: nothing is removed, and that build reads it.\n if (cause instanceof UnsupportedMessageVersionError) return yield* cause\n if (cause instanceof UnreadableMessageError) unreadable.add(pending)\n else return yield* new InvalidOutboxError({ message: 'Invalid outbox' })\n }\n }\n // Storage holds the schema's encoded side, so a transforming `shared`\n // codec round-trips: decode on load, encode before every save. Encoding\n // also rejects an invalid `empty` on first creation rather than at reload.\n const store = Effect.fn('Sync.store')(function* (\n next: ReplicaState<Shared>,\n expectedRevision: number | null,\n ) {\n const encoded = yield* Effect.try({\n try: () => encodeState(next),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the replica state',\n cause,\n }),\n })\n yield* storage.save(encoded, expectedRevision)\n })\n if (saved === undefined) yield* store(state, null)\n // The one write an open makes, under the loaded revision: a tab that\n // opened the same store meanwhile fails it as a conflict.\n const opened: ReplicaState<Shared> =\n unreadable.size === 0\n ? state\n : withRefused(\n {\n ...state,\n revision: state.revision + 1,\n pending: state.pending.filter(operation => !unreadable.has(operation)),\n },\n [...(state.refused ?? []), ...unreadable],\n )\n if (opened !== state) yield* store(opened, state.revision)\n\n const stateRef = yield* SynchronizedRef.make(opened)\n const closed = yield* Ref.make(false)\n const lastError = yield* Ref.make<string | undefined>(undefined)\n const rejectedOps = yield* Ref.make<ReadonlyArray<Rejection>>([])\n // Operations submitted since opening that no exchange has carried yet. Only these may\n // be coalesced: one that was sent may already be committed as it was.\n const unsent = yield* Ref.make<ReadonlySet<string>>(new Set())\n // One pending wake-up is enough: the loop exchanges the whole outbox.\n const wake = yield* Queue.sliding<void>(1)\n const statusSignals = yield* PubSub.sliding<void>(1)\n // The current value, then again after every change. Subscribed before the\n // first read, so a change made while a subscriber holds that value, or\n // between the read and the subscription, is still told.\n const following = <A>(read: Effect.Effect<A>): Stream.Stream<A> =>\n Stream.unwrap(\n Effect.map(PubSub.subscribe(statusSignals), signals =>\n Stream.concat(\n Stream.fromEffect(read),\n Stream.fromSubscription(signals).pipe(Stream.mapEffect(() => read)),\n ),\n ),\n )\n // The projection is pure over an immutable state, so a cached value is\n // reused until a write replaces the state object. A UI reads `shared` far\n // more often than it writes, and replaying a large outbox per read is\n // quadratic (see `bench/projection.bench.ts`).\n const projection = yield* Ref.make<\n { readonly state: ReplicaState<Shared>; readonly shared: Shared } | undefined\n >(undefined)\n const snapshot = Effect.fn('Sync.snapshot')(function* () {\n const current = yield* SynchronizedRef.get(stateRef)\n const cached = yield* Ref.get(projection)\n let projected: Shared\n if (cached !== undefined && cached.state === current) projected = cached.shared\n else {\n projected = optimistic(current)\n yield* Ref.set(projection, { state: current, shared: projected })\n }\n return {\n status: {\n pending: current.pending.length,\n cursor: current.cursor,\n lastError: yield* Ref.get(lastError),\n rejected: yield* Ref.get(rejectedOps),\n refused: current.refused ?? [],\n epoch: Option.fromUndefinedOr(current.epoch),\n },\n shared: projected,\n committed: current.committed,\n nextLocalSequence: current.nextLocalSequence,\n }\n })()\n const shared = Effect.map(snapshot, value => value.shared)\n const status = Effect.map(snapshot, value => value.status)\n\n // `SynchronizedRef.modifyEffect` installs the returned state itself, so\n // persisting must not also set the ref (that would re-enter the lock).\n const persist = (next: ReplicaState<Shared>, current: ReplicaState<Shared>) =>\n store(next, current.revision)\n\n const submit = Effect.fn('Sync.submit')(function* (message: Message) {\n yield* Effect.annotateCurrentSpan({ documentId, replicaId })\n const result = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n if (serverOnly(message))\n return yield* new InvalidOutboxError({\n message: 'Message is one only the server appends',\n })\n if (!definition.durable(message))\n return yield* new InvalidOutboxError({ message: 'Message is local-only' })\n const last = current.pending[current.pending.length - 1]\n const merged =\n last !== undefined &&\n definition.coalesce !== undefined &&\n (yield* Ref.get(unsent)).has(last.opId)\n ? definition.coalesce(messageOf(last, 'history'), message)\n : undefined\n if (merged !== undefined && !definition.durable(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a local-only Message',\n })\n if (merged !== undefined && serverOnly(merged))\n return yield* new InvalidOutboxError({\n message: 'coalesce returned a Message only the server appends',\n })\n // A merged Message takes the place of the last operation, under its identity.\n const operation = yield* Effect.try({\n try: () =>\n write(\n storedFrom(\n write(\n merged === undefined\n ? {\n protocolVersion: PROTOCOL_VERSION,\n schemaVersion: SCHEMA_VERSION,\n documentId,\n replicaId,\n localSequence: current.nextLocalSequence,\n opId: OpId.make(`${replicaId}:${current.nextLocalSequence}`),\n baseCursor: current.cursor,\n message: encodeMessage(message),\n }\n : { ...envelopeOf(last!), message: encodeMessage(merged) },\n ),\n documentId,\n ),\n ),\n catch: () => new InvalidOutboxError({ message: 'Invalid outbox' }),\n })\n // Replay before writing: a Message replay refuses can never be\n // applied, here or on another replica, so it must not reach the\n // outbox. The result is the next optimistic projection, so the\n // cache is seeded instead of replaying the outbox on the next read.\n // Rebuilding the projection replays the outbox, which can throw\n // too (an upgrade that changed `update` for a pending Message), so\n // it sits inside the same typed error as the new Message's replay.\n const cached = yield* Ref.get(projection)\n const replayed = yield* Effect.try({\n try: () =>\n definition.replay(\n cached !== undefined && cached.state === current\n ? cached.shared\n : optimistic(current),\n message,\n ),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n // Validated and encoded by `persist`; decoding here would demand the\n // encoded side and break a transforming `shared` codec.\n // The sequence moves on a merge too, so every submit is visible in it; a gap\n // in local sequences is harmless.\n const next: ReplicaState<Shared> = {\n ...current,\n revision: current.revision + 1,\n nextLocalSequence: localSequence(current.nextLocalSequence + 1),\n pending: [\n ...(merged === undefined ? current.pending : current.pending.slice(0, -1)),\n operation,\n ],\n }\n // Only the new operation is written when the storage can append it.\n if (storage.append === undefined) yield* persist(next, current)\n else {\n const encoded = yield* Effect.try({\n try: () => encodeWritten(operation),\n catch: cause =>\n new InvalidReplicaHistoryError({\n message: 'Could not encode the operation',\n cause,\n }),\n })\n yield* storage.append(\n {\n revision: next.revision,\n nextLocalSequence: next.nextLocalSequence,\n localSequence: operation.localSequence,\n operation: encoded,\n },\n current.revision,\n )\n }\n yield* Ref.set(projection, { state: next, shared: replayed })\n yield* Ref.update(unsent, ids => new Set(ids).add(operation.opId))\n yield* Queue.offer(wake, undefined)\n return [undefined, next] as const\n }),\n )\n // Outside the lock, so a `statusChanges` subscriber reads the new state.\n yield* PubSub.publish(statusSignals, undefined)\n return result\n })\n\n /** One exchange; whether the server has more to send and this one made progress. */\n const exchangeOnce = Effect.fn('Sync.exchange')(function* () {\n yield* Effect.annotateCurrentSpan({ documentId })\n const transport = yield* Transport\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Read under the lock, as a submit writes, so no submit can merge into an operation\n // between its being read here and its being marked sent.\n const sent = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Ref.update(unsent, ids => {\n const left = new Set(ids)\n for (const operation of current.pending) left.delete(operation.opId)\n return left\n }).pipe(Effect.as([current, current] as const)),\n )\n yield* Metric.update(syncMetrics.exchanges, 1)\n yield* Metric.update(syncMetrics.exchangePending, sent.pending.length)\n const response = yield* Effect.gen(function* () {\n const raw = yield* transport.exchange(sent.cursor, sent.pending, sent.epoch)\n // The response is untrusted: a malformed shape is a typed failure, not\n // a defect that escapes the declared error channel.\n return yield* Effect.try({\n try: () => decodeExchange(raw),\n catch: cause =>\n new InvalidExchangeError({ message: 'Invalid sync exchange response', cause }),\n })\n })\n const { restarted, refusals } = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n // A `close` during the exchange must not persist its result.\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n // Another epoch means the server's history is not the one the cursor points\n // into (it was reset): the answer starts from its beginning, so the committed\n // state is rebuilt from it. The outbox is the user's intent and is kept.\n const restarted =\n response.epoch !== undefined &&\n current.epoch !== undefined &&\n response.epoch !== current.epoch\n if (restarted) yield* Diagnostics.report(historyRebuilt(documentId, replicaId))\n let cursor = restarted ? sequence(0) : current.cursor\n let committed = restarted ? definition.empty : current.committed\n // A checkpoint folds committed history into its snapshot, so the\n // retained id set starts over from it, as it does on a new epoch.\n const ids =\n response.checkpoint === undefined && !restarted\n ? new Set(current.committedIds)\n : new Set<string>()\n if (response.checkpoint !== undefined) {\n if (response.checkpoint.cursor < cursor)\n return yield* new CheckpointRegressionError({\n cursor,\n checkpointCursor: response.checkpoint.cursor,\n message: 'Checkpoint is behind the replica',\n })\n committed = response.checkpoint.model\n cursor = response.checkpoint.cursor\n yield* Metric.update(syncMetrics.checkpoints, 1)\n yield* Effect.logDebug('sync checkpoint adopted', { documentId, replicaId, cursor })\n }\n const acknowledged = new Set(response.acknowledged ?? [])\n const rejected = new Set(response.rejected)\n const sentIds = new Set(sent.pending.map(operation => operation.opId))\n for (const id of acknowledged)\n if (!sentIds.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server acknowledged an operation that was not sent',\n })\n for (const id of rejected) {\n if (!sentIds.has(id))\n return yield* new ForeignRejectionError({\n opId: id,\n message: 'Server rejected an operation that was not sent',\n })\n // An id cannot be both; removal would be ambiguous and a faulty\n // server must not be able to make a pending operation vanish.\n if (acknowledged.has(id))\n return yield* new ForeignAcknowledgementError({\n opId: id,\n message: 'Server both acknowledged and rejected an operation',\n })\n }\n for (const { opId } of [...(response.refusals ?? []), ...(response.reasons ?? [])])\n if (!rejected.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave a reason for an operation it did not reject',\n })\n // One each, so there are no more to decode than operations it rejected.\n const refusing = new Set<string>()\n for (const { opId } of response.refusals ?? []) {\n if (refusing.has(opId))\n return yield* new ForeignRejectionError({\n opId,\n message: 'Server gave two refusals for one operation',\n })\n refusing.add(opId)\n }\n const refusals = (response.refusals ?? []).map(\n ({ opId, refusal }) => [opId, decodeRefusal(refusal)] as const,\n )\n // What the server could not read is kept, as this build cannot either\n // once their chains agree: never sent again, never lost.\n const unreadableIds = new Set(\n refusals.flatMap(([opId, refusal]) =>\n Result.match(refusal, {\n onFailure: (): ReadonlyArray<OpId> => [],\n onSuccess: SyncRefusal.match({\n Forbidden: (): ReadonlyArray<OpId> => [],\n Invalid: () => [],\n Unreadable: () => [opId],\n }),\n }),\n ),\n )\n let applied = 0\n for (const raw of response.operations) {\n const { committed: operation, message } = yield* Effect.try({\n try: () => decodeCommittedOperation(raw, documentId),\n catch: cause =>\n cause instanceof UnsupportedMessageVersionError\n ? cause\n : new InvalidReplicaHistoryError({\n message: 'Invalid committed operation',\n cause,\n }),\n })\n if (operation.serverSequence <= cursor) continue\n if (operation.serverSequence !== cursor + 1 || ids.has(operation.opId))\n return yield* new CommittedOrderError({\n expected: cursor + 1,\n actual: operation.serverSequence,\n message: 'Invalid committed order',\n })\n // A throw here would be a defect, which bypasses `lastError` and leaves\n // `start` retrying the same page in silence.\n const replaying = committed\n committed = yield* Effect.try({\n try: () => definition.replay(replaying, message),\n catch: cause =>\n new ReplayError({\n message: cause instanceof Error ? cause.message : 'Replay failed',\n cause,\n }),\n })\n ids.add(operation.opId)\n cursor = operation.serverSequence\n applied += 1\n }\n if (applied > 0) yield* Metric.update(syncMetrics.applied, applied)\n // Validated and encoded by `persist`, for the same reason as submit.\n const epoch = response.epoch ?? current.epoch\n const next = withRefused(\n {\n ...current,\n revision: current.revision + 1,\n committed,\n cursor,\n ...(epoch === undefined ? {} : { epoch }),\n committedIds: [...ids].slice(-COMMITTED_ID_WINDOW),\n // While the server has more to send, an acknowledged operation's committed\n // copy may be on a later page, so it stays in the optimistic view until then.\n // An acknowledged operation the replica is already past (committed before a\n // checkpoint, say) never arrives, so it goes once there is no more to read.\n pending: current.pending.filter(\n operation =>\n !ids.has(operation.opId) &&\n !(acknowledged.has(operation.opId) && response.more !== true) &&\n !rejected.has(operation.opId),\n ),\n },\n [\n ...(current.refused ?? []),\n // A refusal names only a rejected id (anything else failed the\n // exchange above), so what moves here has left `pending`.\n ...current.pending.filter(operation => unreadableIds.has(operation.opId)),\n ],\n )\n yield* persist(next, current)\n return [{ restarted, refusals }, next] as const\n }),\n )\n yield* Ref.set(lastError, undefined)\n if (response.rejected.length > 0) {\n const reasonOf = new Map(\n (response.reasons ?? []).map(({ opId, reason }) => [opId, reason] as const),\n )\n const refusalOf = new Map<string, SyncRefusal>()\n for (const [opId, decoded] of refusals) {\n if (Result.isSuccess(decoded)) refusalOf.set(opId, decoded.success)\n else\n yield* Diagnostics.report(\n unknownRefusal(documentId, replicaId, opId, fitWords(decoded.failure.message)),\n )\n }\n // Every rejected id was sent: an unknown one failed the exchange above.\n const sentOf = new Map(\n sent.pending.map(operation => [operation.opId, operation] as const),\n )\n // Every pending operation reads: one that did not was refused on open.\n const refused = response.rejected.map((opId): Rejection => {\n const operation = sentOf.get(opId)!\n return {\n opId,\n refusal: Option.fromUndefinedOr(refusalOf.get(opId)),\n reason: Option.fromUndefinedOr(reasonOf.get(opId)),\n operation,\n message: encodeMessage(messageOf(operation, 'history')),\n }\n })\n yield* Ref.update(rejectedOps, previous => [...refused, ...previous].slice(0, 32))\n }\n yield* PubSub.publish(statusSignals, undefined)\n const reached = (yield* SynchronizedRef.get(stateRef)).cursor\n return response.more === true && reached > (restarted ? 0 : sent.cursor)\n })\n\n // A server that pages its answer says there is more, and the replica asks again at\n // once; a round that moves the cursor nowhere ends it.\n const synchronize = Effect.gen(function* () {\n while (yield* exchangeOnce()) {}\n }).pipe(\n Effect.withSpan('Sync.synchronize'),\n // Any failed exchange, a refused response included, is what a UI shows,\n // so it is recorded and announced rather than left for the next submit.\n Effect.tapError(error =>\n Effect.gen(function* () {\n yield* Diagnostics.report(exchangeFailed(documentId, replicaId, error))\n yield* Ref.set(lastError, error.message)\n yield* PubSub.publish(statusSignals, undefined)\n }),\n ),\n )\n\n const start: Effect.Effect<void, never, Transport> = Effect.gen(function* () {\n const transport = yield* Transport\n // A server's notice wakes the loop as a submit does; the fiber ends with this one.\n // It starts at once so it is subscribed before the first exchange, which a\n // notice may arrive during.\n if (transport.changes !== undefined)\n yield* Effect.forkChild(\n Stream.runForEach(transport.changes, () => Queue.offer(wake, undefined)),\n { startImmediately: true },\n )\n let failures = 0\n while (!(yield* Ref.get(closed))) {\n const exit = yield* Effect.exit(synchronize)\n if (yield* Ref.get(closed)) return\n yield* Exit.match(exit, {\n onSuccess: () => {\n failures = 0\n return Queue.take(wake)\n },\n onFailure: () => {\n // Retried on a backoff, or sooner on a submit: an outbox must not\n // wait for the next keystroke to be delivered.\n failures += 1\n const backoff = Math.min(\n START_RETRY_MAX,\n START_RETRY_BASE * 2 ** Math.min(failures - 1, 16),\n )\n return Effect.raceFirst(Queue.take(wake), Effect.sleep(backoff))\n },\n })\n }\n })\n\n const dismiss = Effect.fn('Sync.dismiss')(function* (opId: OpId) {\n const dismissed = yield* SynchronizedRef.modifyEffect(stateRef, current =>\n Effect.gen(function* () {\n if (yield* Ref.get(closed))\n return yield* new ReplicaClosedError({ message: 'Replica is closed' })\n const refused = current.refused ?? []\n const left = refused.filter(operation => operation.opId !== opId)\n if (left.length === refused.length) return [false, current] as const\n const next = withRefused({ ...current, revision: current.revision + 1 }, left)\n yield* persist(next, current)\n return [true, next] as const\n }),\n )\n if (dismissed) yield* PubSub.publish(statusSignals, undefined)\n })\n\n return {\n replicaId,\n shared,\n snapshot,\n committed: Effect.map(SynchronizedRef.get(stateRef), state => state.committed),\n pending: Effect.map(SynchronizedRef.get(stateRef), state => state.pending),\n cursor: Effect.map(SynchronizedRef.get(stateRef), state => state.cursor),\n status,\n statusChanges: following(status),\n changes: following(snapshot),\n submit,\n synchronize,\n start,\n dismiss,\n close: Effect.fn('Sync.close')(function* () {\n yield* Ref.set(closed, true)\n // Wake `start` so it can observe `closed` and return.\n yield* Queue.offer(wake, undefined)\n yield* storage.close\n })(),\n }\n },\n (effect, storage) =>\n // Close a partially initialized storage on any failure, including a\n // defect, so a failed open cannot leak the connection.\n effect.pipe(\n Effect.onExit(exit =>\n Exit.isSuccess(exit) ? Effect.void : storage.close.pipe(Effect.ignore),\n ),\n ),\n )\n\n return {\n documentId,\n durable: definition.durable,\n serverOnly,\n codec: {\n messageVersion: current,\n message: messages.current as Schema.Codec<Message, unknown, never, never>,\n normalizeOperation,\n operationFrom,\n writtenFrom,\n committedFrom,\n decodeExchange,\n },\n journalContract,\n openReplica,\n }\n}\n"],"mappings":";;;;;;;;;;AAgDA,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;;;;;;AAOvB,MAAa,wBAAwB;;AAErC,MAAM,sBAAsB;;;;;AAM5B,MAAM,kBAAkB,OAAO,OAAO;CACpC,iBAAiB,OAAO,QAAQ,gBAAgB;CAChD,eAAe,OAAO,QAAQ,cAAc;CAC5C,YAAY;CACZ,WAAW;CACX,eAAe;CACf,MAAM;CACN,YAAY;CACZ,SAAS,OAAO;AAClB,CAAC;;;;;;;AASD,MAAM,gBAAgB,OAAO,OAAO;CAClC,GAAG,gBAAgB;CACnB,gBAAgB,OAAO,YAAY,OAAO,IAAI,MAAM,OAAO,uBAAuB,CAAC,CAAC,CAAC;AACvF,CAAC;;;;;;;AASD,MAAM,yBAAyB,cAAc,KAAK,OAAO,MAAM,+BAA+B,CAAC;;AAG/F,MAAM,WAAW,cAA8C;AAE/D,MAAM,kBAAkB;CACtB,gBAAgB,SAAS,MAAM,OAAO,uBAAuB,CAAC,CAAC;CAC/D,SAAS,OAAO;AAClB;AAEwB,OAAO,OAAO;CAAE,GAAG,gBAAgB;CAAQ,GAAG;AAAgB,CAAC;;AAYvF,MAAM,yBAAyB,OAAO,OAAO;CAC3C,GAAG,cAAc;CACjB,GAAG;AACL,CAAC;AAED,MAAM,gBAAgB,OAAO,kBAAkB,wBAAwB,EACrE,kBAAkB,QACpB,CAAC;;;;;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AC7E,OAAO,QAAQ,MAAM,OAAO;IAC5B,OAAO,CAAC,MAAM,IAAI;GACpB,CAAC,CACH,GACe,OAAO,OAAO,QAAQ,eAAe,KAAA,CAAS;EAC/D,CAAC;EAED,OAAO;GACL;GACA;GACA;GACA,WAAW,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,SAAS;GAC7E,SAAS,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,OAAO;GACzE,QAAQ,OAAO,IAAI,gBAAgB,IAAI,QAAQ,IAAG,UAAS,MAAM,MAAM;GACvE;GACA,eAAe,UAAU,MAAM;GAC/B,SAAS,UAAU,QAAQ;GAC3B;GACA;GACA;GACA;GACA,OAAO,OAAO,GAAG,YAAY,CAAC,CAAC,aAAa;IAC1C,OAAO,IAAI,IAAI,QAAQ,IAAI;IAE3B,OAAO,MAAM,MAAM,MAAM,KAAA,CAAS;IAClC,OAAO,QAAQ;GACjB,CAAC,CAAC,CAAC;EACL;CACF,IACC,QAAQ,YAGP,OAAO,KACL,OAAO,QAAO,SACZ,KAAK,UAAU,IAAI,IAAI,OAAO,OAAO,QAAQ,MAAM,KAAK,OAAO,MAAM,CACvE,CACF,CACJ;CAEA,OAAO;EACL;EACA,SAAS,WAAW;EACpB;EACA,OAAO;GACL,gBAAgB;GAChB,SAAS,SAAS;GAClB;GACA;GACA;GACA;GACA;EACF;EACA;EACA;CACF;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { Context, Duration, Effect, Layer, Schema, Stream } from "effect";
2
- import { TransportClient, WrittenOperation } from "./sync.js";
2
+ import { TransportClient } from "./sync.js";
3
3
  declare const TransportError_base: Schema.Class<TransportError, Schema.TaggedStruct<"SyncTransportError", {
4
4
  readonly message: Schema.String;
5
5
  }>, import("effect/Cause").YieldableError>;
@@ -9,7 +9,7 @@ export declare class TransportError extends TransportError_base {}
9
9
  export interface ExchangeFrame {
10
10
  readonly id: string;
11
11
  readonly cursor: number;
12
- readonly pending: ReadonlyArray<WrittenOperation>;
12
+ readonly pending: ReadonlyArray<unknown>;
13
13
  readonly epoch?: string | undefined;
14
14
  }
15
15
  export interface ExchangeReply {
@@ -26,8 +26,12 @@ export interface NotifyFrame {
26
26
  readonly notify: true;
27
27
  }
28
28
  export interface TransportShape {
29
- /** `epoch` is the server history the replica's cursor points into, when it knows one. */
30
- readonly exchange: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => Effect.Effect<unknown, TransportError>;
29
+ /**
30
+ * `epoch` is the server history the replica's cursor points into, when it
31
+ * knows one. `pending` is unread: whoever answers reads each entry with
32
+ * `codec.writtenFrom` before appending it.
33
+ */
34
+ readonly exchange: (cursor: number, pending: ReadonlyArray<unknown>, epoch?: string | undefined) => Effect.Effect<unknown, TransportError>;
31
35
  /**
32
36
  * Emits when the server may have something new, for a transport that can hear
33
37
  * it: `Replica.start` exchanges on each. A wake-up, not data.
@@ -53,7 +57,7 @@ declare const TransportSocket_base: Context.ServiceClass<TransportSocket, "foldk
53
57
  */
54
58
  export declare class TransportSocket extends TransportSocket_base {}
55
59
  /** A transport backed by an in-process handler, for tests and single-process demos. */
56
- export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => unknown | Promise<unknown>) => Layer.Layer<Transport>;
60
+ export declare const layerLoopback: (handler: (cursor: number, pending: ReadonlyArray<unknown>, epoch?: string | undefined) => unknown | Promise<unknown>) => Layer.Layer<Transport>;
57
61
  /** Wraps the promise-based client the replica already speaks. */
58
62
  export declare const layerFromPromise: (transport: TransportClient) => Layer.Layer<Transport>;
59
63
  /** Bridges the service back to the promise client the replica consumes. */
@@ -68,7 +72,7 @@ export declare const toPromise: (transport: TransportShape) => TransportClient;
68
72
  * Returns a function that stops serving.
69
73
  */
70
74
  export declare const serveSocket: (socket: SocketLike, options: {
71
- readonly exchange: (cursor: number, pending: ReadonlyArray<WrittenOperation>, epoch?: string | undefined) => unknown | Promise<unknown>;
75
+ readonly exchange: (cursor: number, pending: ReadonlyArray<unknown>, epoch?: string | undefined) => unknown | Promise<unknown>;
72
76
  /** Subscribes to the document's commits; returns the unsubscribe. */
73
77
  readonly changes?: ((listener: () => void) => () => void) | undefined;
74
78
  }) => (() => void);
@@ -1 +1 @@
1
- {"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":";;;;;;qBAOa,uBAAuB;;iBAKnB;WACN;WACA;WACA,SAAS,cAAc;WACvB;;iBAGM;WACN;WACA;WACA;;;;;;;iBAQM;WACN;;iBAGM;;WAEN,WACP,gBACA,SAAS,cAAc,mBACvB,+BACG,OAAO,gBAAgB;;;;;WAKnB,UAAU,OAAO;;;;;;;;;;qBAUf,kBAAkB;;;;;;;;;qBAWlB,wBAAwB;;qBAQxB,gBAAa,UAEtB,gBACA,SAAS,cAAc,mBACvB,yCACa,qBACd,MAAM,MAAM;;qBAUF,mBAAgB,WAAe,oBAAkB,MAAM,MAAM;;qBAU7D,YAAS,WAAe,mBAAiB;;;;;;;;;;qBAczC,cAAW,QACd,YAAU;WAEP,WACP,gBACA,SAAS,cAAc,mBACvB,yCACa;;WAEN,YAAY;;;iBAgER;EACf,KAAK;EACL;EACA,UAAU,WAAW;EACrB,QAAQ;;;;;EAKR,QAAQ;;;;;;;YAQE,gBAAgB;WAEX;WAAsB;;WACtB,kBAAkB;WAAqB;;UAG9C;;;;;;WAMC;;WAEA,YAAY,SAAS;;WAErB,gBAAgB,SAAS;;WAEzB;;;qBAIE,eAAY,gBAAkB;;;;;;;;qBAiC9B,aAAU,MACf,aAAW;WACG,SAAS;MAC5B;;;;;;;;qBAwCU,eAAY,QAAY,cAAY;;;;;;;;;;;;;;;;;qBAuEpC,cAAW,SACb,kBACR,MAAM,MAAM,YAAY,iBAAiB"}
1
+ {"version":3,"file":"transport.d.ts","names":[],"sources":["../src/transport.ts"],"mappings":";;;;;;qBAOa,uBAAuB;;iBAKnB;WACN;WACA;WACA,SAAS;WACT;;iBAGM;WACN;WACA;WACA;;;;;;;iBAQM;WACN;;iBAGM;;;;;;WAMN,WACP,gBACA,SAAS,wBACT,+BACG,OAAO,gBAAgB;;;;;WAKnB,UAAU,OAAO;;;;;;;;;;qBAUf,kBAAkB;;;;;;;;;qBAWlB,wBAAwB;;qBAQxB,gBAAa,UAEtB,gBACA,SAAS,wBACT,yCACa,qBACd,MAAM,MAAM;;qBAUF,mBAAgB,WAAe,oBAAkB,MAAM,MAAM;;qBAU7D,YAAS,WAAe,mBAAiB;;;;;;;;;;qBAczC,cAAW,QACd,YAAU;WAEP,WACP,gBACA,SAAS,wBACT,yCACa;;WAEN,YAAY;;;iBAgER;EACf,KAAK;EACL;EACA,UAAU,WAAW;EACrB,QAAQ;;;;;EAKR,QAAQ;;;;;;;YAQE,gBAAgB;WAEX;WAAsB;;WACtB,kBAAkB;WAAqB;;UAG9C;;;;;;WAMC;;WAEA,YAAY,SAAS;;WAErB,gBAAgB,SAAS;;WAEzB;;;qBAIE,eAAY,gBAAkB;;;;;;;;qBAiC9B,aAAU,MACf,aAAW;WACG,SAAS;MAC5B;;;;;;;;qBAwCU,eAAY,QAAY,cAAY;;;;;;;;;;;;;;;;;qBAuEpC,cAAW,SACb,kBACR,MAAM,MAAM,YAAY,iBAAiB"}
@@ -1 +1 @@
1
- {"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { TransportClient, WrittenOperation } from './sync.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { listenerFailed } from './diagnostics.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<WrittenOperation>\n readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /** `epoch` is the server history the replica's cursor points into, when it knows one. */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\n/**\n * The connection `layerSocket` keeps, for another protocol to share, such as\n * presence: a send goes to the socket open now and is dropped while none is,\n * and messages from every socket the transport opens arrive here. It is the\n * transport's to close. Only a socket transport provides it, so a layer that\n * has one says so in its type.\n */\nexport class TransportSocket extends Context.Service<TransportSocket, SocketLike>()(\n 'foldkit-sync/TransportSocket',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result, or\n * throws and the failure is written back as an error frame. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<WrittenOperation>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending) ||\n (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending: pending as ReadonlyArray<WrittenOperation>,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\n send({ id: frame.id, result })\n } catch (error) {\n send({ id: frame.id, error: error instanceof Error ? error.message : String(error) })\n }\n })()\n })\n const stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (\n options: SocketOptions,\n): Layer.Layer<Transport | TransportSocket, TransportError> =>\n Layer.effectContext(\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n // Listeners run in a socket's callback, outside any Effect: their\n // failures go to the reporter this layer was built with.\n const reporter = yield* Effect.service(Diagnostics.Reporter)\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<WrittenOperation>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch (thrown) {\n Effect.runFork(\n Diagnostics.report(listenerFailed('Socket', thrown)).pipe(\n Effect.provideService(Diagnostics.Reporter, reporter),\n ),\n )\n }\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(new TransportError({ message: reply.error })),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\n }\n }),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n const transport = Transport.of({\n changes: Stream.fromPubSub(notices),\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFlight.delete(entry.id)\n })\n }),\n })\n return Context.make(Transport, transport).pipe(Context.add(TransportSocket, shared))\n })(),\n )\n"],"mappings":";;;;;;AAOA,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,sBAAsB,EAC7F,SAAS,OAAO,OAClB,CAAC,CAAC,CAAC,CAAC;;;;;;;;AA8CJ,IAAa,YAAb,cAA+B,QAAQ,QAAmC,CAAC,CACzE,wBACF,CAAC,CAAC,CAAC;;;;;;;;AASH,IAAa,kBAAb,cAAqC,QAAQ,QAAqC,CAAC,CACjF,8BACF,CAAC,CAAC,CAAC;AAEH,MAAM,WAAW,UACf,IAAI,eAAe,EAAE,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,EAAE,CAAC;;AAGxF,MAAa,iBACX,YAMA,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW;CAChB,WAAW,QAAQ,QAAQ,QAAQ,QAAQ,SAAS,KAAK,CAAC;CAC1D,OAAO;AACT,CAAC,EACL,CAAC;;AAGH,MAAa,oBAAoB,cAC/B,MAAM,QAAQ,WAAW,EACvB,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW;CAChB,WAAW,UAAU,SAAS,SAAS,MAAM,GAAG,SAAS,KAAK;CAC9D,OAAO;AACT,CAAC,EACL,CAAC;;AAGH,MAAa,aAAa,eAAgD,EACxE,WAAW,QAAQ,SAAS,UAC1B,OAAO,WAAW,UAAU,SAAS,QAAQ,SAAS,KAAK,CAAC,EAChE;;;;;;;;;;A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K,IAAI,eAAe,EAAE,SAAS,uBAAuB,CAAC,CAAC,CAAC;IAC3E;GACF;GACA,MAAM,QAAe;IAAE,IAAI,OAAO,QAAQ;IAAG;IAAQ;IAAS;IAAO;GAAO;GAC5E,IAAI,OAAO,KAAK,KAAK;QAChB,OAAO,KAAK,KAAK;GAKtB,OAAO,OAAO,WAAW;IACvB,MAAM,cAAc,OAAO,QAAQ,KAAK;IACxC,IAAI,eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;CACD,OAAO,QAAQ,KAAK,WAAW,SAAS,CAAC,CAAC,KAAK,QAAQ,IAAI,iBAAiB,MAAM,CAAC;AACrF,CAAC,CAAC,CAAC,CACL"}
1
+ {"version":3,"file":"transport.js","names":[],"sources":["../src/transport.ts"],"sourcesContent":["import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { TransportClient } from './sync.js'\nimport { Diagnostics } from 'foldkit-surface'\nimport { listenerFailed } from './diagnostics.js'\n\n/** The wire failure of a transport. A refusal is a result, not an error. */\nexport class TransportError extends Schema.TaggedError<TransportError>()('SyncTransportError', {\n message: Schema.String,\n}) {}\n\n/** One request/response frame, as it crosses a wire. */\nexport interface ExchangeFrame {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<unknown>\n readonly epoch?: string | undefined\n}\n\nexport interface ExchangeReply {\n readonly id: string\n readonly result?: unknown\n readonly error?: string\n}\n\n/**\n * Sent by a server, unasked, when the document may have changed. It carries no\n * data: the replica exchanges from its own cursor, so a notice that is lost,\n * late, or one of many is harmless.\n */\nexport interface NotifyFrame {\n readonly notify: true\n}\n\nexport interface TransportShape {\n /**\n * `epoch` is the server history the replica's cursor points into, when it\n * knows one. `pending` is unread: whoever answers reads each entry with\n * `codec.writtenFrom` before appending it.\n */\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<unknown>,\n epoch?: string | undefined,\n ) => Effect.Effect<unknown, TransportError>\n /**\n * Emits when the server may have something new, for a transport that can hear\n * it: `Replica.start` exchanges on each. A wake-up, not data.\n */\n readonly changes?: Stream.Stream<void> | undefined\n}\n\n/**\n * The seam the replica syncs through.\n *\n * A service, not a concrete client, so an application substitutes an in-process\n * transport, a socket, or a test double without the replica knowing. A refusal\n * arrives in the exchange result; only a wire failure is a `TransportError`.\n */\nexport class Transport extends Context.Service<Transport, TransportShape>()(\n 'foldkit-sync/Transport',\n) {}\n\n/**\n * The connection `layerSocket` keeps, for another protocol to share, such as\n * presence: a send goes to the socket open now and is dropped while none is,\n * and messages from every socket the transport opens arrive here. It is the\n * transport's to close. Only a socket transport provides it, so a layer that\n * has one says so in its type.\n */\nexport class TransportSocket extends Context.Service<TransportSocket, SocketLike>()(\n 'foldkit-sync/TransportSocket',\n) {}\n\nconst failure = (error: unknown): TransportError =>\n new TransportError({ message: error instanceof Error ? error.message : String(error) })\n\n/** A transport backed by an in-process handler, for tests and single-process demos. */\nexport const layerLoopback = (\n handler: (\n cursor: number,\n pending: ReadonlyArray<unknown>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>,\n): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => Promise.resolve(handler(cursor, pending, epoch)),\n catch: failure,\n }),\n })\n\n/** Wraps the promise-based client the replica already speaks. */\nexport const layerFromPromise = (transport: TransportClient): Layer.Layer<Transport> =>\n Layer.succeed(Transport, {\n exchange: (cursor, pending, epoch) =>\n Effect.tryPromise({\n try: () => transport.exchange(sequence(cursor), pending, epoch),\n catch: failure,\n }),\n })\n\n/** Bridges the service back to the promise client the replica consumes. */\nexport const toPromise = (transport: TransportShape): TransportClient => ({\n exchange: (cursor, pending, epoch) =>\n Effect.runPromise(transport.exchange(cursor, pending, epoch)),\n})\n\n/**\n * Serves one accepted socket, answering each exchange frame.\n *\n * The counterpart to `layerSocket`: the handler returns the exchange result, or\n * throws and the failure is written back as an error frame. With `changes`, a\n * subscription to the document's commits, the socket is also sent a\n * `NotifyFrame` after each, so a client hears of others' edits without polling.\n * Returns a function that stops serving.\n */\nexport const serveSocket = (\n socket: SocketLike,\n options: {\n readonly exchange: (\n cursor: number,\n pending: ReadonlyArray<unknown>,\n epoch?: string | undefined,\n ) => unknown | Promise<unknown>\n /** Subscribes to the document's commits; returns the unsubscribe. */\n readonly changes?: ((listener: () => void) => () => void) | undefined\n },\n): (() => void) => {\n const send = (reply: ExchangeReply | NotifyFrame): void => {\n try {\n socket.send(JSON.stringify(reply))\n } catch {\n // The socket may have closed while the handler was running.\n }\n }\n const stopMessage = socket.onMessage(data => {\n let parsed: unknown\n try {\n parsed = JSON.parse(data)\n } catch {\n return\n }\n if (typeof parsed !== 'object' || parsed === null) return\n const { id, cursor, pending, epoch } = parsed as {\n id?: unknown\n cursor?: unknown\n pending?: unknown\n epoch?: unknown\n }\n // Without an id there is nobody to answer, so drop the frame.\n if (typeof id !== 'string') return\n if (\n typeof cursor !== 'number' ||\n !Number.isSafeInteger(cursor) ||\n cursor < 0 ||\n !Array.isArray(pending) ||\n (epoch !== undefined && typeof epoch !== 'string')\n ) {\n send({ id, error: 'Invalid exchange frame' })\n return\n }\n const frame: ExchangeFrame = {\n id,\n cursor,\n pending,\n epoch: typeof epoch === 'string' ? epoch : undefined,\n }\n void (async () => {\n try {\n const result = await options.exchange(frame.cursor, frame.pending, frame.epoch)\n send({ id: frame.id, result })\n } catch (error) {\n send({ id: frame.id, error: error instanceof Error ? error.message : String(error) })\n }\n })()\n })\n const stopChanges = options.changes?.(() => send({ notify: true }))\n const stop = (): void => {\n stopMessage()\n stopChanges?.()\n }\n const stopClose = socket.onClose(stop)\n return () => {\n stop()\n stopClose()\n }\n}\n\n/** The minimal socket the layer needs; the global `WebSocket` satisfies it. */\nexport interface SocketLike {\n send(data: string): void\n close(): void\n onMessage(listener: (data: string) => void): () => void\n onClose(listener: () => void): () => void\n /**\n * Optional. When provided, exchanges wait for it before sending, so a\n * transport can connect asynchronously. Absent means already connected.\n */\n onOpen?(listener: () => void): () => void\n}\n\n/**\n * Where `layerSocket` connects: a `url` for the platform `WebSocket`, or a\n * `makeSocket` that opens any other `SocketLike` (a port, a test socket), called\n * again on every reconnect.\n */\nexport type SocketOptions = SocketTuning &\n (\n | { readonly url: string; readonly makeSocket?: undefined }\n | { readonly makeSocket: () => SocketLike; readonly url?: undefined }\n )\n\ninterface SocketTuning {\n /**\n * Consecutive failed connections after which queued work fails and new\n * exchanges fail fast until a connection is healthy again. Reconnecting goes\n * on regardless. Default 5.\n */\n readonly maxRetries?: number | undefined\n /** Base delay of the exponential reconnect backoff. Default `50 millis`. */\n readonly retryBase?: Duration.Input | undefined\n /** Longest wait between reconnect attempts. Default `5 seconds`. */\n readonly maxRetryDelay?: Duration.Input | undefined\n /** Exchanges queued or in flight before new ones fail. Default 64. */\n readonly maxQueue?: number | undefined\n}\n\n/** The default socket factory: the platform `WebSocket`, as a `SocketLike`. */\nexport const nativeSocket = (url: string): SocketLike => {\n const socket = new WebSocket(url)\n return {\n send: data => socket.send(data),\n close: () => socket.close(),\n onOpen: listener => {\n if (socket.readyState === WebSocket.OPEN) {\n listener()\n return () => {}\n }\n socket.addEventListener('open', listener)\n return () => socket.removeEventListener('open', listener)\n },\n onMessage: listener => {\n const handler = (event: MessageEvent): void => listener(String(event.data))\n socket.addEventListener('message', handler)\n return () => socket.removeEventListener('message', handler)\n },\n onClose: listener => {\n const handler = (): void => listener()\n socket.addEventListener('close', handler)\n return () => socket.removeEventListener('close', handler)\n },\n }\n}\n\n/**\n * A socket over a `MessagePort`, for either end: its frames are the port's\n * string messages, and anything else on the port is ignored. A port tells\n * neither end when the other goes, so `onClose` fires once, on `close()` or\n * when `signal` aborts; a host that serves a pane aborts it when the pane is\n * gone, which stops `serveSocket` and anything else listening.\n */\nexport const portSocket = (\n port: MessagePort,\n options: { readonly signal?: AbortSignal | undefined } = {},\n): SocketLike => {\n const closeListeners = new Set<() => void>()\n let closed = false\n const close = (): void => {\n closed = true\n port.close()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n options.signal?.addEventListener('abort', close, { once: true })\n if (options.signal?.aborted === true) close()\n port.start()\n return {\n send: data => port.postMessage(data),\n close,\n onMessage: listener => {\n const handler = (event: MessageEvent): void => {\n if (typeof event.data === 'string') listener(event.data)\n }\n port.addEventListener('message', handler)\n return () => port.removeEventListener('message', handler)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\n/**\n * A socket over an existing `WebSocket`: the accepted end of a Cloudflare\n * `WebSocketPair`, or any other socket the platform hands over. Unlike\n * `nativeSocket` it opens nothing — accept the pair first — and unlike\n * `portSocket` there is no signal: the socket closing, erroring, or being\n * closed fires `onClose` once, which is how a host stops serving it.\n */\nexport const workerSocket = (socket: WebSocket): SocketLike => {\n const messageListeners = new Set<(data: string) => void>()\n const closeListeners = new Set<() => void>()\n let closed = false\n const forget = (): void => {\n socket.removeEventListener('message', onMessageEvent)\n socket.removeEventListener('close', onClosedEvent)\n socket.removeEventListener('error', onClosedEvent)\n }\n const fireClose = (): void => {\n closed = true\n forget()\n for (const listener of [...closeListeners]) listener()\n closeListeners.clear()\n }\n const onMessageEvent = (event: MessageEvent): void => {\n for (const listener of [...messageListeners]) listener(String(event.data))\n }\n const onClosedEvent = (): void => {\n fireClose()\n }\n socket.addEventListener('message', onMessageEvent)\n socket.addEventListener('close', onClosedEvent)\n socket.addEventListener('error', onClosedEvent)\n return {\n send: data => socket.send(data),\n close: () => {\n try {\n socket.close()\n } catch {\n // Already gone: still report the close.\n }\n fireClose()\n },\n onMessage: listener => {\n messageListeners.add(listener)\n return () => messageListeners.delete(listener)\n },\n onClose: listener => {\n if (closed) {\n listener()\n return () => {}\n }\n closeListeners.add(listener)\n return () => closeListeners.delete(listener)\n },\n }\n}\n\nconst connector = (options: SocketOptions): (() => SocketLike) => {\n if (options.makeSocket !== undefined) return options.makeSocket\n const { url } = options\n return () => nativeSocket(url)\n}\n\n/**\n * A WebSocket client transport.\n *\n * One connection is live at a time. While it is connecting, exchanges queue; if\n * it closes, the transport reconnects on an exponential, jittered backoff and\n * re-sends every queued and in-flight frame with its original id, so a lost\n * reply is answered rather than dropped and a late reply cannot resolve a newer\n * frame. It never stops reconnecting: after `maxRetries` consecutive failures\n * queued work fails with a `TransportError`, and exchanges fail fast while no\n * socket is up, until a socket opens. The count resets only when a connection\n * proves healthy, by answering a frame or by staying open for `maxRetryDelay`:\n * a server that accepts a socket and drops it at once is backed off like one\n * that refuses it. A queue over `maxQueue` fails new\n * exchanges with backpressure. The socket is released when the layer's scope\n * ends.\n */\nexport const layerSocket = (\n options: SocketOptions,\n): Layer.Layer<Transport | TransportSocket, TransportError> =>\n Layer.effectContext(\n Effect.fn('Transport.layerSocket')(function* () {\n const makeSocket = connector(options)\n const maxQueue = options.maxQueue ?? 64\n const maxRetries = options.maxRetries ?? 5\n const retryBase = Duration.toMillis(\n Duration.fromInputUnsafe(options.retryBase ?? '50 millis'),\n )\n const maxRetryDelay = Duration.toMillis(\n Duration.fromInputUnsafe(options.maxRetryDelay ?? '5 seconds'),\n )\n const clock = yield* Clock.Clock\n // Listeners run in a socket's callback, outside any Effect: their\n // failures go to the reporter this layer was built with.\n const reporter = yield* Effect.service(Diagnostics.Reporter)\n\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<unknown>\n readonly epoch: string | undefined\n readonly resume: (effect: Effect.Effect<unknown, TransportError>) => void\n }\n const notices = yield* PubSub.sliding<void>(1)\n const listeners = new Set<(data: string) => void>()\n const shared: SocketLike = {\n send: data => {\n if (ready) socket?.send(data)\n },\n close: () => {},\n onMessage: listener => {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n onClose: () => () => {},\n }\n const queued: Array<Entry> = []\n const inFlight = new Map<string, Entry>()\n let socket: SocketLike | undefined\n let ready = false\n let nextId = 0\n let disposed = false\n // Closes since a connection last proved healthy. Past `maxRetries` the\n // transport is offline: nothing waits for a socket that may be minutes away.\n let failures = 0\n const healthy = (): void => {\n failures = 0\n }\n\n const send = (entry: Entry): void => {\n inFlight.set(entry.id, entry)\n socket?.send(\n JSON.stringify({\n id: entry.id,\n cursor: entry.cursor,\n pending: entry.pending,\n ...(entry.epoch === undefined ? {} : { epoch: entry.epoch }),\n } satisfies ExchangeFrame),\n )\n }\n const flush = (): void => {\n if (socket === undefined || !ready) return\n for (const entry of queued.splice(0)) send(entry)\n }\n const requeue = (): void => {\n queued.unshift(...inFlight.values())\n inFlight.clear()\n }\n const failAll = (message: string): void => {\n const entries = [...queued.splice(0), ...inFlight.values()]\n inFlight.clear()\n for (const entry of entries) entry.resume(Effect.fail(new TransportError({ message })))\n }\n\n const connect = Effect.tryPromise({\n try: () =>\n new Promise<void>((resolve, reject) => {\n const next = makeSocket()\n socket = next\n ready = next.onOpen === undefined\n let openedAt = ready ? clock.currentTimeMillisUnsafe() : undefined\n // A socket that just (re)connected may have missed notices, so opening is one.\n const opened = (): void => {\n PubSub.publishUnsafe(notices, undefined)\n }\n const offOpen = next.onOpen?.(() => {\n ready = true\n openedAt = clock.currentTimeMillisUnsafe()\n opened()\n flush()\n })\n const offMessage = next.onMessage(data => {\n // Another protocol's listener must not cost an exchange its reply.\n for (const listener of [...listeners]) {\n try {\n listener(data)\n } catch (thrown) {\n Effect.runFork(\n Diagnostics.report(listenerFailed('Socket', thrown)).pipe(\n Effect.provideService(Diagnostics.Reporter, reporter),\n ),\n )\n }\n }\n let reply: ExchangeReply | NotifyFrame\n try {\n reply = JSON.parse(data) as ExchangeReply | NotifyFrame\n } catch {\n return\n }\n if (typeof reply !== 'object' || reply === null) return\n if ('notify' in reply) {\n if (reply.notify === true) PubSub.publishUnsafe(notices, undefined)\n return\n }\n const entry = inFlight.get(reply.id)\n if (entry === undefined) return\n healthy()\n inFlight.delete(reply.id)\n entry.resume(\n reply.error === undefined\n ? Effect.succeed(reply.result)\n : Effect.fail(new TransportError({ message: reply.error })),\n )\n })\n const offClose = next.onClose(() => {\n offOpen?.()\n offMessage()\n offClose()\n socket = undefined\n ready = false\n if (\n openedAt !== undefined &&\n clock.currentTimeMillisUnsafe() - openedAt >= maxRetryDelay\n )\n healthy()\n // Keep every unanswered frame for the next connection.\n requeue()\n reject(new Error('transport closed'))\n })\n if (ready) {\n opened()\n flush()\n }\n }),\n catch: () => new TransportError({ message: 'transport closed' }),\n })\n\n yield* Effect.forkScoped(\n Effect.gen(function* () {\n while (!disposed) {\n yield* Effect.exit(connect)\n if (disposed) return\n failures += 1\n if (failures > maxRetries) failAll('transport closed')\n const backoff = Math.min(maxRetryDelay, retryBase * 2 ** Math.min(failures - 1, 30))\n yield* Effect.sleep(backoff * (0.8 + Math.random() * 0.4))\n }\n }),\n )\n yield* Effect.addFinalizer(() =>\n Effect.sync(() => {\n disposed = true\n ready = false\n socket?.close()\n socket = undefined\n failAll('transport closed')\n }),\n )\n\n const transport = Transport.of({\n changes: Stream.fromPubSub(notices),\n exchange: (cursor, pending, epoch) =>\n Effect.callback<unknown, TransportError>(resume => {\n if (disposed) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (failures > maxRetries && !ready) {\n resume(Effect.fail(new TransportError({ message: 'transport closed' })))\n return\n }\n if (queued.length + inFlight.size >= maxQueue) {\n resume(Effect.fail(new TransportError({ message: 'transport queue full' })))\n return\n }\n const entry: Entry = { id: String(nextId++), cursor, pending, epoch, resume }\n if (ready) send(entry)\n else queued.push(entry)\n // A caller interrupted before a reply must release its slot, or a\n // socket that never replies can exhaust the queue with abandoned\n // work. The frame may already be on the wire; only the local waiter\n // is forgotten, and a late reply for it is ignored.\n return Effect.sync(() => {\n const queuedIndex = queued.indexOf(entry)\n if (queuedIndex >= 0) queued.splice(queuedIndex, 1)\n if (inFlight.get(entry.id) === entry) inFl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eAAe,GAAG,OAAO,OAAO,aAAa,CAAC;IAClD,IAAI,SAAS,IAAI,MAAM,EAAE,MAAM,OAAO,SAAS,OAAO,MAAM,EAAE;GAChE,CAAC;EACH,CAAC;CACL,CAAC;CACD,OAAO,QAAQ,KAAK,WAAW,SAAS,CAAC,CAAC,KAAK,QAAQ,IAAI,iBAAiB,MAAM,CAAC;AACrF,CAAC,CAAC,CAAC,CACL"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-sync",
3
- "version": "0.16.0",
3
+ "version": "0.17.0",
4
4
  "description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -64,8 +64,8 @@
64
64
  "peerDependencies": {
65
65
  "effect": "^4.1.0",
66
66
  "foldkit": "^0.170.0",
67
- "foldkit-durable": "0.13.0",
68
- "foldkit-remote": "0.25.0"
67
+ "foldkit-durable": "0.14.0",
68
+ "foldkit-remote": "0.26.0"
69
69
  },
70
70
  "peerDependenciesMeta": {
71
71
  "foldkit-durable": {
@@ -90,9 +90,9 @@
90
90
  "typescript": "7.0.2",
91
91
  "ws": "^8.22.0",
92
92
  "foldkit-agent": "0.12.0",
93
- "foldkit-durable": "0.13.0",
94
- "foldkit-entity": "0.17.0",
95
- "foldkit-remote": "0.25.0"
93
+ "foldkit-durable": "0.14.0",
94
+ "foldkit-remote": "0.26.0",
95
+ "foldkit-entity": "0.17.0"
96
96
  },
97
97
  "scripts": {
98
98
  "build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",