@party-stack/ontology-server 0.0.0-stage → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +493 -2
  3. package/lib/attachmentHttp.d.ts +15 -0
  4. package/lib/attachmentHttp.d.ts.map +1 -0
  5. package/lib/attachmentHttp.js +235 -0
  6. package/lib/attachmentHttp.js.map +1 -0
  7. package/lib/attachmentTransfers.d.ts +115 -0
  8. package/lib/attachmentTransfers.d.ts.map +1 -0
  9. package/lib/attachmentTransfers.js +208 -0
  10. package/lib/attachmentTransfers.js.map +1 -0
  11. package/lib/authorization.d.ts +21 -0
  12. package/lib/authorization.d.ts.map +1 -0
  13. package/lib/authorization.js +385 -0
  14. package/lib/authorization.js.map +1 -0
  15. package/lib/bindingFence.d.ts +27 -0
  16. package/lib/bindingFence.d.ts.map +1 -0
  17. package/lib/bindingFence.js +39 -0
  18. package/lib/bindingFence.js.map +1 -0
  19. package/lib/composition.d.ts +467 -0
  20. package/lib/composition.d.ts.map +1 -0
  21. package/lib/composition.js +102 -0
  22. package/lib/composition.js.map +1 -0
  23. package/lib/definitionProjection.d.ts +21 -0
  24. package/lib/definitionProjection.d.ts.map +1 -0
  25. package/lib/definitionProjection.js +441 -0
  26. package/lib/definitionProjection.js.map +1 -0
  27. package/lib/errorProjection.d.ts +22 -0
  28. package/lib/errorProjection.d.ts.map +1 -0
  29. package/lib/errorProjection.js +72 -0
  30. package/lib/errorProjection.js.map +1 -0
  31. package/lib/http.d.ts +23 -0
  32. package/lib/http.d.ts.map +1 -0
  33. package/lib/http.js +17 -0
  34. package/lib/http.js.map +1 -0
  35. package/lib/index.d.ts +5 -0
  36. package/lib/index.js +3 -0
  37. package/lib/internalAccess.d.ts +10 -0
  38. package/lib/internalAccess.d.ts.map +1 -0
  39. package/lib/internalAccess.js +18 -0
  40. package/lib/internalAccess.js.map +1 -0
  41. package/lib/operations.d.ts +1265 -0
  42. package/lib/operations.d.ts.map +1 -0
  43. package/lib/operations.js +621 -0
  44. package/lib/operations.js.map +1 -0
  45. package/lib/policyDefinition.d.ts +19 -0
  46. package/lib/policyDefinition.d.ts.map +1 -0
  47. package/lib/policyDefinition.js +226 -0
  48. package/lib/policyDefinition.js.map +1 -0
  49. package/lib/policyWatches.d.ts +17 -0
  50. package/lib/policyWatches.d.ts.map +1 -0
  51. package/lib/policyWatches.js +49 -0
  52. package/lib/policyWatches.js.map +1 -0
  53. package/lib/receiptPolicy.d.ts +12 -0
  54. package/lib/receiptPolicy.d.ts.map +1 -0
  55. package/lib/receiptPolicy.js +63 -0
  56. package/lib/receiptPolicy.js.map +1 -0
  57. package/lib/replicaBootstrap.d.ts +56 -0
  58. package/lib/replicaBootstrap.d.ts.map +1 -0
  59. package/lib/replicaBootstrap.js +60 -0
  60. package/lib/replicaBootstrap.js.map +1 -0
  61. package/lib/routing.d.ts +87 -0
  62. package/lib/routing.d.ts.map +1 -0
  63. package/lib/routing.js +344 -0
  64. package/lib/routing.js.map +1 -0
  65. package/lib/rpc.d.ts +4799 -0
  66. package/lib/rpc.d.ts.map +1 -0
  67. package/lib/rpc.js +575 -0
  68. package/lib/rpc.js.map +1 -0
  69. package/lib/rpcActivity.d.ts +6 -0
  70. package/lib/rpcActivity.d.ts.map +1 -0
  71. package/lib/rpcActivity.js +8 -0
  72. package/lib/rpcActivity.js.map +1 -0
  73. package/lib/rpcBackend.d.ts +8 -0
  74. package/lib/rpcBackend.d.ts.map +1 -0
  75. package/lib/rpcBackend.js +76 -0
  76. package/lib/rpcBackend.js.map +1 -0
  77. package/lib/rpcHttp.d.ts +24 -0
  78. package/lib/rpcHttp.d.ts.map +1 -0
  79. package/lib/rpcHttp.js +118 -0
  80. package/lib/rpcHttp.js.map +1 -0
  81. package/lib/rpcLocal.d.ts +13 -0
  82. package/lib/rpcLocal.d.ts.map +1 -0
  83. package/lib/rpcLocal.js +26 -0
  84. package/lib/rpcLocal.js.map +1 -0
  85. package/lib/rpcWatch.d.ts +9 -0
  86. package/lib/rpcWatch.d.ts.map +1 -0
  87. package/lib/rpcWatch.js +29 -0
  88. package/lib/rpcWatch.js.map +1 -0
  89. package/lib/rpcWorker.d.ts +38 -0
  90. package/lib/rpcWorker.d.ts.map +1 -0
  91. package/lib/rpcWorker.js +192 -0
  92. package/lib/rpcWorker.js.map +1 -0
  93. package/package.json +53 -3
