@party-stack/ontology-backend 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +148 -2
  3. package/lib/actions.d.ts +47 -0
  4. package/lib/actions.d.ts.map +1 -0
  5. package/lib/actions.js +306 -0
  6. package/lib/actions.js.map +1 -0
  7. package/lib/clients.d.ts +236 -0
  8. package/lib/clients.d.ts.map +1 -0
  9. package/lib/clients.js +211 -0
  10. package/lib/clients.js.map +1 -0
  11. package/lib/delivery.d.ts +746 -0
  12. package/lib/delivery.d.ts.map +1 -0
  13. package/lib/delivery.js +863 -0
  14. package/lib/delivery.js.map +1 -0
  15. package/lib/description.d.ts +29 -0
  16. package/lib/description.d.ts.map +1 -0
  17. package/lib/description.js +28 -0
  18. package/lib/description.js.map +1 -0
  19. package/lib/encrypted.d.ts +41 -0
  20. package/lib/encrypted.d.ts.map +1 -0
  21. package/lib/encrypted.js +111 -0
  22. package/lib/encrypted.js.map +1 -0
  23. package/lib/errors.d.ts +106 -0
  24. package/lib/errors.d.ts.map +1 -0
  25. package/lib/errors.js +275 -0
  26. package/lib/errors.js.map +1 -0
  27. package/lib/fulfillment.d.ts +25 -0
  28. package/lib/fulfillment.d.ts.map +1 -0
  29. package/lib/fulfillment.js +99 -0
  30. package/lib/fulfillment.js.map +1 -0
  31. package/lib/index.d.ts +297 -0
  32. package/lib/index.d.ts.map +1 -0
  33. package/lib/index.js +91 -0
  34. package/lib/index.js.map +1 -0
  35. package/lib/maintenance.d.ts +11 -0
  36. package/lib/maintenance.d.ts.map +1 -0
  37. package/lib/maintenance.js +24 -0
  38. package/lib/maintenance.js.map +1 -0
  39. package/lib/meta.d.ts +26 -0
  40. package/lib/meta.d.ts.map +1 -0
  41. package/lib/meta.js +213 -0
  42. package/lib/meta.js.map +1 -0
  43. package/lib/owned.d.ts +74 -0
  44. package/lib/owned.d.ts.map +1 -0
  45. package/lib/owned.js +593 -0
  46. package/lib/owned.js.map +1 -0
  47. package/lib/policy/indexes.d.ts +12 -0
  48. package/lib/policy/indexes.d.ts.map +1 -0
  49. package/lib/policy/indexes.js +113 -0
  50. package/lib/policy/indexes.js.map +1 -0
  51. package/lib/policy/planner.d.ts +10 -0
  52. package/lib/policy/planner.d.ts.map +1 -0
  53. package/lib/policy/planner.js +118 -0
  54. package/lib/policy/planner.js.map +1 -0
  55. package/lib/policy/view.d.ts +31 -0
  56. package/lib/policy/view.d.ts.map +1 -0
  57. package/lib/policy/view.js +173 -0
  58. package/lib/policy/view.js.map +1 -0
  59. package/lib/policy.d.ts +47 -0
  60. package/lib/policy.d.ts.map +1 -0
  61. package/lib/policy.js +100 -0
  62. package/lib/policy.js.map +1 -0
  63. package/lib/protocol.d.ts +570 -0
  64. package/lib/protocol.d.ts.map +1 -0
  65. package/lib/protocol.js +144 -0
  66. package/lib/protocol.js.map +1 -0
  67. package/lib/query.d.ts +33 -0
  68. package/lib/query.d.ts.map +1 -0
  69. package/lib/query.js +51 -0
  70. package/lib/query.js.map +1 -0
  71. package/lib/references.d.ts +8 -0
  72. package/lib/references.d.ts.map +1 -0
  73. package/lib/references.js +41 -0
  74. package/lib/references.js.map +1 -0
  75. package/lib/storage.d.ts +55 -0
  76. package/lib/storage.d.ts.map +1 -0
  77. package/lib/storage.js +168 -0
  78. package/lib/storage.js.map +1 -0
  79. package/lib/subset.d.ts +19 -0
  80. package/lib/subset.d.ts.map +1 -0
  81. package/lib/subset.js +150 -0
  82. package/lib/subset.js.map +1 -0
  83. package/lib/subsetSchema.d.ts +10 -0
  84. package/lib/subsetSchema.d.ts.map +1 -0
  85. package/lib/subsetSchema.js +20 -0
  86. package/lib/subsetSchema.js.map +1 -0
  87. package/package.json +72 -3
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delivery.js","names":[],"sources":["../src/delivery.ts"],"sourcesContent":["import { cursorOf, eq, field, lte } from \"@party-stack/ontology-storage\";\nimport { digestBytes } from \"@party-stack/ontology-storage/blobs\";\nimport { Table } from \"@party-stack/ontology-storage/tables\";\nimport { Clock, Deferred, Effect, Option, Queue, Schema, Semaphore, Stream } from \"effect\";\nimport { ClientLeaseSchema } from \"./clients.js\";\nimport { CompiledSubsetSchema, PendingActionSchema, protocolValueCodec } from \"./protocol.js\";\nimport { BackendError, classifyBackendFailure } from \"./index.js\";\nimport type { Row } from \"@party-stack/ontology-storage\";\nimport type { TablesService, Transaction, ReadTransaction } from \"@party-stack/ontology-storage/tables\";\nimport type { Scope } from \"effect\";\n\nconst KeySchema = Schema.Union([Schema.String, Schema.Finite]);\nconst Value = Schema.Record(Schema.String, Schema.Unknown);\nexport const DeliveryRefSchema = Schema.Union([\n Schema.Struct({ kind: Schema.Literals([\"base\", \"override\"]), objectType: Schema.String, key: KeySchema }),\n Schema.Struct({ kind: Schema.Literals([\"pending\", \"completed\"]), id: Schema.String }),\n]);\nexport const DeliveryRecordSchema = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"base\"), objectType: Schema.String, key: KeySchema, value: Value }),\n Schema.Struct({\n kind: Schema.Literal(\"override\"),\n objectType: Schema.String,\n key: KeySchema,\n value: Schema.Union([\n Schema.Struct({ deleted: Schema.Literal(true) }),\n Schema.Struct({ deleted: Schema.Literal(false), value: Value }),\n ]),\n }),\n Schema.Struct({\n kind: Schema.Literals([\"pending\", \"completed\"]),\n id: Schema.String,\n value: PendingActionSchema,\n }),\n]);\nexport type DeliveryRef = Schema.Schema.Type<typeof DeliveryRefSchema>;\nexport type DeliveryRecord = Schema.Schema.Type<typeof DeliveryRecordSchema>;\nexport const DeliveryChangeSchema = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"put\"), record: DeliveryRecordSchema }),\n Schema.Struct({ kind: Schema.Literal(\"remove\"), ref: DeliveryRefSchema }),\n]);\nexport type DeliveryChange = Schema.Schema.Type<typeof DeliveryChangeSchema>;\nexport const DeliveryMetadataSchema = Schema.Struct({\n sourceId: Schema.NonEmptyString,\n schemaHash: Schema.NonEmptyString,\n generation: Schema.Int,\n revision: Schema.Int,\n cursor: Schema.optional(Schema.String),\n coverage: Schema.Array(\n Schema.Struct({\n subset: CompiledSubsetSchema,\n complete: Schema.Boolean,\n /** Previously confirmed resident coverage, independently of current freshness. */\n cached: Schema.optional(Schema.Boolean),\n })\n ),\n client: Schema.optional(ClientLeaseSchema),\n});\nexport type DeliveryMetadata = Schema.Schema.Type<typeof DeliveryMetadataSchema>;\nconst Counter = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }));\nexport const DeliveryPositionSchema = Schema.Struct({ streamId: Schema.NonEmptyString, sequence: Counter });\nexport type DeliveryPosition = Schema.Schema.Type<typeof DeliveryPositionSchema>;\nexport const DeliveryFrameSchema = Schema.Struct({\n ...DeliveryPositionSchema.fields,\n sequence: Counter.check(Schema.isGreaterThan(0)),\n previous: Counter,\n part: Counter,\n kind: Schema.Literals([\"snapshot\", \"patch\"]),\n changes: Schema.Array(DeliveryChangeSchema),\n end: Schema.Boolean,\n metadata: Schema.optional(DeliveryMetadataSchema),\n});\nexport type DeliveryFrame = Schema.Schema.Type<typeof DeliveryFrameSchema>;\nexport const DeliveryFrameCodec = protocolValueCodec(DeliveryFrameSchema);\nexport interface DeliverySubscription {\n readonly frames: Stream.Stream<DeliveryFrame, BackendError>;\n readonly acknowledge: (position: DeliveryPosition) => Effect.Effect<void, BackendError>;\n}\nexport interface IncomingDelivery {\n readonly kind: \"snapshot\" | \"patch\";\n readonly position: DeliveryPosition;\n readonly metadata: DeliveryMetadata;\n readonly forEach: (\n visit: (change: DeliveryChange) => Effect.Effect<void, BackendError>\n ) => Effect.Effect<void, BackendError>;\n}\nexport interface DeliveryPolicy {\n readonly maxRecords?: number;\n readonly maxBytes?: number;\n readonly frameBytes?: number;\n readonly frameRecords?: number;\n readonly maxSubscriptions?: number;\n readonly ackTimeoutMs?: number;\n readonly heartbeatMs?: number;\n /** Retain a disconnected logical subscription for resumption. Default 60 seconds. */\n readonly retentionMs?: number;\n}\nexport const deliveryRef = (record: DeliveryRecord): DeliveryRef =>\n record.kind === \"base\" || record.kind === \"override\"\n ? { kind: record.kind, objectType: record.objectType, key: record.key }\n : { kind: record.kind, id: record.id };\nexport const deliveryKey = (ref: DeliveryRef): string =>\n \"objectType\" in ref\n ? JSON.stringify([ref.kind, ref.objectType, ref.key])\n : JSON.stringify([ref.kind, ref.id]);\nconst recordCodec = Table.make<DeliveryRecord>({ name: \"delivery-record\" });\nconst valueCodec = Table.make({ name: \"delivery-value\" });\nconst size = (value: unknown) => new TextEncoder().encode(valueCodec.encode(value)).length;\nconst failure = (message: string, kind: BackendError[\"kind\"] = \"Unavailable\") =>\n new BackendError({\n operation: \"delivery\",\n kind,\n message,\n retryable: kind === \"Unavailable\" || kind === \"RateLimited\",\n });\nconst boundary = <A, E, R>(work: Effect.Effect<A, E, R>) =>\n work.pipe(Effect.mapError((cause) => classifyBackendFailure(\"delivery.storage\", cause)));\n\n/** Storage cursors keep baseline/staging scans bounded, including after a crash. */\nexport const scanDeliveryRows = Effect.fnUntraced(function* <A>(\n tx: Transaction,\n table: Table<A>,\n query: import(\"@party-stack/ontology-storage\").Query,\n visit: (\n row: Row<A>\n ) => Effect.Effect<void, BackendError | import(\"@party-stack/ontology-storage\").OntologyStorageError>\n) {\n let after = query.after;\n let remaining = query.limit;\n let offset = query.offset;\n for (;;) {\n const rows = yield* tx.query(table, {\n ...query,\n offset,\n after,\n limit: Math.min(128, remaining ?? 128),\n });\n if (!rows.length) return;\n for (const row of rows) yield* visit(row);\n if (remaining !== undefined) {\n remaining -= rows.length;\n if (remaining <= 0) return;\n }\n after = cursorOf(rows.at(-1)!, query);\n offset = undefined;\n if (rows.length < 128) return;\n }\n});\n\n/** Query pages preserve the original window while advancing by its complete sort cursor. */\nexport const scanSelectedRows = Effect.fnUntraced(function* <A>(\n load: (\n query: import(\"@party-stack/ontology-storage\").Query\n ) => Effect.Effect<readonly Row<A>[], BackendError>,\n query: import(\"@party-stack/ontology-storage\").Query = {},\n visit: (row: Row<A>) => Effect.Effect<void, BackendError>\n) {\n let after = query.after;\n let remaining = query.limit;\n let offset = query.offset;\n for (;;) {\n const rows = yield* load({ ...query, offset, after, limit: Math.min(128, remaining ?? 128) });\n if (!rows.length) return;\n for (const row of rows) yield* visit(row);\n if (remaining !== undefined) {\n remaining -= rows.length;\n if (remaining <= 0) return;\n }\n after = cursorOf(rows.at(-1)!, query);\n offset = undefined;\n if (rows.length < 128) return;\n }\n});\n\ninterface DeliverySession {\n format: 3;\n expiresAt: number;\n expected: number;\n acknowledged: number;\n binding: string;\n identity: string;\n rowSelection?: string;\n producer: string;\n installed: number;\n signature?: string;\n pending?: { sequence: number; metadata: DeliveryMetadata; nextSignature: string; count: number };\n}\nconst sessionTable = (namespace: string) =>\n Table.make<DeliverySession>({ name: JSON.stringify([namespace, \"delivery\", \"sessions\"]) });\nconst deleteStreamRows = Effect.fnUntraced(function* <A extends { stream: string }>(\n tx: Transaction,\n table: Table<A>,\n stream: string\n) {\n for (;;) {\n const rows = yield* tx.query(table, { where: eq(field(\"stream\"), stream), limit: 128 });\n if (!rows.length) return;\n // Keys are disjoint. Submit a bounded batch together instead of waiting\n // for an IndexedDB round trip for every expired witness/patch.\n yield* Effect.forEach(rows, (row) => tx.delete(table, row.key), { concurrency: 128, discard: true });\n }\n});\n/** Bounded indexed expiry, shared by admission and host maintenance. */\nexport const collectDeliveryGarbage = Effect.fn(\"Delivery.collectGarbage\")(function* (\n tables: TablesService,\n namespace: string,\n maxSessions = 4\n) {\n return yield* boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n const sessions = sessionTable(namespace);\n yield* tx.ensureIndex(sessions, { name: \"expiry\", field: field(\"expiresAt\") });\n const expired = yield* tx.query(sessions, {\n where: lte(field(\"expiresAt\"), yield* Clock.currentTimeMillis),\n limit: maxSessions,\n });\n for (const row of expired) {\n for (const part of [\"records\", \"patches\"]) {\n const table = Table.make<{ stream: string }>({\n name: JSON.stringify([namespace, \"delivery\", part]),\n });\n yield* tx.ensureIndex(table, { name: \"stream\", field: field(\"stream\") });\n yield* deleteStreamRows(tx, table, String(row.key));\n }\n yield* tx.delete(sessions, row.key);\n }\n return expired.length;\n })\n )\n );\n});\n/** Durable watermarks support ACK requests handled by another server instance.\n * The owning manager adds a local wakeup; producers also observe this stored position.\n */\nexport const acknowledgeDelivery = Effect.fn(\"Delivery.acknowledge\")(function* (\n tables: TablesService,\n namespace: string,\n position: DeliveryPosition\n) {\n yield* boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n const table = sessionTable(namespace);\n const session = yield* tx.get(table, position.streamId);\n if (!session || session.expiresAt < (yield* Clock.currentTimeMillis))\n return yield* failure(\"Delivery expired.\", \"HistoryExpired\");\n if (\n !Number.isSafeInteger(position.sequence) ||\n position.sequence < 0 ||\n position.sequence > session.expected\n )\n return yield* failure(\"Invalid delivery acknowledgment.\", \"Conflict\");\n if (position.sequence > session.acknowledged)\n yield* tx.put(table, position.streamId, { ...session, acknowledged: position.sequence });\n })\n )\n );\n});\ninterface DeliveryMemory {\n readonly gate: Semaphore.Semaphore;\n readonly acknowledgments: Queue.Queue<void>;\n gone: Deferred.Deferred<never, BackendError>;\n producer: string;\n expiresAt: number;\n witnesses: Map<string, { readonly ref: DeliveryRef; readonly hash: string }>;\n pending?: {\n readonly sequence: number;\n readonly changes: readonly string[];\n readonly sizes: readonly number[];\n };\n}\nexport interface DeliveryOpenOptions {\n /** Notify after every change affecting captured records or metadata. Events\n * may coalesce; reconnect captures current state to repair a subscription gap.\n * Heartbeats renew leases and fencing only, never poll the selected data. */\n readonly changes: Effect.Effect<Stream.Stream<void, BackendError>, BackendError, Scope.Scope>;\n readonly capture: (\n tx: Transaction,\n emit: (record: DeliveryRecord) => Effect.Effect<void, BackendError>\n ) => Effect.Effect<DeliveryMetadata, BackendError>;\n /** Renew an associated scoped client lease without capturing or advancing\n * delivered state. Runs with the producer fence in the same transaction. */\n readonly renew?: (tx: Transaction) => Effect.Effect<void, BackendError>;\n readonly policy?: DeliveryPolicy;\n readonly binding: string;\n readonly identity: string;\n /** Stable selected rows, excluding action interests and local generations. */\n readonly rowSelection?: string;\n readonly resume?: DeliveryPosition;\n}\nexport interface DeliveryManager {\n readonly open: (\n options: DeliveryOpenOptions\n ) => Effect.Effect<DeliverySubscription, BackendError, Scope.Scope>;\n readonly acknowledge: (position: DeliveryPosition) => Effect.Effect<void, BackendError>;\n readonly collectGarbage: Effect.Effect<number, BackendError>;\n}\n\n/** One source owner retains bounded view buffers. Losing this scope requires a new\n * data snapshot; action acceptance, receipts and results remain in their own durable stores.\n * The small session header stays durable so an ACK handled by another process can\n * advance the live producer's watermark without sharing its temporary row buffers.\n */\nexport const makeDeliveryManager = Effect.fnUntraced(function* (options: {\n readonly tables: TablesService;\n readonly namespace: string;\n}): Effect.fn.Return<DeliveryManager, never, Scope.Scope> {\n const { tables, namespace } = options;\n const sessions = sessionTable(namespace);\n const memories = new Map<string, DeliveryMemory>();\n const admission = Semaphore.makeUnsafe(1);\n let closed = false;\n const forget = Effect.fnUntraced(function* (\n stream: string,\n kind: \"HistoryExpired\" | \"SessionReplaced\" = \"HistoryExpired\"\n ) {\n const memory = memories.get(stream);\n if (!memory) return;\n memories.delete(stream);\n memory.pending = undefined;\n memory.witnesses.clear();\n yield* Deferred.fail(memory.gone, failure(\"Delivery view owner changed.\", kind));\n yield* Queue.offer(memory.acknowledgments, undefined);\n });\n const prune = Effect.fnUntraced(function* () {\n const now = yield* Clock.currentTimeMillis;\n for (const [stream, memory] of memories) if (memory.expiresAt <= now) yield* forget(stream);\n });\n yield* Effect.addFinalizer(() =>\n Effect.gen(function* () {\n closed = true;\n for (const stream of memories.keys()) yield* forget(stream);\n })\n );\n const legacy = (part: string) =>\n Table.make<{ stream: string }>({ name: JSON.stringify([namespace, \"delivery\", part]) });\n const clearLegacy = Effect.fnUntraced(function* (tx: Transaction, stream: string) {\n for (const part of [\"records\", \"patches\"]) yield* deleteStreamRows(tx, legacy(part), stream);\n });\n const acknowledge = Effect.fn(\"Delivery.acknowledgeLocal\")(function* (position: DeliveryPosition) {\n yield* acknowledgeDelivery(tables, namespace, position);\n const memory = memories.get(position.streamId);\n if (memory) yield* Queue.offer(memory.acknowledgments, undefined);\n });\n const open = Effect.fn(\"Delivery.open\")(function* (\n options: DeliveryOpenOptions\n ): Effect.fn.Return<DeliverySubscription, BackendError, Scope.Scope> {\n const limits = {\n maxRecords: 10_000,\n maxBytes: 16 * 1024 * 1024,\n frameBytes: 256 * 1024,\n frameRecords: 128,\n maxSubscriptions: 32,\n ackTimeoutMs: 30_000,\n heartbeatMs: 15_000,\n ...options.policy,\n retentionMs: options.policy?.retentionMs ?? 60_000,\n };\n if (Object.values(limits).some((n) => !Number.isSafeInteger(n) || n < 1))\n return yield* failure(\"Delivery limits must be positive integers.\", \"InvalidConfiguration\");\n const activeRetentionMs = Math.max(limits.retentionMs, limits.ackTimeoutMs + limits.heartbeatMs * 3);\n const producer = crypto.randomUUID();\n const acquire = admission.withPermits(1)(\n Effect.gen(function* () {\n if (closed) return yield* failure(\"Delivery owner closed.\", \"HistoryExpired\");\n yield* prune();\n const gone = yield* Deferred.make<never, BackendError>();\n const priorMemory = options.resume && memories.get(options.resume.streamId);\n const configure = Effect.gen(function* () {\n const outcome = yield* boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n yield* tx.ensureIndex(sessions, {\n name: \"expiry\",\n field: field(\"expiresAt\"),\n });\n const now = yield* Clock.currentTimeMillis;\n for (const expired of yield* tx.query(sessions, {\n where: lte(field(\"expiresAt\"), now),\n limit: limits.maxSubscriptions,\n })) {\n yield* clearLegacy(tx, String(expired.key));\n yield* tx.delete(sessions, expired.key);\n }\n let streamId = options.resume?.streamId ?? crypto.randomUUID();\n if (options.resume) {\n const prior = yield* tx.get(sessions, streamId);\n if (!prior || prior.expiresAt <= now || prior.binding !== options.binding)\n return yield* failure(\"Delivery history expired.\", \"HistoryExpired\");\n if (\n prior.format !== 3 ||\n !priorMemory ||\n (prior.pending &&\n priorMemory.pending?.sequence !== prior.pending.sequence)\n ) {\n // A lost owner cannot reconstruct its target hashes. Retire\n // only this binding-matched session, then report expiry after\n // commit so a bounded fresh snapshot can take its slot.\n yield* clearLegacy(tx, streamId);\n yield* tx.delete(sessions, streamId);\n return { kind: \"expired\" as const, streamId };\n }\n if (prior.identity === options.identity) {\n const position = options.resume.sequence;\n if (position < prior.installed || position > prior.expected)\n return yield* failure(\n \"Delivery position cannot resume.\",\n \"HistoryExpired\"\n );\n const header = {\n ...prior,\n producer,\n acknowledged: Math.max(prior.acknowledged, position),\n expiresAt: now + activeRetentionMs,\n };\n yield* tx.put(sessions, streamId, header);\n return {\n kind: \"resumed\" as const,\n streamId,\n memory: priorMemory,\n header,\n };\n }\n if (\n prior.pending &&\n prior.rowSelection !== undefined &&\n prior.rowSelection === options.rowSelection &&\n options.resume.sequence === prior.installed\n ) {\n // Action interests may change while a data target is still\n // in flight. Replay its immutable bytes before capturing the\n // new interests; only an installed target may be promoted.\n const header = {\n ...prior,\n identity: options.identity,\n producer,\n expiresAt: now + activeRetentionMs,\n };\n yield* tx.put(sessions, streamId, header);\n return {\n kind: \"resumed\" as const,\n streamId,\n memory: priorMemory,\n header,\n };\n }\n if (\n options.resume.sequence > 0 &&\n options.resume.sequence === prior.expected &&\n (!prior.pending || prior.pending.sequence === options.resume.sequence)\n ) {\n // The client proves it installed the target, even with a\n // lost ACK. Diff the new membership against that target;\n // never relabel the previous pending batch's bytes.\n const header = {\n ...prior,\n identity: options.identity,\n rowSelection: options.rowSelection,\n producer,\n acknowledged: options.resume.sequence,\n installed: options.resume.sequence,\n signature: prior.pending?.nextSignature ?? prior.signature,\n pending: undefined,\n expiresAt: now + activeRetentionMs,\n };\n yield* tx.put(sessions, streamId, header);\n return {\n kind: \"promoted\" as const,\n streamId,\n memory: priorMemory,\n header,\n };\n }\n yield* clearLegacy(tx, streamId);\n yield* tx.delete(sessions, streamId);\n streamId = crypto.randomUUID();\n }\n if (\n (yield* tx.query(sessions, { limit: limits.maxSubscriptions })).length >=\n limits.maxSubscriptions\n )\n return yield* failure(\n \"Delivery subscription capacity reached.\",\n \"RateLimited\"\n );\n const header: DeliverySession = {\n format: 3,\n expiresAt: now + activeRetentionMs,\n expected: 0,\n acknowledged: 0,\n installed: 0,\n binding: options.binding,\n identity: options.identity,\n rowSelection: options.rowSelection,\n producer,\n };\n yield* tx.put(sessions, streamId, header);\n return {\n kind: \"fresh\" as const,\n streamId,\n header,\n memory: {\n gate: Semaphore.makeUnsafe(1),\n acknowledgments: yield* Queue.sliding<void>(1),\n gone,\n producer,\n expiresAt: header.expiresAt,\n witnesses: new Map<string, { ref: DeliveryRef; hash: string }>(),\n } satisfies DeliveryMemory,\n };\n })\n )\n );\n if (outcome.kind === \"expired\") {\n yield* forget(outcome.streamId);\n return yield* failure(\n \"Delivery view owner changed; acquire a new snapshot.\",\n \"HistoryExpired\"\n );\n }\n if (closed) return yield* failure(\"Delivery owner closed.\", \"HistoryExpired\");\n if (options.resume && options.resume.streamId !== outcome.streamId)\n yield* forget(options.resume.streamId, \"SessionReplaced\");\n if (outcome.kind !== \"fresh\")\n yield* Deferred.fail(\n outcome.memory.gone,\n failure(\"Delivery connection was superseded.\", \"SessionReplaced\")\n );\n if (closed) return yield* failure(\"Delivery owner closed.\", \"HistoryExpired\");\n const memory: DeliveryMemory = outcome.memory;\n memory.gone = gone;\n memory.producer = producer;\n memory.expiresAt = outcome.header.expiresAt;\n if (outcome.kind === \"promoted\") memory.pending = undefined;\n memories.set(outcome.streamId, memory);\n return { streamId: outcome.streamId, memory, gone };\n });\n return yield* priorMemory ? priorMemory.gate.withPermits(1)(configure) : configure;\n })\n );\n const { streamId, memory, gone } = yield* Effect.acquireRelease(acquire, ({ streamId, memory }) =>\n memory.gate.withPermits(1)(\n boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n const session = yield* tx.get(sessions, streamId);\n if (session?.producer !== producer) return;\n const expiresAt = (yield* Clock.currentTimeMillis) + limits.retentionMs;\n yield* tx.put(sessions, streamId, { ...session, expiresAt });\n return expiresAt;\n })\n )\n ).pipe(\n Effect.tap((expiresAt) =>\n Effect.sync(() => {\n if (expiresAt !== undefined && memory.producer === producer)\n memory.expiresAt = expiresAt;\n })\n ),\n Effect.catch(() => Effect.void),\n Effect.ensuring(\n Effect.suspend(() =>\n memories.get(streamId) !== memory\n ? Queue.shutdown(memory.acknowledgments)\n : Effect.void\n )\n )\n )\n )\n );\n const current = (tx: ReadTransaction) =>\n Effect.gen(function* () {\n if (closed || memories.get(streamId) !== memory)\n return yield* failure(\"Delivery view owner changed.\", \"HistoryExpired\");\n const session = yield* tx.get(sessions, streamId);\n if (!session || session.producer !== producer || memory.producer !== producer)\n return yield* failure(\"Delivery connection was superseded.\", \"SessionReplaced\");\n return session;\n });\n const changes = yield* options.changes;\n const dirty = yield* Queue.sliding<void>(1);\n yield* Effect.addFinalizer(() => Queue.shutdown(dirty));\n yield* Stream.runForEach(changes, () => Queue.offer(dirty, undefined)).pipe(Effect.forkScoped);\n let consumed = false;\n const renew = memory.gate\n .withPermits(1)(\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const expiresAt = yield* restore(\n boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n const session = yield* current(tx);\n if (options.renew) yield* options.renew(tx);\n const expiresAt =\n (yield* Clock.currentTimeMillis) + activeRetentionMs;\n yield* tx.put(sessions, streamId, { ...session, expiresAt });\n return expiresAt;\n })\n )\n )\n );\n if (closed || memories.get(streamId) !== memory || memory.producer !== producer)\n return yield* failure(\"Delivery view owner changed.\", \"HistoryExpired\");\n memory.expiresAt = expiresAt;\n })\n )\n )\n .pipe(Effect.withSpan(\"Delivery.renew\", { attributes: { streamId } }));\n const waitForChange = Effect.gen(function* () {\n for (;;) {\n const changed = yield* Effect.raceFirst(\n // Keep the hint queued if the heartbeat wins the race.\n Queue.peek(dirty).pipe(Effect.as(true)),\n Effect.sleep(limits.heartbeatMs).pipe(Effect.as(false))\n );\n if (changed) {\n yield* Queue.take(dirty);\n return;\n }\n yield* renew;\n }\n });\n const prepare = memory.gate\n .withPermits(1)(\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n let prepared:\n | {\n witnesses: DeliveryMemory[\"witnesses\"];\n pending: DeliveryMemory[\"pending\"];\n expiresAt: number;\n }\n | undefined;\n const result = yield* restore(\n boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n const session = yield* current(tx);\n const installed = session.installed;\n const signature = session.signature;\n yield* Effect.annotateCurrentSpan({\n streamId,\n installed,\n acknowledged: session.acknowledged,\n expected: session.expected,\n replay: Boolean(session.pending),\n });\n if (session.pending) {\n if (memory.pending?.sequence !== session.pending.sequence)\n return yield* failure(\n \"Delivery view buffer expired.\",\n \"HistoryExpired\"\n );\n // Replay precedes a fresh capture: changes while this\n // subscriber was disconnected had no live notification.\n yield* Queue.offer(dirty, undefined);\n return session.pending;\n }\n const sequence = installed + 1;\n const witnesses = new Map(memory.witnesses);\n const patches = new Map<string, DeliveryChange>();\n const seen = new Map<string, number>();\n let count = 0;\n let bytes = 0;\n const buffered = new Map<\n string,\n { record: DeliveryRecord; encoded: Uint8Array }\n >();\n const flush = Effect.gen(function* () {\n const page = [...buffered];\n buffered.clear();\n const hashed = yield* Effect.forEach(\n page,\n ([ref, value]) =>\n Effect.map(\n digestBytes({\n type: \"application/json\",\n stream: Stream.make(value.encoded),\n }),\n (hash) => ({ ref, record: value.record, hash })\n ),\n { concurrency: 128 }\n );\n for (const { ref, record, hash } of hashed) {\n if (witnesses.get(ref)?.hash === hash) continue;\n witnesses.set(ref, { ref: deliveryRef(record), hash });\n patches.set(ref, { kind: \"put\", record });\n }\n });\n const emit = Effect.fnUntraced(function* (record: DeliveryRecord) {\n const ref = deliveryKey(deliveryRef(record));\n const encoded = yield* Effect.try({\n try: () => recordCodec.encode(record),\n catch: () =>\n failure(\n \"Selected data cannot be encoded.\",\n \"InvalidResponse\"\n ),\n });\n const encodedBytes = new TextEncoder().encode(encoded);\n if (encodedBytes.length > limits.frameBytes / 2)\n return yield* failure(\n \"A delivery record exceeds the configured frame budget.\",\n \"RateLimited\"\n );\n const previousSize = seen.get(ref);\n if (previousSize === undefined) count++;\n bytes += encodedBytes.length - (previousSize ?? 0);\n seen.set(ref, encodedBytes.length);\n if (count > limits.maxRecords || bytes > limits.maxBytes)\n return yield* failure(\n \"Selected delivery exceeds its configured size budget.\",\n \"RateLimited\"\n );\n // Persistence used to clone each record. Retained buffers must\n // likewise be independent of mutable objects owned by capture.\n const canonical = yield* Effect.try({\n try: () => recordCodec.decode(encoded),\n catch: () =>\n failure(\n \"Selected data cannot be decoded.\",\n \"InvalidResponse\"\n ),\n });\n buffered.set(ref, { record: canonical, encoded: encodedBytes });\n if (buffered.size === 128) yield* flush;\n });\n const captured = yield* options\n .capture(tx, (record) => boundary(emit(record)))\n .pipe(Effect.withSpan(\"Delivery.capture\"));\n yield* flush;\n const encodedMetadata = valueCodec.encode(captured);\n if (\n new TextEncoder().encode(encodedMetadata).length >\n limits.frameBytes / 2\n )\n return yield* failure(\n \"Delivery metadata exceeds the frame budget.\",\n \"RateLimited\"\n );\n const metadata = valueCodec.decode(\n encodedMetadata\n ) as DeliveryMetadata;\n const { client: _client, ...identity } = metadata;\n const nextSignature = valueCodec.encode(identity);\n for (const [ref, witness] of witnesses) {\n if (seen.has(ref)) continue;\n patches.set(ref, { kind: \"remove\", ref: witness.ref });\n witnesses.delete(ref);\n }\n const order = patches.size;\n const pending =\n installed && order === 0 && signature === nextSignature\n ? undefined\n : { sequence, metadata, nextSignature, count: order };\n yield* Effect.annotateCurrentSpan({\n sequence,\n changes: order,\n records: count,\n generation: metadata.generation,\n revision: metadata.revision,\n });\n const expiresAt =\n (yield* Clock.currentTimeMillis) + activeRetentionMs;\n yield* tx.put(sessions, streamId, {\n ...session,\n expiresAt,\n pending,\n expected: pending ? sequence : installed,\n });\n const payload = [...patches.values()].map((change) =>\n valueCodec.encode(change)\n );\n prepared = {\n witnesses,\n expiresAt,\n pending: pending\n ? {\n sequence,\n changes: payload,\n sizes: payload.map(\n (encoded) =>\n new TextEncoder().encode(encoded).length\n ),\n }\n : undefined,\n };\n return pending;\n })\n )\n )\n );\n // Publish only after capture and the small header commit. Failed or\n // interrupted capture cannot replace the last installed target.\n if (prepared) {\n if (closed || memories.get(streamId) !== memory || memory.producer !== producer)\n return yield* failure(\"Delivery view owner changed.\", \"HistoryExpired\");\n memory.witnesses = prepared.witnesses;\n memory.pending = prepared.pending;\n memory.expiresAt = prepared.expiresAt;\n }\n return result;\n })\n )\n )\n .pipe(Effect.withSpan(\"Delivery.prepare\"));\n const loop = (): Stream.Stream<DeliveryFrame, BackendError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const next = yield* prepare;\n if (!next) {\n yield* waitForChange;\n return Stream.suspend(loop);\n }\n let part = 0;\n const frames = Stream.paginate(0, (start) =>\n boundary(\n tables.read((tx) =>\n Effect.gen(function* () {\n // The durable producer fence is checked per frame, including\n // when a different server owner superseded this stream.\n const head = yield* current(tx);\n const payload = memory.pending;\n if (!payload || payload.sequence !== next.sequence)\n return yield* failure(\n \"Delivery view buffer expired.\",\n \"HistoryExpired\"\n );\n const changes: DeliveryChange[] = [];\n let bytes = 256;\n let order = start;\n while (order < next.count && changes.length < limits.frameRecords) {\n const length = payload.sizes[order]!;\n if (changes.length && bytes + length > limits.frameBytes) break;\n changes.push(\n yield* Effect.try({\n try: () =>\n valueCodec.decode(\n payload.changes[order]!\n ) as DeliveryChange,\n catch: () =>\n failure(\n \"Delivery buffer cannot be decoded.\",\n \"InvalidResponse\"\n ),\n })\n );\n bytes += length;\n order++;\n }\n const end = order === next.count;\n const frame: DeliveryFrame = {\n streamId,\n sequence: next.sequence,\n previous: head.installed,\n part: part++,\n kind: head.installed ? \"patch\" : \"snapshot\",\n changes,\n end,\n ...(end ? { metadata: next.metadata } : {}),\n };\n return [\n [frame],\n end ? Option.none<number>() : Option.some(order),\n ] as const;\n })\n )\n )\n );\n const observeAck = Effect.gen(function* () {\n for (;;) {\n const session = yield* boundary(tables.read((tx) => current(tx)));\n if (session.acknowledged >= next.sequence) return;\n yield* Effect.raceFirst(Queue.take(memory.acknowledgments), Effect.sleep(250));\n }\n }).pipe(\n Effect.withSpan(\"Delivery.awaitAcknowledgment\", {\n attributes: { streamId, sequence: next.sequence },\n })\n );\n const advance = observeAck.pipe(\n Effect.timeoutOrElse({\n duration: limits.ackTimeoutMs,\n orElse: () => Effect.fail(failure(\"Delivery acknowledgment timed out.\")),\n }),\n Effect.andThen(\n memory.gate.withPermits(1)(\n Effect.uninterruptibleMask((restore) =>\n Effect.gen(function* () {\n const expiresAt = yield* restore(\n boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n const head = yield* current(tx);\n const expiresAt =\n (yield* Clock.currentTimeMillis) +\n activeRetentionMs;\n yield* tx.put(sessions, streamId, {\n ...head,\n installed: next.sequence,\n signature: next.nextSignature,\n pending: undefined,\n expiresAt,\n });\n return expiresAt;\n })\n )\n )\n );\n memory.pending = undefined;\n memory.expiresAt = expiresAt;\n })\n )\n )\n ),\n Effect.andThen(waitForChange)\n );\n return Stream.concat(\n Stream.concat(frames, Stream.fromEffect(advance).pipe(Stream.drain)),\n Stream.suspend(loop)\n );\n })\n );\n return {\n frames: Stream.suspend(() => {\n if (consumed)\n return Stream.fail(failure(\"A delivery subscription has one consumer.\", \"Conflict\"));\n consumed = true;\n return loop();\n }).pipe(Stream.interruptWhen(Deferred.await(gone))),\n acknowledge: (position) =>\n position.streamId === streamId\n ? acknowledge(position)\n : Effect.fail(failure(\"Invalid delivery acknowledgment.\", \"Conflict\")),\n };\n });\n return {\n open,\n acknowledge,\n collectGarbage: admission.withPermits(1)(\n prune().pipe(Effect.andThen(collectDeliveryGarbage(tables, namespace)))\n ),\n };\n});\n\nconst bufferedFrameHash = (encoded: string) =>\n boundary(\n digestBytes({ type: \"application/json\", stream: Stream.make(new TextEncoder().encode(encoded)) })\n );\nconst decodeDeliveryFrame = Schema.decodeUnknownEffect(DeliveryFrameSchema);\n\ninterface InstalledDelivery {\n streamId: string;\n sequence: number;\n previous: number;\n nextPart: number;\n count: number;\n bytes: number;\n hash: string;\n kind: \"snapshot\" | \"patch\";\n duplicate: boolean;\n metadata?: DeliveryMetadata;\n}\ninterface BufferedDelivery extends InstalledDelivery {\n readonly frames: readonly { readonly encoded: string; readonly hash: string }[];\n}\n\n/** A scoped receiver retains bounded immutable frame bytes until atomic installation.\n * Installed positions and receipt evidence stay durable; losing partial frame bytes\n * requires replay from the installed position, or a fresh snapshot.\n */\nexport const makeDeliveryReceiver = Effect.fnUntraced(function* (options: {\n tables: TablesService;\n namespace: string;\n maxRecords?: number;\n maxBytes?: number;\n /** Durable outcome evidence can survive a later alias/application failure. */\n beforeApply?: (tx: Transaction, batch: IncomingDelivery) => Effect.Effect<void, BackendError>;\n apply: (tx: Transaction, batch: IncomingDelivery) => Effect.Effect<void, BackendError>;\n}) {\n const { tables } = options;\n const state = Table.make<InstalledDelivery>({\n name: JSON.stringify([options.namespace, \"incoming-delivery\", \"state\"]),\n });\n const owners = Table.make<number>({\n name: JSON.stringify([options.namespace, \"incoming-delivery\", \"owner\"]),\n });\n const maxRecords = options.maxRecords ?? 20_000;\n const maxBytes = options.maxBytes ?? 32 * 1024 * 1024;\n const gate = Semaphore.makeUnsafe(1);\n let pending: BufferedDelivery | undefined;\n let closed = false;\n const owner = yield* boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n const stored = yield* tx.get(owners, \"active\", { forUpdate: true });\n const previous = stored ?? 0;\n if (!Number.isSafeInteger(previous) || previous >= Number.MAX_SAFE_INTEGER)\n return yield* failure(\"Delivery receiver incarnation exhausted.\", \"InvalidConfiguration\");\n if (stored === undefined) {\n // Upgrade cleanup only: no receiver in this implementation stages row records.\n yield* tx.clear(\n Table.make({\n name: JSON.stringify([options.namespace, \"incoming-delivery\", \"changes\"]),\n })\n );\n yield* tx.clear(\n Table.make({\n name: JSON.stringify([options.namespace, \"incoming-delivery\", \"frames\"]),\n })\n );\n yield* tx.delete(state, \"pending\");\n }\n yield* tx.put(owners, \"active\", previous + 1);\n return previous + 1;\n })\n )\n );\n const assertOwner = Effect.fnUntraced(function* (tx: ReadTransaction, write = false) {\n if (\n closed ||\n (yield* write\n ? (tx as Transaction).get(owners, \"active\", { forUpdate: true })\n : tx.get(owners, \"active\")) !== owner\n )\n return yield* failure(\"Delivery receiver owner changed.\", \"ViewReplaced\");\n });\n yield* Effect.addFinalizer(() =>\n gate.withPermit(\n Effect.sync(() => {\n closed = true;\n pending = undefined;\n })\n )\n );\n const installed = boundary(\n tables.read((tx) =>\n Effect.gen(function* () {\n yield* assertOwner(tx);\n return yield* tx.get(state, \"installed\");\n })\n )\n );\n const decodeFrame = (encoded: string) =>\n Effect.try({\n try: () => valueCodec.decode(encoded) as DeliveryFrame,\n catch: () => failure(\"Buffered delivery data cannot be decoded.\", \"InvalidResponse\"),\n });\n const batch = Effect.fnUntraced(function* (ready: BufferedDelivery) {\n // Give each callback fresh metadata, and each traversal fresh mutable records.\n // Metadata-only consumers must not reconstruct every record in the final\n // frame. The private snapshot never follows a callback's mutable copy.\n const metadata = yield* Effect.try({\n try: () => valueCodec.decode(valueCodec.encode(ready.metadata)) as DeliveryMetadata,\n catch: () => failure(\"Buffered delivery metadata cannot be decoded.\", \"InvalidResponse\"),\n }).pipe(Effect.withSpan(\"Delivery.install.copyMetadata\"));\n const result: IncomingDelivery = {\n kind: ready.kind,\n position: { streamId: ready.streamId, sequence: ready.sequence },\n metadata,\n forEach: Effect.fnUntraced(function* (visit) {\n for (const retained of ready.frames) {\n const frame = yield* decodeFrame(retained.encoded);\n for (const change of frame.changes) yield* visit(change);\n }\n }),\n };\n return result;\n });\n return {\n installed,\n resume: Effect.map(installed, (current) =>\n pending && pending.streamId !== current?.streamId\n ? { streamId: pending.streamId, sequence: 0 }\n : current\n ? { streamId: current.streamId, sequence: current.sequence }\n : undefined\n ),\n forget: gate.withPermit(\n Effect.uninterruptibleMask((restore) =>\n restore(\n boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n yield* assertOwner(tx, true);\n yield* tx.clear(state);\n })\n )\n )\n ).pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n pending = undefined;\n })\n )\n )\n )\n ),\n receive: Effect.fn(\"Delivery.install\")(\n function* (input: DeliveryFrame) {\n const current = yield* installed.pipe(Effect.withSpan(\"Delivery.install.readPosition\"));\n const frame = yield* decodeDeliveryFrame(input).pipe(\n Effect.mapError(() => failure(\"Invalid delivery frame.\", \"InvalidResponse\")),\n Effect.withSpan(\"Delivery.install.validateFrame\")\n );\n yield* Effect.annotateCurrentSpan({\n streamId: frame.streamId,\n sequence: frame.sequence,\n part: frame.part,\n end: frame.end,\n changes: frame.changes.length,\n });\n if (\n frame.previous !== frame.sequence - 1 ||\n (frame.kind === \"snapshot\" && frame.sequence !== 1) ||\n (!frame.end && frame.metadata)\n )\n return yield* failure(\"Invalid delivery frame metadata or sequence.\", \"InvalidResponse\");\n const buffered = yield* Effect.try({\n try: () => {\n // Capture metadata and encode the retained frame in one\n // synchronous section, before hashing can yield to callers.\n const metadata = frame.metadata\n ? (valueCodec.decode(valueCodec.encode(frame.metadata)) as DeliveryMetadata)\n : undefined;\n return {\n metadata,\n encoded: valueCodec.encode({ ...frame, ...(metadata ? { metadata } : {}) }),\n };\n },\n catch: () => failure(\"Delivery data cannot be encoded.\", \"InvalidResponse\"),\n }).pipe(Effect.withSpan(\"Delivery.install.serializeFrame\"));\n const { encoded } = buffered;\n const bytes = new TextEncoder().encode(encoded).length;\n const frameHash = yield* bufferedFrameHash(encoded).pipe(\n Effect.withSpan(\"Delivery.install.hashFrame\")\n );\n let ready: BufferedDelivery | undefined;\n if (\n pending?.streamId === frame.streamId &&\n pending.sequence === frame.sequence &&\n frame.part < pending.nextPart\n ) {\n if (pending.frames[frame.part]?.hash !== frameHash)\n return yield* failure(\n \"A delivery frame was reused with different contents.\",\n \"Conflict\"\n );\n ready = frame.end && pending.metadata ? pending : undefined;\n } else {\n let prior = pending;\n if (frame.part === 0) {\n const duplicate =\n current?.streamId === frame.streamId && current.sequence === frame.sequence;\n const starts =\n frame.kind === \"snapshot\" &&\n frame.sequence === 1 &&\n frame.previous === 0 &&\n current?.streamId !== frame.streamId;\n const follows =\n frame.kind === \"patch\" &&\n current?.streamId === frame.streamId &&\n frame.sequence === current.sequence + 1 &&\n frame.previous === current.sequence;\n if (!duplicate && !starts && !follows)\n return yield* failure(\n \"Delivery position cannot resume; a snapshot is required.\",\n \"HistoryExpired\"\n );\n prior = {\n streamId: frame.streamId,\n sequence: frame.sequence,\n previous: frame.previous,\n nextPart: 0,\n count: 0,\n bytes: 0,\n hash: \"\",\n kind: frame.kind,\n duplicate,\n frames: [],\n };\n }\n if (\n !prior ||\n prior.streamId !== frame.streamId ||\n prior.sequence !== frame.sequence ||\n prior.kind !== frame.kind ||\n prior.previous !== frame.previous ||\n frame.part !== prior.nextPart\n )\n return yield* failure(\"Delivery frames are out of order.\", \"HistoryExpired\");\n if (\n prior.bytes + bytes > maxBytes ||\n prior.count + frame.changes.length > maxRecords ||\n frame.part > maxRecords + 1\n )\n return yield* failure(\n \"Incoming delivery exceeds its configured budget.\",\n \"InvalidResponse\"\n );\n const next: BufferedDelivery = {\n ...prior,\n count: prior.count + frame.changes.length,\n nextPart: prior.nextPart + 1,\n bytes: prior.bytes + bytes,\n hash: yield* bufferedFrameHash(prior.hash + frameHash).pipe(\n Effect.withSpan(\"Delivery.install.hashChain\")\n ),\n frames: [...prior.frames, { encoded, hash: frameHash }],\n };\n if (frame.end) {\n if (!buffered.metadata)\n return yield* failure(\"A completed delivery needs metadata.\", \"InvalidResponse\");\n if (next.duplicate && current?.hash !== next.hash)\n return yield* failure(\n \"A delivery sequence was reused with different contents.\",\n \"Conflict\"\n );\n next.metadata = buffered.metadata;\n ready = next;\n }\n pending = next;\n }\n if (!ready?.metadata) return undefined;\n // Defensive recovery if interruption followed the durable install but preceded local cleanup.\n if (\n current?.streamId === ready.streamId &&\n current.sequence === ready.sequence &&\n current.hash === ready.hash\n )\n ready = { ...ready, duplicate: true };\n const completed = ready;\n if (options.beforeApply && !completed.duplicate)\n yield* boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n yield* assertOwner(tx, true);\n yield* options.beforeApply!(tx, yield* batch(completed));\n })\n )\n ).pipe(Effect.withSpan(\"Delivery.install.checkpointTransaction\"));\n return yield* Effect.uninterruptibleMask((restore) =>\n restore(\n boundary(\n tables.transaction((tx) =>\n Effect.gen(function* () {\n yield* assertOwner(tx, true);\n if (!completed.duplicate) {\n yield* options.apply(tx, yield* batch(completed));\n // Persist a fresh decode, never a callback's mutable metadata.\n const canonical = yield* batch(completed);\n const { frames: _, ...position } = completed;\n yield* tx\n .put(state, \"installed\", {\n ...position,\n metadata: canonical.metadata,\n })\n .pipe(Effect.withSpan(\"Delivery.install.savePosition\"));\n }\n return {\n position: {\n streamId: completed.streamId,\n sequence: completed.sequence,\n },\n metadata: (yield* batch(completed)).metadata,\n duplicate: completed.duplicate,\n };\n })\n )\n ).pipe(Effect.withSpan(\"Delivery.install.transaction\"))\n ).pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n pending = undefined;\n })\n )\n )\n );\n },\n // The outer fn span includes admission wait. useSpan observes the\n // active body without changing its parent or frame annotations.\n (work) => gate.withPermit(Effect.useSpan(\"Delivery.install.active\", () => work))\n ),\n };\n});\n"],"mappings":";;;;;;;;;AAWA,MAAM,YAAY,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAC7D,MAAM,QAAQ,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;AACzD,MAAa,oBAAoB,OAAO,MAAM,CAC1C,OAAO,OAAO;CAAE,MAAM,OAAO,SAAS,CAAC,QAAQ,UAAU,CAAC;CAAG,YAAY,OAAO;CAAQ,KAAK;AAAU,CAAC,GACxG,OAAO,OAAO;CAAE,MAAM,OAAO,SAAS,C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O,aAAa,OAChB,OAAO,IAAI,aAAa;IACpB,OAAO,YAAY,IAAI,IAAI;IAC3B,IAAI,CAAC,UAAU,WAAW;KACtB,OAAO,QAAQ,MAAM,IAAI,OAAO,MAAM,SAAS,CAAC;KAEhD,MAAM,YAAY,OAAO,MAAM,SAAS;KACxC,MAAM,EAAE,QAAQ,GAAG,GAAG,aAAa;KACnC,OAAO,GACF,IAAI,OAAO,aAAa;MACrB,GAAG;MACH,UAAU,UAAU;KACxB,CAAC,CAAC,CACD,KAAK,OAAO,SAAS,+BAA+B,CAAC;IAC9D;IACA,OAAO;KACH,UAAU;MACN,UAAU,UAAU;MACpB,UAAU,UAAU;KACxB;KACA,WAAW,OAAO,MAAM,SAAS,EAAA,CAAG;KACpC,WAAW,UAAU;IACzB;GACJ,CAAC,CACL,CACJ,CAAC,CAAC,KAAK,OAAO,SAAS,8BAA8B,CAAC,CAC1D,CAAC,CAAC,KACE,OAAO,UACH,OAAO,WAAW;IACd,UAAU,KAAA;GACd,CAAC,CACL,CACJ,CACJ;EACJ,IAGC,SAAS,KAAK,WAAW,OAAO,QAAQ,iCAAiC,IAAI,CAAC,CACnF;CACJ;AACJ,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { Schema } from "effect";
2
+ //#region src/description.d.ts
3
+ /** Definition, authenticated binding and capabilities needed to reopen a protocol client. */
4
+ export declare const OntologyDescriptionCodec: Schema.Struct<{
5
+ readonly version: Schema.Literal<1>;
6
+ readonly replication: Schema.Literals<readonly ["committed", "speculative"]>;
7
+ readonly definitionHash: Schema.optional<Schema.String>;
8
+ readonly sourceId: Schema.NonEmptyString;
9
+ readonly ir: Schema.optional<Schema.Codec<import("@party-stack/ontology-spec").OntologyIR, string, never, never>>;
10
+ readonly context: Schema.optional<Schema.Codec<{
11
+ readonly [x: string]: unknown;
12
+ }, string, never, never>>;
13
+ readonly supportsIdempotency: Schema.Boolean;
14
+ readonly delivery: Schema.optional<Schema.Boolean>;
15
+ readonly stateDelivery: Schema.optional<Schema.Boolean>;
16
+ readonly changes: Schema.optional<Schema.Boolean>;
17
+ readonly watchChanges: Schema.optional<Schema.Boolean>;
18
+ readonly watchSubset: Schema.optional<Schema.Boolean>;
19
+ readonly actionParameterResolution: Schema.optional<Schema.Boolean>;
20
+ readonly queries: Schema.optional<Schema.Boolean>;
21
+ readonly pins: Schema.optional<Schema.Boolean>;
22
+ readonly attachments: Schema.optional<Schema.Struct<{
23
+ readonly stage: Schema.Boolean;
24
+ }>>;
25
+ readonly encrypted: Schema.optional<Schema.Boolean>;
26
+ }>;
27
+ export type OntologyDescription = typeof OntologyDescriptionCodec.Type;
28
+ //#endregion
29
+ //# sourceMappingURL=description.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"description.d.ts","names":[],"sources":["../src/description.ts"],"mappings":";;;qBAKa,0BAAwB,OAAA;;;;;;;;;;;;;;;;;;;;;;;YAmBzB,6BAA6B,yBAAyB"}
@@ -0,0 +1,28 @@
1
+ import { protocolValueCodec } from "./protocol.js";
2
+ import { Schema } from "effect";
3
+ import { OntologyIRSchema } from "@party-stack/ontology-spec/effect";
4
+ //#region src/description.ts
5
+ /** Definition, authenticated binding and capabilities needed to reopen a protocol client. */
6
+ const OntologyDescriptionCodec = Schema.Struct({
7
+ version: Schema.Literal(1),
8
+ replication: Schema.Literals(["committed", "speculative"]),
9
+ definitionHash: Schema.optional(Schema.String),
10
+ sourceId: Schema.NonEmptyString,
11
+ ir: Schema.optional(protocolValueCodec(OntologyIRSchema)),
12
+ context: Schema.optional(protocolValueCodec(Schema.Record(Schema.String, Schema.Unknown))),
13
+ supportsIdempotency: Schema.Boolean,
14
+ delivery: Schema.optional(Schema.Boolean),
15
+ stateDelivery: Schema.optional(Schema.Boolean),
16
+ changes: Schema.optional(Schema.Boolean),
17
+ watchChanges: Schema.optional(Schema.Boolean),
18
+ watchSubset: Schema.optional(Schema.Boolean),
19
+ actionParameterResolution: Schema.optional(Schema.Boolean),
20
+ queries: Schema.optional(Schema.Boolean),
21
+ pins: Schema.optional(Schema.Boolean),
22
+ attachments: Schema.optional(Schema.Struct({ stage: Schema.Boolean })),
23
+ encrypted: Schema.optional(Schema.Boolean)
24
+ });
25
+ //#endregion
26
+ export { OntologyDescriptionCodec };
27
+
28
+ //# sourceMappingURL=description.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"description.js","names":[],"sources":["../src/description.ts"],"sourcesContent":["import { OntologyIRSchema } from \"@party-stack/ontology-spec/effect\";\nimport { Schema } from \"effect\";\nimport { protocolValueCodec } from \"./protocol.js\";\n\n/** Definition, authenticated binding and capabilities needed to reopen a protocol client. */\nexport const OntologyDescriptionCodec = Schema.Struct({\n version: Schema.Literal(1),\n replication: Schema.Literals([\"committed\", \"speculative\"]),\n definitionHash: Schema.optional(Schema.String),\n sourceId: Schema.NonEmptyString,\n ir: Schema.optional(protocolValueCodec(OntologyIRSchema)),\n context: Schema.optional(protocolValueCodec(Schema.Record(Schema.String, Schema.Unknown))),\n supportsIdempotency: Schema.Boolean,\n delivery: Schema.optional(Schema.Boolean),\n stateDelivery: Schema.optional(Schema.Boolean),\n changes: Schema.optional(Schema.Boolean),\n watchChanges: Schema.optional(Schema.Boolean),\n watchSubset: Schema.optional(Schema.Boolean),\n actionParameterResolution: Schema.optional(Schema.Boolean),\n queries: Schema.optional(Schema.Boolean),\n pins: Schema.optional(Schema.Boolean),\n attachments: Schema.optional(Schema.Struct({ stage: Schema.Boolean })),\n encrypted: Schema.optional(Schema.Boolean),\n});\nexport type OntologyDescription = typeof OntologyDescriptionCodec.Type;\n"],"mappings":";;;;;AAKA,MAAa,2BAA2B,OAAO,OAAO;CAClD,SAAS,OAAO,QAAQ,CAAC;CACzB,aAAa,OAAO,SAAS,CAAC,aAAa,aAAa,CAAC;CACzD,gBAAgB,OAAO,SAAS,OAAO,MAAM;CAC7C,UAAU,OAAO;CACjB,IAAI,OAAO,SAAS,mBAAmB,gBAAgB,CAAC;CACxD,SAAS,OAAO,SAAS,mBAAmB,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO,CAAC,CAAC;CACzF,qBAAqB,OAAO;CAC5B,UAAU,OAAO,SAAS,OAAO,OAAO;CACxC,eAAe,OAAO,SAAS,OAAO,OAAO;CAC7C,SAAS,OAAO,SAAS,OAAO,OAAO;CACvC,cAAc,OAAO,SAAS,OAAO,OAAO;CAC5C,aAAa,OAAO,SAAS,OAAO,OAAO;CAC3C,2BAA2B,OAAO,SAAS,OAAO,OAAO;CACzD,SAAS,OAAO,SAAS,OAAO,OAAO;CACvC,MAAM,OAAO,SAAS,OAAO,OAAO;CACpC,aAAa,OAAO,SAAS,OAAO,OAAO,EAAE,OAAO,OAAO,QAAQ,CAAC,CAAC;CACrE,WAAW,OAAO,SAAS,OAAO,OAAO;AAC7C,CAAC"}
@@ -0,0 +1,41 @@
1
+ import { BackendError } from "./errors.js";
2
+ import { BackendEncryptedValues } from "./index.js";
3
+ import { Key } from "@party-stack/ontology-storage";
4
+ import { Effect, Schema } from "effect";
5
+ import { OntologyIR } from "@party-stack/ontology-spec";
6
+ import { Encrypted } from "@party-stack/ontology-spec/values";
7
+ //#region src/encrypted.d.ts
8
+ export declare const EncryptedValueSchema: Schema.Struct<{
9
+ readonly ciphertext: Schema.NonEmptyString;
10
+ readonly source: Schema.optional<Schema.Struct<{
11
+ readonly objectType: Schema.NonEmptyString;
12
+ readonly primaryKey: Schema.Union<readonly [Schema.String, Schema.Finite]>;
13
+ readonly property: Schema.NonEmptyString;
14
+ }>>;
15
+ }>;
16
+ /** value uses the property's portable JSON representation, including Temporal and Result values. */
17
+ export declare const DecryptedValueSchema: Schema.Struct<{
18
+ readonly value: Schema.Unknown;
19
+ /** Ciphertext associated with this plaintext. Contradictions are rejected; absent binding prevents caching.
20
+ * Prefer an authority-proven value. Adapters using current-property APIs must explicitly document any assumption.
21
+ */
22
+ readonly ciphertext: Schema.optional<Schema.NonEmptyString>;
23
+ }>;
24
+ export type DecryptedValue = typeof DecryptedValueSchema.Type;
25
+ /** Resolve and validate a top-level encrypted property without trusting a caller-supplied plaintext type. */
26
+ export declare function encryptedPropertyCodec(ir: OntologyIR, handle: Encrypted): {
27
+ type: import("@party-stack/ontology-spec").TypeDef;
28
+ encode: (value: unknown) => Schema.Json;
29
+ decode: (value: unknown) => unknown;
30
+ };
31
+ /** Authoritative property decryption, shared by owned storage and credential authorities.
32
+ * Server projection supplies caller authorization; this binds decryption to the
33
+ * current row/property and validates its plaintext contract.
34
+ */
35
+ export declare function makePropertyDecryption(options: {
36
+ readonly ir: OntologyIR;
37
+ readonly get: (objectType: string, key: Key) => Effect.Effect<Record<string, unknown> | undefined, BackendError>;
38
+ readonly decrypt: (handle: Encrypted) => Effect.Effect<unknown, BackendError>;
39
+ }): BackendEncryptedValues;
40
+ //#endregion
41
+ //# sourceMappingURL=encrypted.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encrypted.d.ts","names":[],"sources":["../src/encrypted.ts"],"mappings":";;;;;;;qBAUa,sBAAoB,OAAA;;;;;;;;;qBAYpB,sBAAoB,OAAA;;;;;;;YAOrB,wBAAwB,qBAAqB;;wBAGzC,uBAAuB,IAAI,YAAY,QAAQ;EA2BvD,2CAAI;EACJ,SAAM,mBAAiB,OAAA;EACvB,SAAM;;;;;;wBAQE,uBAAuB;WAC1B,IAAI;WACJ,MACL,oBACA,KAAK,QACJ,OAAO,OAAO,qCAAqC;WAC/C,UAAU,QAAQ,cAAc,OAAO,gBAAgB;IAChE"}
@@ -0,0 +1,111 @@
1
+ import { BackendError } from "./errors.js";
2
+ import { resolveType } from "@party-stack/ontology-spec/utils";
3
+ import { Effect, Schema } from "effect";
4
+ import { compileEffectSchemas } from "@party-stack/ontology-spec/effect";
5
+ import { decode, encode } from "@party-stack/ontology-spec/json";
6
+ //#region src/encrypted.ts
7
+ const EncryptedValueSchema = Schema.Struct({
8
+ ciphertext: Schema.NonEmptyString,
9
+ source: Schema.optional(Schema.Struct({
10
+ objectType: Schema.NonEmptyString,
11
+ primaryKey: Schema.Union([Schema.String, Schema.Finite]),
12
+ property: Schema.NonEmptyString
13
+ }))
14
+ });
15
+ /** value uses the property's portable JSON representation, including Temporal and Result values. */
16
+ const DecryptedValueSchema = Schema.Struct({
17
+ value: Schema.Unknown,
18
+ /** Ciphertext associated with this plaintext. Contradictions are rejected; absent binding prevents caching.
19
+ * Prefer an authority-proven value. Adapters using current-property APIs must explicitly document any assumption.
20
+ */
21
+ ciphertext: Schema.optional(Schema.NonEmptyString)
22
+ });
23
+ /** Resolve and validate a top-level encrypted property without trusting a caller-supplied plaintext type. */
24
+ function encryptedPropertyCodec(ir, handle) {
25
+ const source = handle.source;
26
+ const property = ir.objectTypes.find((object) => object.name === source?.objectType)?.properties.find((property) => property.name === source?.property);
27
+ if (!property) throw new TypeError("Decryption requires a known encrypted property source.");
28
+ let type = resolveType(ir, property.type);
29
+ while (type.kind === "optional") type = resolveType(ir, type.value.type);
30
+ if (type.kind !== "encrypted") throw new TypeError("The property is not encrypted.");
31
+ const plaintext = type.value.type;
32
+ const schemaIr = {
33
+ ...ir,
34
+ queryFunctionTypes: [{
35
+ name: "plaintext",
36
+ displayName: "Plaintext",
37
+ parameters: [],
38
+ returnType: plaintext
39
+ }]
40
+ };
41
+ const schema = Schema.toEncoded(Schema.toCodecJson(compileEffectSchemas(schemaIr).queryReturnSchemas.plaintext));
42
+ const validate = Schema.decodeUnknownSync(schema);
43
+ const target = {
44
+ kind: "queryFunctionReturn",
45
+ queryFunctionType: "plaintext"
46
+ };
47
+ return {
48
+ type: plaintext,
49
+ encode: (value) => validate(encode({
50
+ ir: schemaIr,
51
+ target,
52
+ value
53
+ })),
54
+ decode: (value) => decode({
55
+ ir: schemaIr,
56
+ target,
57
+ value: validate(value)
58
+ })
59
+ };
60
+ }
61
+ /** Authoritative property decryption, shared by owned storage and credential authorities.
62
+ * Server projection supplies caller authorization; this binds decryption to the
63
+ * current row/property and validates its plaintext contract.
64
+ */
65
+ function makePropertyDecryption(options) {
66
+ return { decrypt: Effect.fn("Backend.decrypt")(function* (value) {
67
+ const checked = yield* Effect.try({
68
+ try: () => {
69
+ const handle = Schema.decodeUnknownSync(EncryptedValueSchema)(value);
70
+ return {
71
+ handle,
72
+ codec: encryptedPropertyCodec(options.ir, handle)
73
+ };
74
+ },
75
+ catch: () => new BackendError({
76
+ operation: "decrypt",
77
+ kind: "InvalidRequest",
78
+ retryable: false,
79
+ message: "Invalid encrypted property handle."
80
+ })
81
+ });
82
+ const source = checked.handle.source;
83
+ const current = (yield* options.get(source.objectType, source.primaryKey))?.[source.property];
84
+ if (!current || typeof current !== "object" || !("ciphertext" in current) || current.ciphertext !== checked.handle.ciphertext) return yield* new BackendError({
85
+ operation: "decrypt",
86
+ kind: "Conflict",
87
+ retryable: false,
88
+ message: "The encrypted property changed or is unavailable."
89
+ });
90
+ const plaintext = yield* options.decrypt(checked.handle);
91
+ return yield* Effect.try({
92
+ try: () => {
93
+ checked.codec.decode(plaintext);
94
+ return {
95
+ value: plaintext,
96
+ ciphertext: checked.handle.ciphertext
97
+ };
98
+ },
99
+ catch: () => new BackendError({
100
+ operation: "decrypt",
101
+ kind: "Internal",
102
+ retryable: false,
103
+ message: "Invalid decrypted plaintext."
104
+ })
105
+ });
106
+ }) };
107
+ }
108
+ //#endregion
109
+ export { DecryptedValueSchema, EncryptedValueSchema, encryptedPropertyCodec, makePropertyDecryption };
110
+
111
+ //# sourceMappingURL=encrypted.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"encrypted.js","names":[],"sources":["../src/encrypted.ts"],"sourcesContent":["import { compileEffectSchemas } from \"@party-stack/ontology-spec/effect\";\nimport { decode, encode } from \"@party-stack/ontology-spec/json\";\nimport { resolveType } from \"@party-stack/ontology-spec/utils\";\nimport { Effect, Schema } from \"effect\";\nimport { BackendError } from \"./errors.js\";\nimport type { BackendEncryptedValues } from \"./index.js\";\nimport type { OntologyIR } from \"@party-stack/ontology-spec\";\nimport type { Encrypted } from \"@party-stack/ontology-spec/values\";\nimport type { Key } from \"@party-stack/ontology-storage\";\n\nexport const EncryptedValueSchema = Schema.Struct({\n ciphertext: Schema.NonEmptyString,\n source: Schema.optional(\n Schema.Struct({\n objectType: Schema.NonEmptyString,\n primaryKey: Schema.Union([Schema.String, Schema.Finite]),\n property: Schema.NonEmptyString,\n })\n ),\n});\n\n/** value uses the property's portable JSON representation, including Temporal and Result values. */\nexport const DecryptedValueSchema = Schema.Struct({\n value: Schema.Unknown,\n /** Ciphertext associated with this plaintext. Contradictions are rejected; absent binding prevents caching.\n * Prefer an authority-proven value. Adapters using current-property APIs must explicitly document any assumption.\n */\n ciphertext: Schema.optional(Schema.NonEmptyString),\n});\nexport type DecryptedValue = typeof DecryptedValueSchema.Type;\n\n/** Resolve and validate a top-level encrypted property without trusting a caller-supplied plaintext type. */\nexport function encryptedPropertyCodec(ir: OntologyIR, handle: Encrypted) {\n const source = handle.source;\n const property = ir.objectTypes\n .find((object) => object.name === source?.objectType)\n ?.properties.find((property) => property.name === source?.property);\n if (!property) throw new TypeError(\"Decryption requires a known encrypted property source.\");\n let type = resolveType(ir, property.type);\n while (type.kind === \"optional\") type = resolveType(ir, type.value.type);\n if (type.kind !== \"encrypted\") throw new TypeError(\"The property is not encrypted.\");\n const plaintext = type.value.type;\n const schemaIr = {\n ...ir,\n queryFunctionTypes: [\n {\n name: \"plaintext\",\n displayName: \"Plaintext\",\n parameters: [],\n returnType: plaintext,\n },\n ],\n };\n const schema = Schema.toEncoded(\n Schema.toCodecJson(compileEffectSchemas(schemaIr).queryReturnSchemas.plaintext!)\n );\n const validate = Schema.decodeUnknownSync(schema);\n const target = { kind: \"queryFunctionReturn\" as const, queryFunctionType: \"plaintext\" };\n return {\n type: plaintext,\n encode: (value: unknown) => validate(encode({ ir: schemaIr, target, value })),\n decode: (value: unknown) => decode({ ir: schemaIr, target, value: validate(value) }),\n };\n}\n\n/** Authoritative property decryption, shared by owned storage and credential authorities.\n * Server projection supplies caller authorization; this binds decryption to the\n * current row/property and validates its plaintext contract.\n */\nexport function makePropertyDecryption(options: {\n readonly ir: OntologyIR;\n readonly get: (\n objectType: string,\n key: Key\n ) => Effect.Effect<Record<string, unknown> | undefined, BackendError>;\n readonly decrypt: (handle: Encrypted) => Effect.Effect<unknown, BackendError>;\n}): BackendEncryptedValues {\n return {\n decrypt: Effect.fn(\"Backend.decrypt\")(function* (value) {\n const checked = yield* Effect.try({\n try: () => {\n const handle = Schema.decodeUnknownSync(EncryptedValueSchema)(value);\n return { handle, codec: encryptedPropertyCodec(options.ir, handle) };\n },\n catch: () =>\n new BackendError({\n operation: \"decrypt\",\n kind: \"InvalidRequest\",\n retryable: false,\n message: \"Invalid encrypted property handle.\",\n }),\n });\n const source = checked.handle.source!;\n const current = (yield* options.get(source.objectType, source.primaryKey))?.[source.property];\n if (\n !current ||\n typeof current !== \"object\" ||\n !(\"ciphertext\" in current) ||\n current.ciphertext !== checked.handle.ciphertext\n )\n return yield* new BackendError({\n operation: \"decrypt\",\n kind: \"Conflict\",\n retryable: false,\n message: \"The encrypted property changed or is unavailable.\",\n });\n const plaintext = yield* options.decrypt(checked.handle);\n return yield* Effect.try({\n try: () => {\n checked.codec.decode(plaintext);\n return { value: plaintext, ciphertext: checked.handle.ciphertext };\n },\n catch: () =>\n new BackendError({\n operation: \"decrypt\",\n kind: \"Internal\",\n retryable: false,\n message: \"Invalid decrypted plaintext.\",\n }),\n });\n }),\n };\n}\n"],"mappings":";;;;;;AAUA,MAAa,uBAAuB,OAAO,OAAO;CAC9C,YAAY,OAAO;CACnB,QAAQ,OAAO,SACX,OAAO,OAAO;EACV,YAAY,OAAO;EACnB,YAAY,OAAO,MAAM,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;EACvD,UAAU,OAAO;CACrB,CAAC,CACL;AACJ,CAAC;;AAGD,MAAa,uBAAuB,OAAO,OAAO;CAC9C,OAAO,OAAO;;;;CAId,YAAY,OAAO,SAAS,OAAO,cAAc;AACrD,CAAC;;AAID,SAAgB,uBAAuB,IAAgB,QAAmB;CACtE,MAAM,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EACD,MAAM,SAAS,QAAQ,OAAO;EAC9B,MAAM,WAAW,OAAO,QAAQ,IAAI,OAAO,YAAY,OAAO,UAAU,EAAA,GAAK,OAAO;EACpF,IACI,CAAC,WACD,OAAO,YAAY,YACnB,EAAE,gBAAgB,YAClB,QAAQ,eAAe,QAAQ,OAAO,YAEtC,OAAO,OAAO,IAAI,aAAa;GAC3B,WAAW;GACX,MAAM;GACN,WAAW;GACX,SAAS;EACb,CAAC;EACL,MAAM,YAAY,OAAO,QAAQ,QAAQ,QAAQ,MAAM;EACvD,OAAO,OAAO,OAAO,IAAI;GACrB,WAAW;IACP,QAAQ,MAAM,OAAO,SAAS;IAC9B,OAAO;KAAE,OAAO;KAAW,YAAY,QAAQ,OAAO;IAAW;GACrE;GACA,aACI,IAAI,aAAa;IACb,WAAW;IACX,MAAM;IACN,WAAW;IACX,SAAS;GACb,CAAC;EACT,CAAC;CACL,CAAC,EACL;AACJ"}
@@ -0,0 +1,106 @@
1
+ import { Schema } from "effect";
2
+ import { ValidationIssue } from "@party-stack/ontology-spec";
3
+ //#region src/errors.d.ts
4
+ export declare const ValidationIssueSchema: Schema.Struct<{
5
+ readonly message: Schema.String;
6
+ readonly path: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.String, Schema.Number]>>>;
7
+ readonly code: Schema.optional<Schema.String>;
8
+ readonly category: Schema.optional<Schema.Literals<readonly ["input", "reference", "custom"]>>;
9
+ readonly source: Schema.optional<Schema.Literals<readonly ["parameter", "submission", "user-facing"]>>;
10
+ readonly messageSource: Schema.optional<Schema.Literals<readonly ["standard", "configured"]>>;
11
+ }>;
12
+ export declare const ValidationReportSchema: Schema.Union<readonly [Schema.Struct<{
13
+ readonly certain: Schema.Literal<false>;
14
+ }>, Schema.Struct<{
15
+ readonly certain: Schema.Literal<true>;
16
+ readonly value: Schema.Union<readonly [Schema.Struct<{
17
+ readonly kind: Schema.Literal<"ok">;
18
+ readonly value: Schema.Void;
19
+ }>, Schema.Struct<{
20
+ readonly kind: Schema.Literal<"err">;
21
+ readonly value: Schema.$Array<Schema.Struct<{
22
+ readonly message: Schema.String;
23
+ readonly path: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.String, Schema.Number]>>>;
24
+ readonly code: Schema.optional<Schema.String>;
25
+ readonly category: Schema.optional<Schema.Literals<readonly ["input", "reference", "custom"]>>;
26
+ readonly source: Schema.optional<Schema.Literals<readonly ["parameter", "submission", "user-facing"]>>;
27
+ readonly messageSource: Schema.optional<Schema.Literals<readonly ["standard", "configured"]>>;
28
+ }>>;
29
+ }>]>;
30
+ }>]>;
31
+ export type ValidationReport = typeof ValidationReportSchema.Type;
32
+ export declare const BackendErrorKindSchema: Schema.Literals<readonly ["Unauthenticated", "Forbidden", "NotFound", "ValidationFailed", "InvalidRequest", "InvalidResponse", "InvalidConfiguration", "Conflict", "NotImplemented", "RateLimited", "Unavailable", "Internal", "HistoryExpired", "SessionExpired", "SessionReplaced", "ViewReplaced", "ResultExpired", "SourceMismatch", "SchemaMismatch"]>;
33
+ export type BackendErrorKind = typeof BackendErrorKindSchema.Type;
34
+ declare const Fields: {
35
+ operation: Schema.String;
36
+ kind: Schema.Literals<readonly ["Unauthenticated", "Forbidden", "NotFound", "ValidationFailed", "InvalidRequest", "InvalidResponse", "InvalidConfiguration", "Conflict", "NotImplemented", "RateLimited", "Unavailable", "Internal", "HistoryExpired", "SessionExpired", "SessionReplaced", "ViewReplaced", "ResultExpired", "SourceMismatch", "SchemaMismatch"]>;
37
+ message: Schema.String;
38
+ retryable: Schema.Boolean;
39
+ actionOutcome: Schema.optional<Schema.Literals<readonly ["not-committed", "unknown"]>>;
40
+ retryAfterMs: Schema.optional<Schema.Finite>;
41
+ issues: Schema.optional<Schema.$Array<Schema.Struct<{
42
+ readonly message: Schema.String;
43
+ readonly path: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.String, Schema.Number]>>>;
44
+ readonly code: Schema.optional<Schema.String>;
45
+ readonly category: Schema.optional<Schema.Literals<readonly ["input", "reference", "custom"]>>;
46
+ readonly source: Schema.optional<Schema.Literals<readonly ["parameter", "submission", "user-facing"]>>;
47
+ readonly messageSource: Schema.optional<Schema.Literals<readonly ["standard", "configured"]>>;
48
+ }>>>;
49
+ cause: Schema.optional<Schema.Defect>;
50
+ };
51
+ declare const BackendError_base: Schema.Class<BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, Schema.TaggedStruct<"BackendError", {
52
+ operation: Schema.String;
53
+ kind: Schema.Literals<readonly ["Unauthenticated", "Forbidden", "NotFound", "ValidationFailed", "InvalidRequest", "InvalidResponse", "InvalidConfiguration", "Conflict", "NotImplemented", "RateLimited", "Unavailable", "Internal", "HistoryExpired", "SessionExpired", "SessionReplaced", "ViewReplaced", "ResultExpired", "SourceMismatch", "SchemaMismatch"]>;
54
+ message: Schema.String;
55
+ retryable: Schema.Boolean;
56
+ actionOutcome: Schema.optional<Schema.Literals<readonly ["not-committed", "unknown"]>>;
57
+ retryAfterMs: Schema.optional<Schema.Finite>;
58
+ issues: Schema.optional<Schema.$Array<Schema.Struct<{
59
+ readonly message: Schema.String;
60
+ readonly path: Schema.optional<Schema.$Array<Schema.Union<readonly [Schema.String, Schema.Number]>>>;
61
+ readonly code: Schema.optional<Schema.String>;
62
+ readonly category: Schema.optional<Schema.Literals<readonly ["input", "reference", "custom"]>>;
63
+ readonly source: Schema.optional<Schema.Literals<readonly ["parameter", "submission", "user-facing"]>>;
64
+ readonly messageSource: Schema.optional<Schema.Literals<readonly ["standard", "configured"]>>;
65
+ }>>>;
66
+ cause: Schema.optional<Schema.Defect>;
67
+ }>, import("effect/Cause").YieldableError>;
68
+ /** Shared wire schema; hooks narrow the kind without duplicating error classes. */
69
+ export declare class BackendError<K extends BackendErrorKind = BackendErrorKind> extends BackendError_base {
70
+ readonly kind: K;
71
+ constructor(properties: Omit<Schema.Struct.Type<typeof Fields>, "kind"> & {
72
+ readonly kind: K;
73
+ });
74
+ }
75
+ /** HTTP bindings share these statuses; RPC still carries the typed error schema. */
76
+ export declare const backendErrorStatus: (error: Pick<BackendError, "kind">) => number;
77
+ export type OperationErrorKind = "Unauthenticated" | "Forbidden" | "NotFound" | "ValidationFailed" | "InvalidRequest" | "InvalidResponse" | "InvalidConfiguration" | "Conflict" | "NotImplemented" | "RateLimited" | "Unavailable" | "Internal";
78
+ export type ApplyActionError = BackendError<OperationErrorKind>;
79
+ export type ValidateActionError = BackendError<OperationErrorKind>;
80
+ export type ReplicationErrorKind = "HistoryExpired" | "SessionExpired" | "SessionReplaced" | "ViewReplaced" | "ResultExpired" | "SourceMismatch" | "SchemaMismatch";
81
+ export type ReplicationError = BackendError<ReplicationErrorKind>;
82
+ export type LoadSubsetError = BackendError<Exclude<OperationErrorKind, "ValidationFailed"> | "HistoryExpired">;
83
+ export declare const unauthenticated: (message?: string, options?: ErrorOptions) => BackendError<"Unauthenticated">;
84
+ export declare const isUnauthenticatedError: (error: unknown) => error is BackendError<"Unauthenticated">;
85
+ /** Unknown outcomes apply to dispatch/execution failures, never ordinary rejections. */
86
+ export declare const isUnknownActionOutcome: (error: BackendError) => boolean;
87
+ /** Normalize SDK failures. No provider message/body is made public by this classifier. */
88
+ export declare function classifyBackendFailure(operation: string, cause: unknown): BackendError;
89
+ export interface ErrorProjectionContext {
90
+ /** Visible action parameter paths. Hidden/fixed parameters must not appear in public issues. */
91
+ readonly parameters?: readonly string[];
92
+ readonly objectReferenceParameters?: readonly string[];
93
+ /** An upstream connection failure cannot request downstream sign-in. */
94
+ readonly upstream?: boolean;
95
+ }
96
+ export type ErrorProjection = "forward" | "projected" | ((error: BackendError, context: ErrorProjectionContext) => BackendError);
97
+ export declare function projectValidationIssue(issue: ValidationIssue, context: ErrorProjectionContext): ValidationIssue | undefined;
98
+ /** Forwarding preserves the original error. Projection removes raw causes and
99
+ * cannot change execution/retry facts. */
100
+ export declare function projectBackendError(error: BackendError, policy?: ErrorProjection, context?: ErrorProjectionContext): BackendError;
101
+ export type UnauthenticatedError = BackendError<"Unauthenticated">;
102
+ /** Schema diagnostics retain paths without echoing input values or internal schemas. */
103
+ export declare function schemaValidationIssues(error: Schema.SchemaError): readonly ValidationIssue[];
104
+ //#endregion
105
+ export type { ValidationIssue };
106
+ //# sourceMappingURL=errors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","names":[],"sources":["../src/errors.ts"],"mappings":";;;qBAQa,uBAAqB,OAAA;;;;;;;;qBAQrB,wBAAsB,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;YAUvB,0BAA0B,uBAAuB;qBAEhD,wBAAsB,OAAA;YAqBvB,0BAA0B,uBAAuB;cACvD;EACF,WAAS,OAAA;EACT,MAAI,OAAA;EACJ,SAAO,OAAA;EACP,WAAS,OAAA;EACT,eAAa,OAAA,SAAA,OAAA;EACb,cAAY,OAAA,SAAA,OAAA;EACZ,QAAM,OAAA,SAAA,OAAA,OAAA,OAAA;;;;;;;;EACN,OAAK,OAAA,SAAA,OAAA;;;;;;;;;;;;;;;;;;;;qBAGI,aACT,UAAU,mBAAmB,0BACvB;WACW,MAAM;EACvB,YAAY,YAAY,KAAK,OAAO,OAAO,YAAY;aAA8B,MAAM;;;;qBAKlF,qBAAkB,OAAW,KAAK;YAsBnC;YAaA,mBAAmB,aAAa;YAChC,sBAAsB,aAAa;YACnC;YAQA,mBAAmB,aAAa;YAChC,kBAAkB,aAC1B,QAAQ;qBAGC,kBAAe,kBAAA,UAAuD,iBAAY;qBASlF,yBAAsB,mBAAqB,SAAS;;qBAIpD,yBAAsB,OAAW;;wBAuB9B,uBAAuB,mBAAmB,iBAAiB;iBA6L1D;;WAEJ;WACA;;WAEA;;YAED,8CAGJ,OAAO,cAAc,SAAS,2BAA2B;wBACjD,uBACZ,OAAO,iBACP,SAAS,yBACV;;;wBA4Ba,oBACZ,OAAO,cACP,SAAQ,iBACR,UAAS,yBACV;YA2CS,uBAAuB;;wBAGnB,uBAAuB,OAAO,OAAO,uBAAuB"}