foldkit-sync 0.12.2 → 0.12.4
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/dist/do.d.mts +1 -3
- package/dist/do.d.mts.map +1 -1
- package/dist/do.mjs +3 -4
- package/dist/entity.d.mts +0 -2
- package/dist/entity.d.mts.map +1 -1
- package/dist/entity.mjs +1 -2
- package/dist/index.d.mts +1 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -17
- package/dist/index.mjs.map +1 -1
- package/dist/{journal-BtYEDz0E.mjs → journal-D5h-jqXE.mjs} +4 -6
- package/dist/{journal-BtYEDz0E.mjs.map → journal-D5h-jqXE.mjs.map} +1 -1
- package/dist/journal.d.mts +1 -3
- package/dist/journal.d.mts.map +1 -1
- package/dist/journal.mjs +1 -1
- package/dist/{make-CFOcLcQ1.d.mts → make-DJ0Q1SSc.d.mts} +1 -13
- package/dist/make-DJ0Q1SSc.d.mts.map +1 -0
- package/dist/remote.d.mts +0 -2
- package/dist/remote.d.mts.map +1 -1
- package/dist/remote.mjs +1 -2
- package/dist/{transport-DiKXy5zx.mjs → transport-BZ6utYmB.mjs} +3 -5
- package/dist/{transport-DiKXy5zx.mjs.map → transport-BZ6utYmB.mjs.map} +1 -1
- package/package.json +4 -4
- package/dist/make-CFOcLcQ1.d.mts.map +0 -1
|
@@ -1,14 +1,13 @@
|
|
|
1
|
-
import { b as sequence, c as serveSocket } from "./transport-
|
|
1
|
+
import { b as sequence, c as serveSocket } from "./transport-BZ6utYmB.mjs";
|
|
2
2
|
import { Cause, Context, Duration, Effect, Exit, Fiber, Layer, Match, Option, Result, Schema, Scope, Stream } from "effect";
|
|
3
3
|
import { Cursor, DocumentId, Sequence } from "foldkit-durable/core";
|
|
4
|
-
|
|
4
|
+
// src/revalidate.ts
|
|
5
5
|
/** Shared by `documentHost` and `defineDocumentHost`; not part of either entry's API. */
|
|
6
6
|
/** Refuses a revalidation interval that would ask the session store without pause. */
|
|
7
7
|
const checkRevalidate = (revalidate, who) => {
|
|
8
8
|
if (revalidate !== void 0 && !Duration.isGreaterThan(Duration.fromInputUnsafe(revalidate.every), Duration.zero)) throw new Error(`${who}: revalidate.every must be longer than zero`);
|
|
9
9
|
};
|
|
10
|
-
|
|
11
|
-
//#region src/journal.ts
|
|
10
|
+
// src/journal.ts
|
|
12
11
|
/**
|
|
13
12
|
* `foldkit-sync/journal` — the server's side of an exchange, over a
|
|
14
13
|
* `foldkit-durable` journal. Every Sync server needs the same loop: append
|
|
@@ -295,7 +294,6 @@ const documentHost = (options) => {
|
|
|
295
294
|
});
|
|
296
295
|
};
|
|
297
296
|
};
|
|
298
|
-
//#endregion
|
|
299
297
|
export { journalExchange as a, journalChanges as i, documentHost as n, serveJournal as o, editsJournal as r, checkRevalidate as s, TableAheadOfJournalError as t };
|
|
300
298
|
|
|
301
|
-
//# sourceMappingURL=journal-
|
|
299
|
+
//# sourceMappingURL=journal-D5h-jqXE.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal-BtYEDz0E.mjs","names":["JournalDocumentId"],"sources":["../src/revalidate.ts","../src/journal.ts"],"sourcesContent":["/** Shared by `documentHost` and `defineDocumentHost`; not part of either entry's API. */\nimport { Duration } from 'effect'\n\n/** Refuses a revalidation interval that would ask the session store without pause. */\nexport const checkRevalidate = (\n revalidate: { readonly every: Duration.Input } | undefined,\n who: string,\n): void => {\n if (\n revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(revalidate.every), Duration.zero)\n )\n throw new Error(`${who}: revalidate.every must be longer than zero`)\n}\n","/**\n * `foldkit-sync/journal` — the server's side of an exchange, over a\n * `foldkit-durable` journal. Every Sync server needs the same loop: append\n * what a replica sends, refuse what cannot be taken, and read back what\n * committed since the replica's cursor. Written by hand three times, it\n * failed the same way: an operation that did not decode failed the whole\n * exchange, so the replica sent it again on every one and the edits behind it\n * never went. Here, refused operations are reported by id, and the replica\n * drops them.\n */\nimport {\n Cause,\n Context,\n Duration,\n Effect,\n Exit,\n Fiber,\n Layer,\n Match,\n Option,\n Result,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n Sequence,\n type Committed,\n type Journal,\n} from 'foldkit-durable/core'\nimport { sequence } from './ids.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync, TransportClient } from './sync.js'\nimport { checkRevalidate } from './revalidate.js'\nimport { serveSocket, type SocketLike } from './transport.js'\n\nexport interface JournalExchangeOptions<Message, Shared, Principal> {\n /** The document's contract: its codecs, and the snapshot a checkpoint encodes. */\n readonly sync: Sync<Message, Shared>\n /**\n * The journal made from `sync.journalContract()`, which orders and keeps the\n * document. One that takes any input, or only operations, is accepted.\n */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * Who is exchanging, as the transport established it. The journal's\n * `authorize` reads it; a refused operation is reported as rejected.\n */\n readonly principal: Principal\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. It runs on\n * every exchange, so a write that failed is tried again on the next.\n */\n readonly settle?: Effect.Effect<void, unknown> | undefined\n /**\n * Whether the connection may open the document at all, to read it or to\n * change it: a principal outside its readers. Refused, every exchange fails,\n * and nothing is read or appended.\n */\n readonly opens?: Effect.Effect<boolean> | undefined\n /**\n * Whether an operation may be appended, decided before the journal sees it,\n * by what the transport established rather than by the document: a principal\n * that may only read, or a rule that reads the rows an edit names, which\n * cannot run under the journal's lock (`foldkit-guard/sync`). `true` admits;\n * a refusal is rejected by the operation's id, with its reason when it gives\n * one. One that fails fails the exchange, as the journal failing does. The\n * journal's own `authorize` is where a rule about the document goes.\n */\n readonly admit?:\n | ((operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /** The most committed operations one reply carries; a replica further behind asks again. Default 500. */\n readonly limit?: number | undefined\n}\n\n/** The id an entry names, read without trusting the rest of it. */\nconst idOf = (input: unknown): Option.Option<string> =>\n Option.map(\n Schema.decodeUnknownOption(Schema.Struct({ opId: Schema.String }))(input),\n ({ opId }) => opId,\n )\n\n/**\n * One replica's exchanges with the journal, as the replica's transport\n * speaks them (`Sync.transport.fromPromise`, or behind\n * `Sync.transport.serve` on a socket). Each pending operation is appended in\n * order, and acknowledged once committed, or already committed. One is\n * rejected by its id when its message does not decode, it names another\n * document, or the journal refuses it (`authorize`, `validate`); the replica\n * drops it rather than send it again. Only an entry with no id at all, a\n * cursor ahead of the journal's, a connection `opens` refuses, or `admit` or\n * the journal failing fails the exchange. The reply carries what committed\n * after the replica's cursor, a checkpoint when that history was compacted,\n * and the journal's epoch, so a replica of a reset journal starts again.\n */\nexport const journalExchange = <Message, Shared, Principal>(\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): TransportClient => {\n const { sync, journal, principal } = options\n const limit = options.limit ?? 500\n const key = JournalDocumentId.make(sync.documentId)\n const snapshot = sync.journalContract().snapshot\n const operationOf = Option.liftThrowable((input: unknown) =>\n sync.codec.operationFrom(input, sync.documentId),\n )\n const committedOf = (committed: Committed<Operation>) =>\n sync.codec.committedFrom(\n { ...committed.operation, serverSequence: committed.sequence, actorId: committed.actorId },\n sync.documentId,\n )\n\n const exchange = (cursor: number, pending: ReadonlyArray<unknown>, seen?: string) =>\n Effect.gen(function* () {\n if (options.opens !== undefined && !(yield* options.opens)) {\n return yield* Effect.fail(new Error('This connection may not open the document'))\n }\n // A replica that saw another epoch holds a cursor into history this journal\n // lacks (it was reset): it is answered from the start. Otherwise a cursor\n // past the journal's is refused before anything is appended, or the\n // operations would commit and their acknowledgements be lost.\n const epoch = yield* journal.epoch(key)\n const from = seen !== undefined && seen !== epoch ? 0 : cursor\n const at = yield* journal.cursor(key)\n if (from > at) {\n return yield* Effect.fail(new Error(`Cursor ${cursor} is ahead of the server's ${at}`))\n }\n const rejected: Array<string> = []\n const reasons: Array<{ readonly opId: string; readonly reason: string }> = []\n // Each reason is words for the person whose edit came back: a policy's own,\n // or a fixed sentence, never an error's message, which may carry internals.\n const reject = (opId: string, reason: string) => {\n rejected.push(opId)\n reasons.push({ opId, reason })\n }\n const acknowledged: Array<string> = []\n for (const input of pending) {\n const decoded = operationOf(input)\n if (Option.isNone(decoded)) {\n const id = idOf(input)\n if (Option.isNone(id))\n return yield* Effect.fail(new Error('A pending entry names no operation'))\n reject(id.value, 'Not an operation this server accepts')\n continue\n }\n const operation = decoded.value\n const admitted = options.admit === undefined ? true : options.admit(operation)\n const decision = Effect.isEffect(admitted) ? yield* admitted : admitted\n if (decision !== true) {\n reject(\n operation.opId,\n decision === false ? 'This connection may not make changes' : decision.reason,\n )\n continue\n }\n yield* journal.append(key, operation, principal).pipe(\n Effect.map(appended =>\n acknowledged.push(\n Match.valueTags(appended, {\n Committed: ({ committed }): string => committed.operation.opId,\n AlreadyCommitted: ({ opId }): string => opId,\n }),\n ),\n ),\n // A refusal, an operation the journal cannot apply, and an id reused for\n // other content fail the same way on every retry, so they are rejected; a\n // `JournalError` may not, so it still fails the exchange.\n Effect.catchTags({\n OperationRejectedError: error =>\n Effect.sync(() => reject(error.opId, error.reason ?? 'Refused by the server')),\n InvalidOperationError: () =>\n Effect.sync(() => reject(operation.opId, 'Not a valid operation')),\n IdentityConflictError: () =>\n Effect.sync(() => reject(operation.opId, 'Its id was already used for another')),\n }),\n )\n }\n if (options.settle !== undefined) yield* options.settle\n // A cursor below the compacted floor is answered with the snapshot; the\n // read decides that itself, so a compaction cannot slip in between.\n const read = yield* journal.read(key, Cursor.make(from), { limit }).pipe(\n Effect.map(rows => Option.some(rows)),\n Effect.catchTag('CompactedCursorError', () => Effect.succeed(Option.none())),\n )\n return yield* Option.match(read, {\n onSome: rows =>\n Effect.succeed({\n operations: rows.map(committedOf),\n rejected,\n reasons,\n acknowledged,\n more: rows.length === limit,\n epoch,\n }),\n onNone: () =>\n Effect.map(journal.load(key), loaded => ({\n operations: [],\n rejected,\n reasons,\n acknowledged,\n checkpoint: { cursor: loaded.cursor, model: snapshot.encode(loaded.snapshot) },\n epoch,\n })),\n })\n })\n\n return {\n exchange: (cursor, pending, seen) => Effect.runPromise(exchange(cursor, pending, seen)),\n }\n}\n\n/**\n * Calls `listener` each time the document commits, for `Sync.transport.serve`'s\n * `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.\n */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, Operation>,\n documentId: string,\n ): ((listener: () => void) => () => void) =>\n listener => {\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () => Effect.sync(listener),\n ),\n )\n return () => Effect.runSync(Fiber.interrupt(fiber))\n }\n\n/**\n * Serves one accepted socket over the journal: each exchange frame answered by\n * `journalExchange` with the connection's principal, and a notice sent after\n * each commit, so the replica hears of others' edits. Returns the stop.\n */\nexport const serveJournal = <Message, Shared, Principal>(\n socket: SocketLike,\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): (() => void) => {\n const client = journalExchange(options)\n const notices = journalChanges(options.journal, options.sync.documentId)\n const { opens } = options\n return serveSocket(socket, {\n exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),\n // A connection that may not open the document is told nothing of its commits.\n changes:\n opens === undefined\n ? notices\n : listener =>\n notices(\n () =>\n void Effect.runPromise(opens).then(\n open => {\n if (open) listener()\n },\n () => {},\n ),\n ),\n })\n}\n\n/**\n * The table holds revisions past every sequence the journal has: it outlived\n * a reset of the journal, or was built from another. New edits commit at\n * sequences the table already passed, so `apply` would skip every one and\n * the replicas count each absorbed: rebuild the table with the journal.\n */\nexport class TableAheadOfJournalError extends Schema.TaggedError<TableAheadOfJournalError>()(\n 'SyncTableAheadOfJournalError',\n { table: Schema.Number, journal: Schema.Number },\n) {\n override get message(): string {\n return `The table holds revision ${this.table}, past the journal's ${this.journal}: rebuild the table with the journal`\n }\n}\n\nexport interface EditsJournalOptions<Shared, Principal, Change> {\n /** The document whose edits the table reads. */\n readonly documentId: string\n /** The journal the edits commit to. */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * The cells an operation edits, with the sequence its stamp wrote in; none\n * for an operation that edits nothing. An edit committed without a sequence\n * is not this journal's: its intents fail rather than write revision 0.\n */\n readonly editsOf: (operation: Operation) => Option.Option<{\n readonly changes: ReadonlyArray<Change>\n readonly at: Option.Option<number>\n }>\n /**\n * Writes one committed change to the table, with the sequence it committed\n * at. It runs as a recovery intent, so it may run again after a crash: it\n * must never move a row back (`revision <= at`). A failure stops recovery\n * there, and the next settle tries it again.\n *\n * It cannot refuse an edit: the edit has committed. One naming a row the\n * table lacks is refused at commit instead, by the journal's `validate`,\n * so its sender is told; let through, it would change nothing and vanish\n * once absorbed.\n */\n readonly apply: (change: Change, at: number) => Effect.Effect<void, unknown>\n /**\n * The highest revision the table holds. Settling refuses to start while it\n * is past the journal's cursor (`TableAheadOfJournalError`), since every\n * edit would then be skipped and counted absorbed; it asks again on each\n * settle until the two agree.\n */\n readonly tableRevision: Effect.Effect<number, unknown>\n /** Whether the snapshot still keeps an edit committed through `through`: whether to absorb. */\n readonly holdsThrough: (snapshot: Shared, through: number) => boolean\n /**\n * The server's operation saying the table holds every edit through\n * `through`, sequenced from `cursor`, the journal's: the replicas drop those\n * edits on hearing it.\n */\n readonly absorbed: (through: number, cursor: number) => Operation\n /** Who the server commits `absorbed` as; the contract's `authorize` should let only it. */\n readonly server: Principal\n}\n\n/**\n * The table as the journal's read model: `settle` applies each committed\n * edit through `apply`, as a recovery intent, and `absorb` records in the\n * journal what the table holds and compacts the log behind it. For\n * `journalExchange`'s `settle`, and a clock that absorbs.\n *\n * Recovery starts at the journal's floor, where compaction left it, so a\n * server restarted over a journal that outlived it does not ask for history\n * that is gone. Intents are keyed by the journal's epoch as well as the\n * operation, so after a reset an operation sent again is applied again, not\n * taken as already run.\n */\nexport const editsJournal = <Shared, Principal, Change>(\n options: EditsJournalOptions<Shared, Principal, Change>,\n): {\n readonly settle: Effect.Effect<void, unknown>\n readonly absorb: Effect.Effect<void, unknown>\n} => {\n const { journal } = options\n const key = JournalDocumentId.make(options.documentId)\n // Operations at or before `applied.cursor` have every change in the table,\n // in `applied.epoch`: none until a settle has run in this process.\n let applied: Option.Option<{ readonly cursor: Cursor; readonly epoch: string }> = Option.none()\n const intents = (epoch: string) => (operation: Operation) =>\n Option.match(options.editsOf(operation), {\n onNone: () => [],\n onSome: ({ changes, at }) =>\n changes.map((change, index) => ({\n key: `${epoch}:${operation.opId}:${index}`,\n run: Option.match(at, {\n onNone: () =>\n Effect.fail(new Error(`Edit ${operation.opId} committed without its sequence`)),\n onSome: sequence => options.apply(change, sequence),\n }),\n })),\n })\n // Before the first recovery of an epoch: the table must not be past it.\n const checked = Effect.gen(function* () {\n const table = yield* options.tableRevision\n const at = yield* journal.cursor(key)\n if (table > at) return yield* new TableAheadOfJournalError({ table, journal: at })\n return Cursor.make(yield* journal.floor(key))\n })\n const settle = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n // A new epoch is a new history: recovery starts over at its floor.\n const from = yield* Option.match(\n Option.filter(applied, previous => previous.epoch === epoch),\n {\n onSome: ({ cursor }) => Effect.succeed(cursor),\n onNone: () => checked,\n },\n )\n const cursor = yield* journal.recover({ key, from, intents: intents(epoch) })\n applied = Option.some({ cursor, epoch })\n })\n // Two absorbs at once need no lock: both name the record by the journal's\n // cursor, so the second is the first's retry, answered from history.\n const absorb = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n const known = Option.filter(applied, previous => previous.epoch === epoch)\n if (Option.isNone(known)) return\n const through = known.value.cursor\n const { snapshot, cursor } = yield* journal.load(key)\n if (!options.holdsThrough(snapshot, through)) return\n yield* journal.append(key, options.absorbed(through, cursor), options.server)\n // What the log holds through `through` is in the table and gone from\n // the snapshot; a replica behind it is sent the snapshot instead.\n yield* journal.compact(key, Sequence.make(through))\n })\n return { settle, absorb }\n}\n\n/** A server socket a host serves on: Sync's socket, and a close with a code the replica reads. */\nexport interface HostSocket extends SocketLike {\n /** Closes with `code` and `reason`; one already closed stays so. */\n closeWith(code: number, reason: string): void\n}\n\n/**\n * An upgrade `documentHost` accepted. Exactly one of the two must follow:\n * `serve` once the runtime has opened the socket, or `abandon` when it never\n * will (the client left, the runtime refused the handshake), which releases\n * what the upgrade built.\n */\nexport interface Accepted {\n readonly serve: (socket: HostSocket) => void\n readonly abandon: () => void\n}\n\n/** What `documentHost` needs: one document, who may open it, and what they may do. */\nexport interface DocumentHostOptions<Message, Shared, Principal, RP = never> {\n readonly sync: Sync<Message, Shared>\n /**\n * The document's journal, asked on each upgrade a principal passed; keep\n * it open between calls. A rejection answers the upgrade with a 500.\n */\n readonly journal: () => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening the socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`) to refuse it:\n * a 401 carrying its message. A defect is a 500 that says nothing of it.\n * A browser's `WebSocket` sends no header of the page's: `Origin` and the\n * cookie are what it has.\n */\n readonly resolvePrincipal: (\n request: Request,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket serves the\n * principal it opened with until it closes, a revoked session included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** After each exchange's appends, given the journal. See `journalExchange`'s `settle`. */\n readonly settle?:\n | ((journal: Journal<Operation, Shared, Principal, Operation>) => Effect.Effect<void, unknown>)\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /** Whether an operation from `principal` may be appended. See `journalExchange`'s `admit`. */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n}\n\n/** What a revalidation that found another principal fails with. */\nconst changed = Symbol('changed')\n\nconst internalError = () => Response.json({ error: 'Internal error' }, { status: 500 })\n\n/**\n * What the resolver needs (a session store), required exactly when it\n * needs something. Built per upgrade and kept until the socket closes,\n * since `revalidate` asks again while it is open; an upgrade it refuses\n * closes it at once.\n */\nexport type DocumentHostOptionsLayer<RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: () => Layer.Layer<RP> }\n\n/**\n * One document's Sync host, for any runtime that upgrades a request to a\n * socket: a Durable Object (`foldkit-sync/do`), or Node's `ws`. Each\n * upgrade is answered before the socket opens: refused (`Result.fail`, a\n * 401 for a principal refused, a 500 for a resolver or journal that broke),\n * or accepted (`Accepted`): `serve` the socket once the runtime has opened\n * it, against the journal, as the principal it resolved, asking again while\n * it is open when `revalidate` says to; or `abandon` it when the runtime\n * never will, which releases what the upgrade built.\n */\nexport const documentHost = <Message, Shared, Principal, RP = never>(\n options: DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>,\n): ((request: Request) => Promise<Result.Result<Accepted, Response>>) => {\n checkRevalidate(options.revalidate, 'documentHost')\n return async request => {\n // The upgrade's services live as long as its socket.\n const scope = Effect.runSync(Scope.make())\n const release = (): void => void Effect.runFork(Scope.close(scope, Exit.void))\n const refuse = (response: Response) => {\n release()\n return Result.fail(response)\n }\n const { layer } = options\n // Suspended, so the resolver is called each time this runs (a resolver\n // may decide when called, not when its Effect runs), and one that throws\n // is a 500 like one that dies.\n const ask = Effect.suspend(() => options.resolvePrincipal(request))\n // The layer and the first answer in one run: either breaking is a 500.\n const opened = await Effect.runPromise(\n Effect.gen(function* () {\n const services: Context.Context<RP> =\n layer === undefined\n ? // No layer is a resolver that needs nothing (`DocumentHostLayer`).\n (Context.empty() as Context.Context<RP>)\n : yield* Layer.buildWithScope(layer(), scope)\n const resolve = Effect.provide(ask, services)\n return { resolve, resolved: yield* Effect.result(resolve) }\n }),\n ).catch(() => undefined)\n if (opened === undefined) return refuse(internalError())\n const { resolve, resolved } = opened\n if (Result.isFailure(resolved))\n return refuse(Response.json({ error: resolved.failure.message }, { status: 401 }))\n const principal = resolved.success\n // A throw is a rejection like any other: a 500.\n const journal = await Promise.resolve()\n .then(options.journal)\n .catch(() => undefined)\n if (journal === undefined) return refuse(internalError())\n // An application's `opens` or `settle` may throw: a 500, before any socket opens.\n let exchange: JournalExchangeOptions<Message, Shared, Principal>\n try {\n const { admit, settle, opens } = options\n exchange = {\n sync: options.sync,\n journal,\n principal,\n ...(settle === undefined ? {} : { settle: settle(journal) }),\n ...(opens === undefined ? {} : { opens: opens(principal) }),\n ...(admit === undefined\n ? {}\n : { admit: (operation: Operation) => admit(principal, operation) }),\n }\n } catch (error) {\n console.error('[foldkit-sync] answering an upgrade broke:', error)\n return refuse(internalError())\n }\n return Result.succeed({\n abandon: release,\n serve: socket => {\n const stop = serveJournal(socket, exchange)\n const { revalidate } = options\n if (revalidate !== undefined) {\n const { every, key } = revalidate\n const checking = Effect.sleep(every).pipe(\n Effect.andThen(resolve),\n Effect.flatMap(now =>\n key === undefined || key(principal) === key(now) ? Effect.void : Effect.fail(changed),\n ),\n Effect.forever,\n Effect.catchCause(cause =>\n Effect.sync(() => {\n // Before closing: a socket may fire its own close only on the\n // replica's reply, and frames in flight until then would\n // still be appended as the principal just refused.\n stop()\n const [code, reason] = Option.match(Cause.findErrorOption(cause), {\n // A defect: this side broke, and the replica learns that it did.\n onNone: () => [1011, 'Internal error'] as const,\n onSome: error =>\n error === changed\n ? ([1012, 'Who is asking changed'] as const)\n : ([4401, error.message] as const),\n })\n try {\n socket.closeWith(code, reason)\n } catch {\n // A reason the platform refuses (past 123 bytes): the code alone.\n socket.close()\n } finally {\n release()\n }\n }),\n ),\n )\n const fiber = Effect.runFork(checking)\n socket.onClose(() => void Effect.runFork(Fiber.interrupt(fiber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,KAAa,IAAI,SAAS,MAAM,IAAI,GAAG,IAAI,OAAO,OAAO,OAAO,KAAK,OAAO,CACtF,GACA,OAAO,SACP,OAAO,YAAW,UAChB,OAAO,WAAW;MAIhB,KAAK;MACL,MAAM,CAAC,MAAM,UAAU,OAAO,MAAM,MAAM,gBAAgB,KAAK,GAAG;OAEhE,cAAc,CAAC,MAAM,gBAAgB;OACrC,SAAQ,UACN,UAAU,UACL,CAAC,MAAM,uBAAuB,IAC9B,CAAC,MAAM,MAAM,OAAO;MAC7B,CAAC;MACD,IAAI;OACF,OAAO,UAAU,MAAM,MAAM;MAC/B,QAAQ;OAEN,OAAO,MAAM;MACf,UAAU;OACR,QAAQ;MACV;KACF,CAAC,CACH,CACF;KACA,MAAM,QAAQ,OAAO,QAAQ,QAAQ;KACrC,OAAO,cAAc,KAAK,OAAO,QAAQ,MAAM,UAAU,KAAK,CAAC,CAAC;IAClE;IACA,OAAO,QAAQ,OAAO;GACxB;EACF,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"journal-D5h-jqXE.mjs","names":["JournalDocumentId"],"sources":["../src/revalidate.ts","../src/journal.ts"],"sourcesContent":["/** Shared by `documentHost` and `defineDocumentHost`; not part of either entry's API. */\nimport { Duration } from 'effect'\n\n/** Refuses a revalidation interval that would ask the session store without pause. */\nexport const checkRevalidate = (\n revalidate: { readonly every: Duration.Input } | undefined,\n who: string,\n): void => {\n if (\n revalidate !== undefined &&\n !Duration.isGreaterThan(Duration.fromInputUnsafe(revalidate.every), Duration.zero)\n )\n throw new Error(`${who}: revalidate.every must be longer than zero`)\n}\n","/**\n * `foldkit-sync/journal` — the server's side of an exchange, over a\n * `foldkit-durable` journal. Every Sync server needs the same loop: append\n * what a replica sends, refuse what cannot be taken, and read back what\n * committed since the replica's cursor. Written by hand three times, it\n * failed the same way: an operation that did not decode failed the whole\n * exchange, so the replica sent it again on every one and the edits behind it\n * never went. Here, refused operations are reported by id, and the replica\n * drops them.\n */\nimport {\n Cause,\n Context,\n Duration,\n Effect,\n Exit,\n Fiber,\n Layer,\n Match,\n Option,\n Result,\n Schema,\n Scope,\n Stream,\n} from 'effect'\nimport type { RemoteUnauthenticated } from 'foldkit-remote'\nimport {\n Cursor,\n DocumentId as JournalDocumentId,\n Sequence,\n type Committed,\n type Journal,\n} from 'foldkit-durable/core'\nimport { sequence } from './ids.js'\nimport type { AuthorizeDecision } from './make.js'\nimport type { Operation, Sync, TransportClient } from './sync.js'\nimport { checkRevalidate } from './revalidate.js'\nimport { serveSocket, type SocketLike } from './transport.js'\n\nexport interface JournalExchangeOptions<Message, Shared, Principal> {\n /** The document's contract: its codecs, and the snapshot a checkpoint encodes. */\n readonly sync: Sync<Message, Shared>\n /**\n * The journal made from `sync.journalContract()`, which orders and keeps the\n * document. One that takes any input, or only operations, is accepted.\n */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * Who is exchanging, as the transport established it. The journal's\n * `authorize` reads it; a refused operation is reported as rejected.\n */\n readonly principal: Principal\n /**\n * Runs after each exchange's appends and before the reply is read: apply\n * what committed to another store, through `journal.recover`. It runs on\n * every exchange, so a write that failed is tried again on the next.\n */\n readonly settle?: Effect.Effect<void, unknown> | undefined\n /**\n * Whether the connection may open the document at all, to read it or to\n * change it: a principal outside its readers. Refused, every exchange fails,\n * and nothing is read or appended.\n */\n readonly opens?: Effect.Effect<boolean> | undefined\n /**\n * Whether an operation may be appended, decided before the journal sees it,\n * by what the transport established rather than by the document: a principal\n * that may only read, or a rule that reads the rows an edit names, which\n * cannot run under the journal's lock (`foldkit-guard/sync`). `true` admits;\n * a refusal is rejected by the operation's id, with its reason when it gives\n * one. One that fails fails the exchange, as the journal failing does. The\n * journal's own `authorize` is where a rule about the document goes.\n */\n readonly admit?:\n | ((operation: Operation) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n /** The most committed operations one reply carries; a replica further behind asks again. Default 500. */\n readonly limit?: number | undefined\n}\n\n/** The id an entry names, read without trusting the rest of it. */\nconst idOf = (input: unknown): Option.Option<string> =>\n Option.map(\n Schema.decodeUnknownOption(Schema.Struct({ opId: Schema.String }))(input),\n ({ opId }) => opId,\n )\n\n/**\n * One replica's exchanges with the journal, as the replica's transport\n * speaks them (`Sync.transport.fromPromise`, or behind\n * `Sync.transport.serve` on a socket). Each pending operation is appended in\n * order, and acknowledged once committed, or already committed. One is\n * rejected by its id when its message does not decode, it names another\n * document, or the journal refuses it (`authorize`, `validate`); the replica\n * drops it rather than send it again. Only an entry with no id at all, a\n * cursor ahead of the journal's, a connection `opens` refuses, or `admit` or\n * the journal failing fails the exchange. The reply carries what committed\n * after the replica's cursor, a checkpoint when that history was compacted,\n * and the journal's epoch, so a replica of a reset journal starts again.\n */\nexport const journalExchange = <Message, Shared, Principal>(\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): TransportClient => {\n const { sync, journal, principal } = options\n const limit = options.limit ?? 500\n const key = JournalDocumentId.make(sync.documentId)\n const snapshot = sync.journalContract().snapshot\n const operationOf = Option.liftThrowable((input: unknown) =>\n sync.codec.operationFrom(input, sync.documentId),\n )\n const committedOf = (committed: Committed<Operation>) =>\n sync.codec.committedFrom(\n { ...committed.operation, serverSequence: committed.sequence, actorId: committed.actorId },\n sync.documentId,\n )\n\n const exchange = (cursor: number, pending: ReadonlyArray<unknown>, seen?: string) =>\n Effect.gen(function* () {\n if (options.opens !== undefined && !(yield* options.opens)) {\n return yield* Effect.fail(new Error('This connection may not open the document'))\n }\n // A replica that saw another epoch holds a cursor into history this journal\n // lacks (it was reset): it is answered from the start. Otherwise a cursor\n // past the journal's is refused before anything is appended, or the\n // operations would commit and their acknowledgements be lost.\n const epoch = yield* journal.epoch(key)\n const from = seen !== undefined && seen !== epoch ? 0 : cursor\n const at = yield* journal.cursor(key)\n if (from > at) {\n return yield* Effect.fail(new Error(`Cursor ${cursor} is ahead of the server's ${at}`))\n }\n const rejected: Array<string> = []\n const reasons: Array<{ readonly opId: string; readonly reason: string }> = []\n // Each reason is words for the person whose edit came back: a policy's own,\n // or a fixed sentence, never an error's message, which may carry internals.\n const reject = (opId: string, reason: string) => {\n rejected.push(opId)\n reasons.push({ opId, reason })\n }\n const acknowledged: Array<string> = []\n for (const input of pending) {\n const decoded = operationOf(input)\n if (Option.isNone(decoded)) {\n const id = idOf(input)\n if (Option.isNone(id))\n return yield* Effect.fail(new Error('A pending entry names no operation'))\n reject(id.value, 'Not an operation this server accepts')\n continue\n }\n const operation = decoded.value\n const admitted = options.admit === undefined ? true : options.admit(operation)\n const decision = Effect.isEffect(admitted) ? yield* admitted : admitted\n if (decision !== true) {\n reject(\n operation.opId,\n decision === false ? 'This connection may not make changes' : decision.reason,\n )\n continue\n }\n yield* journal.append(key, operation, principal).pipe(\n Effect.map(appended =>\n acknowledged.push(\n Match.valueTags(appended, {\n Committed: ({ committed }): string => committed.operation.opId,\n AlreadyCommitted: ({ opId }): string => opId,\n }),\n ),\n ),\n // A refusal, an operation the journal cannot apply, and an id reused for\n // other content fail the same way on every retry, so they are rejected; a\n // `JournalError` may not, so it still fails the exchange.\n Effect.catchTags({\n OperationRejectedError: error =>\n Effect.sync(() => reject(error.opId, error.reason ?? 'Refused by the server')),\n InvalidOperationError: () =>\n Effect.sync(() => reject(operation.opId, 'Not a valid operation')),\n IdentityConflictError: () =>\n Effect.sync(() => reject(operation.opId, 'Its id was already used for another')),\n }),\n )\n }\n if (options.settle !== undefined) yield* options.settle\n // A cursor below the compacted floor is answered with the snapshot; the\n // read decides that itself, so a compaction cannot slip in between.\n const read = yield* journal.read(key, Cursor.make(from), { limit }).pipe(\n Effect.map(rows => Option.some(rows)),\n Effect.catchTag('CompactedCursorError', () => Effect.succeed(Option.none())),\n )\n return yield* Option.match(read, {\n onSome: rows =>\n Effect.succeed({\n operations: rows.map(committedOf),\n rejected,\n reasons,\n acknowledged,\n more: rows.length === limit,\n epoch,\n }),\n onNone: () =>\n Effect.map(journal.load(key), loaded => ({\n operations: [],\n rejected,\n reasons,\n acknowledged,\n checkpoint: { cursor: loaded.cursor, model: snapshot.encode(loaded.snapshot) },\n epoch,\n })),\n })\n })\n\n return {\n exchange: (cursor, pending, seen) => Effect.runPromise(exchange(cursor, pending, seen)),\n }\n}\n\n/**\n * Calls `listener` each time the document commits, for `Sync.transport.serve`'s\n * `changes`, so a socket wakes its replica to exchange. Returns the unsubscribe.\n */\nexport const journalChanges =\n <Shared, Principal>(\n journal: Journal<Operation, Shared, Principal, Operation>,\n documentId: string,\n ): ((listener: () => void) => () => void) =>\n listener => {\n const fiber = Effect.runFork(\n Stream.runForEach(\n Stream.filter(journal.subscribe, key => key === documentId),\n () => Effect.sync(listener),\n ),\n )\n return () => Effect.runSync(Fiber.interrupt(fiber))\n }\n\n/**\n * Serves one accepted socket over the journal: each exchange frame answered by\n * `journalExchange` with the connection's principal, and a notice sent after\n * each commit, so the replica hears of others' edits. Returns the stop.\n */\nexport const serveJournal = <Message, Shared, Principal>(\n socket: SocketLike,\n options: JournalExchangeOptions<Message, Shared, Principal>,\n): (() => void) => {\n const client = journalExchange(options)\n const notices = journalChanges(options.journal, options.sync.documentId)\n const { opens } = options\n return serveSocket(socket, {\n exchange: (cursor, pending, epoch) => client.exchange(sequence(cursor), pending, epoch),\n // A connection that may not open the document is told nothing of its commits.\n changes:\n opens === undefined\n ? notices\n : listener =>\n notices(\n () =>\n void Effect.runPromise(opens).then(\n open => {\n if (open) listener()\n },\n () => {},\n ),\n ),\n })\n}\n\n/**\n * The table holds revisions past every sequence the journal has: it outlived\n * a reset of the journal, or was built from another. New edits commit at\n * sequences the table already passed, so `apply` would skip every one and\n * the replicas count each absorbed: rebuild the table with the journal.\n */\nexport class TableAheadOfJournalError extends Schema.TaggedError<TableAheadOfJournalError>()(\n 'SyncTableAheadOfJournalError',\n { table: Schema.Number, journal: Schema.Number },\n) {\n override get message(): string {\n return `The table holds revision ${this.table}, past the journal's ${this.journal}: rebuild the table with the journal`\n }\n}\n\nexport interface EditsJournalOptions<Shared, Principal, Change> {\n /** The document whose edits the table reads. */\n readonly documentId: string\n /** The journal the edits commit to. */\n readonly journal: Journal<Operation, Shared, Principal, Operation>\n /**\n * The cells an operation edits, with the sequence its stamp wrote in; none\n * for an operation that edits nothing. An edit committed without a sequence\n * is not this journal's: its intents fail rather than write revision 0.\n */\n readonly editsOf: (operation: Operation) => Option.Option<{\n readonly changes: ReadonlyArray<Change>\n readonly at: Option.Option<number>\n }>\n /**\n * Writes one committed change to the table, with the sequence it committed\n * at. It runs as a recovery intent, so it may run again after a crash: it\n * must never move a row back (`revision <= at`). A failure stops recovery\n * there, and the next settle tries it again.\n *\n * It cannot refuse an edit: the edit has committed. One naming a row the\n * table lacks is refused at commit instead, by the journal's `validate`,\n * so its sender is told; let through, it would change nothing and vanish\n * once absorbed.\n */\n readonly apply: (change: Change, at: number) => Effect.Effect<void, unknown>\n /**\n * The highest revision the table holds. Settling refuses to start while it\n * is past the journal's cursor (`TableAheadOfJournalError`), since every\n * edit would then be skipped and counted absorbed; it asks again on each\n * settle until the two agree.\n */\n readonly tableRevision: Effect.Effect<number, unknown>\n /** Whether the snapshot still keeps an edit committed through `through`: whether to absorb. */\n readonly holdsThrough: (snapshot: Shared, through: number) => boolean\n /**\n * The server's operation saying the table holds every edit through\n * `through`, sequenced from `cursor`, the journal's: the replicas drop those\n * edits on hearing it.\n */\n readonly absorbed: (through: number, cursor: number) => Operation\n /** Who the server commits `absorbed` as; the contract's `authorize` should let only it. */\n readonly server: Principal\n}\n\n/**\n * The table as the journal's read model: `settle` applies each committed\n * edit through `apply`, as a recovery intent, and `absorb` records in the\n * journal what the table holds and compacts the log behind it. For\n * `journalExchange`'s `settle`, and a clock that absorbs.\n *\n * Recovery starts at the journal's floor, where compaction left it, so a\n * server restarted over a journal that outlived it does not ask for history\n * that is gone. Intents are keyed by the journal's epoch as well as the\n * operation, so after a reset an operation sent again is applied again, not\n * taken as already run.\n */\nexport const editsJournal = <Shared, Principal, Change>(\n options: EditsJournalOptions<Shared, Principal, Change>,\n): {\n readonly settle: Effect.Effect<void, unknown>\n readonly absorb: Effect.Effect<void, unknown>\n} => {\n const { journal } = options\n const key = JournalDocumentId.make(options.documentId)\n // Operations at or before `applied.cursor` have every change in the table,\n // in `applied.epoch`: none until a settle has run in this process.\n let applied: Option.Option<{ readonly cursor: Cursor; readonly epoch: string }> = Option.none()\n const intents = (epoch: string) => (operation: Operation) =>\n Option.match(options.editsOf(operation), {\n onNone: () => [],\n onSome: ({ changes, at }) =>\n changes.map((change, index) => ({\n key: `${epoch}:${operation.opId}:${index}`,\n run: Option.match(at, {\n onNone: () =>\n Effect.fail(new Error(`Edit ${operation.opId} committed without its sequence`)),\n onSome: sequence => options.apply(change, sequence),\n }),\n })),\n })\n // Before the first recovery of an epoch: the table must not be past it.\n const checked = Effect.gen(function* () {\n const table = yield* options.tableRevision\n const at = yield* journal.cursor(key)\n if (table > at) return yield* new TableAheadOfJournalError({ table, journal: at })\n return Cursor.make(yield* journal.floor(key))\n })\n const settle = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n // A new epoch is a new history: recovery starts over at its floor.\n const from = yield* Option.match(\n Option.filter(applied, previous => previous.epoch === epoch),\n {\n onSome: ({ cursor }) => Effect.succeed(cursor),\n onNone: () => checked,\n },\n )\n const cursor = yield* journal.recover({ key, from, intents: intents(epoch) })\n applied = Option.some({ cursor, epoch })\n })\n // Two absorbs at once need no lock: both name the record by the journal's\n // cursor, so the second is the first's retry, answered from history.\n const absorb = Effect.gen(function* () {\n const epoch = yield* journal.epoch(key)\n const known = Option.filter(applied, previous => previous.epoch === epoch)\n if (Option.isNone(known)) return\n const through = known.value.cursor\n const { snapshot, cursor } = yield* journal.load(key)\n if (!options.holdsThrough(snapshot, through)) return\n yield* journal.append(key, options.absorbed(through, cursor), options.server)\n // What the log holds through `through` is in the table and gone from\n // the snapshot; a replica behind it is sent the snapshot instead.\n yield* journal.compact(key, Sequence.make(through))\n })\n return { settle, absorb }\n}\n\n/** A server socket a host serves on: Sync's socket, and a close with a code the replica reads. */\nexport interface HostSocket extends SocketLike {\n /** Closes with `code` and `reason`; one already closed stays so. */\n closeWith(code: number, reason: string): void\n}\n\n/**\n * An upgrade `documentHost` accepted. Exactly one of the two must follow:\n * `serve` once the runtime has opened the socket, or `abandon` when it never\n * will (the client left, the runtime refused the handshake), which releases\n * what the upgrade built.\n */\nexport interface Accepted {\n readonly serve: (socket: HostSocket) => void\n readonly abandon: () => void\n}\n\n/** What `documentHost` needs: one document, who may open it, and what they may do. */\nexport interface DocumentHostOptions<Message, Shared, Principal, RP = never> {\n readonly sync: Sync<Message, Shared>\n /**\n * The document's journal, asked on each upgrade a principal passed; keep\n * it open between calls. A rejection answers the upgrade with a 500.\n */\n readonly journal: () => Promise<Journal<Operation, Shared, Principal, Operation>>\n /**\n * Who is opening the socket, from the upgrade request. Fails with a\n * `RemoteUnauthenticated` (`RemoteServer.unauthenticated()`) to refuse it:\n * a 401 carrying its message. A defect is a 500 that says nothing of it.\n * A browser's `WebSocket` sends no header of the page's: `Origin` and the\n * cookie are what it has.\n */\n readonly resolvePrincipal: (\n request: Request,\n ) => Effect.Effect<Principal, RemoteUnauthenticated, RP>\n /**\n * Asks `resolvePrincipal` again, of the upgrade request, every `every`\n * while the socket is open: a refusal closes it with 4401, and a principal\n * whose `key` differs from the one it opened with (`Policy.keyOf`) closes\n * it with 1012, which the replica reconnects after, as the new principal;\n * without `key` only a refusal closes it. Without it a socket serves the\n * principal it opened with until it closes, a revoked session included.\n */\n readonly revalidate?:\n | {\n readonly every: Duration.Input\n readonly key?: ((principal: Principal) => unknown) | undefined\n }\n | undefined\n /** After each exchange's appends, given the journal. See `journalExchange`'s `settle`. */\n readonly settle?:\n | ((journal: Journal<Operation, Shared, Principal, Operation>) => Effect.Effect<void, unknown>)\n | undefined\n /** Whether `principal` may open the document. See `journalExchange`'s `opens`. */\n readonly opens?: ((principal: Principal) => Effect.Effect<boolean>) | undefined\n /** Whether an operation from `principal` may be appended. See `journalExchange`'s `admit`. */\n readonly admit?:\n | ((\n principal: Principal,\n operation: Operation,\n ) => AuthorizeDecision | Effect.Effect<AuthorizeDecision, unknown>)\n | undefined\n}\n\n/** What a revalidation that found another principal fails with. */\nconst changed = Symbol('changed')\n\nconst internalError = () => Response.json({ error: 'Internal error' }, { status: 500 })\n\n/**\n * What the resolver needs (a session store), required exactly when it\n * needs something. Built per upgrade and kept until the socket closes,\n * since `revalidate` asks again while it is open; an upgrade it refuses\n * closes it at once.\n */\nexport type DocumentHostOptionsLayer<RP> = [RP] extends [never]\n ? { readonly layer?: undefined }\n : { readonly layer: () => Layer.Layer<RP> }\n\n/**\n * One document's Sync host, for any runtime that upgrades a request to a\n * socket: a Durable Object (`foldkit-sync/do`), or Node's `ws`. Each\n * upgrade is answered before the socket opens: refused (`Result.fail`, a\n * 401 for a principal refused, a 500 for a resolver or journal that broke),\n * or accepted (`Accepted`): `serve` the socket once the runtime has opened\n * it, against the journal, as the principal it resolved, asking again while\n * it is open when `revalidate` says to; or `abandon` it when the runtime\n * never will, which releases what the upgrade built.\n */\nexport const documentHost = <Message, Shared, Principal, RP = never>(\n options: DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>,\n): ((request: Request) => Promise<Result.Result<Accepted, Response>>) => {\n checkRevalidate(options.revalidate, 'documentHost')\n return async request => {\n // The upgrade's services live as long as its socket.\n const scope = Effect.runSync(Scope.make())\n const release = (): void => void Effect.runFork(Scope.close(scope, Exit.void))\n const refuse = (response: Response) => {\n release()\n return Result.fail(response)\n }\n const { layer } = options\n // Suspended, so the resolver is called each time this runs (a resolver\n // may decide when called, not when its Effect runs), and one that throws\n // is a 500 like one that dies.\n const ask = Effect.suspend(() => options.resolvePrincipal(request))\n // The layer and the first answer in one run: either breaking is a 500.\n const opened = await Effect.runPromise(\n Effect.gen(function* () {\n const services: Context.Context<RP> =\n layer === undefined\n ? // No layer is a resolver that needs nothing (`DocumentHostLayer`).\n (Context.empty() as Context.Context<RP>)\n : yield* Layer.buildWithScope(layer(), scope)\n const resolve = Effect.provide(ask, services)\n return { resolve, resolved: yield* Effect.result(resolve) }\n }),\n ).catch(() => undefined)\n if (opened === undefined) return refuse(internalError())\n const { resolve, resolved } = opened\n if (Result.isFailure(resolved))\n return refuse(Response.json({ error: resolved.failure.message }, { status: 401 }))\n const principal = resolved.success\n // A throw is a rejection like any other: a 500.\n const journal = await Promise.resolve()\n .then(options.journal)\n .catch(() => undefined)\n if (journal === undefined) return refuse(internalError())\n // An application's `opens` or `settle` may throw: a 500, before any socket opens.\n let exchange: JournalExchangeOptions<Message, Shared, Principal>\n try {\n const { admit, settle, opens } = options\n exchange = {\n sync: options.sync,\n journal,\n principal,\n ...(settle === undefined ? {} : { settle: settle(journal) }),\n ...(opens === undefined ? {} : { opens: opens(principal) }),\n ...(admit === undefined\n ? {}\n : { admit: (operation: Operation) => admit(principal, operation) }),\n }\n } catch (error) {\n console.error('[foldkit-sync] answering an upgrade broke:', error)\n return refuse(internalError())\n }\n return Result.succeed({\n abandon: release,\n serve: socket => {\n const stop = serveJournal(socket, exchange)\n const { revalidate } = options\n if (revalidate !== undefined) {\n const { every, key } = revalidate\n const checking = Effect.sleep(every).pipe(\n Effect.andThen(resolve),\n Effect.flatMap(now =>\n key === undefined || key(principal) === key(now) ? Effect.void : Effect.fail(changed),\n ),\n Effect.forever,\n Effect.catchCause(cause =>\n Effect.sync(() => {\n // Before closing: a socket may fire its own close only on the\n // replica's reply, and frames in flight until then would\n // still be appended as the principal just refused.\n stop()\n const [code, reason] = Option.match(Cause.findErrorOption(cause), {\n // A defect: this side broke, and the replica learns that it did.\n onNone: () => [1011, 'Internal error'] as const,\n onSome: error =>\n error === changed\n ? ([1012, 'Who is asking changed'] as const)\n : ([4401, error.message] as const),\n })\n try {\n socket.closeWith(code, reason)\n } catch {\n // A reason the platform refuses (past 123 bytes): the code alone.\n socket.close()\n } finally {\n release()\n }\n }),\n ),\n )\n const fiber = Effect.runFork(checking)\n socket.onClose(() => void Effect.runFork(Fiber.interrupt(fiber)))\n }\n socket.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SAAS,MAAM,IAAI,GAAG,IAAI,OAAO,OAAO,OAAO,KAAK,OAAO,CACtF,GACA,OAAO,SACP,OAAO,YAAW,UAChB,OAAO,WAAW;MAIhB,KAAK;MACL,MAAM,CAAC,MAAM,UAAU,OAAO,MAAM,MAAM,gBAAgB,KAAK,GAAG;OAEhE,cAAc,CAAC,MAAM,gBAAgB;OACrC,SAAQ,UACN,UAAU,UACL,CAAC,MAAM,uBAAuB,IAC9B,CAAC,MAAM,MAAM,OAAO;MAC7B,CAAC;MACD,IAAI;OACF,OAAO,UAAU,MAAM,MAAM;MAC/B,QAAQ;OAEN,OAAO,MAAM;MACf,UAAU;OACR,QAAQ;MACV;KACF,CAAC,CACH,CACF;KACA,MAAM,QAAQ,OAAO,QAAQ,QAAQ;KACrC,OAAO,cAAc,KAAK,OAAO,QAAQ,MAAM,UAAU,KAAK,CAAC,CAAC;IAClE;IACA,OAAO,QAAQ,OAAO;GACxB;EACF,CAAC;CACH;AACF"}
|
package/dist/journal.d.mts
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import { E as TransportClient, M as SocketLike, n as AuthorizeDecision, v as Operation, w as Sync } from "./make-
|
|
1
|
+
import { E as TransportClient, M as SocketLike, n as AuthorizeDecision, v as Operation, w as Sync } from "./make-DJ0Q1SSc.mjs";
|
|
2
2
|
import { Cause, Duration, Effect, Layer, Option, Result, Schema } from "effect";
|
|
3
3
|
import { Journal } from "foldkit-durable/core";
|
|
4
4
|
import { RemoteUnauthenticated } from "foldkit-remote";
|
|
5
|
-
//#region src/journal.d.ts
|
|
6
5
|
export interface JournalExchangeOptions<Message, Shared, Principal> {
|
|
7
6
|
/** The document's contract: its codecs, and the snapshot a checkpoint encodes. */
|
|
8
7
|
readonly sync: Sync<Message, Shared>;
|
|
@@ -211,6 +210,5 @@ export type DocumentHostOptionsLayer<RP> = [RP] extends [never] ? {
|
|
|
211
210
|
* never will, which releases what the upgrade built.
|
|
212
211
|
*/
|
|
213
212
|
export declare const documentHost: <Message, Shared, Principal, RP = never>(options: DocumentHostOptions<Message, Shared, Principal, RP> & DocumentHostOptionsLayer<RP>) => ((request: Request) => Promise<Result.Result<Accepted, Response>>);
|
|
214
|
-
//#endregion
|
|
215
213
|
export {};
|
|
216
214
|
//# sourceMappingURL=journal.d.mts.map
|
package/dist/journal.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal.d.mts","names":[],"sources":["../src/journal.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"journal.d.mts","names":[],"sources":["../src/journal.ts"],"mappings":";;;;iBAuCiB,uBAAuB,SAAS,QAAQ;;WAE9C,MAAM,KAAK,SAAS;;;;;WAKpB,SAAS,QAAQ,WAAW,QAAQ,WAAW;;;;;WAK/C,WAAW;;;;;;WAMX,SAAS,OAAO;;;;;;WAMhB,QAAQ,OAAO;;;;;;;;;;WAUf,UACH,WAAW,cAAc,oBAAoB,OAAO,OAAO;;WAGxD;;;;;;;;;;;;;;;qBAuBE,kBAAmB,SAAS,QAAQ,WAAS,SAC/C,uBAAuB,SAAS,QAAQ,eAChD;;;;;qBAqHU,iBACV,QAAQ,WAAS,SACP,QAAQ,WAAW,QAAQ,WAAW,YAAU,yBAEtD;;;;;;qBAgBM,eAAgB,SAAS,QAAQ,WAAS,QAC7C,YAAU,SACT,uBAAuB,SAAS,QAAQ;;;;;;;;;;;qBA8BtC,iCAAiC;MAI/B;;iBAKE,oBAAoB,QAAQ,WAAW;;WAE7C;;WAEA,SAAS,QAAQ,WAAW,QAAQ,WAAW;;;;;;WAM/C,UAAU,WAAW,cAAc,OAAO;aACxC,SAAS,cAAc;aACvB,IAAI,OAAO;;;;;;;;;;;;;WAab,QAAQ,QAAQ,QAAQ,eAAe,OAAO;;;;;;;WAO9C,eAAe,OAAO;;WAEtB,eAAe,UAAU,QAAQ;;;;;;WAMjC,WAAW,iBAAiB,mBAAmB;;WAE/C,QAAQ;;;;;;;;;;;;;;qBAeN,eAAgB,QAAQ,WAAW,QAAM,SAC3C,oBAAoB,QAAQ,WAAW;WAEvC,QAAQ,OAAO;WACf,QAAQ,OAAO;;;iBA0DT,mBAAmB;;EAElC,UAAU,cAAc;;;;;;;;iBAST;WACN,QAAQ,QAAQ;WAChB;;;iBAIM,oBAAoB,SAAS,QAAQ,WAAW;WACtD,MAAM,KAAK,SAAS;;;;;WAKpB,eAAe,QAAQ,QAAQ,WAAW,QAAQ,WAAW;;;;;;;;WAQ7D,mBACP,SAAS,YACN,OAAO,OAAO,WAAW,uBAAuB;;;;;;;;;WAS5C;aAEM,OAAO,SAAS;aAChB,QAAQ,WAAW;;;WAIzB,WACH,SAAS,QAAQ,WAAW,QAAQ,WAAW,eAAe,OAAO;;WAGlE,UAAU,WAAW,cAAc,OAAO;;WAE1C,UAEH,WAAW,WACX,WAAW,cACR,oBAAoB,OAAO,OAAO;;;;;;;;YAejC,yBAAyB,OAAO;WAC7B;;WACA,aAAa,MAAM,MAAM;;;;;;;;;;;;qBAY3B,eAAgB,SAAS,QAAQ,WAAW,YAAU,SACxD,oBAAoB,SAAS,QAAQ,WAAW,MAAM,yBAAyB,UACrF,SAAS,YAAY,QAAQ,OAAO,OAAO,UAAU"}
|
package/dist/journal.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as TableAheadOfJournalError, n as documentHost, r as editsJournal, i as journalChanges, a as journalExchange, o as serveJournal } from "./journal-
|
|
1
|
+
export { t as TableAheadOfJournalError, n as documentHost, r as editsJournal, i as journalChanges, a as journalExchange, o as serveJournal } from "./journal-D5h-jqXE.mjs";
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Config, Context, Duration, Effect, Layer, Metric, Option, Schema, Stream } from "effect";
|
|
2
2
|
import { AppScope, Contract, MergeConstructors, MergeFields, MessageSet, RunnableApplication, Surface, Wiring, WritableProjection } from "foldkit-surface";
|
|
3
|
-
//#region src/ids.d.ts
|
|
4
3
|
/** Identifies the replicated document a replica or operation belongs to. */
|
|
5
4
|
declare const DocumentId: Schema.brand<Schema.NonEmptyString, "@foldkit-sync/DocumentId">;
|
|
6
5
|
type DocumentId = typeof DocumentId.Type;
|
|
@@ -29,8 +28,6 @@ declare const replicaId: (value: string) => ReplicaId;
|
|
|
29
28
|
declare const opId: (value: string) => OpId;
|
|
30
29
|
declare const sequence: (value: number) => Sequence;
|
|
31
30
|
declare const localSequence: (value: number) => LocalSequence;
|
|
32
|
-
//#endregion
|
|
33
|
-
//#region src/errors.d.ts
|
|
34
31
|
declare const StorageError_base: Schema.Class<StorageError, Schema.TaggedStruct<"StorageError", {
|
|
35
32
|
readonly message: Schema.String;
|
|
36
33
|
readonly cause: Schema.optional<Schema.Unknown>;
|
|
@@ -119,8 +116,6 @@ declare const ReplayError_base: Schema.Class<ReplayError, Schema.TaggedStruct<"R
|
|
|
119
116
|
*/
|
|
120
117
|
declare class ReplayError extends ReplayError_base {}
|
|
121
118
|
type ReplicaError = StorageError | ReplayError | WrongReplicaStorageError | InvalidReplicaHistoryError | InvalidExchangeError | UnsupportedReplicaVersionError | InvalidOutboxError | CheckpointRegressionError | CommittedOrderError | ForeignRejectionError | ForeignAcknowledgementError | ReplicaClosedError;
|
|
122
|
-
//#endregion
|
|
123
|
-
//#region src/indexedDb.d.ts
|
|
124
119
|
/** One submitted operation, as `Storage.append` records it. */
|
|
125
120
|
interface OutboxEntry {
|
|
126
121
|
/** The replica's revision once this operation is in its outbox. */
|
|
@@ -154,8 +149,6 @@ interface Storage {
|
|
|
154
149
|
}
|
|
155
150
|
/** One database per document/replica; CAS prevents two tabs from sharing a writer identity. */
|
|
156
151
|
declare const indexedDb: (name: string | Config.Config<string>, factory?: IDBFactory | undefined) => Effect.Effect<Required<Storage>, StorageError, import("effect/Scope").Scope>;
|
|
157
|
-
//#endregion
|
|
158
|
-
//#region src/transport.d.ts
|
|
159
152
|
declare const TransportError_base: Schema.Class<TransportError, Schema.TaggedStruct<"SyncTransportError", {
|
|
160
153
|
readonly message: Schema.String;
|
|
161
154
|
}>, import("effect/Cause").YieldableError>;
|
|
@@ -300,8 +293,6 @@ declare const workerSocket: (socket: WebSocket) => SocketLike;
|
|
|
300
293
|
* ends.
|
|
301
294
|
*/
|
|
302
295
|
declare const layerSocket: (options: SocketOptions) => Layer.Layer<Transport, TransportError>;
|
|
303
|
-
//#endregion
|
|
304
|
-
//#region src/sync.d.ts
|
|
305
296
|
/** Wire and persisted-format versions. A bump must handle the older value explicitly. */
|
|
306
297
|
declare const PROTOCOL_VERSION = 1;
|
|
307
298
|
declare const SCHEMA_VERSION = 1;
|
|
@@ -551,8 +542,6 @@ interface JournalContract<Operation, Shared> {
|
|
|
551
542
|
* and reconciliation as Effects, and never runs a second reducer.
|
|
552
543
|
*/
|
|
553
544
|
declare const defineSync: <Message, Shared, MessageEncoded, SharedEncoded>(definition: SyncDefinition<Message, Shared, MessageEncoded, SharedEncoded>) => Sync<Message, Shared>;
|
|
554
|
-
//#endregion
|
|
555
|
-
//#region src/make.d.ts
|
|
556
545
|
type MessageConstructor<Message> = (...args: never[]) => Message;
|
|
557
546
|
/** The Message union a tuple of constructors produces. */
|
|
558
547
|
type MsgOf<Ms extends readonly unknown[]> = Ms[number] extends ((...args: never[]) => infer M) ? M : never;
|
|
@@ -709,6 +698,5 @@ interface ApplicationSync<AppModel, F extends Schema.Struct.Fields, Cases extend
|
|
|
709
698
|
* derive from.
|
|
710
699
|
*/
|
|
711
700
|
declare const forApplication: <AppModel, F extends Schema.Struct.Fields, Cases extends Record<string, Schema.Struct.Fields>>(app: RunnableApplication<AppModel, F, Cases, any>) => ApplicationSync<AppModel, F, Cases>;
|
|
712
|
-
//#endregion
|
|
713
701
|
export { InvalidOutboxError as $, ExchangeReply as A, nativeSocket as B, ReplicaStatus as C, defineSync as D, TransportClient as E, TransportError as F, OutboxEntry as G, serveSocket as H, TransportShape as I, CheckpointRegressionError as J, Storage as K, layerFromPromise as L, SocketLike as M, SocketOptions as N, syncMetrics as O, Transport as P, InvalidExchangeError as Q, layerLoopback as R, ReplicaState as S, SyncDefinition as T, toPromise as U, portSocket as V, workerSocket as W, ForeignAcknowledgementError as X, CommittedOrderError as Y, ForeignRejectionError as Z, JournalContract as _, sequence as _t, DefinedSync as a, UnsupportedClockVersionError as at, Replica as b, MsgOf as c, DocumentId as ct, SyncFragment as d, ReplicaId as dt, InvalidReplicaHistoryError as et, forApplication as f, Sequence as ft, Exchange as g, replicaId as gt, CommittedOperation as h, opId as ht, AuthorizeRequest as i, StorageError as it, NotifyFrame as j, ExchangeFrame as k, PolicyJournalContract as l, LocalSequence as lt, CommitStamp as m, localSequence as mt, AuthorizeDecision as n, ReplicaClosedError as nt, FragmentMessages as o, UnsupportedReplicaVersionError as ot, Checkpoint as p, documentId as pt, indexedDb as q, AuthorizePolicy as r, ReplicaError as rt, MakeOptions as s, WrongReplicaStorageError as st, ApplicationSync as t, ReplayError as tt, StampPolicy as u, OpId as ut, Operation as v, Sync as w, ReplicaSnapshot as x, Rejection as y, layerSocket as z };
|
|
714
|
-
//# sourceMappingURL=make-
|
|
702
|
+
//# sourceMappingURL=make-DJ0Q1SSc.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"make-DJ0Q1SSc.d.mts","names":[],"sources":["../src/ids.ts","../src/errors.ts","../src/indexedDb.ts","../src/transport.ts","../src/sync.ts","../src/make.ts"],"mappings":";;;cAGa,YAAU,OAAA,MAAA,OAAA;KACX,oBAAoB,WAAW;;cAG9B,WAAS,OAAA,MAAA,OAAA;KACV,mBAAmB,UAAU;;cAG5B,MAAI,OAAA,MAAA,OAAA;KACL,cAAc,KAAK;;;;;cAMlB,UAAQ,OAAA,MAAA,OAAA;KAKT,kBAAkB,SAAS;;cAG1B,eAAa,OAAA,MAAA,OAAA;KAKd,uBAAuB,cAAc;;;;;;cAOpC,aAAU,kBAAoB;cAC9B,YAAS,kBAAoB;cAC7B,OAAI,kBAAoB;cACxB,WAAQ,kBAAoB;cAC5B,gBAAa,kBAAoB;;;;;;cCvCjC,qB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Q,IAAI;eACxC,WAAW,gBAAgB,WAAW,QAAQ,SAAS,QAAQ;QAEzE,YAAY,UAAU,QAAQ,WAAW,UAAU,GAAG,QAAQ,IAAI;KAEnE,eAAe,OAAO,OAAO,QAC7B,QACA,oBAAoB,mBAAmB,WAAW,UAAU,GAAG,WAE/D,SAAS,YAAY,UAAU,QAAQ,QAAQ,IAAI,aAClD,YAAY,UAAU,QAAQ,WAAW,UAAU,GAAG,QAAQ,IAAI;;;;;;;;;;;cAqF5D,iBACX,UACA,UAAU,OAAO,OAAO,QACxB,cAAc,eAAe,OAAO,OAAO,SAAO,KAE7C,oBAAoB,UAAU,GAAG,gBACrC,gBAAgB,UAAU,GAAG"}
|
package/dist/remote.d.mts
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { Author } from "./entity.mjs";
|
|
2
2
|
import { Option, Schema } from "effect";
|
|
3
3
|
import { OptimisticOperation, RemoteModel } from "foldkit-remote";
|
|
4
|
-
//#region src/remote.d.ts
|
|
5
4
|
/** What `RemoteEdits.make` uses of a Remote domain: `Remote.make`'s value is one. */
|
|
6
5
|
export interface RemoteOverlays<AppModel> {
|
|
7
6
|
readonly store: {
|
|
@@ -90,6 +89,5 @@ export declare const RemoteEdits: {
|
|
|
90
89
|
make: typeof make;
|
|
91
90
|
};
|
|
92
91
|
export type RemoteEdits<AppModel, Edit extends AnyEdit> = ReturnType<typeof make<AppModel, Edit>>;
|
|
93
|
-
//#endregion
|
|
94
92
|
export {};
|
|
95
93
|
//# sourceMappingURL=remote.d.mts.map
|
package/dist/remote.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote.d.mts","names":[],"sources":["../src/remote.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"remote.d.mts","names":[],"sources":["../src/remote.ts"],"mappings":";;;;iBAyBiB,eAAe;WACrB;IAAS,IAAI,OAAO,WAAW;;EACxC,QAAQ,OAAO,UAAU,YAAY,YAAY,cAAc,uBAAuB;EACtF,KAAK,OAAO,UAAU,aAAa;EACnC,SAAS,OAAO,WAAW;;;iBAIZ,QAAQ;WACd;aAAmB;;WACnB,MAAM,OAAO,MAAM;EAC5B,KAAK,MAAM,MAAM;;;UAIT;WACC;WACA,IAAI,OAAO;WACX,IAAI,OAAO,OAAO;;;iBAWZ,UAAU;WAChB,MAAM;;WAEN;;;iBAIM,WAAW,UAAU;WAC3B,OAAO;;;;;;WAMP,MAAM,cAAc;;;;;;WAMpB,UAAU,cAAc;;cAG7B,OAAQ,UAAU,aAAa,SAAO,MACpC,eAAe,WAAS,OACvB,QAAQ;;;;;;;;;;;;;;;;;EA6Eb,YAAS,OACA,UAAQ,OACR,cAAc,OAAK,oBAEzB,WAAW,UAAU;;;;;;EA8DxB,QAAK,OAAU,aAAW,cAAc,UAAU;;;;;EAWlD,QAAK,OAAU,aAAW;;qBAKjB;;;;;;;;;;;;YAYD,YAAY,UAAU,aAAa,WAAW,kBAAkB,KAAK,UAAU"}
|
package/dist/remote.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Equal, Option, Schema } from "effect";
|
|
2
2
|
import { entityKey, readField } from "foldkit-remote";
|
|
3
|
-
|
|
3
|
+
// src/remote.ts
|
|
4
4
|
/**
|
|
5
5
|
* `foldkit-sync/remote`: a slice's cell edits shown through Remote, as
|
|
6
6
|
* request-less overlays every read draws, until the row Remote holds has them.
|
|
@@ -157,7 +157,6 @@ const RemoteEdits = {
|
|
|
157
157
|
* ```
|
|
158
158
|
*/
|
|
159
159
|
make };
|
|
160
|
-
//#endregion
|
|
161
160
|
export { RemoteEdits };
|
|
162
161
|
|
|
163
162
|
//# sourceMappingURL=remote.mjs.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from "effect";
|
|
2
|
-
|
|
2
|
+
// src/ids.ts
|
|
3
3
|
/** Identifies the replicated document a replica or operation belongs to. */
|
|
4
4
|
const DocumentId = Schema.NonEmptyString.pipe(Schema.brand("@foldkit-sync/DocumentId"));
|
|
5
5
|
/** Identifies one replica (writer identity) within a document. */
|
|
@@ -23,8 +23,7 @@ const replicaId = (value) => Schema.decodeUnknownSync(ReplicaId)(value);
|
|
|
23
23
|
const opId = (value) => Schema.decodeUnknownSync(OpId)(value);
|
|
24
24
|
const sequence = (value) => Schema.decodeUnknownSync(Sequence)(value);
|
|
25
25
|
const localSequence = (value) => Schema.decodeUnknownSync(LocalSequence)(value);
|
|
26
|
-
|
|
27
|
-
//#region src/transport.ts
|
|
26
|
+
// src/transport.ts
|
|
28
27
|
/** The wire failure of a transport. A refusal is a result, not an error. */
|
|
29
28
|
var TransportError = class extends Schema.TaggedError()("SyncTransportError", { message: Schema.String }) {};
|
|
30
29
|
/**
|
|
@@ -406,7 +405,6 @@ const layerSocket = (options) => Layer.effect(Transport, Effect.fn("Transport.la
|
|
|
406
405
|
})
|
|
407
406
|
});
|
|
408
407
|
})());
|
|
409
|
-
//#endregion
|
|
410
408
|
export { localSequence as _, layerSocket as a, sequence as b, serveSocket as c, DocumentId as d, LocalSequence as f, documentId as g, Sequence as h, layerLoopback as i, toPromise as l, ReplicaId as m, TransportError as n, nativeSocket as o, OpId as p, layerFromPromise as r, portSocket as s, Transport as t, workerSocket as u, opId as v, replicaId as y };
|
|
411
409
|
|
|
412
|
-
//# sourceMappingURL=transport-
|
|
410
|
+
//# sourceMappingURL=transport-BZ6utYmB.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport-DiKXy5zx.mjs","names":[],"sources":["../src/ids.ts","../src/transport.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Identifies the replicated document a replica or operation belongs to. */\nexport const DocumentId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/DocumentId'))\nexport type DocumentId = typeof DocumentId.Type\n\n/** Identifies one replica (writer identity) within a document. */\nexport const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/ReplicaId'))\nexport type ReplicaId = typeof ReplicaId.Type\n\n/** The stable identity of one operation within a document. */\nexport const OpId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/OpId'))\nexport type OpId = typeof OpId.Type\n\n/**\n * A position in the committed document order. `0` is the start; a committed\n * operation's `serverSequence` and a replica's `cursor` are the same family.\n */\nexport const Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/Sequence'))\nexport type Sequence = typeof Sequence.Type\n\n/** A replica's own operation counter within a document; 1-based. */\nexport const LocalSequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/LocalSequence'))\nexport type LocalSequence = typeof LocalSequence.Type\n\n/**\n * Decode-and-brand helpers. A branded schema constructs the same value with\n * `DocumentId.make('todos')`, which is the spelling to lead with; these stay\n * for callers that already have them.\n */\nexport const documentId = (value: string): DocumentId => Schema.decodeUnknownSync(DocumentId)(value)\nexport const replicaId = (value: string): ReplicaId => Schema.decodeUnknownSync(ReplicaId)(value)\nexport const opId = (value: string): OpId => Schema.decodeUnknownSync(OpId)(value)\nexport const sequence = (value: number): Sequence => Schema.decodeUnknownSync(Sequence)(value)\nexport const localSequence = (value: number): LocalSequence =>\n Schema.decodeUnknownSync(LocalSequence)(value)\n","import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.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<Operation>\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<Operation>,\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 * The connection itself, for another protocol to share, such as presence: a send goes to\n * the socket open now and is dropped while none is, and messages from every socket the\n * transport opens arrive here. It is the transport's to close.\n */\n readonly socket?: SocketLike | 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\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<Operation>,\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<Operation>,\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<Operation>,\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 = (options: SocketOptions): Layer.Layer<Transport, TransportError> =>\n Layer.effect(\n Transport,\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\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\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 {}\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 return Transport.of({\n changes: Stream.fromPubSub(notices),\n socket: shared,\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.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kC,WAAU;GACjD,IAAI,UAAU;IACZ,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,WAAW,cAAc,CAAC,OAAO;IACnC,OAAO,OAAO,KAAK,IAAI,eAAe,EAAE,SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,OAAO,SAAS,SAAS,QAAQ,UAAU;IAC7C,OAAO,OAAO,KAAK,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;AACH,CAAC,CAAC,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"transport-BZ6utYmB.mjs","names":[],"sources":["../src/ids.ts","../src/transport.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** Identifies the replicated document a replica or operation belongs to. */\nexport const DocumentId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/DocumentId'))\nexport type DocumentId = typeof DocumentId.Type\n\n/** Identifies one replica (writer identity) within a document. */\nexport const ReplicaId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/ReplicaId'))\nexport type ReplicaId = typeof ReplicaId.Type\n\n/** The stable identity of one operation within a document. */\nexport const OpId = Schema.NonEmptyString.pipe(Schema.brand('@foldkit-sync/OpId'))\nexport type OpId = typeof OpId.Type\n\n/**\n * A position in the committed document order. `0` is the start; a committed\n * operation's `serverSequence` and a replica's `cursor` are the same family.\n */\nexport const Sequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(0),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/Sequence'))\nexport type Sequence = typeof Sequence.Type\n\n/** A replica's own operation counter within a document; 1-based. */\nexport const LocalSequence = Schema.Number.check(\n Schema.isInt(),\n Schema.isGreaterThanOrEqualTo(1),\n Schema.isLessThanOrEqualTo(Number.MAX_SAFE_INTEGER),\n).pipe(Schema.brand('@foldkit-sync/LocalSequence'))\nexport type LocalSequence = typeof LocalSequence.Type\n\n/**\n * Decode-and-brand helpers. A branded schema constructs the same value with\n * `DocumentId.make('todos')`, which is the spelling to lead with; these stay\n * for callers that already have them.\n */\nexport const documentId = (value: string): DocumentId => Schema.decodeUnknownSync(DocumentId)(value)\nexport const replicaId = (value: string): ReplicaId => Schema.decodeUnknownSync(ReplicaId)(value)\nexport const opId = (value: string): OpId => Schema.decodeUnknownSync(OpId)(value)\nexport const sequence = (value: number): Sequence => Schema.decodeUnknownSync(Sequence)(value)\nexport const localSequence = (value: number): LocalSequence =>\n Schema.decodeUnknownSync(LocalSequence)(value)\n","import { Clock, Context, Duration, Effect, Layer, PubSub, Schema, Stream } from 'effect'\nimport { sequence } from './ids.js'\nimport type { Operation, TransportClient } from './sync.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<Operation>\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<Operation>,\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 * The connection itself, for another protocol to share, such as presence: a send goes to\n * the socket open now and is dropped while none is, and messages from every socket the\n * transport opens arrive here. It is the transport's to close.\n */\n readonly socket?: SocketLike | 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\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<Operation>,\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<Operation>,\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<Operation>,\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 = (options: SocketOptions): Layer.Layer<Transport, TransportError> =>\n Layer.effect(\n Transport,\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\n interface Entry {\n readonly id: string\n readonly cursor: number\n readonly pending: ReadonlyArray<Operation>\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 {}\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 return Transport.of({\n changes: Stream.fromPubSub(notices),\n socket: shared,\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 })(),\n )\n"],"mappings":";;;AAGA,MAAa,aAAa,OAAO,eAAe,KAAK,OAAO,MAAM,0BAA0B,CAAC;;AAI7F,MAAa,YAAY,OAAO,eAAe,KAAK,OAAO,MAAM,yBAAyB,CAAC;;AAI3F,MAAa,OAAO,OA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SAAS,mBAAmB,CAAC,CAAC,CAAC;IACvE;GACF;GACA,IAAI,OAAO,SAAS,SAAS,QAAQ,UAAU;IAC7C,OAAO,OAAO,KAAK,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;AACH,CAAC,CAAC,CAAC,CACL"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-sync",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.4",
|
|
4
4
|
"description": "A local-first replica of a shared Foldkit projection: offline outbox, optimistic updates, and reconciliation.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -65,7 +65,7 @@
|
|
|
65
65
|
"effect": "^4.0.0",
|
|
66
66
|
"foldkit": "^0.169.0",
|
|
67
67
|
"foldkit-durable": "0.9.1",
|
|
68
|
-
"foldkit-remote": "0.
|
|
68
|
+
"foldkit-remote": "0.21.0"
|
|
69
69
|
},
|
|
70
70
|
"peerDependenciesMeta": {
|
|
71
71
|
"foldkit-durable": {
|
|
@@ -88,8 +88,8 @@
|
|
|
88
88
|
"typescript": "7.0.2",
|
|
89
89
|
"foldkit-agent": "0.8.3",
|
|
90
90
|
"foldkit-durable": "0.9.1",
|
|
91
|
-
"foldkit-
|
|
92
|
-
"foldkit-
|
|
91
|
+
"foldkit-entity": "0.13.0",
|
|
92
|
+
"foldkit-remote": "0.21.0"
|
|
93
93
|
},
|
|
94
94
|
"scripts": {
|
|
95
95
|
"build": "tsdown",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"make-CFOcLcQ1.d.mts","names":[],"sources":["../src/ids.ts","../src/errors.ts","../src/indexedDb.ts","../src/transport.ts","../src/sync.ts","../src/make.ts"],"mappings":";;;;cAGa,YAAU,OAAA,MAAA,OAAA;KACX,oBAAoB,WAAW;;cAG9B,WAAS,OAAA,MAAA,OAAA;KACV,mBAAmB,UAAU;;cAG5B,MAAI,OAAA,MAAA,OAAA;KACL,cAAc,KAAK;;;;;cAMlB,UAAQ,OAAA,MAAA,OAAA;KAKT,kBAAkB,SAAS;;cAG1B,eAAa,OAAA,MAAA,OAAA;KAKd,uBAAuB,cAAc;;;;;;cAOpC,aAAU,kBAAoB;cAC9B,YAAS,kBAAoB;cAC7B,OAAI,kBAAoB;cACxB,WAAQ,kBAAoB;cAC5B,gBAAa,kBAAoB;;;;;;;;cCvCjC,qBAAqB;;;;;;cAMrB,qCAAqC;;;;;;;cASrC,iCAAiC;;;;;;cAUjC,mCAAmC;;;;;;cASnC,6BAA6B;;;;;cAS7B,2BAA2B;;;;;;;cAQ3B,kCAAkC;;;;;;;cAUlC,4BAA4B;;;;;;cAU5B,8BAA8B;;;;;;;;;;cAa9B,oCAAoC;;;;;cASpC,2BAA2B;;;;;;;cAQ3B,uCAAuC;;;;;;;;;cAavC,oBAAoB;KAKrB,eACR,eACA,cACA,2BACA,6BACA,uBACA,iCACA,qBACA,4BACA,sBACA,wBACA,8BACA;;;;UClIa;;WAEN;WACA;;;;;WAKA;;WAEA;;;UAIM;;;;;EAKf,YAAY,OAAO,gBAAgB;;EAEnC,OAAO,gBAAgB,oCAAoC,OAAO,aAAa;;;;;;EAM/E,UAAU,OAAO,aAAa,6BAA6B,OAAO,aAAa;;EAE/E,OAAO,OAAO;;;cAwCH,YAAS,eAAA,OAAA,gBAAA,UAAA,2BAAA,O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