package/lib/rpc.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc.js","names":[],"sources":["../src/rpc.ts"],"sourcesContent":["import { BackendError, classifyBackendFailure } from \"@party-stack/ontology-backend\";\nimport {\n ClientLeaseSchema,\n ClientSessionSchema,\n ClientTokenSchema,\n} from \"@party-stack/ontology-backend/clients\";\nimport { DeliveryFrameCodec, DeliveryPositionSchema } from \"@party-stack/ontology-backend/delivery\";\nimport { OntologyDescriptionCodec } from \"@party-stack/ontology-backend/description\";\nimport {\n CompiledSubsetCodec,\n ClientStateCodec,\n ClientSubmissionCodec,\n ClientViewCodec,\n ObjectSelectionCodec,\n} from \"@party-stack/ontology-backend/protocol\";\nimport { objectSubset } from \"@party-stack/ontology-backend/subset\";\nimport { pinOntology } from \"@party-stack/ontology-replica\";\nimport {\n ontologyDefinitionSignature,\n ontologyDefinitionContractSignature,\n} from \"@party-stack/ontology-storage\";\nimport { digestBytes } from \"@party-stack/ontology-storage/blobs\";\nimport { Table } from \"@party-stack/ontology-storage/tables\";\nimport {\n Cause,\n Context,\n Deferred,\n Effect,\n Exit,\n Layer,\n PubSub,\n Schema,\n Scope,\n Stream,\n SubscriptionRef,\n} from \"effect\";\nimport { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcSchema } from \"effect/rpc\";\nimport { expectedBindingHeaders, withExpectedBinding } from \"./bindingFence.js\";\nimport {\n OntologyErrorProjection,\n errorProjectionLayer,\n projectStateFailures,\n projectActionFailure,\n type ErrorProjectionOptions,\n} from \"./errorProjection.js\";\nimport {\n OntologyOperationRpcs,\n ontologyOperationHandlers,\n makeOntologyOperationsClient,\n type OntologyOperationRequest,\n type OntologyOperationsClient,\n} from \"./operations.js\";\nimport { RpcActivity } from \"./rpcActivity.js\";\nimport { makeRpcBackend } from \"./rpcBackend.js\";\nimport type { AttachmentTransferPolicy } from \"./attachmentTransfers.js\";\nimport type { ObjectSelection } from \"@party-stack/ontology-backend\";\nimport type { ClientSession, ClientToken } from \"@party-stack/ontology-backend/clients\";\nimport type { DeliveryFrame } from \"@party-stack/ontology-backend/delivery\";\nimport type { OntologyDescription } from \"@party-stack/ontology-backend/description\";\nimport type { ClientSubmission, ClientView, OntologySource } from \"@party-stack/ontology-backend/protocol\";\nimport type { CompiledSubset } from \"@party-stack/ontology-backend/subset\";\nimport type { ReplicaService, ReplicaPinControls } from \"@party-stack/ontology-replica\";\nimport type { TraceStore } from \"@party-stack/runtime/tracing\";\nimport type { Headers } from \"effect/http/Headers\";\n\nconst Counter = Schema.Int.check(Schema.isBetween({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER }));\nconst DeliveryStrategy = Schema.Literals([\"auto\", \"snapshot\", \"incremental\"]);\nconst Description = OntologyDescriptionCodec;\nconst ReplicaRpcs = RpcGroup.make(\n Rpc.make(\"Describe\", { success: Description, error: BackendError }),\n Rpc.make(\"SubscribeSelection\", {\n payload: { selection: ObjectSelectionCodec, resume: Schema.optional(DeliveryPositionSchema) },\n success: DeliveryFrameCodec,\n error: BackendError,\n stream: true,\n }),\n Rpc.make(\"SubscribeState\", {\n payload: {\n session: ClientSessionSchema,\n view: ClientViewCodec,\n resume: Schema.optional(DeliveryPositionSchema),\n },\n success: DeliveryFrameCodec,\n error: BackendError,\n stream: true,\n }),\n Rpc.make(\"AckDelivery\", {\n payload: { kind: Schema.Literals([\"committed\", \"speculative\"]), position: DeliveryPositionSchema },\n error: BackendError,\n }),\n Rpc.make(\"Accept\", { payload: ClientSubmissionCodec, error: BackendError }),\n Rpc.make(\"OpenClient\", {\n payload: { resume: Schema.optional(ClientTokenSchema) },\n success: ClientLeaseSchema,\n error: BackendError,\n }),\n Rpc.make(\"Read\", {\n payload: { session: ClientSessionSchema, view: Schema.optional(ClientViewCodec) },\n success: ClientStateCodec,\n error: BackendError,\n }),\n Rpc.make(\"Submit\", { payload: ClientSubmissionCodec, success: ClientStateCodec, error: BackendError }),\n Rpc.make(\"Acknowledge\", {\n payload: {\n session: ClientSessionSchema,\n revision: Counter,\n through: Counter,\n viewGeneration: Schema.optional(Counter),\n },\n error: BackendError,\n }),\n Rpc.make(\"Demand\", {\n payload: CompiledSubsetCodec,\n success: Schema.Literal(\"ready\"),\n error: BackendError,\n stream: true,\n }),\n Rpc.make(\"Changes\", { success: Schema.Literal(\"invalidate\"), error: BackendError, stream: true })\n);\n\nexport const OntologyRpcs = ReplicaRpcs.merge(OntologyOperationRpcs).middleware(OntologyErrorProjection);\n\n// Client-only telemetry middleware: classification follows the RPC schema, not\n// method-name guesses or elapsed duration. The server wire contract is unchanged.\nclass SubscriptionTracing extends RpcMiddleware.Service<SubscriptionTracing>()(\n \"@party-stack/ontology-server/SubscriptionTracing\",\n { requiredForClient: true }\n) {}\nconst subscriptionTracingLayer = RpcMiddleware.layerClient(SubscriptionTracing, ({ rpc, request, next }) =>\n RpcSchema.isStreamSchema(rpc.successSchema)\n ? Effect.annotateCurrentSpan(\"activity\", Context.get(rpc.annotations, RpcActivity)).pipe(\n Effect.andThen(next(request))\n )\n : next(request)\n);\nexport const makeTracedRpcClient = <Rpcs extends Rpc.Any>(group: RpcGroup.RpcGroup<Rpcs>) =>\n RpcClient.make(group.middleware(SubscriptionTracing)).pipe(Effect.provide(subscriptionTracingLayer));\n\n/** The in-process transport keeps the same subscription/transfer trace classification. */\nexport const makeTracedRpcClientNoSerialization = <Rpcs extends Rpc.Any, E>(\n group: RpcGroup.RpcGroup<Rpcs>,\n options: Parameters<\n typeof RpcClient.makeNoSerialization<Rpc.AddMiddleware<Rpcs, typeof SubscriptionTracing>, E>\n >[1]\n) =>\n RpcClient.makeNoSerialization(group.middleware(SubscriptionTracing), options).pipe(\n Effect.provide(subscriptionTracingLayer)\n );\n\nexport const makeOntologyRpcClient = makeTracedRpcClient(OntologyRpcs);\n\nexport type { OntologyDescription } from \"@party-stack/ontology-backend/description\";\nexport interface OntologyClientOptions {\n /** Previously accepted, public source binding; never inferred from cached rows. */\n readonly description?: OntologyDescription;\n /** Validate/adopt definition compatibility after source/context/protocol checks. */\n readonly validate?: (fresh: OntologyDescription) => Effect.Effect<void, BackendError>;\n /** Notification only. Coordinate replacement outside this client scope. */\n readonly onIncompatible?: (error: BackendError) => Effect.Effect<void>;\n}\nexport interface OntologyClientDefinitionStatus {\n readonly status: \"retained\" | \"current\" | \"incompatible\";\n readonly refreshing: boolean;\n readonly error?: BackendError;\n}\nexport interface OntologyClientDefinition {\n readonly get: Effect.Effect<OntologyClientDefinitionStatus>;\n readonly changes: Stream.Stream<OntologyClientDefinitionStatus>;\n /** Explicit, coalesced metadata acquisition. Never required before ordinary operations. */\n readonly refresh: Effect.Effect<OntologyDescription, BackendError>;\n}\n/** A scoped client of an ontology server, separate from Connect's account connections. */\n/** One transport shared by independently scoped, ontology-bound handles. */\nexport interface OntologyServerClient {\n readonly ontology: (\n name?: string,\n options?: OntologyClientOptions\n ) => Effect.Effect<OntologyClient, BackendError, Scope.Scope>;\n}\n\nexport interface OntologyClient {\n /** The accepted description used to construct this binding's fixed capabilities. */\n readonly description: OntologyDescription;\n readonly definition: OntologyClientDefinition;\n readonly sourceId: string;\n readonly definitionHash?: string;\n readonly ir?: import(\"@party-stack/ontology-spec\").OntologyIR;\n readonly context?: Record<string, unknown>;\n readonly operations: OntologyOperationsClient;\n /** Pin controls on the selected persistent replica, when the server advertises them. */\n readonly pins?: ReplicaPinControls;\n /** Ordinary ontology operations over the selected replica's download inventory. */\n readonly pinBackend?: Effect.Effect<\n import(\"@party-stack/ontology-backend\").OntologyBackendService,\n BackendError,\n Scope.Scope\n >;\n /** Finite operations are available for all server roles. */\n readonly backend: import(\"@party-stack/ontology-backend\").OntologyBackendService;\n readonly replication:\n | { readonly kind: \"committed\" }\n | { readonly kind: \"speculative\"; readonly source: OntologySource };\n}\n\nexport type OntologyRpcRequest =\n | OntologyOperationRequest\n | { readonly operation: \"Describe\" | \"Changes\" }\n | { readonly operation: \"OpenClient\"; readonly resume?: ClientToken }\n | { readonly operation: \"Read\"; readonly session: ClientSession; readonly view?: ClientView }\n | { readonly operation: \"Submit\" | \"Accept\"; readonly submission: ClientSubmission }\n | {\n readonly operation: \"SubscribeSelection\";\n readonly selection: ObjectSelection;\n }\n | { readonly operation: \"SubscribeState\"; readonly session: ClientSession; readonly view: ClientView }\n | {\n readonly operation: \"AckDelivery\";\n readonly kind: \"committed\" | \"speculative\";\n readonly position: import(\"@party-stack/ontology-backend/delivery\").DeliveryPosition;\n }\n | {\n readonly operation: \"Acknowledge\";\n readonly session: ClientSession;\n readonly revision: number;\n readonly through: number;\n readonly viewGeneration?: number;\n }\n | { readonly operation: \"Demand\"; readonly subset: CompiledSubset };\n\n/** Bind to an authenticated source/principal partition. Authorization is mandatory:\n * granting domain row access alone does not authorize action parameters or base\n * state inspection. Restricted sources must also project their returned state.\n */\nexport interface OntologyRpcServerOptions<R = never> extends ErrorProjectionOptions {\n /** Already projected client context. Never use request payloads as trusted context. */\n readonly context?: Record<string, unknown>;\n readonly attachmentTransfers?: AttachmentTransferPolicy<R>;\n /** Opt into downstream watches, change reads and replication sessions. Finite\n * queries/actions and the backend's own upstream lifecycle remain available.\n */\n readonly enableRealtime?: boolean;\n /** Outgoing replication only. Snapshot uses invalidations and finite reads;\n * incremental requires native selected delivery. Auto preserves capability selection.\n */\n readonly deliveryStrategy?: Schema.Schema.Type<typeof DeliveryStrategy>;\n /** Server-controlled selected-delivery capacity, frame and acknowledgment bounds. */\n readonly delivery?: import(\"@party-stack/ontology-backend/delivery\").DeliveryPolicy;\n readonly source?: OntologySource;\n readonly replica?: ReplicaService;\n readonly pins?: ReplicaPinControls;\n readonly traces?: TraceStore;\n readonly backend?: import(\"@party-stack/ontology-backend\").OntologyBackendService;\n /** Worker bootstrap may run while transport starts accepting requests. */\n readonly ready?: Effect.Effect<void, BackendError, R>;\n /** Explicit local-partition administration; omitted helpers cannot delete data or stop an owner. */\n readonly deleteLocalData?: Effect.Effect<void, BackendError, R>;\n readonly releaseOwner?: Effect.Effect<void, BackendError, R>;\n readonly authorize: (\n request: OntologyRpcRequest,\n headers: Headers\n ) => Effect.Effect<void, BackendError, R>;\n}\n\n// This gate also rejects direct RPC calls: capability discovery is not enforcement.\nconst clientSyncOperations: ReadonlySet<OntologyRpcRequest[\"operation\"]> = new Set([\n \"WatchSubset\",\n \"WatchChanges\",\n \"PullChanges\",\n \"SubscribeSelection\",\n \"AckDelivery\",\n \"SubscribeState\",\n \"OpenClient\",\n \"Read\",\n \"Submit\",\n \"Accept\",\n \"Acknowledge\",\n \"Demand\",\n \"Changes\",\n]);\n\nconst baseOntologyRpcHandlers = <R>(options: OntologyRpcServerOptions<R>) => {\n const clientSync = options.enableRealtime === true;\n const bindingAuthorization = withExpectedBinding(options);\n const authorize = Effect.fnUntraced(function* (request: OntologyRpcRequest, headers: Headers) {\n yield* bindingAuthorization(request, headers);\n if (!clientSync && clientSyncOperations.has(request.operation))\n return yield* new BackendError({\n operation: request.operation,\n kind: \"NotImplemented\",\n message: \"Client synchronization is disabled on this endpoint.\",\n retryable: false,\n actionOutcome: \"not-committed\",\n });\n });\n const snapshots = options.deliveryStrategy === \"snapshot\";\n // Snapshot readers must not silently switch to the committed journal path.\n // Its watch stream can still provide ordinary subset invalidation hints.\n const operationOptions = snapshots\n ? {\n ...options,\n get replica() {\n return options.replica;\n },\n get backend() {\n const backend = options.backend;\n if (!backend) return undefined;\n const watch = backend.changes?.watch;\n return {\n ...backend,\n changes: undefined,\n watchSubset: backend.watchSubset ?? (watch ? () => watch : undefined),\n };\n },\n }\n : options;\n const unavailableSource = () =>\n Effect.fail(\n new BackendError({\n operation: \"replication\",\n kind: \"NotImplemented\",\n message: \"This endpoint serves stateless operations only.\",\n retryable: false,\n })\n );\n const unavailableDelivery = () =>\n Effect.fail(\n new BackendError({\n operation: \"delivery\",\n kind: \"NotImplemented\",\n message: \"Selected incremental delivery is disabled or unavailable on this endpoint.\",\n retryable: false,\n })\n );\n const source: OntologySource = options.source ?? {\n sourceId: options.backend?.sourceId ?? \"stateless\",\n supportsIdempotency: options.backend?.supportsIdempotency ?? false,\n openClient: unavailableSource,\n read: unavailableSource,\n submit: unavailableSource,\n acknowledge: unavailableSource,\n demand: () => Stream.fromEffect(unavailableSource()),\n subscribeChanges: unavailableSource(),\n };\n return ReplicaRpcs.toLayer({\n Describe: (_, context) =>\n authorize({ operation: \"Describe\" }, context.headers).pipe(\n Effect.andThen(options.ready ?? Effect.void),\n Effect.andThen(\n Effect.gen(function* () {\n const strategy = yield* Schema.decodeUnknownEffect(DeliveryStrategy)(\n options.deliveryStrategy ?? \"auto\"\n ).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"describe\",\n kind: \"InvalidConfiguration\",\n message: \"Invalid delivery strategy.\",\n retryable: false,\n })\n )\n );\n const committedDelivery =\n clientSync &&\n Boolean(\n options.backend?.subscribeSelection && options.backend.acknowledgeDelivery\n );\n const speculativeDelivery =\n clientSync &&\n Boolean(source.subscribe && source.acknowledgeDelivery && source.accept);\n if (\n clientSync &&\n strategy === \"incremental\" &&\n !(options.source ? speculativeDelivery : committedDelivery)\n )\n return yield* new BackendError({\n operation: \"describe\",\n kind: \"NotImplemented\",\n message: \"This source does not support incremental selected delivery.\",\n retryable: false,\n });\n const signature = options.ir\n ? yield* Effect.try({\n try: () => ontologyDefinitionSignature(options.ir!),\n catch: (cause) =>\n new BackendError({\n operation: \"describe\",\n kind: \"InvalidConfiguration\",\n message: \"Invalid ontology definition.\",\n retryable: false,\n cause,\n }),\n })\n : undefined;\n const definitionHash = options.ir\n ? yield* digestBytes({\n type: \"application/json\",\n stream: Stream.make(new TextEncoder().encode(signature!)),\n }).pipe(Effect.mapError((cause) => classifyBackendFailure(\"describe\", cause)))\n : undefined;\n return {\n version: 1 as const,\n replication:\n clientSync && options.source\n ? (\"speculative\" as const)\n : (\"committed\" as const),\n definitionHash,\n sourceId: options.source?.sourceId ?? options.backend?.sourceId ?? \"stateless\",\n ir: options.ir,\n context: options.context,\n supportsIdempotency:\n options.source?.supportsIdempotency ??\n options.backend?.supportsIdempotency ??\n false,\n delivery: !snapshots && committedDelivery,\n stateDelivery: Boolean(options.source) && !snapshots && speculativeDelivery,\n changes: clientSync && Boolean(operationOptions.backend?.changes),\n watchChanges: clientSync && Boolean(operationOptions.backend?.changes?.watch),\n watchSubset:\n clientSync &&\n Boolean(\n operationOptions.backend?.watchSubset ||\n options.ir?.objectTypes.some(\n (type) =>\n typeof operationOptions.backend?.refresh?.(\n objectSubset(type.name)\n )?.pollIntervalMs === \"number\"\n )\n ),\n actionParameterResolution: Boolean(\n options.backend?.resolveActionParameters || options.replica\n ),\n queries: Boolean(options.backend),\n pins: Boolean(options.pins ?? options.replica),\n attachments: options.backend\n ? options.backend.attachments && {\n stage: Boolean(options.backend.attachments.stage),\n }\n : options.replica\n ? { stage: true }\n : undefined,\n encrypted: Boolean(options.backend ? options.backend.encrypted : options.replica),\n };\n })\n )\n ),\n SubscribeSelection: (request, context) =>\n Stream.unwrap(\n Effect.gen(function* () {\n yield* authorize(\n { operation: \"SubscribeSelection\", selection: request.selection },\n context.headers\n );\n if (snapshots || !options.backend?.subscribeSelection)\n return yield* unavailableDelivery();\n const delivery = yield* options.backend.subscribeSelection(\n request.selection,\n options.delivery,\n request.resume\n );\n return delivery.frames.pipe(\n Stream.mapEffect((frame) =>\n Effect.gen(function* () {\n if (!frame.metadata) return frame;\n if (frame.metadata.sourceId !== options.backend!.sourceId)\n return yield* new BackendError({\n operation: \"delivery\",\n kind: \"SourceMismatch\",\n message: \"The committed delivery source changed.\",\n retryable: false,\n });\n // The endpoint binds one logical source/session lifetime. A replica\n // server's committed facet forwards upstream rows under that identity.\n return {\n ...frame,\n metadata: {\n ...frame.metadata,\n sourceId:\n options.source?.sourceId ??\n options.backend?.sourceId ??\n \"stateless\",\n },\n };\n })\n )\n );\n })\n ),\n SubscribeState: (request, context) =>\n Stream.unwrap(\n Effect.gen(function* () {\n yield* authorize({ operation: \"SubscribeState\", ...request }, context.headers);\n if (snapshots || !source.subscribe) return yield* unavailableDelivery();\n const delivery = yield* source.subscribe(\n request.session,\n request.view,\n options.delivery,\n request.resume\n );\n return delivery.frames.pipe(\n Stream.map((frame) => ({\n ...frame,\n changes: frame.changes.map((change) =>\n change.kind === \"put\" &&\n (change.record.kind === \"pending\" || change.record.kind === \"completed\")\n ? {\n ...change,\n record: {\n ...change.record,\n value: projectActionFailure(change.record.value, options),\n },\n }\n : change\n ),\n }))\n );\n })\n ),\n AckDelivery: (request, context) =>\n authorize({ operation: \"AckDelivery\", ...request }, context.headers).pipe(\n Effect.andThen(() => {\n if (snapshots) return unavailableDelivery();\n const ack =\n request.kind === \"committed\"\n ? options.backend?.acknowledgeDelivery\n : source.acknowledgeDelivery;\n return ack ? ack(request.position) : unavailableSource();\n })\n ),\n Accept: (request, context) =>\n authorize({ operation: \"Accept\", submission: request }, context.headers).pipe(\n Effect.andThen(() => (source.accept ? source.accept(request) : unavailableSource()))\n ),\n OpenClient: (request, context) =>\n authorize({ operation: \"OpenClient\", ...request }, context.headers).pipe(\n Effect.andThen(() => source.openClient(request.resume))\n ),\n Read: (request, context) =>\n authorize({ operation: \"Read\", ...request }, context.headers).pipe(\n Effect.andThen(() =>\n source.read(request.session, request.view).pipe(\n Effect.map((result) => ({\n ...result,\n state: projectStateFailures(result.state, options),\n }))\n )\n )\n ),\n Submit: (request, context) =>\n authorize({ operation: \"Submit\", submission: request }, context.headers).pipe(\n Effect.andThen(() =>\n source.submit(request).pipe(\n Effect.map((result) => ({\n ...result,\n state: projectStateFailures(result.state, options),\n }))\n )\n )\n ),\n Acknowledge: (request, context) =>\n authorize({ operation: \"Acknowledge\", ...request }, context.headers).pipe(\n Effect.andThen(() =>\n source.acknowledge(\n request.session,\n request.revision,\n request.through,\n request.viewGeneration\n )\n )\n ),\n Demand: (subset, context) =>\n Stream.unwrap(\n Effect.gen(function* () {\n yield* Effect.annotateCurrentSpan(\"activity\", \"subscription\");\n yield* authorize({ operation: \"Demand\", subset }, context.headers);\n return source.demand(subset).pipe(Stream.as(\"ready\" as const));\n })\n ),\n Changes: (_, context) =>\n Stream.unwrap(\n Effect.gen(function* () {\n yield* Effect.annotateCurrentSpan(\"activity\", \"subscription\");\n yield* authorize({ operation: \"Changes\" }, context.headers);\n const changes = options.source ? yield* source.subscribeChanges : undefined;\n if (!changes) return yield* unavailableSource();\n // A new stream is a repair boundary, not proof that no updates were missed.\n return Stream.concat(\n Stream.make(\"invalidate\" as const),\n Stream.map(changes, () => \"invalidate\" as const)\n );\n })\n ),\n }).pipe(\n Layer.merge(ontologyOperationHandlers(operationOptions, authorize)),\n Layer.merge(errorProjectionLayer(options))\n );\n};\n\nconst resourceHeader = \"x-party-stack-resource\";\n\n/** Administrative resources use the same ontology RPCs and transport. Access is\n * still gated by the parent endpoint before the resource is acquired. */\nexport const ontologyRpcHandlers = <R>(options: OntologyRpcServerOptions<R>) =>\n Layer.unwrap(\n Effect.gen(function* () {\n const scope = yield* Effect.scope;\n const ordinary = yield* Layer.buildWithScope(baseOntologyRpcHandlers(options), scope);\n const pins = yield* Effect.cached(\n Effect.gen(function* () {\n if (!options.replica)\n return yield* new BackendError({\n operation: \"pins\",\n kind: \"NotImplemented\",\n retryable: false,\n message: \"This endpoint does not own downloads.\",\n });\n const backend = yield* options.replica.demand.pins.backend;\n return yield* Layer.buildWithScope(\n baseOntologyRpcHandlers({\n backend,\n ir: pinOntology,\n context: options.context,\n enableRealtime: options.enableRealtime,\n errors: options.errors,\n authorize: (_, headers) => options.authorize({ operation: \"ReadPin\" }, headers),\n }),\n scope\n );\n })\n );\n type Rpcs = RpcGroup.Rpcs<typeof OntologyRpcs>;\n type Handler = RpcGroup.HandlersFrom<Rpcs>[Rpcs[\"_tag\"]];\n const handlers = Object.fromEntries(\n [...OntologyRpcs.requests].map(([tag, rpc]) => {\n const invoke = (payload: never, request: Parameters<Handler>[1]) =>\n Effect.gen(function* () {\n const resource = request.headers[resourceHeader];\n if (resource !== undefined && resource !== \"pins\")\n return yield* new BackendError({\n operation: \"ontology.resource\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Unknown ontology resource.\",\n });\n if (resource === \"pins\")\n yield* options.authorize({ operation: \"ReadPin\" }, request.headers);\n const context = resource === \"pins\" ? yield* pins : ordinary;\n const handler = yield* OntologyRpcs.accessHandler(tag as Rpcs[\"_tag\"]).pipe(\n Effect.provideContext(context)\n );\n return handler(payload, request);\n });\n return [\n tag,\n RpcSchema.isStreamSchema(rpc.successSchema)\n ? (payload: never, request: Parameters<Handler>[1]) =>\n Stream.unwrap(\n invoke(payload, request).pipe(\n Effect.map(\n (result) => result as Stream.Stream<unknown, BackendError, R>\n )\n )\n )\n : (payload: never, request: Parameters<Handler>[1]) =>\n Effect.flatten(\n invoke(payload, request).pipe(\n Effect.map(\n (result) => result as Effect.Effect<unknown, BackendError, R>\n )\n )\n ),\n ];\n })\n ) as unknown as {\n readonly [Procedure in Rpcs as Procedure[\"_tag\"]]: Rpc.ToHandlerFn<\n Procedure,\n R | Scope.Scope\n >;\n };\n return Layer.merge(OntologyRpcs.toLayer(handlers), errorProjectionLayer(options));\n })\n );\n\nconst selectPinResource = (client: OntologyRpcClient): OntologyRpcClient =>\n Object.fromEntries(\n [...OntologyRpcs.requests.keys()].map((tag) => [\n tag,\n (payload: unknown, settings?: { readonly headers?: Record<string, string> }) =>\n Reflect.apply(Reflect.get(client, tag), client, [\n payload,\n { ...settings, headers: { ...settings?.headers, [resourceHeader]: \"pins\" } },\n ]),\n ])\n ) as OntologyRpcClient;\n\nexport type OntologyRpcClient = Effect.Success<\n ReturnType<typeof RpcClient.make<RpcGroup.Rpcs<typeof OntologyRpcs>>>\n>;\nconst unavailable = (cause: unknown) => classifyBackendFailure(\"remote.protocol\", cause);\nconst copyDescription = (description: OntologyDescription) =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(Description)(Schema.encodeSync(Description)(description)),\n catch: (cause) =>\n new BackendError({\n operation: \"remote.describe\",\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"Invalid ontology description.\",\n cause,\n }),\n });\n\nconst descriptionValue = Table.make<unknown>({ name: \"ontology-description-identity\" });\nconst sameDescriptionValue = (left: unknown, right: unknown) =>\n descriptionValue.encode(left) === descriptionValue.encode(right);\nconst protocolIdentity = (description: OntologyDescription) => ({\n version: description.version,\n replication: description.replication,\n supportsIdempotency: description.supportsIdempotency,\n delivery: Boolean(description.delivery),\n stateDelivery: Boolean(description.stateDelivery),\n changes: Boolean(description.changes),\n watchChanges: Boolean(description.watchChanges),\n watchSubset: Boolean(description.watchSubset),\n actionParameterResolution: Boolean(description.actionParameterResolution),\n queries: Boolean(description.queries),\n pins: Boolean(description.pins),\n attachments: Boolean(description.attachments),\n stageAttachments: Boolean(description.attachments?.stage),\n encrypted: Boolean(description.encrypted),\n});\nconst checkBootstrapBinding = (accepted: OntologyDescription, fresh: OntologyDescription) =>\n Effect.gen(function* () {\n if (fresh.sourceId !== accepted.sourceId)\n return yield* new BackendError({\n operation: \"remote.validate\",\n kind: \"SourceMismatch\",\n retryable: false,\n message: \"The ontology source changed.\",\n });\n if (!sameDescriptionValue(fresh.context ?? {}, accepted.context ?? {}))\n return yield* new BackendError({\n operation: \"remote.validate\",\n kind: \"SourceMismatch\",\n retryable: false,\n message: \"The ontology context changed.\",\n });\n if (!sameDescriptionValue(protocolIdentity(fresh), protocolIdentity(accepted)))\n return yield* new BackendError({\n operation: \"remote.validate\",\n kind: \"SchemaMismatch\",\n retryable: false,\n message: \"The ontology protocol capabilities changed.\",\n });\n });\n\nconst definitionFailure: unique symbol = Symbol(\"OntologyClient.definitionFailure\");\ninterface InternalDefinition extends OntologyClientDefinition {\n readonly [definitionFailure]: (error: BackendError) => Effect.Effect<void>;\n}\n/** HTTP byte operations use the same incompatibility notification as typed RPC. */\nexport const observeOntologyClientFailure = <A, R>(\n client: OntologyClient,\n work: Effect.Effect<A, BackendError, R>\n) =>\n work.pipe(\n Effect.tapError(\n (error) =>\n (client.definition as Partial<InternalDefinition>)[definitionFailure]?.(error) ?? Effect.void\n )\n );\n\nconst makeDefinitionClient = Effect.fnUntraced(function* (\n raw: OntologyRpcClient,\n description: OntologyDescription,\n options?: OntologyClientOptions\n) {\n const scope = yield* Effect.scope;\n const state = yield* SubscriptionRef.make<OntologyClientDefinitionStatus>({\n status: options?.description ? \"retained\" : \"current\",\n refreshing: false,\n });\n yield* Effect.addFinalizer(() => PubSub.shutdown(state.pubsub));\n let attempt: Deferred.Deferred<OntologyDescription, BackendError> | undefined;\n const incompatible = (error: BackendError) =>\n error.kind === \"SchemaMismatch\" || error.kind === \"SourceMismatch\";\n const notify = (error: BackendError) => options?.onIncompatible?.(error) ?? Effect.void;\n const failed = Effect.fnUntraced(function* (error: BackendError) {\n const previous = yield* SubscriptionRef.get(state);\n yield* SubscriptionRef.set(state, {\n ...previous,\n status: incompatible(error) ? \"incompatible\" : previous.status,\n refreshing: false,\n error: previous.status === \"incompatible\" && !incompatible(error) ? previous.error : error,\n });\n if (\n incompatible(error) &&\n (previous.status !== \"incompatible\" || previous.error?.kind !== error.kind)\n )\n yield* notify(error).pipe(\n Effect.catchCause((cause) =>\n Effect.logError(\"Ontology incompatibility callback failed\", cause)\n ),\n Effect.forkIn(scope),\n Effect.asVoid\n );\n });\n const validate =\n options?.validate ??\n ((fresh: OntologyDescription) =>\n (!fresh.ir && !description.ir) ||\n (fresh.ir &&\n description.ir &&\n ontologyDefinitionContractSignature(fresh.ir) ===\n ontologyDefinitionContractSignature(description.ir))\n ? Effect.void\n : Effect.fail(\n new BackendError({\n operation: \"remote.definition\",\n kind: \"SchemaMismatch\",\n retryable: false,\n message: \"The ontology definition changed.\",\n })\n ));\n const refresh = Effect.uninterruptibleMask((restore) =>\n Effect.suspend(() => {\n if (attempt) return restore(Deferred.await(attempt));\n const pending = Deferred.makeUnsafe<OntologyDescription, BackendError>();\n attempt = pending;\n const check = SubscriptionRef.update(state, (current) => ({ ...current, refreshing: true })).pipe(\n Effect.andThen(\n raw.Describe().pipe(Effect.mapError(unavailable), Effect.flatMap(copyDescription))\n ),\n Effect.tap((fresh) => checkBootstrapBinding(description, fresh)),\n Effect.tap(validate),\n Effect.tap(() => SubscriptionRef.set(state, { status: \"current\", refreshing: false })),\n Effect.onExit((exit) =>\n Effect.gen(function* () {\n if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {\n const error = Cause.findErrorOption(exit.cause);\n yield* failed(\n error._tag === \"Some\" ? error.value : unavailable(Cause.squash(exit.cause))\n );\n }\n if (attempt === pending) attempt = undefined;\n yield* Deferred.done(pending, exit);\n })\n ),\n Effect.catchCause(() => Effect.void)\n );\n return Effect.forkIn(check, scope, { startImmediately: true }).pipe(\n Effect.andThen(restore(Deferred.await(pending)))\n );\n })\n );\n const report = Effect.fnUntraced(function* (error: BackendError) {\n if (!incompatible(error)) return;\n yield* failed(error);\n // Rebinding a source/account needs an explicit acquisition. A metadata\n // refresh must not turn that failure into permission to reset its cache.\n if (error.kind === \"SourceMismatch\") return;\n yield* refresh.pipe(\n Effect.catchCause(() => Effect.void),\n Effect.forkIn(scope),\n Effect.asVoid\n );\n });\n const headers = expectedBindingHeaders(description);\n // Delivery metadata already carries the contract hash. Check it at the\n // client boundary too, so a receiver's schema failure reaches definition\n // lifecycle handling even when the transport successfully delivered a frame.\n const schemaHash = yield* Effect.cached(\n Effect.suspend(() =>\n description.ir\n ? digestBytes({\n type: \"application/json\",\n stream: Stream.make(\n new TextEncoder().encode(ontologyDefinitionContractSignature(description.ir))\n ),\n })\n : Effect.succeed(undefined)\n ).pipe(Effect.mapError(unavailable))\n );\n const checkFrame = Effect.fnUntraced(function* (frame: DeliveryFrame) {\n if (frame.metadata) {\n if (frame.metadata.sourceId !== description.sourceId)\n return yield* new BackendError({\n operation: \"remote.definition\",\n kind: \"SourceMismatch\",\n retryable: false,\n message: \"The delivered ontology source changed.\",\n });\n const expected = yield* schemaHash;\n if (expected !== undefined && frame.metadata.schemaHash !== expected)\n return yield* new BackendError({\n operation: \"remote.definition\",\n kind: \"SchemaMismatch\",\n retryable: false,\n message: \"The delivered ontology definition changed.\",\n });\n }\n return frame;\n });\n const client = Object.fromEntries(\n [...OntologyRpcs.requests].map(([tag, rpc]) => [\n tag,\n (payload: unknown, options?: { readonly headers?: Record<string, string> }) => {\n const invoke = () =>\n Reflect.apply(Reflect.get(raw, tag), raw, [\n payload,\n tag === \"Describe\"\n ? options\n : { ...options, headers: { ...options?.headers, ...headers } },\n ]);\n if (RpcSchema.isStreamSchema(rpc.successSchema)) {\n const stream =\n tag === \"SubscribeSelection\" || tag === \"SubscribeState\"\n ? (invoke() as Stream.Stream<DeliveryFrame, BackendError>).pipe(\n Stream.mapEffect(checkFrame)\n )\n : (invoke() as Stream.Stream<unknown, BackendError>);\n return stream.pipe(Stream.tapError(report));\n }\n return (invoke() as Effect.Effect<unknown, BackendError>).pipe(Effect.tapError(report));\n },\n ])\n ) as unknown as OntologyRpcClient;\n const definition: InternalDefinition = {\n get: SubscriptionRef.get(state),\n changes: SubscriptionRef.changes(state),\n refresh,\n [definitionFailure]: report,\n };\n return {\n client,\n definition,\n };\n});\n\n/** Use the same source contract with Effect RPC's worker, HTTP or socket transport. */\nexport const makeOntologyProtocolClient = Effect.fn(\"RemoteOntology.protocol\")(function* (\n client: OntologyRpcClient,\n options?: OntologyClientOptions\n): Effect.fn.Return<OntologyClient, BackendError, Scope.Scope> {\n const description = yield* options?.description\n ? copyDescription(options.description)\n : client.Describe().pipe(Effect.mapError(unavailable), Effect.flatMap(copyDescription));\n if (options?.description && !description.ir)\n return yield* new BackendError({\n operation: \"remote.bootstrap\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"A retained ontology description must include its definition.\",\n });\n const described = yield* makeDefinitionClient(client, description, options);\n const pinBackend = description.pins\n ? makeOntologyProtocolClient(selectPinResource(client)).pipe(\n Effect.map((resource) => resource.backend)\n )\n : undefined;\n client = described.client;\n const operations = yield* makeOntologyOperationsClient(client);\n const common = {\n description,\n definition: described.definition,\n operations,\n pins: description.pins ? operations.pins : undefined,\n pinBackend,\n sourceId: description.sourceId,\n definitionHash: description.definitionHash,\n ir: description.ir,\n context: description.context,\n backend: makeRpcBackend(client, description, operations),\n };\n if (description.replication === \"committed\") return { ...common, replication: { kind: \"committed\" } };\n const source: OntologySource = {\n sourceId: description.sourceId,\n outbox: operations.outbox,\n supportsIdempotency: description.supportsIdempotency,\n openClient: (resume) => client.OpenClient({ resume }).pipe(Effect.mapError(unavailable)),\n read: (session, view) => client.Read({ session, view }).pipe(Effect.mapError(unavailable)),\n submit: (request) => client.Submit(request).pipe(Effect.mapError(unavailable)),\n accept: description.stateDelivery\n ? (request) => client.Accept(request).pipe(Effect.mapError(unavailable))\n : undefined,\n subscribe: description.stateDelivery\n ? (session, view, _policy, resume) =>\n Effect.succeed({\n frames: client\n .SubscribeState({ session, view, resume })\n .pipe(Stream.mapError(unavailable)),\n acknowledge: (position) =>\n client\n .AckDelivery({ kind: \"speculative\", position })\n .pipe(Effect.mapError(unavailable)),\n })\n : undefined,\n acknowledgeDelivery: description.stateDelivery\n ? (position) =>\n client.AckDelivery({ kind: \"speculative\", position }).pipe(Effect.mapError(unavailable))\n : undefined,\n acknowledge: (session, revision, through, viewGeneration) =>\n client\n .Acknowledge({ session, revision, through, viewGeneration })\n .pipe(Effect.mapError(unavailable)),\n subscribeChanges: Effect.succeed(\n client.Changes().pipe(\n Stream.map(() => undefined),\n Stream.mapError(unavailable)\n )\n ),\n demand: (subset) => client.Demand(subset).pipe(Stream.as(undefined), Stream.mapError(unavailable)),\n };\n return { ...common, replication: { kind: \"speculative\", source } };\n});\n\nexport { errorProjectionLayer } from \"./errorProjection.js\";\n"],"mappings":";;;;;;;;;;;;;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K,YAAY;GAAE;GAAS;GAAU;GAAS;EAAe,CAAC,CAAC,CAC3D,KAAK,OAAO,SAAS,WAAW,CAAC;EAC1C,kBAAkB,OAAO,QACrB,OAAO,QAAQ,CAAC,CAAC,KACb,OAAO,UAAU,KAAA,CAAS,GAC1B,OAAO,SAAS,WAAW,CAC/B,CACJ;EACA,SAAS,WAAW,OAAO,OAAO,MAAM,CAAC,CAAC,KAAK,OAAO,GAAG,KAAA,CAAS,GAAG,OAAO,SAAS,WAAW,CAAC;CACrG;CACA,OAAO;EAAE,GAAG;EAAQ,aAAa;GAAE,MAAM;GAAe;EAAO;CAAE;AACrE,CAAC"}
@@ -0,0 +1,6 @@
1
+ import { Context } from "effect";
2
+ //#region src/rpcActivity.d.ts
3
+ /** Stream lifetime alone cannot distinguish subscriptions from finite byte transfers. */
4
+ export declare const RpcActivity: Context.Reference<"subscription" | "transfer">;
5
+ //#endregion
6
+ //# sourceMappingURL=rpcActivity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcActivity.d.ts","names":[],"sources":["../src/rpcActivity.ts"],"mappings":";;;qBAGa,aAAW,QAAA"}
@@ -0,0 +1,8 @@
1
+ import { Context } from "effect";
2
+ //#region src/rpcActivity.ts
3
+ /** Stream lifetime alone cannot distinguish subscriptions from finite byte transfers. */
4
+ const RpcActivity = Context.Reference("@party-stack/ontology-server/RpcActivity", { defaultValue: () => "subscription" });
5
+ //#endregion
6
+ export { RpcActivity };
7
+
8
+ //# sourceMappingURL=rpcActivity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcActivity.js","names":[],"sources":["../src/rpcActivity.ts"],"sourcesContent":["import { Context } from \"effect\";\n\n/** Stream lifetime alone cannot distinguish subscriptions from finite byte transfers. */\nexport const RpcActivity = Context.Reference<\"subscription\" | \"transfer\">(\n \"@party-stack/ontology-server/RpcActivity\",\n { defaultValue: () => \"subscription\" }\n);\n"],"mappings":";;;AAGA,MAAa,cAAc,QAAQ,UAC/B,4CACA,EAAE,oBAAoB,eAAe,CACzC"}
@@ -0,0 +1,8 @@
1
+ import { OntologyOperationsClient } from "./operations.js";
2
+ import { OntologyDescription, OntologyRpcClient } from "./rpc.js";
3
+ import { OntologyBackendService } from "@party-stack/ontology-backend";
4
+ //#region src/rpcBackend.d.ts
5
+ /** Committed-data/finite-operation facet shared by every RPC transport. */
6
+ export declare function makeRpcBackend(client: OntologyRpcClient, description: OntologyDescription, operations: OntologyOperationsClient): OntologyBackendService;
7
+ //#endregion
8
+ //# sourceMappingURL=rpcBackend.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcBackend.d.ts","names":[],"sources":["../src/rpcBackend.ts"],"mappings":";;;;;wBASgB,eACZ,QAAQ,mBACR,aAAa,qBACb,YAAY,2BACb"}
@@ -0,0 +1,76 @@
1
+ import { acquireRpcWatch } from "./rpcWatch.js";
2
+ import { BackendError, classifyBackendFailure } from "@party-stack/ontology-backend";
3
+ import { sliceByteSource } from "@party-stack/ontology-storage/blobs";
4
+ import { Effect, Stream } from "effect";
5
+ //#region src/rpcBackend.ts
6
+ /** Committed-data/finite-operation facet shared by every RPC transport. */
7
+ function makeRpcBackend(client, description, operations) {
8
+ return {
9
+ attachments: description.attachments ? {
10
+ stage: description.attachments.stage ? (value, bytes) => operations.attachments.create(bytes, {
11
+ id: value.id,
12
+ eager: description.replication === "committed"
13
+ }).pipe(Effect.map((created) => created.attachment)) : void 0,
14
+ read: (value, range) => operations.attachments.source(value).pipe(Effect.map((source) => range ? sliceByteSource(source, range.offset ?? 0, range.length) : source)),
15
+ metadata: (value, settings) => client.AttachmentMetadata({
16
+ attachment: value,
17
+ select: settings?.select
18
+ }).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.attachment.metadata", cause)))
19
+ } : void 0,
20
+ encrypted: description.encrypted ? { decrypt: (value) => client.Decrypt({ value }).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.decrypt", cause))) } : void 0,
21
+ name: "protocol",
22
+ sourceId: description.sourceId,
23
+ supportsIdempotency: description.supportsIdempotency,
24
+ query: (document, settings) => operations.query(document, settings?.inputs),
25
+ resolveActionParameters: description.actionParameterResolution ? operations.resolveActionParameters : void 0,
26
+ changes: description.changes ? {
27
+ pull: (request) => client.PullChanges(request).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.pullChanges", cause))),
28
+ watch: description.watchChanges ? acquireRpcWatch(client.WatchChanges().pipe(Stream.mapError((cause) => classifyBackendFailure("remote.changes", cause))), "invalidate", "remote.changes").pipe(Effect.map((stream) => stream.pipe(Stream.as(void 0)))) : void 0
29
+ } : void 0,
30
+ watchSubset: description.watchSubset ? (subset) => acquireRpcWatch(client.WatchSubset(subset).pipe(Stream.mapError((cause) => classifyBackendFailure("remote.watchSubset", cause))), "reset", "remote.watchSubset").pipe(Effect.map((stream) => stream.pipe(Stream.map((event) => event === "reset" ? "reset" : void 0)))) : void 0,
31
+ subscribeSelection: description.delivery ? (selection, _policy, resume) => Effect.succeed({
32
+ frames: client.SubscribeSelection({
33
+ selection,
34
+ resume
35
+ }).pipe(Stream.mapError((cause) => classifyBackendFailure("remote.delivery", cause))),
36
+ acknowledge: (position) => client.AckDelivery({
37
+ kind: "committed",
38
+ position
39
+ }).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.delivery", cause)))
40
+ }) : void 0,
41
+ acknowledgeDelivery: description.delivery ? (position) => client.AckDelivery({
42
+ kind: "committed",
43
+ position
44
+ }).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.delivery", cause))) : void 0,
45
+ loadSubset: (subset) => client.LoadSubset(subset).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.request", cause))),
46
+ applyAction: Effect.fn("OntologyBackend.invokeRemote")(function* (invocation) {
47
+ for (const upload of invocation.attachmentUploads ?? []) {
48
+ const { attachment: staged } = yield* operations.attachments.create(upload.blob, { id: upload.attachment.id });
49
+ if (staged.id !== upload.attachment.id) return yield* new BackendError({
50
+ operation: "applyAction.upload",
51
+ kind: "NotImplemented",
52
+ retryable: false,
53
+ actionOutcome: "not-committed",
54
+ message: "This transport requires attachment staging to preserve its handle."
55
+ });
56
+ }
57
+ return yield* client.ApplyAction({
58
+ ...invocation,
59
+ attachmentUploads: void 0
60
+ }).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.applyAction", cause)));
61
+ }),
62
+ queryFunction: (name, parameters) => client.QueryFunction({
63
+ name,
64
+ parameters
65
+ }).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.request", cause))),
66
+ validateAction: (name, parameters, settings) => client.ValidateAction({
67
+ name,
68
+ parameters,
69
+ knownParameters: settings?.knownParameters
70
+ }).pipe(Effect.mapError((cause) => classifyBackendFailure("remote.request", cause)))
71
+ };
72
+ }
73
+ //#endregion
74
+ export { makeRpcBackend };
75
+
76
+ //# sourceMappingURL=rpcBackend.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcBackend.js","names":[],"sources":["../src/rpcBackend.ts"],"sourcesContent":["import { BackendError, classifyBackendFailure } from \"@party-stack/ontology-backend\";\nimport { sliceByteSource } from \"@party-stack/ontology-storage/blobs\";\nimport { Effect, Stream } from \"effect\";\nimport { acquireRpcWatch } from \"./rpcWatch.js\";\nimport type { OntologyOperationsClient } from \"./operations.js\";\nimport type { OntologyDescription, OntologyRpcClient } from \"./rpc.js\";\nimport type { OntologyBackendService } from \"@party-stack/ontology-backend\";\n\n/** Committed-data/finite-operation facet shared by every RPC transport. */\nexport function makeRpcBackend(\n client: OntologyRpcClient,\n description: OntologyDescription,\n operations: OntologyOperationsClient\n): OntologyBackendService {\n // One stream represents one attempt, like every other adapter. Replica watch\n // supervision must see EOF/errors to invalidate coverage and apply retry policy.\n return {\n attachments: description.attachments\n ? {\n stage: description.attachments.stage\n ? (value, bytes) =>\n operations.attachments\n .create(bytes, {\n id: value.id,\n eager: description.replication === \"committed\",\n })\n .pipe(Effect.map((created) => created.attachment))\n : undefined,\n read: (value, range) =>\n operations.attachments\n .source(value)\n .pipe(\n Effect.map((source) =>\n range ? sliceByteSource(source, range.offset ?? 0, range.length) : source\n )\n ),\n metadata: (value, settings) =>\n client\n .AttachmentMetadata({ attachment: value, select: settings?.select })\n .pipe(\n Effect.mapError((cause) =>\n classifyBackendFailure(\"remote.attachment.metadata\", cause)\n )\n ),\n }\n : undefined,\n encrypted: description.encrypted\n ? {\n decrypt: (value) =>\n client\n .Decrypt({ value })\n .pipe(Effect.mapError((cause) => classifyBackendFailure(\"remote.decrypt\", cause))),\n }\n : undefined,\n name: \"protocol\",\n sourceId: description.sourceId,\n supportsIdempotency: description.supportsIdempotency,\n query: (document, settings) => operations.query(document, settings?.inputs),\n resolveActionParameters: description.actionParameterResolution\n ? operations.resolveActionParameters\n : undefined,\n changes: description.changes\n ? {\n pull: (request) =>\n client\n .PullChanges(request)\n .pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"remote.pullChanges\", cause))\n ),\n watch: description.watchChanges\n ? acquireRpcWatch(\n client\n .WatchChanges()\n .pipe(\n Stream.mapError((cause) =>\n classifyBackendFailure(\"remote.changes\", cause)\n )\n ),\n \"invalidate\",\n \"remote.changes\"\n ).pipe(Effect.map((stream) => stream.pipe(Stream.as(undefined))))\n : undefined,\n }\n : undefined,\n watchSubset: description.watchSubset\n ? (subset) =>\n acquireRpcWatch(\n client\n .WatchSubset(subset)\n .pipe(\n Stream.mapError((cause) => classifyBackendFailure(\"remote.watchSubset\", cause))\n ),\n \"reset\",\n \"remote.watchSubset\"\n ).pipe(\n Effect.map((stream) =>\n stream.pipe(\n Stream.map((event) => (event === \"reset\" ? (\"reset\" as const) : undefined))\n )\n )\n )\n : undefined,\n subscribeSelection: description.delivery\n ? (selection, _policy, resume) =>\n Effect.succeed({\n frames: client\n .SubscribeSelection({ selection, resume })\n .pipe(Stream.mapError((cause) => classifyBackendFailure(\"remote.delivery\", cause))),\n acknowledge: (position) =>\n client\n .AckDelivery({ kind: \"committed\", position })\n .pipe(\n Effect.mapError((cause) => classifyBackendFailure(\"remote.delivery\", cause))\n ),\n })\n : undefined,\n acknowledgeDelivery: description.delivery\n ? (position) =>\n client\n .AckDelivery({ kind: \"committed\", position })\n .pipe(Effect.mapError((cause) => classifyBackendFailure(\"remote.delivery\", cause)))\n : undefined,\n loadSubset: (subset) =>\n client\n .LoadSubset(subset)\n .pipe(Effect.mapError((cause) => classifyBackendFailure(\"remote.request\", cause))),\n applyAction: Effect.fn(\"OntologyBackend.invokeRemote\")(function* (invocation) {\n for (const upload of invocation.attachmentUploads ?? []) {\n const { attachment: staged } = yield* operations.attachments.create(upload.blob, {\n id: upload.attachment.id,\n });\n // Local storage parents preserve handles. HTTP multipart remains the\n // atomic provider path when uploads require parameter canonicalization.\n if (staged.id !== upload.attachment.id)\n return yield* new BackendError({\n operation: \"applyAction.upload\",\n kind: \"NotImplemented\",\n retryable: false,\n actionOutcome: \"not-committed\",\n message: \"This transport requires attachment staging to preserve its handle.\",\n });\n }\n return yield* client\n .ApplyAction({ ...invocation, attachmentUploads: undefined })\n .pipe(Effect.mapError((cause) => classifyBackendFailure(\"remote.applyAction\", cause)));\n }),\n queryFunction: (name, parameters) =>\n client\n .QueryFunction({ name, parameters })\n .pipe(Effect.mapError((cause) => classifyBackendFailure(\"remote.request\", cause))),\n validateAction: (name, parameters, settings) =>\n client\n .ValidateAction({ name, parameters, knownParameters: settings?.knownParameters })\n .pipe(Effect.mapError((cause) => classifyBackendFailure(\"remote.request\", cause))),\n };\n}\n"],"mappings":";;;;;;AASA,SAAgB,eACZ,QACA,aACA,YACsB;CAGtB,OAAO;EACH,aAAa,YAAY,cACnB;GACI,OAAO,YAAY,YAAY,SACxB,OAAO,UACJ,WAAW,YACN,OAAO,OAAO;IACX,IAAI,MAAM;IACV,OAAO,YAAY,gBAAgB;GACvC,CAAC,CAAC,CACD,KAAK,OAAO,KAAK,YAAY,QAAQ,UAAU,CAAC,IACzD,KAAA;GACN,OAAO,OAAO,UACV,WAAW,YACN,OAAO,KAAK,CAAC,CACb,KACG,OAAO,KAAK,WACR,QAAQ,gBA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,UAAU;EAAgB,CAAC,CAAC,CAChF,KAAK,OAAO,UAAU,UAAU,uBAAuB,kBAAkB,KAAK,CAAC,CAAC;CAC7F;AACJ"}
@@ -0,0 +1,24 @@
1
+ import { OntologyRpcServerOptions, OntologyServerClient } from "./rpc.js";
2
+ import { OntologyServer } from "./routing.js";
3
+ import { BackendError } from "@party-stack/ontology-backend";
4
+ import { Effect, Scope } from "effect";
5
+ import { HttpClient } from "effect/http";
6
+ //#region src/rpcHttp.d.ts
7
+ /** Mount the returned Fetch handler at a dedicated route. Its enclosing scope owns
8
+ * the server and active streams; each request still passes mandatory authorization.
9
+ */
10
+ export declare const makeOntologyHttpHandler: <R>(options: OntologyRpcServerOptions<R> | OntologyServer<R>) => Effect.Effect<(request: Request) => Promise<Response>, never, R | Scope.Scope>;
11
+ /** Supply an Effect HttpClient with the desired authentication and fetch policy.
12
+ * NDJSON keeps demand and invalidation subscriptions streaming until cancellation.
13
+ */
14
+ export declare const makeOntologyHttpClient: (options: {
15
+ readonly url: string;
16
+ readonly ontology?: string;
17
+ }) => Effect.Effect<OntologyServerClient, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, HttpClient.HttpClient | Scope.Scope>;
18
+ /** Stateless request/response binding: never opens a replication client session. */
19
+ export declare const makeOntologyHttpBackend: (options: {
20
+ readonly url: string;
21
+ readonly ontology?: string;
22
+ }) => Effect.Effect<import("@party-stack/ontology-backend").OntologyBackendService, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, HttpClient.HttpClient | Scope.Scope>;
23
+ //#endregion
24
+ //# sourceMappingURL=rpcHttp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcHttp.d.ts","names":[],"sources":["../src/rpcHttp.ts"],"mappings":";;;;;;;;;qBAmDa,0BAA6E,GAAC,SAAA,yBAAA,KAAA,eAAA,OAAA,OAAA,QAAA,SAE7D,YAAY,QAAQ,kBAAS,IAAA,MAAA;;;;qBAwG9C,yBAAsB;WACjB;WACM;MAiGtB,OAAA,OAAA,sBAAA,iWAAA,WAAA,aAAA,MAAA;;qBAGW,0BAAuB;WAClB;WACM;MAGtB,OAAA,+CAAA,wBAAA,iWAAA,WAAA,aAAA,MAAA"}
package/lib/rpcHttp.js ADDED
@@ -0,0 +1,118 @@
1
+ import { expectedBindingHeaders } from "./bindingFence.js";
2
+ import { isAttachmentHttpRequest, makeAttachmentHttpHandler, makeHttpAttachmentClient } from "./attachmentHttp.js";
3
+ import { OntologyRpcs, makeOntologyProtocolClient, makeOntologyRpcClient, observeOntologyClientFailure, ontologyRpcHandlers } from "./rpc.js";
4
+ import { OntologyTransportBinding, OntologyTransportRequest, OntologyTransportTarget, ontologyServerDispatch, ontologyUrl, selectOntology } from "./routing.js";
5
+ import { BackendError, backendErrorStatus, classifyBackendFailure, projectBackendError } from "@party-stack/ontology-backend";
6
+ import { Effect, Fiber, Layer, Schema } from "effect";
7
+ import { HttpClient, HttpClientError, HttpClientRequest, HttpEffect, HttpServerRequest, HttpServerResponse } from "effect/http";
8
+ import { RpcClient, RpcSerialization, RpcServer } from "effect/rpc";
9
+ import { CurrentExecutionContext } from "@party-stack/ontology-backend/policy";
10
+ //#region src/rpcHttp.ts
11
+ /** Mount the returned Fetch handler at a dedicated route. Its enclosing scope owns
12
+ * the server and active streams; each request still passes mandatory authorization.
13
+ */
14
+ const makeOntologyHttpHandler = Effect.fn("RemoteOntology.httpHandler")(function* (options) {
15
+ const app = yield* RpcServer.toHttpEffect(OntologyRpcs).pipe(Effect.provide("_tag" in options ? ontologyServerDispatch(options) : ontologyRpcHandlers({
16
+ ...options,
17
+ authorize: (request, headers) => request.operation === "CreateAttachment" ? Effect.fail(new BackendError({
18
+ operation: "attachment.http",
19
+ kind: "NotImplemented",
20
+ message: "Use the HTTP binding for streamed uploads.",
21
+ retryable: false
22
+ })) : options.authorize(request, headers)
23
+ })), Effect.provide(RpcSerialization.layerNdjson));
24
+ if ("_tag" in options) {
25
+ const owner = yield* Effect.scope;
26
+ const routed = Effect.gen(function* () {
27
+ const incoming = yield* HttpServerRequest.HttpServerRequest;
28
+ const request = yield* HttpServerRequest.toWeb(incoming).pipe(Effect.mapError((cause) => new BackendError({
29
+ operation: "ontology.http",
30
+ kind: "InvalidRequest",
31
+ retryable: false,
32
+ message: "Invalid HTTP request.",
33
+ cause
34
+ })));
35
+ const target = new URL(request.url).searchParams.get("ontology") ?? request.headers.get("x-party-stack-ontology") ?? options.defaultOntology;
36
+ const bound = target === void 0 ? void 0 : yield* options.bind(target, request);
37
+ if (isAttachmentHttpRequest(request)) {
38
+ const selected = bound ?? (yield* options.bind(target ?? "", request));
39
+ const upload = yield* makeAttachmentHttpHandler(selected.options);
40
+ return yield* HttpEffect.fromWebHandler(upload).pipe(Effect.provideService(CurrentExecutionContext, selected.executionContext));
41
+ }
42
+ return yield* app.pipe(Effect.provideService(OntologyTransportRequest, request), Effect.provideService(OntologyTransportTarget, target), Effect.provideService(OntologyTransportBinding, bound ? {
43
+ ontology: target,
44
+ bound
45
+ } : void 0));
46
+ }).pipe(Effect.catchDefect((cause) => Effect.fail(new BackendError({
47
+ operation: "ontology.http",
48
+ kind: "Internal",
49
+ retryable: false,
50
+ message: "Ontology request failed.",
51
+ cause
52
+ }))), Effect.catch((cause) => {
53
+ const error = projectBackendError(classifyBackendFailure("ontology.http", cause), options.errors);
54
+ return Effect.succeed(HttpServerResponse.jsonUnsafe(Schema.encodeSync(BackendError)(error), { status: backendErrorStatus(error) }));
55
+ }), Effect.interruptible);
56
+ const captured = yield* Effect.context();
57
+ return HttpEffect.toWebHandlerWith(captured)(Effect.acquireUseRelease(Effect.forkIn(routed, owner), Fiber.join, Fiber.interrupt).pipe(Effect.interruptible));
58
+ }
59
+ const rpcHandler = HttpEffect.toWebHandler(app.pipe(Effect.interruptible));
60
+ const uploadHandler = yield* makeAttachmentHttpHandler(options);
61
+ return (request) => isAttachmentHttpRequest(request) ? uploadHandler(request) : rpcHandler(request);
62
+ });
63
+ /** Supply an Effect HttpClient with the desired authentication and fetch policy.
64
+ * NDJSON keeps demand and invalidation subscriptions streaming until cancellation.
65
+ */
66
+ const makeOntologyHttpClient = Effect.fn("OntologyClient.http")(function* (options) {
67
+ const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient).pipe(HttpClient.catch((error) => {
68
+ const response = error.response;
69
+ if (!response) return Effect.fail(error);
70
+ return response.json.pipe(Effect.flatMap(Schema.decodeUnknownEffect(BackendError)), Effect.matchEffect({
71
+ onFailure: () => Effect.fail(error),
72
+ onSuccess: (cause) => Effect.fail(new HttpClientError.HttpClientError({ reason: new HttpClientError.StatusCodeError({
73
+ request: error.request,
74
+ response,
75
+ cause
76
+ }) }))
77
+ }));
78
+ }));
79
+ const url = options.url;
80
+ const rpc = yield* makeOntologyRpcClient.pipe(Effect.provide(RpcClient.layerProtocolHttp({
81
+ url,
82
+ transformClient: (client) => HttpClient.mapRequest(client, HttpClientRequest.setUrl(new URL(url)))
83
+ }).pipe(Layer.provide(RpcSerialization.layerNdjson))), Effect.provideService(HttpClient.HttpClient, http));
84
+ return { ontology: Effect.fn("OntologyClient.select")(function* (selected, clientOptions) {
85
+ const name = selected ?? options.ontology;
86
+ const client = yield* makeOntologyProtocolClient(name ? selectOntology(rpc, name) : rpc, clientOptions);
87
+ const uploads = yield* makeHttpAttachmentClient(ontologyUrl(url, name)).pipe(Effect.provideService(HttpClient.HttpClient, HttpClient.mapRequest(http, HttpClientRequest.setHeaders(expectedBindingHeaders(client.description)))));
88
+ return {
89
+ ...client,
90
+ backend: {
91
+ ...client.backend,
92
+ attachments: client.backend.attachments && {
93
+ ...client.backend.attachments,
94
+ stage: client.backend.attachments.stage ? (value, bytes) => observeOntologyClientFailure(client, uploads.create(bytes, {
95
+ id: value.id,
96
+ eager: client.replication.kind === "committed"
97
+ })).pipe(Effect.map((created) => created.attachment)) : void 0
98
+ },
99
+ applyAction: (invocation) => invocation.attachmentUploads?.length ? observeOntologyClientFailure(client, uploads.applyAction(invocation)) : client.backend.applyAction(invocation)
100
+ },
101
+ operations: {
102
+ ...client.operations,
103
+ attachments: {
104
+ ...client.operations.attachments,
105
+ create: (input, options) => observeOntologyClientFailure(client, uploads.create(input, options))
106
+ }
107
+ }
108
+ };
109
+ }, Effect.provideService(HttpClient.HttpClient, http)) };
110
+ });
111
+ /** Stateless request/response binding: never opens a replication client session. */
112
+ const makeOntologyHttpBackend = Effect.fn("OntologyBackend.http")(function* (options) {
113
+ return (yield* (yield* makeOntologyHttpClient(options)).ontology()).backend;
114
+ });
115
+ //#endregion
116
+ export { makeOntologyHttpBackend, makeOntologyHttpClient, makeOntologyHttpHandler };
117
+
118
+ //# sourceMappingURL=rpcHttp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcHttp.js","names":[],"sources":["../src/rpcHttp.ts"],"sourcesContent":["import {\n BackendError,\n classifyBackendFailure,\n projectBackendError,\n backendErrorStatus,\n} from \"@party-stack/ontology-backend\";\nimport { CurrentExecutionContext } from \"@party-stack/ontology-backend/policy\";\nimport { Effect, Fiber, Layer, Schema } from \"effect\";\nimport {\n HttpClient,\n HttpClientError,\n HttpClientRequest,\n HttpEffect,\n HttpServerRequest,\n HttpServerResponse,\n} from \"effect/http\";\nimport { RpcClient, RpcSerialization, RpcServer } from \"effect/rpc\";\nimport {\n isAttachmentHttpRequest,\n makeAttachmentHttpHandler,\n makeHttpAttachmentClient,\n} from \"./attachmentHttp.js\";\nimport { expectedBindingHeaders } from \"./bindingFence.js\";\nimport {\n ontologyUrl,\n ontologyHeader,\n selectOntology,\n ontologyServerDispatch,\n OntologyTransportRequest,\n OntologyTransportTarget,\n OntologyTransportBinding,\n} from \"./routing.js\";\nimport {\n makeOntologyProtocolClient,\n ontologyRpcHandlers,\n OntologyRpcs,\n makeOntologyRpcClient,\n observeOntologyClientFailure,\n} from \"./rpc.js\";\nimport type { OntologyServer } from \"./routing.js\";\nimport type {\n OntologyRpcServerOptions,\n OntologyServerClient,\n OntologyClient,\n OntologyClientOptions,\n} from \"./rpc.js\";\nimport type { Scope } from \"effect\";\n\n/** Mount the returned Fetch handler at a dedicated route. Its enclosing scope owns\n * the server and active streams; each request still passes mandatory authorization.\n */\nexport const makeOntologyHttpHandler = Effect.fn(\"RemoteOntology.httpHandler\")(function* <R>(\n options: OntologyRpcServerOptions<R> | OntologyServer<R>\n): Effect.fn.Return<(request: Request) => Promise<Response>, never, R | Scope.Scope> {\n const app = yield* RpcServer.toHttpEffect(OntologyRpcs).pipe(\n Effect.provide(\n \"_tag\" in options\n ? ontologyServerDispatch(options)\n : ontologyRpcHandlers({\n ...options,\n authorize: (request, headers) =>\n request.operation === \"CreateAttachment\"\n ? Effect.fail(\n new BackendError({\n operation: \"attachment.http\",\n kind: \"NotImplemented\",\n message: \"Use the HTTP binding for streamed uploads.\",\n retryable: false,\n })\n )\n : options.authorize(request, headers),\n })\n ),\n Effect.provide(RpcSerialization.layerNdjson)\n );\n // HttpEffect handles request scopes uninterruptibly by default. Restore interruption\n // while waiting for an RPC response so disconnecting before the first NDJSON chunk\n // closes the request scope and cancels the corresponding server handler.\n if (\"_tag\" in options) {\n const owner = yield* Effect.scope;\n const routed = Effect.gen(function* () {\n const incoming = yield* HttpServerRequest.HttpServerRequest;\n const request = yield* HttpServerRequest.toWeb(incoming).pipe(\n Effect.mapError(\n (cause) =>\n new BackendError({\n operation: \"ontology.http\",\n kind: \"InvalidRequest\",\n retryable: false,\n message: \"Invalid HTTP request.\",\n cause,\n })\n )\n );\n const target =\n new URL(request.url).searchParams.get(\"ontology\") ??\n request.headers.get(ontologyHeader) ??\n options.defaultOntology;\n const bound = target === undefined ? undefined : yield* options.bind(target, request);\n if (isAttachmentHttpRequest(request)) {\n const selected = bound ?? (yield* options.bind(target ?? \"\", request));\n const upload = yield* makeAttachmentHttpHandler(selected.options);\n return yield* HttpEffect.fromWebHandler(upload).pipe(\n Effect.provideService(CurrentExecutionContext, selected.executionContext)\n );\n }\n return yield* app.pipe(\n Effect.provideService(OntologyTransportRequest, request),\n Effect.provideService(OntologyTransportTarget, target),\n Effect.provideService(\n OntologyTransportBinding,\n bound ? { ontology: target!, bound } : undefined\n )\n );\n }).pipe(\n Effect.catchDefect((cause) =>\n Effect.fail(\n new BackendError({\n operation: \"ontology.http\",\n kind: \"Internal\",\n retryable: false,\n message: \"Ontology request failed.\",\n cause,\n })\n )\n ),\n Effect.catch((cause) => {\n const error = projectBackendError(\n classifyBackendFailure(\"ontology.http\", cause),\n options.errors\n );\n return Effect.succeed(\n HttpServerResponse.jsonUnsafe(Schema.encodeSync(BackendError)(error), {\n status: backendErrorStatus(error),\n })\n );\n }),\n Effect.interruptible\n );\n const captured = yield* Effect.context<R>();\n return HttpEffect.toWebHandlerWith<R, R | Scope.Scope | HttpServerRequest.HttpServerRequest, never>(\n captured\n )(\n Effect.acquireUseRelease(Effect.forkIn(routed, owner), Fiber.join, Fiber.interrupt).pipe(\n Effect.interruptible\n )\n );\n }\n const rpcHandler = HttpEffect.toWebHandler(app.pipe(Effect.interruptible));\n const uploadHandler = yield* makeAttachmentHttpHandler(options);\n return (request: Request) =>\n isAttachmentHttpRequest(request) ? uploadHandler(request) : rpcHandler(request);\n});\n\n/** Supply an Effect HttpClient with the desired authentication and fetch policy.\n * NDJSON keeps demand and invalidation subscriptions streaming until cancellation.\n */\nexport const makeOntologyHttpClient = Effect.fn(\"OntologyClient.http\")(function* (options: {\n readonly url: string;\n readonly ontology?: string;\n}): Effect.fn.Return<OntologyServerClient, BackendError, HttpClient.HttpClient | Scope.Scope> {\n // Authentication and infrastructure can reject the HTTP request before any\n // RPC frame exists. Classify its status instead of parsing that body as NDJSON.\n const http = HttpClient.filterStatusOk(yield* HttpClient.HttpClient).pipe(\n HttpClient.catch((error) => {\n const response = error.response;\n if (!response) return Effect.fail(error);\n // A router or authentication hook can fail before there is an RPC\n // frame. Preserve a normal serialized BackendError when present;\n // other hosts' HTML/JSON errors retain ordinary HTTP classification.\n return response.json.pipe(\n Effect.flatMap(Schema.decodeUnknownEffect(BackendError)),\n Effect.matchEffect({\n onFailure: () => Effect.fail(error),\n onSuccess: (cause) =>\n Effect.fail(\n new HttpClientError.HttpClientError({\n reason: new HttpClientError.StatusCodeError({\n request: error.request,\n response,\n cause,\n }),\n })\n ),\n })\n );\n })\n );\n const url = options.url;\n const rpc = yield* makeOntologyRpcClient.pipe(\n Effect.provide(\n RpcClient.layerProtocolHttp({\n url,\n // Set the complete URL so query parameters remain URL parameters;\n // prependUrl treats its argument as a path segment.\n transformClient: (client) =>\n HttpClient.mapRequest(client, HttpClientRequest.setUrl(new URL(url))),\n }).pipe(Layer.provide(RpcSerialization.layerNdjson))\n ),\n Effect.provideService(HttpClient.HttpClient, http)\n );\n return {\n ontology: Effect.fn(\"OntologyClient.select\")(\n function* (\n selected?: string,\n clientOptions?: OntologyClientOptions\n ): Effect.fn.Return<OntologyClient, BackendError, HttpClient.HttpClient | Scope.Scope> {\n const name = selected ?? options.ontology;\n const client = yield* makeOntologyProtocolClient(\n name ? selectOntology(rpc, name) : rpc,\n clientOptions\n );\n const uploads = yield* makeHttpAttachmentClient(ontologyUrl(url, name)).pipe(\n Effect.provideService(\n HttpClient.HttpClient,\n HttpClient.mapRequest(\n http,\n HttpClientRequest.setHeaders(expectedBindingHeaders(client.description))\n )\n )\n );\n return {\n ...client,\n backend: {\n ...client.backend,\n attachments: client.backend.attachments && {\n ...client.backend.attachments,\n stage: client.backend.attachments.stage\n ? (value, bytes) =>\n observeOntologyClientFailure(\n client,\n uploads.create(bytes, {\n id: value.id,\n eager: client.replication.kind === \"committed\",\n })\n ).pipe(Effect.map((created) => created.attachment))\n : undefined,\n },\n applyAction: (invocation) =>\n invocation.attachmentUploads?.length\n ? observeOntologyClientFailure(client, uploads.applyAction(invocation))\n : client.backend.applyAction(invocation),\n },\n operations: {\n ...client.operations,\n attachments: {\n ...client.operations.attachments,\n create: (input, options) =>\n observeOntologyClientFailure(client, uploads.create(input, options)),\n },\n },\n };\n },\n Effect.provideService(HttpClient.HttpClient, http)\n ),\n };\n});\n\n/** Stateless request/response binding: never opens a replication client session. */\nexport const makeOntologyHttpBackend = Effect.fn(\"OntologyBackend.http\")(function* (options: {\n readonly url: string;\n readonly ontology?: string;\n}) {\n return (yield* (yield* makeOntologyHttpClient(options)).ontology()).backend;\n});\n"],"mappings":";;;;;;;;;;;;;AAmDA,MAAa,0BAA0B,OAAO,GAAG,4BAA4B,CAAC,CAAC,WAC3E,SACiF;CACjF,MAAM,MAAM,OAAO,UAAU,aAAa,YAAY,CAAC,CAAC,KACpD,OAAO,QACH,UAAU,UACJ,uBAAuB,OAAO,IAC9B,oBAAoB;EAChB,GAAG;EACH,YAAY,SAAS,YACjB,QAAQ,cAAc,qBAChB,OAAO,KACH,IAAI,aAAa;GACb,WAAW;GACX,MAAM;GACN,SAAS;GACT,WAAW;EACf,CAAC,CACL,IACA,QAAQ,UAAU,SAAS,OAAO;CAChD,CAAC,CACX,GACA,OAAO,QAAQ,iBAAiB,WAAW,CAC/C;CAIA,IAAI,UAAU,SAAS;EACnB,MAAM,QAAQ,OAAO,OAAO;EAC5B,MAAM,SAAS,OAAO,IAAI,aAAa;GACnC,MAAM,WAAW,OAAO,kBAAkB;GAC1C,MAAM,UAAU,OAAO,kBAAkB,MAAM,QAAQ,CAAC,CAAC,KACrD,OAAO,UACF,UACG,IAAI,aAAa;IACb,WAAW;IACX,MAAM;IACN,WAAW;IACX,SAAS;IACT;GACJ,CAAC,CACT,CACJ;GACA,MAAM,SACF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,OAAO,WAAW,CAAC,CAC3E,CACJ,CACJ;EACA,OAAO;GACH,GAAG;GACH,SAAS;IACL,GAAG,OAAO;IACV,aAAa,OAAO,QAAQ,eAAe;KACvC,GAAG,OAAO,QAAQ;KAClB,OAAO,OAAO,QAAQ,YAAY,SAC3B,OAAO,UACJ,6BACI,QACA,QAAQ,OAAO,OAAO;MAClB,IAAI,MAAM;MACV,OAAO,OAAO,YAAY,SAAS;KACvC,CAAC,CACL,CAAC,CAAC,KAAK,OAAO,KAAK,YAAY,QAAQ,UAAU,CAAC,IACtD,KAAA;IACV;IACA,cAAc,eACV,WAAW,mBAAmB,SACxB,6BAA6B,QAAQ,QAAQ,YAAY,UAAU,CAAC,IACpE,OAAO,QAAQ,YAAY,UAAU;GACnD;GACA,YAAY;IACR,GAAG,OAAO;IACV,aAAa;KACT,GAAG,OAAO,WAAW;KACrB,SAAS,OAAO,YACZ,6BAA6B,QAAQ,QAAQ,OAAO,OAAO,OAAO,CAAC;IAC3E;GACJ;EACJ;CACJ,GACA,OAAO,eAAe,WAAW,YAAY,IAAI,CACrD,EACJ;AACJ,CAAC;;AAGD,MAAa,0BAA0B,OAAO,GAAG,sBAAsB,CAAC,CAAC,WAAW,SAGjF;CACC,QAAQ,QAAQ,OAAO,uBAAuB,OAAO,EAAA,CAAG,SAAS,EAAA,CAAG;AACxE,CAAC"}
@@ -0,0 +1,13 @@
1
+ import { OntologyServerClient } from "./rpc.js";
2
+ import { OntologyServer } from "./routing.js";
3
+ import { Effect, Scope } from "effect";
4
+ //#region src/rpcLocal.d.ts
5
+ /** Connect to a borrowed server in the same JavaScript runtime. The connection
6
+ * owns its RPC requests and subscriptions; closing it never closes the server.
7
+ * Local routes use their trusted context binding, like worker routes.
8
+ */
9
+ export declare const makeOntologyLocalClient: <R>(server: OntologyServer<R>, options?: {
10
+ readonly ontology?: string;
11
+ } | undefined) => Effect.Effect<OntologyServerClient, never, R | Scope.Scope>;
12
+ //#endregion
13
+ //# sourceMappingURL=rpcLocal.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcLocal.d.ts","names":[],"sources":["../src/rpcLocal.ts"],"mappings":";;;;;;;;qBAYa,0BAAuE,GAAC,QAAA,eAAA,IAAA;WAEjD;kBAwBlC,OAAA,OAAA,6BAAA,IAAA,MAAA"}
@@ -0,0 +1,26 @@
1
+ import { OntologyRpcs, makeOntologyProtocolClient, makeTracedRpcClientNoSerialization } from "./rpc.js";
2
+ import { ontologyServerDispatch, selectOntology } from "./routing.js";
3
+ import { Effect } from "effect";
4
+ import { RpcServer } from "effect/rpc";
5
+ //#region src/rpcLocal.ts
6
+ /** Connect to a borrowed server in the same JavaScript runtime. The connection
7
+ * owns its RPC requests and subscriptions; closing it never closes the server.
8
+ * Local routes use their trusted context binding, like worker routes.
9
+ */
10
+ const makeOntologyLocalClient = Effect.fn("OntologyClient.local")(function* (server, options) {
11
+ let client;
12
+ const dispatch = yield* RpcServer.makeNoSerialization(OntologyRpcs, { onFromServer: (response) => client.write(response) }).pipe(Effect.provide(ontologyServerDispatch(server)));
13
+ client = yield* makeTracedRpcClientNoSerialization(OntologyRpcs, {
14
+ supportsAck: true,
15
+ onFromClient: ({ message }) => dispatch.write(0, message)
16
+ });
17
+ const rpc = client.client;
18
+ return { ontology: Effect.fn("OntologyClient.select")(function* (selected, clientOptions) {
19
+ const name = selected ?? options?.ontology;
20
+ return yield* makeOntologyProtocolClient(name === void 0 ? rpc : selectOntology(rpc, name), clientOptions);
21
+ }) };
22
+ });
23
+ //#endregion
24
+ export { makeOntologyLocalClient };
25
+
26
+ //# sourceMappingURL=rpcLocal.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcLocal.js","names":[],"sources":["../src/rpcLocal.ts"],"sourcesContent":["import { Effect } from \"effect\";\nimport { RpcGroup, RpcServer } from \"effect/rpc\";\nimport { ontologyServerDispatch, selectOntology } from \"./routing.js\";\nimport { makeOntologyProtocolClient, makeTracedRpcClientNoSerialization, OntologyRpcs } from \"./rpc.js\";\nimport type { OntologyServer } from \"./routing.js\";\nimport type { OntologyServerClient, OntologyClientOptions } from \"./rpc.js\";\nimport type { Scope } from \"effect\";\n\n/** Connect to a borrowed server in the same JavaScript runtime. The connection\n * owns its RPC requests and subscriptions; closing it never closes the server.\n * Local routes use their trusted context binding, like worker routes.\n */\nexport const makeOntologyLocalClient = Effect.fn(\"OntologyClient.local\")(function* <R>(\n server: OntologyServer<R>,\n options?: { readonly ontology?: string }\n): Effect.fn.Return<OntologyServerClient, never, R | Scope.Scope> {\n type Rpcs = RpcGroup.Rpcs<typeof OntologyRpcs>;\n let client!: Effect.Success<ReturnType<typeof makeTracedRpcClientNoSerialization<Rpcs, never>>>;\n const dispatch = yield* RpcServer.makeNoSerialization(OntologyRpcs, {\n onFromServer: (response) => client.write(response),\n }).pipe(Effect.provide(ontologyServerDispatch(server)));\n client = yield* makeTracedRpcClientNoSerialization(OntologyRpcs, {\n supportsAck: true,\n onFromClient: ({ message }) => dispatch.write(0, message),\n });\n const rpc = client.client;\n return {\n ontology: Effect.fn(\"OntologyClient.select\")(function* (\n selected?: string,\n clientOptions?: OntologyClientOptions\n ) {\n const name = selected ?? options?.ontology;\n return yield* makeOntologyProtocolClient(\n name === undefined ? rpc : selectOntology(rpc, name),\n clientOptions\n );\n }),\n };\n});\n"],"mappings":";;;;;;;;;AAYA,MAAa,0BAA0B,OAAO,GAAG,sBAAsB,CAAC,CAAC,WACrE,QACA,SAC8D;CAE9D,IAAI;CACJ,MAAM,WAAW,OAAO,UAAU,oBAAoB,cAAc,EAChE,eAAe,aAAa,OAAO,MAAM,QAAQ,EACrD,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,uBAAuB,MAAM,CAAC,CAAC;CACtD,SAAS,OAAO,mCAAmC,cAAc;EAC7D,aAAa;EACb,eAAe,EAAE,cAAc,SAAS,MAAM,GAAG,OAAO;CAC5D,CAAC;CACD,MAAM,MAAM,OAAO;CACnB,OAAO,EACH,UAAU,OAAO,GAAG,uBAAuB,CAAC,CAAC,WACzC,UACA,eACF;EACE,MAAM,OAAO,YAAY,SAAS;EAClC,OAAO,OAAO,2BACV,SAAS,KAAA,IAAY,MAAM,eAAe,KAAK,IAAI,GACnD,aACJ;CACJ,CAAC,EACL;AACJ,CAAC"}
@@ -0,0 +1,9 @@
1
+ import { BackendError } from "@party-stack/ontology-backend";
2
+ import { Effect, Scope, Stream } from "effect";
3
+ //#region src/rpcWatch.d.ts
4
+ /** Keep the same scoped RPC pull alive after its first readiness frame. Reading
5
+ * a head in a separate scope would close the upstream watch before the snapshot.
6
+ */
7
+ export declare const acquireRpcWatch: <A>(stream: Stream.Stream<A, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>, ready: A, operation: string) => Effect.Effect<Stream.Stream<A, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, never>, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, Scope.Scope>;
8
+ //#endregion
9
+ //# sourceMappingURL=rpcWatch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcWatch.d.ts","names":[],"sources":["../src/rpcWatch.ts"],"mappings":";;;;;;qBAMa,kBAA+C,GAAC,QAAA,OAAA,OAAA,GAAA,yWAAA,OAAA,GAAA,sBAAA,OAAA,OAAA,OAAA,OAAA,GAAA,yWAAA,iWAAA,MAAA"}
@@ -0,0 +1,29 @@
1
+ import { BackendError } from "@party-stack/ontology-backend";
2
+ import { Effect, Exit, Pull, Scope, Stream } from "effect";
3
+ //#region src/rpcWatch.ts
4
+ /** Keep the same scoped RPC pull alive after its first readiness frame. Reading
5
+ * a head in a separate scope would close the upstream watch before the snapshot.
6
+ */
7
+ const acquireRpcWatch = Effect.fnUntraced(function* (stream, ready, operation) {
8
+ const scope = yield* Scope.fork(yield* Effect.scope);
9
+ return yield* Scope.provide(Effect.gen(function* () {
10
+ const pull = yield* Stream.toPull(stream);
11
+ const first = yield* pull.pipe(Pull.catchDone(() => Effect.fail(new BackendError({
12
+ operation,
13
+ kind: "Unavailable",
14
+ retryable: true,
15
+ message: "The watch ended before its subscription was ready."
16
+ }))));
17
+ if (first[0] !== ready) return yield* new BackendError({
18
+ operation,
19
+ kind: "InvalidResponse",
20
+ retryable: false,
21
+ message: "The watch did not confirm its subscription."
22
+ });
23
+ return Stream.concat(Stream.fromIterable(first.slice(1)), Stream.fromPull(Effect.succeed(pull)));
24
+ }), scope).pipe(Effect.onExit((exit) => Exit.isFailure(exit) ? Scope.close(scope, exit) : Effect.void));
25
+ });
26
+ //#endregion
27
+ export { acquireRpcWatch };
28
+
29
+ //# sourceMappingURL=rpcWatch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpcWatch.js","names":[],"sources":["../src/rpcWatch.ts"],"sourcesContent":["import { BackendError } from \"@party-stack/ontology-backend\";\nimport { Effect, Exit, Pull, Scope, Stream } from \"effect\";\n\n/** Keep the same scoped RPC pull alive after its first readiness frame. Reading\n * a head in a separate scope would close the upstream watch before the snapshot.\n */\nexport const acquireRpcWatch = Effect.fnUntraced(function* <A>(\n stream: Stream.Stream<A, BackendError>,\n ready: A,\n operation: string\n) {\n const scope = yield* Scope.fork(yield* Effect.scope);\n return yield* Scope.provide(\n Effect.gen(function* () {\n const pull = yield* Stream.toPull(stream);\n const first = yield* pull.pipe(\n Pull.catchDone(() =>\n Effect.fail(\n new BackendError({\n operation,\n kind: \"Unavailable\",\n retryable: true,\n message: \"The watch ended before its subscription was ready.\",\n })\n )\n )\n );\n if (first[0] !== ready)\n return yield* new BackendError({\n operation,\n kind: \"InvalidResponse\",\n retryable: false,\n message: \"The watch did not confirm its subscription.\",\n });\n return Stream.concat(Stream.fromIterable(first.slice(1)), Stream.fromPull(Effect.succeed(pull)));\n }),\n scope\n ).pipe(Effect.onExit((exit) => (Exit.isFailure(exit) ? Scope.close(scope, exit) : Effect.void)));\n});\n"],"mappings":";;;;;;AAMA,MAAa,kBAAkB,OAAO,WAAW,WAC7C,QACA,OACA,WACF;CACE,MAAM,QAAQ,OAAO,MAAM,KAAK,OAAO,OAAO,KAAK;CACnD,OAAO,OAAO,MAAM,QAChB,OAAO,IAAI,aAAa;EACpB,MAAM,OAAO,OAAO,OAAO,OAAO,MAAM;EACxC,MAAM,QAAQ,OAAO,KAAK,KACtB,KAAK,gBACD,OAAO,KACH,IAAI,aAAa;GACb;GACA,MAAM;GACN,WAAW;GACX,SAAS;EACb,CAAC,CACL,CACJ,CACJ;EACA,IAAI,MAAM,OAAO,OACb,OAAO,OAAO,IAAI,aAAa;GAC3B;GACA,MAAM;GACN,WAAW;GACX,SAAS;EACb,CAAC;EACL,OAAO,OAAO,OAAO,OAAO,aAAa,MAAM,MAAM,CAAC,CAAC,GAAG,OAAO,SAAS,OAAO,QAAQ,IAAI,CAAC,CAAC;CACnG,CAAC,GACD,KACJ,CAAC,CAAC,KAAK,OAAO,QAAQ,SAAU,KAAK,UAAU,IAAI,IAAI,MAAM,MAAM,OAAO,IAAI,IAAI,OAAO,IAAK,CAAC;AACnG,CAAC"}