@party-stack/ontology-server 0.13.0 → 0.14.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.
@@ -1 +1 @@
1
- {"version":3,"file":"routing.js","names":[],"sources":["../src/routing.ts"],"sourcesContent":["import { BackendError, projectBackendError } from \"@party-stack/ontology-backend\";\nimport { CurrentExecutionContext } from \"@party-stack/ontology-backend/policy\";\nimport { replicaBackend } from \"@party-stack/ontology-replica/infrastructure\";\nimport { makeReplicaPartitionCatalog } from \"@party-stack/ontology-replica/registry\";\nimport { Runtimes } from \"@party-stack/runtime\";\nimport { Context, Effect, Equal, Exit, Hash, Layer, Option, RcMap, Schema, Scope, Stream } from \"effect\";\nimport { Rpc, RpcGroup, RpcSchema } from \"effect/rpc\";\nimport { prepareOntologyServer, bindOntologyServer } from \"./composition.js\";\nimport { errorProjectionLayer, errorContext, OntologyErrorProjection } from \"./errorProjection.js\";\nimport { upstreamReplicaRegistration } from \"./replicaBootstrap.js\";\nimport { OntologyRpcs, ontologyRpcHandlers } from \"./rpc.js\";\nimport type { OntologyAuthenticate, OntologyBindingOptions, OntologyInternalAccess } from \"./composition.js\";\nimport type { ErrorProjectionOptions } from \"./errorProjection.js\";\nimport type { UpstreamReplicaRegistration } from \"./replicaBootstrap.js\";\nimport type { OntologyRpcClient, OntologyRpcServerOptions } from \"./rpc.js\";\nimport type { PinRecord } from \"@party-stack/ontology-replica\";\nimport type { ReplicaRegistration, StoredReplicaPartition } from \"@party-stack/ontology-replica/registry\";\n\n/** Routing belongs to the transport envelope, not to individual ontology operations. */\nexport const ontologyHeader = \"x-party-stack-ontology\";\nconst ontologyParameter = \"ontology\";\nconst nameSchema = Schema.NonEmptyString.check(Schema.isMaxLength(4096));\nconst name = (value: unknown) =>\n Schema.decodeUnknownEffect(nameSchema)(value).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"ontology.route\",\n kind: \"InvalidRequest\",\n retryable: false,\n message: \"An ontology name is required.\",\n })\n )\n );\n\nexport interface OntologyResolver<T, R = never> {\n (ontology: string): Effect.Effect<T, BackendError, R | Scope.Scope>;\n}\n\n/** Select a target before Describe; the server may resolve that name dynamically. */\nexport function selectOntology(client: OntologyRpcClient, ontology: string): OntologyRpcClient {\n return 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 {\n ...settings,\n headers: { ...settings?.headers, [ontologyHeader]: ontology },\n },\n ]),\n ])\n ) as OntologyRpcClient;\n}\n\n/** URL selection also covers multipart uploads, not just RPC frames. */\nexport function ontologyUrl(url: string, ontology?: string): string {\n if (ontology === undefined) return url;\n const target = new URL(url);\n target.searchParams.set(ontologyParameter, ontology);\n return target.href;\n}\n\n/** Native acquisition owns sharing. Re-resolve on every request so a replacement\n * owner is visible even while an older endpoint still has subscribed readers.\n * Binding settings stay stable for one native owner's lifetime; command Effects\n * are deliberately not identities (resolvers commonly construct them per call).\n */\n/** A replica binding serves the definition, and syncs with the backend, its replica is open\n * under now. A replica that follows its definition reopens behind the same handle, so a new\n * definition gets its own endpoint while requests to the old one finish. */\nconst replicaGeneration = <R>(target: OntologyBindingOptions<R>): OntologyBindingOptions<R> => {\n if (target.kind !== \"replica\") return target;\n const ir = target.replica.ir;\n const backend = replicaBackend(target.replica) ?? target.backend;\n return ir === target.ir && backend === target.backend\n ? target\n : ({ ...target, ir, backend } as OntologyBindingOptions<R>);\n};\n\nclass EndpointKey<T extends OntologyBindingOptions<unknown>> implements Equal.Equal {\n readonly identity;\n constructor(\n readonly ontology: string,\n readonly options: T,\n readonly context: Record<string, unknown> | undefined\n ) {\n this.identity = [\n ontology,\n options.kind,\n options.backend,\n options.kind === \"replica\"\n ? options.replica\n : options.kind === \"cached-proxy\"\n ? options.cache\n : undefined,\n options.ir,\n JSON.stringify(context),\n options.authenticate,\n options.dangerouslyAllowInternalAccess,\n options.enableRealtime,\n options.upstreamErrors,\n options.deliveryStrategy,\n options.delivery,\n options.attachmentTransfers,\n options.traces,\n ];\n }\n [Hash.symbol]() {\n return Hash.array(this.identity);\n }\n [Equal.symbol](other: Equal.Equal) {\n return (\n other instanceof EndpointKey &&\n this.identity.every((value, index) => Equal.equals(value, other.identity[index]))\n );\n }\n}\n\n/** Supplied by HTTP bindings; worker routes use already authenticated contexts. */\nexport const OntologyTransportRequest = Context.Reference<Request | undefined>(\n \"@party-stack/ontology-server/TransportRequest\",\n { defaultValue: () => undefined }\n);\nexport const OntologyTransportTarget = Context.Reference<string | undefined>(\n \"@party-stack/ontology-server/TransportTarget\",\n { defaultValue: () => undefined }\n);\nexport const OntologyTransportBinding = Context.Reference<\n { readonly ontology: string; readonly bound: BoundOntology<unknown> } | undefined\n>(\"@party-stack/ontology-server/TransportBinding\", { defaultValue: () => undefined });\ntype Rpcs = RpcGroup.Rpcs<typeof OntologyRpcs>;\ninterface BoundOntology<R> {\n readonly options: OntologyRpcServerOptions<R>;\n readonly handlers: Context.Context<Rpc.ToHandler<Rpcs> | OntologyErrorProjection>;\n readonly executionContext: Record<string, unknown> | undefined;\n}\n\n/** A transport-neutral dispatcher. The surrounding Scope owns its endpoint bindings. */\nexport interface OntologyServer<R = never> extends ErrorProjectionOptions {\n readonly _tag: \"OntologyServer\";\n readonly defaultOntology?: string;\n readonly invalidate: (ontology: string) => Effect.Effect<void, BackendError>;\n readonly forget: (ontology: string) => Effect.Effect<void, BackendError>;\n readonly partitions: Effect.Effect<readonly StoredReplicaPartition[], BackendError>;\n /** Run a bounded native checkpoint through the route's existing replica owner. */\n /** Checkpoint one ontology. `revalidate` reloads demanded data even when a realtime\n * watch reports it current; use it for user-initiated refresh. Resolves to the\n * replica's named downloads, each with its readiness and error after the checkpoint. */\n readonly syncOnce: (\n ontology: string,\n options?: { readonly revalidate?: boolean }\n ) => Effect.Effect<{ readonly pins: readonly PinRecord[] }, BackendError, R>;\n readonly bind: (\n ontology: string,\n request?: Request\n ) => Effect.Effect<BoundOntology<R>, BackendError, R | Scope.Scope>;\n}\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n/**\n * A replica the server's partition catalog creates, stores and reopens: fed by a `backend`, or by\n * another party-stack server through `upstream`. The protocol source and saved bootstrap are\n * filled in by the server and are not part of a route.\n */\nexport type ManagedReplicaRoute<R = never> = DistributiveOmit<\n ReplicaRegistration | UpstreamReplicaRegistration,\n \"source\" | \"bootstrap\"\n> &\n Omit<\n OntologyRpcServerOptions<R>,\n \"source\" | \"replica\" | \"backend\" | \"authorize\" | \"context\" | \"ir\" | \"errors\"\n > & {\n readonly kind: \"replica\";\n readonly replica?: never;\n readonly dangerouslyAllowInternalAccess?: never;\n readonly authenticate?: never;\n };\n/** What a route's `open` returns. Access and authentication are settings of the route itself. */\nexport type OpenedOntologyRoute<R = never> =\n | (DistributiveOmit<OntologyBindingOptions<R>, \"dangerouslyAllowInternalAccess\" | \"authenticate\"> & {\n readonly dangerouslyAllowInternalAccess?: never;\n readonly authenticate?: never;\n })\n | ManagedReplicaRoute<R>;\n/** A route that needs no opening: a ready binding, or a managed replica registration. */\nexport type OntologyRoute<R = never> =\n | OntologyBindingOptions<R>\n | (DistributiveOmit<ManagedReplicaRoute<R>, \"dangerouslyAllowInternalAccess\"> & {\n readonly dangerouslyAllowInternalAccess: true;\n });\ntype SegmentParameter<Segment extends string> = Segment extends `:${infer Name}` | `*${infer Name}`\n ? Name\n : never;\ntype RouteParameter<Path extends string> = Path extends `${infer Head}/${infer Tail}`\n ? SegmentParameter<Head> | RouteParameter<Tail>\n : SegmentParameter<Path>;\nexport type OntologyRouteParams<Path extends string> = string extends Path\n ? Readonly<Record<string, string>>\n : Readonly<{ [Name in RouteParameter<Path>]: string }>;\n\n/**\n * A route whose backend is acquired on demand. For each request the server authenticates the\n * caller, opens the route (once per address, kept for `idleRetentionMs`), then binds.\n */\nexport interface OntologyRouteDeclaration<\n R = never,\n Path extends string = string,\n Opened extends OpenedOntologyRoute<R> = OpenedOntologyRoute<R>,\n> {\n /**\n * Allow internal commands (replica status, traces, outbox recovery, local-data deletion, owner\n * release) for every caller (`true`) or for callers whose context passes the predicate. A route\n * without an IR policy requires it, and then exposes raw backend capabilities and full error\n * messages. Replica routes require `true`.\n *\n * A caller allowed internal access also gets the original error when the route fails to open\n * (for example because its definition failed to load). A predicate can only allow that when\n * `authenticate` supplies the caller's context.\n */\n readonly dangerouslyAllowInternalAccess?: OntologyInternalAccess;\n /** Establish each request's context before the route opens. Without it, `open` supplies a fixed context. */\n readonly authenticate?: OntologyAuthenticate<R>;\n /** Acquire the route's backend and binding. */\n readonly open:\n | Effect.Effect<Opened, BackendError, R | Scope.Scope>\n | ((params: OntologyRouteParams<Path>) => Effect.Effect<Opened, BackendError, R | Scope.Scope>);\n}\nexport type OntologyRouteFactory<\n R = never,\n Path extends string = string,\n Opened extends OpenedOntologyRoute<R> = OpenedOntologyRoute<R>,\n> =\n | OntologyBindingOptions<R>\n | (ManagedReplicaRoute<R> extends Opened ? OntologyRoute<R> : never)\n | OntologyRouteDeclaration<R, Path, Opened>;\nexport interface OntologyServerRoutes<\n R = never,\n Paths extends string = string,\n Opened extends OpenedOntologyRoute<R> = OpenedOntologyRoute<R>,\n> extends Omit<ErrorProjectionOptions, \"errors\"> {\n /** Opt into client watches and replication sessions. Individual routes may override this default. */\n readonly enableRealtime?: boolean;\n readonly routes?: { readonly [Path in Paths]: OntologyRouteFactory<R, Path, Opened> };\n /** Advanced resolution for addresses outside the declared route table. */\n readonly resolve?: OntologyResolver<OntologyBindingOptions<R>, R>;\n /** Keep an opened route for this long after its last request. Default 60 seconds; zero\n * releases it immediately. A route that fails to open is not kept, so the next request\n * opens it again.\n */\n readonly idleRetentionMs?: number;\n /** Optional storage namespacing. Managed replica routes acquire their catalog automatically. */\n readonly replicas?: { readonly scope?: string };\n}\n\nexport type OntologyServerOptions<R = never> = OntologyServerRoutes<R> | OntologyBindingOptions<R>;\n\nconst normalizePath = (path: string) => path.replace(/^\\/+|\\/+$/g, \"\");\nconst compileRoutes = <R>(routes: Readonly<Record<string, OntologyRouteFactory<R>>>) => {\n const exact = new Map<string, { factory: OntologyRouteFactory<R>; pattern: string }>();\n const patterns: {\n regex: RegExp;\n names: string[];\n factory: OntologyRouteFactory<R>;\n pattern: string;\n score: number;\n }[] = [];\n const shapes = new Set<string>();\n for (const [raw, factory] of Object.entries(routes)) {\n const pattern = normalizePath(raw);\n const names: string[] = [];\n const segments = pattern.split(\"/\");\n const regex = segments\n .map((segment, index) => {\n if (segment.startsWith(\":\") || segment.startsWith(\"*\")) {\n const name = segment.slice(1);\n if (\n !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||\n names.includes(name) ||\n (segment.startsWith(\"*\") && index !== segments.length - 1)\n )\n throw new TypeError(\"Invalid ontology route parameter.\");\n names.push(name);\n return segment.startsWith(\"*\") ? \"(.+)\" : \"([^/]+)\";\n }\n return segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n })\n .join(\"/\");\n if (!names.length) {\n if (exact.has(pattern)) throw new TypeError(\"Duplicate ontology route.\");\n exact.set(pattern, { factory, pattern });\n } else {\n if (shapes.has(regex)) throw new TypeError(\"Ambiguous ontology routes.\");\n shapes.add(regex);\n patterns.push({\n regex: new RegExp(`^${regex}$`),\n names,\n factory,\n pattern,\n score: segments.filter((part) => !part.startsWith(\":\") && !part.startsWith(\"*\")).length,\n });\n }\n }\n patterns.sort((a, b) => b.score - a.score || b.pattern.length - a.pattern.length);\n return { exact, patterns };\n};\n\nconst isRouteDeclaration = <R>(factory: OntologyRouteFactory<R>): factory is OntologyRouteDeclaration<R> =>\n \"open\" in factory;\n\nconst allowsInternalAccess = (\n access: OntologyInternalAccess | undefined,\n context: Record<string, unknown> | undefined\n) => {\n if (access === true) return true;\n if (typeof access !== \"function\" || context === undefined) return false;\n try {\n return access(context) === true;\n } catch {\n return false;\n }\n};\n\nconst constructServer = Effect.fn(\"OntologyServer.make\")(function* <R = never>(\n options: OntologyServerRoutes<R> | OntologyBindingOptions<R>\n) {\n const single = \"kind\" in options;\n const settings: OntologyServerRoutes<R> = single ? {} : options;\n // Startup failures a route chose to show its caller in full; every other failure\n // before a route is bound gets the generic projection.\n const forwardedStartupErrors = new WeakSet<BackendError>();\n const ttl = settings.idleRetentionMs ?? 60_000;\n if (\n !Number.isFinite(ttl) ||\n ttl < 0 ||\n (settings.replicas?.scope !== undefined && !Schema.is(Schema.NonEmptyString)(settings.replicas.scope))\n )\n return yield* new BackendError({\n operation: \"server.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Server replica scope and idle retention are invalid.\",\n });\n const compiled = yield* Effect.try({\n try: () => compileRoutes(settings.routes ?? {}),\n catch: (cause) =>\n new BackendError({\n operation: \"server.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Invalid ontology routes.\",\n cause,\n }),\n });\n const serverScope = yield* Effect.scope;\n const runtimes = yield* Effect.serviceOption(Runtimes);\n // Capture storage at server construction, but only open the inventory when\n // a managed route or an inventory operation needs it. Route declarations,\n // not the presence of an options object, determine the service requirement.\n const getCatalog = yield* Effect.cached(\n Scope.provide(\n Option.isSome(runtimes)\n ? makeReplicaPartitionCatalog(settings.replicas?.scope).pipe(\n Effect.provideService(Runtimes, runtimes.value)\n )\n : Effect.fail(\n new BackendError({\n operation: \"server.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Managed replica routes require Runtimes.\",\n })\n ),\n serverScope\n )\n );\n // Role composition is shared across authenticated bindings. Cache invalidation\n // belongs to the cache owner, rather than to an individual caller.\n const roles = yield* RcMap.make({\n lookup: (key: EndpointKey<OntologyBindingOptions<R>>) => prepareOntologyServer(key.options),\n });\n const endpoints = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (key: EndpointKey<OntologyBindingOptions<R>>) {\n const role = yield* RcMap.get(roles, new EndpointKey(key.ontology, key.options, undefined));\n const prepared = {\n ...role,\n ...key.options,\n enableRealtime: key.options.enableRealtime ?? settings.enableRealtime ?? false,\n backend: role.backend,\n source: role.source,\n ir: key.options.ir ?? role.ir,\n };\n const configured = yield* bindOntologyServer(\n prepared,\n key.context,\n key.options.dangerouslyAllowInternalAccess\n );\n return {\n options: configured,\n handlers: yield* Layer.buildWithScope(ontologyRpcHandlers(configured), yield* Effect.scope),\n executionContext:\n prepared.kind === \"owned\" && prepared.ir?.context?.type ? configured.context : undefined,\n };\n }),\n });\n const matched = (target: string) =>\n Effect.try({\n try: () => {\n const path = normalizePath(target);\n const staticRoute = compiled.exact.get(path);\n if (staticRoute)\n return { key: path, factory: staticRoute.factory, params: {} as Record<string, string> };\n for (const route of compiled.patterns) {\n const match = route.regex.exec(path);\n if (!match) continue;\n const params = Object.fromEntries(\n route.names.map((key, index) => [key, decodeURIComponent(match[index + 1]!)])\n );\n const key = route.pattern\n .split(\"/\")\n .map((part) =>\n part.startsWith(\":\") || part.startsWith(\"*\")\n ? encodeURIComponent(params[part.slice(1)]!)\n : part\n )\n .join(\"/\");\n return { key, factory: route.factory, params };\n }\n },\n catch: (cause) =>\n new BackendError({\n operation: \"ontology.route\",\n kind: \"InvalidRequest\",\n retryable: false,\n message: \"Invalid ontology address.\",\n cause,\n }),\n });\n const openRoute = Effect.fn(\"OntologyServer.openRoute\")(function* (target: string) {\n const route = yield* matched(target);\n if (!route)\n return yield* new BackendError({\n operation: \"ontology.route\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Unknown ontology.\",\n });\n const factory = route.factory;\n const declaration = (\n !isRouteDeclaration(factory)\n ? factory\n : typeof factory.open === \"function\"\n ? yield* factory.open(route.params)\n : yield* factory.open\n ) as OntologyRoute<R>;\n const access = factory.dangerouslyAllowInternalAccess;\n const settings = { dangerouslyAllowInternalAccess: access, authenticate: factory.authenticate };\n if (declaration.kind === \"replica\" && access !== true)\n return yield* new BackendError({\n operation: \"server.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Replica routes require dangerouslyAllowInternalAccess: true.\",\n });\n let binding: OntologyBindingOptions<R>;\n if (declaration.kind === \"replica\" && !declaration.replica) {\n // The catalog opens the replica once; it follows its definition by reopening behind\n // the same handle, and binds pick up the definition it is open under.\n const catalog = yield* getCatalog;\n const registration =\n \"upstream\" in declaration\n ? yield* upstreamReplicaRegistration(route.key, declaration, catalog)\n : (declaration as ReplicaRegistration);\n const resource = yield* catalog.open(route.key, registration);\n binding = {\n ...declaration,\n ...settings,\n ir: resource.ir,\n replica: resource.replica,\n backend: resource.backend,\n traces: resource.traces,\n deleteLocalData: forget(route.key),\n } as unknown as OntologyBindingOptions<R>;\n } else binding = { ...declaration, ...settings } as OntologyBindingOptions<R>;\n if (!binding.authenticate) {\n const context = binding.kind === \"replica\" ? binding.replica.context : binding.context;\n const bound = yield* RcMap.get(endpoints, new EndpointKey(route.key, binding, context));\n // A fixed route owns its handler resources, including chunk-transfer\n // registries, for the same lifetime as its backend.\n binding = { ...binding, context: bound.options.context } as OntologyBindingOptions<R>;\n }\n return binding;\n });\n // An opened route stays warm for `idleRetentionMs` after its last request. RcMap keeps a\n // failed lookup the same way, so every retry would get the cached failure and restart its\n // idle timer. Drop a failed open instead; the attempt number keeps a late failure from\n // removing a newer open of the same route.\n let openAttempts = 0;\n const latestOpen = new Map<string, number>();\n const resources = yield* RcMap.make({\n idleTimeToLive: ttl,\n lookup: (target: string): ReturnType<typeof openRoute> =>\n Effect.suspend(() => {\n const attempt = ++openAttempts;\n latestOpen.set(target, attempt);\n return openRoute(target).pipe(\n Effect.onExit((exit) =>\n Effect.suspend(() => {\n if (latestOpen.get(target) !== attempt) return Effect.void;\n latestOpen.delete(target);\n // RcMap already drops an interrupted lookup.\n return Exit.isFailure(exit) && !Exit.hasInterrupts(exit)\n ? RcMap.invalidate(resources, target)\n : Effect.void;\n })\n )\n );\n }),\n });\n const retire = (key: string): Effect.Effect<void> => RcMap.invalidate(resources, key);\n const invalidate = (target: string): Effect.Effect<void, BackendError> =>\n Effect.flatMap(matched(target), (route) => retire(route?.key ?? normalizePath(target)));\n const forget = (target: string): Effect.Effect<void, BackendError> =>\n Effect.gen(function* () {\n const route = yield* matched(target);\n const key = route?.key ?? normalizePath(target);\n if (Option.isSome(runtimes)) {\n const catalog = yield* getCatalog;\n yield* catalog.forget(key);\n }\n yield* RcMap.invalidate(resources, key);\n });\n const authenticateRequest = (authenticate: OntologyAuthenticate<R>, request: Request | undefined) =>\n Effect.gen(function* () {\n if (!request)\n return yield* new BackendError({\n operation: \"ontology.authenticate\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"This ontology requires an HTTP authentication binding.\",\n });\n const context = yield* authenticate(request);\n yield* Schema.decodeUnknownEffect(Schema.Record(Schema.String, Schema.Unknown))(context).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"ontology.authenticate\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Authentication must return an ontology context.\",\n })\n )\n );\n return context;\n });\n const bind = Effect.fn(\"OntologyServer.bind\")(function* (ontology: string, request?: Request) {\n if (!single) yield* name(ontology);\n const route = single ? undefined : yield* matched(ontology);\n if (route) {\n // Authenticate before opening, so an unauthenticated request never opens a route\n // and an open failure can be shown in full to a caller allowed internal access.\n const { authenticate, dangerouslyAllowInternalAccess: access } = route.factory;\n const caller = authenticate ? yield* authenticateRequest(authenticate, request) : undefined;\n const opened = yield* RcMap.get(resources, route.key).pipe(\n Effect.tapError((error) =>\n Effect.sync(() => {\n if (allowsInternalAccess(access, caller)) forwardedStartupErrors.add(error);\n })\n )\n );\n const target = replicaGeneration(opened);\n const context = caller ?? (target.kind === \"replica\" ? target.replica.context : target.context);\n return yield* RcMap.get(endpoints, new EndpointKey(ontology, target, context));\n }\n const resolved = single\n ? (options as OntologyBindingOptions<R>)\n : settings.resolve\n ? yield* settings.resolve(ontology)\n : yield* Effect.fail(\n new BackendError({\n operation: \"ontology.route\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Unknown ontology.\",\n })\n );\n const target = replicaGeneration(resolved);\n const context = target.authenticate\n ? yield* authenticateRequest(target.authenticate, request)\n : target.kind === \"replica\"\n ? target.replica.context\n : target.context;\n return yield* RcMap.get(endpoints, new EndpointKey(ontology, target, context));\n });\n const server: OntologyServer<R> = {\n _tag: \"OntologyServer\",\n defaultOntology: single ? \"\" : undefined,\n bind,\n invalidate,\n forget,\n partitions: Option.isSome(runtimes)\n ? Effect.flatMap(getCatalog, (catalog) => catalog.partitions)\n : Effect.succeed([]),\n syncOnce: (ontology, settings) =>\n Effect.scoped(\n Effect.gen(function* () {\n const bound: OntologyRpcServerOptions<R> = (yield* bind(ontology)).options;\n if (!bound.replica)\n return yield* new BackendError({\n operation: \"server.syncOnce\",\n kind: \"InvalidRequest\",\n retryable: false,\n message: \"Only replica routes support native synchronization checkpoints.\",\n });\n yield* settings?.revalidate ? bound.replica.revalidate : bound.replica.syncOnce;\n return { pins: yield* bound.replica.demand.pins.list };\n })\n ),\n // Failures before a route is bound: its IR policy is not known yet.\n errors: (error) =>\n forwardedStartupErrors.has(error) ? error : projectBackendError(error, \"projected\"),\n ir: settings.ir,\n upstreamErrors: settings.upstreamErrors,\n };\n // Preserve eager configuration validation for the single-ontology shorthand.\n if (\"kind\" in options && !options.authenticate) {\n const bound = yield* bind(\"\");\n // Configuration is a binding, not a live reference to mutable app state.\n options = { ...options, context: bound.options.context } as OntologyBindingOptions<R>;\n }\n return server;\n});\n\nexport interface MakeOntologyServer {\n <R = never, const Paths extends string = string>(\n options:\n | OntologyServerRoutes<R, Paths, Exclude<OpenedOntologyRoute<R>, ManagedReplicaRoute<R>>>\n | OntologyBindingOptions<R>\n ): Effect.Effect<OntologyServer<Exclude<R, Scope.Scope>>, BackendError, R | Scope.Scope>;\n <R = never, const Paths extends string = string>(\n options: OntologyServerRoutes<R, Paths>\n ): Effect.Effect<OntologyServer<Exclude<R, Scope.Scope>>, BackendError, R | Runtimes | Scope.Scope>;\n}\nexport const makeOntologyServer: MakeOntologyServer = constructServer as MakeOntologyServer;\n\n/** One RPC server dispatches all targets, including calls in the same HTTP batch. */\nexport const ontologyServerDispatch = <R = never>(router: OntologyServer<R>) => {\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 ontology =\n request.headers[ontologyHeader] ?? (yield* OntologyTransportTarget) ?? \"\";\n const existing = yield* OntologyTransportBinding;\n const bound =\n existing?.ontology === ontology\n ? (existing.bound as BoundOntology<R>)\n : yield* router.bind(ontology, yield* OntologyTransportRequest);\n const handler = yield* OntologyRpcs.accessHandler(tag as Rpcs[\"_tag\"]).pipe(\n Effect.provideContext(bound.handlers)\n );\n const result = handler(payload, request) as\n | Effect.Effect<unknown, BackendError, R>\n | Stream.Stream<unknown, BackendError, R>;\n const action = payload as { name?: string; invocation?: { name?: string } } | undefined;\n const project = (error: BackendError) =>\n projectBackendError(\n error,\n bound.options.errors,\n errorContext(bound.options, action?.name ?? action?.invocation?.name)\n );\n return RpcSchema.isStreamSchema(rpc.successSchema)\n ? (result as Stream.Stream<unknown, BackendError, R>).pipe(\n Stream.mapError(project),\n Stream.provideService(CurrentExecutionContext, bound.executionContext)\n )\n : (result as Effect.Effect<unknown, BackendError, R>).pipe(\n Effect.mapError(project),\n Effect.provideService(CurrentExecutionContext, bound.executionContext)\n );\n }).pipe(Effect.mapError((error) => projectBackendError(error, router.errors)));\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((result) => result as Stream.Stream<unknown, BackendError, R>)\n )\n )\n : (payload: never, request: Parameters<Handler>[1]) =>\n Effect.scoped(\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 })\n ) as unknown as {\n readonly [Procedure in Rpcs as Procedure[\"_tag\"]]: Rpc.ToHandlerFn<Procedure, R | Scope.Scope>;\n };\n // Errors have already been projected for the selected ontology. Keep the\n // outer middleware for defect conversion without projecting them a second time.\n return Layer.merge(OntologyRpcs.toLayer(handlers), errorProjectionLayer({ errors: \"forward\" }));\n};\n"],"mappings":";;;;;;;;;;;;;AAmBA,MAAa,iBAAiB;AAC9B,MAAM,oBAAoB;AAC1B,MAAM,aAAa,OAAO,eAAe,MAAM,OAAO,YAAY,IAAI,CAAC;AACvE,MAAM,QAAQ,UACV,OAAO,oBAAoB,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,KAC1C,OAAO,eAEC,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,SAAS;AACb,CAAC,CACT,CACJ;;AAOJ,SAAgB,eAAe,QAA2B,UAAqC;CAC3F,OAAO,OAAO,YACV,CAAC,GAAG,aAAa,SAAS,KAAK,CAAC,CAAC,CAAC,KAAK,QAAQ,CAC3C,MACC,SAAkB,aACf,QAAQ,MAAM,QAAQ,IAAI,QAAQ,GAAG,GAAG,QAAQ,CAC5C,SACA;EACI,GAAG;EACH,SAAS;GAAE,GAAG,UAAU;IAAU,iBAAiB;EAAS;CAChE,CACJ,CAAC,CACT,CAAC,CACL;AACJ;;AAGA,SAAgB,YAAY,KAAa,UAA2B;CAChE,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,MAAM,SAAS,IAAI,IAAI,GAAG;CAC1B,OAAO,aAAa,IAAI,mBAAmB,QAAQ;CACnD,OAAO,OAAO;AAClB;;;;;;;;;AAUA,MAAM,qBAAwB,WAAiE;CAC3F,IAAI,OAAO,SAAS,WAAW,OAAO;CACtC,MAAM,KAAK,OAAO,QAAQ;CAC1B,MAAM,UAAU,eAAe,OAAO,OAAO,KAAK,OAAO;CACzD,OAAO,OAAO,OAAO,MAAM,YAAY,OAAO,UACxC,SACC;EAAE,GAAG;EAAQ;EAAI;CAAQ;AACpC;AA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AChD,OAAO,SAAS,OAAO,GACvB,OAAO,eAAe,yBAAyB,MAAM,gBAAgB,CACzE;EACV,CAAC,CAAC,CAAC,KAAK,OAAO,UAAU,UAAU,oBAAoB,OAAO,OAAO,MAAM,CAAC,CAAC;EACjF,OAAO,CACH,KACA,UAAU,eAAe,IAAI,aAAa,KACnC,SAAgB,YACb,OAAO,OACH,OAAO,SAAS,OAAO,CAAC,CAAC,KACrB,OAAO,KAAK,WAAW,MAAiD,CAC5E,CACJ,KACH,SAAgB,YACb,OAAO,OACH,OAAO,QACH,OAAO,SAAS,OAAO,CAAC,CAAC,KACrB,OAAO,KACF,WAAW,MAChB,CACJ,CACJ,CACJ,CACd;CACJ,CAAC,CACL;CAKA,OAAO,MAAM,MAAM,aAAa,QAAQ,QAAQ,GAAG,qBAAqB,EAAE,QAAQ,UAAU,CAAC,CAAC;AAClG"}
1
+ {"version":3,"file":"routing.js","names":[],"sources":["../src/routing.ts"],"sourcesContent":["import { BackendError, projectBackendError } from \"@party-stack/ontology-backend\";\nimport { CurrentExecutionContext } from \"@party-stack/ontology-backend/policy\";\nimport { replicaBackend } from \"@party-stack/ontology-replica/infrastructure\";\nimport { makeReplicaPartitionCatalog } from \"@party-stack/ontology-replica/registry\";\nimport { Table } from \"@party-stack/ontology-storage/tables\";\nimport { Runtimes } from \"@party-stack/runtime\";\nimport { Context, Effect, Equal, Exit, Hash, Layer, Option, RcMap, Schema, Scope, Stream } from \"effect\";\nimport { Rpc, RpcGroup, RpcSchema } from \"effect/rpc\";\nimport { prepareOntologyServer, bindOntologyServer } from \"./composition.js\";\nimport { errorProjectionLayer, errorContext, OntologyErrorProjection } from \"./errorProjection.js\";\nimport { upstreamReplicaRegistration } from \"./replicaBootstrap.js\";\nimport { OntologyRpcs, ontologyRpcHandlers } from \"./rpc.js\";\nimport type { OntologyAuthenticate, OntologyBindingOptions, OntologyInternalAccess } from \"./composition.js\";\nimport type { ErrorProjectionOptions } from \"./errorProjection.js\";\nimport type { UpstreamReplicaRegistration } from \"./replicaBootstrap.js\";\nimport type { OntologyRpcClient, OntologyRpcServerOptions } from \"./rpc.js\";\nimport type { PinRecord } from \"@party-stack/ontology-replica\";\nimport type { ReplicaRegistration, StoredReplicaPartition } from \"@party-stack/ontology-replica/registry\";\n\n/** Routing belongs to the transport envelope, not to individual ontology operations. */\nexport const ontologyHeader = \"x-party-stack-ontology\";\nconst ontologyParameter = \"ontology\";\nconst nameSchema = Schema.NonEmptyString.check(Schema.isMaxLength(4096));\nconst name = (value: unknown) =>\n Schema.decodeUnknownEffect(nameSchema)(value).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"ontology.route\",\n kind: \"InvalidRequest\",\n retryable: false,\n message: \"An ontology name is required.\",\n })\n )\n );\n\nexport interface OntologyResolver<T, R = never> {\n (ontology: string): Effect.Effect<T, BackendError, R | Scope.Scope>;\n}\n\n/** Select a target before Describe; the server may resolve that name dynamically. */\nexport function selectOntology(client: OntologyRpcClient, ontology: string): OntologyRpcClient {\n return 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 {\n ...settings,\n headers: { ...settings?.headers, [ontologyHeader]: ontology },\n },\n ]),\n ])\n ) as OntologyRpcClient;\n}\n\n/** URL selection also covers multipart uploads, not just RPC frames. */\nexport function ontologyUrl(url: string, ontology?: string): string {\n if (ontology === undefined) return url;\n const target = new URL(url);\n target.searchParams.set(ontologyParameter, ontology);\n return target.href;\n}\n\n/** Native acquisition owns sharing. Re-resolve on every request so a replacement\n * owner is visible even while an older endpoint still has subscribed readers.\n * Binding settings stay stable for one native owner's lifetime; command Effects\n * are deliberately not identities (resolvers commonly construct them per call).\n */\n/** A replica binding serves the definition, and syncs with the backend, its replica is open\n * under now. A replica that follows its definition reopens behind the same handle, so a new\n * definition gets its own endpoint while requests to the old one finish. */\nconst replicaGeneration = <R>(target: OntologyBindingOptions<R>): OntologyBindingOptions<R> => {\n if (target.kind !== \"replica\") return target;\n const ir = target.replica.ir;\n const backend = replicaBackend(target.replica) ?? target.backend;\n return ir === target.ir && backend === target.backend\n ? target\n : ({ ...target, ir, backend } as OntologyBindingOptions<R>);\n};\n\nconst contextIdentity = Table.make<unknown>({ name: \"endpoint-context\" });\n\nclass EndpointKey<T extends OntologyBindingOptions<unknown>> implements Equal.Equal {\n readonly identity;\n constructor(\n readonly ontology: string,\n readonly options: T,\n readonly context: Record<string, unknown> | undefined\n ) {\n this.identity = [\n ontology,\n options.kind,\n options.backend,\n options.kind === \"replica\"\n ? options.replica\n : options.kind === \"cached-proxy\"\n ? options.cache\n : undefined,\n options.ir,\n // Through the value codec, so contexts that differ only in a date, map, set or\n // undefined field never share an endpoint.\n context === undefined ? undefined : contextIdentity.encode(context),\n options.authenticate,\n options.dangerouslyAllowInternalAccess,\n options.enableRealtime,\n options.upstreamErrors,\n options.deliveryStrategy,\n options.delivery,\n options.attachmentTransfers,\n options.traces,\n ];\n }\n [Hash.symbol]() {\n return Hash.array(this.identity);\n }\n [Equal.symbol](other: Equal.Equal) {\n return (\n other instanceof EndpointKey &&\n this.identity.every((value, index) => Equal.equals(value, other.identity[index]))\n );\n }\n}\n\n/** Supplied by HTTP bindings; worker routes use already authenticated contexts. */\nexport const OntologyTransportRequest = Context.Reference<Request | undefined>(\n \"@party-stack/ontology-server/TransportRequest\",\n { defaultValue: () => undefined }\n);\nexport const OntologyTransportTarget = Context.Reference<string | undefined>(\n \"@party-stack/ontology-server/TransportTarget\",\n { defaultValue: () => undefined }\n);\nexport const OntologyTransportBinding = Context.Reference<\n { readonly ontology: string; readonly bound: BoundOntology<unknown> } | undefined\n>(\"@party-stack/ontology-server/TransportBinding\", { defaultValue: () => undefined });\ntype Rpcs = RpcGroup.Rpcs<typeof OntologyRpcs>;\ninterface BoundOntology<R> {\n readonly options: OntologyRpcServerOptions<R>;\n readonly handlers: Context.Context<Rpc.ToHandler<Rpcs> | OntologyErrorProjection>;\n readonly executionContext: Record<string, unknown> | undefined;\n}\n\n/** A transport-neutral dispatcher. The surrounding Scope owns its endpoint bindings. */\nexport interface OntologyServer<R = never> extends ErrorProjectionOptions {\n readonly _tag: \"OntologyServer\";\n readonly defaultOntology?: string;\n readonly invalidate: (ontology: string) => Effect.Effect<void, BackendError>;\n readonly forget: (ontology: string) => Effect.Effect<void, BackendError>;\n readonly partitions: Effect.Effect<readonly StoredReplicaPartition[], BackendError>;\n /** Run a bounded native checkpoint through the route's existing replica owner. */\n /** Checkpoint one ontology. `revalidate` reloads demanded data even when a realtime\n * watch reports it current; use it for user-initiated refresh. Resolves to the\n * replica's named downloads, each with its readiness and error after the checkpoint. */\n readonly syncOnce: (\n ontology: string,\n options?: { readonly revalidate?: boolean }\n ) => Effect.Effect<{ readonly pins: readonly PinRecord[] }, BackendError, R>;\n readonly bind: (\n ontology: string,\n request?: Request\n ) => Effect.Effect<BoundOntology<R>, BackendError, R | Scope.Scope>;\n}\n\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;\n/**\n * A replica the server's partition catalog creates, stores and reopens: fed by a `backend`, or by\n * another party-stack server through `upstream`. The protocol source and saved bootstrap are\n * filled in by the server and are not part of a route.\n */\nexport type ManagedReplicaRoute<R = never> = DistributiveOmit<\n ReplicaRegistration | UpstreamReplicaRegistration,\n \"source\" | \"bootstrap\"\n> &\n Omit<\n OntologyRpcServerOptions<R>,\n \"source\" | \"replica\" | \"backend\" | \"authorize\" | \"context\" | \"ir\" | \"errors\"\n > & {\n readonly kind: \"replica\";\n readonly replica?: never;\n readonly dangerouslyAllowInternalAccess?: never;\n readonly authenticate?: never;\n };\n/** What a route's `open` returns. Access and authentication are settings of the route itself. */\nexport type OpenedOntologyRoute<R = never> =\n | (DistributiveOmit<OntologyBindingOptions<R>, \"dangerouslyAllowInternalAccess\" | \"authenticate\"> & {\n readonly dangerouslyAllowInternalAccess?: never;\n readonly authenticate?: never;\n })\n | ManagedReplicaRoute<R>;\n/** A route that needs no opening: a ready binding, or a managed replica registration. */\nexport type OntologyRoute<R = never> =\n | OntologyBindingOptions<R>\n | (DistributiveOmit<ManagedReplicaRoute<R>, \"dangerouslyAllowInternalAccess\"> & {\n readonly dangerouslyAllowInternalAccess: true;\n });\ntype SegmentParameter<Segment extends string> = Segment extends `:${infer Name}` | `*${infer Name}`\n ? Name\n : never;\ntype RouteParameter<Path extends string> = Path extends `${infer Head}/${infer Tail}`\n ? SegmentParameter<Head> | RouteParameter<Tail>\n : SegmentParameter<Path>;\nexport type OntologyRouteParams<Path extends string> = string extends Path\n ? Readonly<Record<string, string>>\n : Readonly<{ [Name in RouteParameter<Path>]: string }>;\n\n/**\n * A route whose backend is acquired on demand. For each request the server authenticates the\n * caller, opens the route (once per address, kept for `idleRetentionMs`), then binds.\n */\nexport interface OntologyRouteDeclaration<\n R = never,\n Path extends string = string,\n Opened extends OpenedOntologyRoute<R> = OpenedOntologyRoute<R>,\n> {\n /**\n * Allow internal commands (replica status, traces, outbox recovery, local-data deletion, owner\n * release) for every caller (`true`) or for callers whose context passes the predicate. A route\n * without an IR policy requires it, and then exposes raw backend capabilities and full error\n * messages. Replica routes require `true`.\n *\n * A caller allowed internal access also gets the original error when the route fails to open\n * (for example because its definition failed to load). A predicate can only allow that when\n * `authenticate` supplies the caller's context.\n */\n readonly dangerouslyAllowInternalAccess?: OntologyInternalAccess;\n /** Establish each request's context before the route opens. Without it, `open` supplies a fixed context. */\n readonly authenticate?: OntologyAuthenticate<R>;\n /** Acquire the route's backend and binding. */\n readonly open:\n | Effect.Effect<Opened, BackendError, R | Scope.Scope>\n | ((params: OntologyRouteParams<Path>) => Effect.Effect<Opened, BackendError, R | Scope.Scope>);\n}\nexport type OntologyRouteFactory<\n R = never,\n Path extends string = string,\n Opened extends OpenedOntologyRoute<R> = OpenedOntologyRoute<R>,\n> =\n | OntologyBindingOptions<R>\n | (ManagedReplicaRoute<R> extends Opened ? OntologyRoute<R> : never)\n | OntologyRouteDeclaration<R, Path, Opened>;\nexport interface OntologyServerRoutes<\n R = never,\n Paths extends string = string,\n Opened extends OpenedOntologyRoute<R> = OpenedOntologyRoute<R>,\n> extends Omit<ErrorProjectionOptions, \"errors\"> {\n /** Opt into client watches and replication sessions. Individual routes may override this default. */\n readonly enableRealtime?: boolean;\n readonly routes?: { readonly [Path in Paths]: OntologyRouteFactory<R, Path, Opened> };\n /** Advanced resolution for addresses outside the declared route table. */\n readonly resolve?: OntologyResolver<OntologyBindingOptions<R>, R>;\n /** Keep an opened route for this long after its last request. Default 60 seconds; zero\n * releases it immediately. A route that fails to open is not kept, so the next request\n * opens it again.\n */\n readonly idleRetentionMs?: number;\n /** Optional storage namespacing. Managed replica routes acquire their catalog automatically. */\n readonly replicas?: { readonly scope?: string };\n}\n\nexport type OntologyServerOptions<R = never> = OntologyServerRoutes<R> | OntologyBindingOptions<R>;\n\nconst normalizePath = (path: string) => path.replace(/^\\/+|\\/+$/g, \"\");\nconst compileRoutes = <R>(routes: Readonly<Record<string, OntologyRouteFactory<R>>>) => {\n const exact = new Map<string, { factory: OntologyRouteFactory<R>; pattern: string }>();\n const patterns: {\n regex: RegExp;\n names: string[];\n factory: OntologyRouteFactory<R>;\n pattern: string;\n score: number;\n }[] = [];\n const shapes = new Set<string>();\n for (const [raw, factory] of Object.entries(routes)) {\n const pattern = normalizePath(raw);\n const names: string[] = [];\n const segments = pattern.split(\"/\");\n const regex = segments\n .map((segment, index) => {\n if (segment.startsWith(\":\") || segment.startsWith(\"*\")) {\n const name = segment.slice(1);\n if (\n !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) ||\n names.includes(name) ||\n (segment.startsWith(\"*\") && index !== segments.length - 1)\n )\n throw new TypeError(\"Invalid ontology route parameter.\");\n names.push(name);\n return segment.startsWith(\"*\") ? \"(.+)\" : \"([^/]+)\";\n }\n return segment.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n })\n .join(\"/\");\n if (!names.length) {\n if (exact.has(pattern)) throw new TypeError(\"Duplicate ontology route.\");\n exact.set(pattern, { factory, pattern });\n } else {\n if (shapes.has(regex)) throw new TypeError(\"Ambiguous ontology routes.\");\n shapes.add(regex);\n patterns.push({\n regex: new RegExp(`^${regex}$`),\n names,\n factory,\n pattern,\n score: segments.filter((part) => !part.startsWith(\":\") && !part.startsWith(\"*\")).length,\n });\n }\n }\n patterns.sort((a, b) => b.score - a.score || b.pattern.length - a.pattern.length);\n return { exact, patterns };\n};\n\nconst isRouteDeclaration = <R>(factory: OntologyRouteFactory<R>): factory is OntologyRouteDeclaration<R> =>\n \"open\" in factory;\n\nconst allowsInternalAccess = (\n access: OntologyInternalAccess | undefined,\n context: Record<string, unknown> | undefined\n) => {\n if (access === true) return true;\n if (typeof access !== \"function\" || context === undefined) return false;\n try {\n return access(context) === true;\n } catch {\n return false;\n }\n};\n\nconst constructServer = Effect.fn(\"OntologyServer.make\")(function* <R = never>(\n options: OntologyServerRoutes<R> | OntologyBindingOptions<R>\n) {\n const single = \"kind\" in options;\n const settings: OntologyServerRoutes<R> = single ? {} : options;\n // Startup failures a route chose to show its caller in full; every other failure\n // before a route is bound gets the generic projection.\n const forwardedStartupErrors = new WeakSet<BackendError>();\n const ttl = settings.idleRetentionMs ?? 60_000;\n if (\n !Number.isFinite(ttl) ||\n ttl < 0 ||\n (settings.replicas?.scope !== undefined && !Schema.is(Schema.NonEmptyString)(settings.replicas.scope))\n )\n return yield* new BackendError({\n operation: \"server.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Server replica scope and idle retention are invalid.\",\n });\n const compiled = yield* Effect.try({\n try: () => compileRoutes(settings.routes ?? {}),\n catch: (cause) =>\n new BackendError({\n operation: \"server.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Invalid ontology routes.\",\n cause,\n }),\n });\n const serverScope = yield* Effect.scope;\n const runtimes = yield* Effect.serviceOption(Runtimes);\n // Capture storage at server construction, but only open the inventory when\n // a managed route or an inventory operation needs it. Route declarations,\n // not the presence of an options object, determine the service requirement.\n const getCatalog = yield* Effect.cached(\n Scope.provide(\n Option.isSome(runtimes)\n ? makeReplicaPartitionCatalog(settings.replicas?.scope).pipe(\n Effect.provideService(Runtimes, runtimes.value)\n )\n : Effect.fail(\n new BackendError({\n operation: \"server.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Managed replica routes require Runtimes.\",\n })\n ),\n serverScope\n )\n );\n // Role composition is shared across authenticated bindings. Cache invalidation\n // belongs to the cache owner, rather than to an individual caller.\n const roles = yield* RcMap.make({\n lookup: (key: EndpointKey<OntologyBindingOptions<R>>) => prepareOntologyServer(key.options),\n });\n const endpoints = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (key: EndpointKey<OntologyBindingOptions<R>>) {\n const role = yield* RcMap.get(roles, new EndpointKey(key.ontology, key.options, undefined));\n const prepared = {\n ...role,\n ...key.options,\n enableRealtime: key.options.enableRealtime ?? settings.enableRealtime ?? false,\n backend: role.backend,\n source: role.source,\n ir: key.options.ir ?? role.ir,\n };\n const configured = yield* bindOntologyServer(\n prepared,\n key.context,\n key.options.dangerouslyAllowInternalAccess\n );\n return {\n options: configured,\n handlers: yield* Layer.buildWithScope(ontologyRpcHandlers(configured), yield* Effect.scope),\n executionContext:\n prepared.kind === \"owned\" && prepared.ir?.context?.type ? configured.context : undefined,\n };\n }),\n });\n const matched = (target: string) =>\n Effect.try({\n try: () => {\n const path = normalizePath(target);\n const staticRoute = compiled.exact.get(path);\n if (staticRoute)\n return { key: path, factory: staticRoute.factory, params: {} as Record<string, string> };\n for (const route of compiled.patterns) {\n const match = route.regex.exec(path);\n if (!match) continue;\n const params = Object.fromEntries(\n route.names.map((key, index) => [key, decodeURIComponent(match[index + 1]!)])\n );\n const key = route.pattern\n .split(\"/\")\n .map((part) =>\n part.startsWith(\":\") || part.startsWith(\"*\")\n ? encodeURIComponent(params[part.slice(1)]!)\n : part\n )\n .join(\"/\");\n return { key, factory: route.factory, params };\n }\n },\n catch: (cause) =>\n new BackendError({\n operation: \"ontology.route\",\n kind: \"InvalidRequest\",\n retryable: false,\n message: \"Invalid ontology address.\",\n cause,\n }),\n });\n const openRoute = Effect.fn(\"OntologyServer.openRoute\")(function* (target: string) {\n const route = yield* matched(target);\n if (!route)\n return yield* new BackendError({\n operation: \"ontology.route\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Unknown ontology.\",\n });\n const factory = route.factory;\n const declaration = (\n !isRouteDeclaration(factory)\n ? factory\n : typeof factory.open === \"function\"\n ? yield* factory.open(route.params)\n : yield* factory.open\n ) as OntologyRoute<R>;\n const access = factory.dangerouslyAllowInternalAccess;\n const settings = { dangerouslyAllowInternalAccess: access, authenticate: factory.authenticate };\n if (declaration.kind === \"replica\" && access !== true)\n return yield* new BackendError({\n operation: \"server.configure\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Replica routes require dangerouslyAllowInternalAccess: true.\",\n });\n let binding: OntologyBindingOptions<R>;\n if (declaration.kind === \"replica\" && !declaration.replica) {\n // The catalog opens the replica once; it follows its definition by reopening behind\n // the same handle, and binds pick up the definition it is open under.\n const catalog = yield* getCatalog;\n const registration =\n \"upstream\" in declaration\n ? yield* upstreamReplicaRegistration(route.key, declaration, catalog)\n : (declaration as ReplicaRegistration);\n const resource = yield* catalog.open(route.key, registration);\n binding = {\n ...declaration,\n ...settings,\n ir: resource.ir,\n replica: resource.replica,\n backend: resource.backend,\n traces: resource.traces,\n deleteLocalData: forget(route.key),\n } as unknown as OntologyBindingOptions<R>;\n } else binding = { ...declaration, ...settings } as OntologyBindingOptions<R>;\n if (!binding.authenticate) {\n const context = binding.kind === \"replica\" ? binding.replica.context : binding.context;\n const bound = yield* RcMap.get(endpoints, new EndpointKey(route.key, binding, context));\n // A fixed route owns its handler resources, including chunk-transfer\n // registries, for the same lifetime as its backend.\n binding = { ...binding, context: bound.options.context } as OntologyBindingOptions<R>;\n }\n return binding;\n });\n // An opened route stays warm for `idleRetentionMs` after its last request. RcMap keeps a\n // failed lookup the same way, so every retry would get the cached failure and restart its\n // idle timer. Drop a failed open instead; the attempt number keeps a late failure from\n // removing a newer open of the same route.\n let openAttempts = 0;\n const latestOpen = new Map<string, number>();\n const resources = yield* RcMap.make({\n idleTimeToLive: ttl,\n lookup: (target: string): ReturnType<typeof openRoute> =>\n Effect.suspend(() => {\n const attempt = ++openAttempts;\n latestOpen.set(target, attempt);\n return openRoute(target).pipe(\n Effect.onExit((exit) =>\n Effect.suspend(() => {\n if (latestOpen.get(target) !== attempt) return Effect.void;\n latestOpen.delete(target);\n // RcMap already drops an interrupted lookup.\n return Exit.isFailure(exit) && !Exit.hasInterrupts(exit)\n ? RcMap.invalidate(resources, target)\n : Effect.void;\n })\n )\n );\n }),\n });\n const retire = (key: string): Effect.Effect<void> => RcMap.invalidate(resources, key);\n const invalidate = (target: string): Effect.Effect<void, BackendError> =>\n Effect.flatMap(matched(target), (route) => retire(route?.key ?? normalizePath(target)));\n const forget = (target: string): Effect.Effect<void, BackendError> =>\n Effect.gen(function* () {\n const route = yield* matched(target);\n const key = route?.key ?? normalizePath(target);\n if (Option.isSome(runtimes)) {\n const catalog = yield* getCatalog;\n yield* catalog.forget(key);\n }\n yield* RcMap.invalidate(resources, key);\n });\n const authenticateRequest = (authenticate: OntologyAuthenticate<R>, request: Request | undefined) =>\n Effect.gen(function* () {\n if (!request)\n return yield* new BackendError({\n operation: \"ontology.authenticate\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"This ontology requires an HTTP authentication binding.\",\n });\n const context = yield* authenticate(request);\n yield* Schema.decodeUnknownEffect(Schema.Record(Schema.String, Schema.Unknown))(context).pipe(\n Effect.mapError(\n () =>\n new BackendError({\n operation: \"ontology.authenticate\",\n kind: \"InvalidConfiguration\",\n retryable: false,\n message: \"Authentication must return an ontology context.\",\n })\n )\n );\n return context;\n });\n const bind = Effect.fn(\"OntologyServer.bind\")(function* (ontology: string, request?: Request) {\n if (!single) yield* name(ontology);\n const route = single ? undefined : yield* matched(ontology);\n if (route) {\n // Authenticate before opening, so an unauthenticated request never opens a route\n // and an open failure can be shown in full to a caller allowed internal access.\n const { authenticate, dangerouslyAllowInternalAccess: access } = route.factory;\n const caller = authenticate ? yield* authenticateRequest(authenticate, request) : undefined;\n const opened = yield* RcMap.get(resources, route.key).pipe(\n Effect.tapError((error) =>\n Effect.sync(() => {\n if (allowsInternalAccess(access, caller)) forwardedStartupErrors.add(error);\n })\n )\n );\n const target = replicaGeneration(opened);\n const context = caller ?? (target.kind === \"replica\" ? target.replica.context : target.context);\n return yield* RcMap.get(endpoints, new EndpointKey(ontology, target, context));\n }\n const resolved = single\n ? (options as OntologyBindingOptions<R>)\n : settings.resolve\n ? yield* settings.resolve(ontology)\n : yield* Effect.fail(\n new BackendError({\n operation: \"ontology.route\",\n kind: \"NotFound\",\n retryable: false,\n message: \"Unknown ontology.\",\n })\n );\n const target = replicaGeneration(resolved);\n const context = target.authenticate\n ? yield* authenticateRequest(target.authenticate, request)\n : target.kind === \"replica\"\n ? target.replica.context\n : target.context;\n return yield* RcMap.get(endpoints, new EndpointKey(ontology, target, context));\n });\n const server: OntologyServer<R> = {\n _tag: \"OntologyServer\",\n defaultOntology: single ? \"\" : undefined,\n bind,\n invalidate,\n forget,\n partitions: Option.isSome(runtimes)\n ? Effect.flatMap(getCatalog, (catalog) => catalog.partitions)\n : Effect.succeed([]),\n syncOnce: (ontology, settings) =>\n Effect.scoped(\n Effect.gen(function* () {\n const bound: OntologyRpcServerOptions<R> = (yield* bind(ontology)).options;\n if (!bound.replica)\n return yield* new BackendError({\n operation: \"server.syncOnce\",\n kind: \"InvalidRequest\",\n retryable: false,\n message: \"Only replica routes support native synchronization checkpoints.\",\n });\n yield* settings?.revalidate ? bound.replica.revalidate : bound.replica.syncOnce;\n return { pins: yield* bound.replica.demand.pins.list };\n })\n ),\n // Failures before a route is bound: its IR policy is not known yet.\n errors: (error) =>\n forwardedStartupErrors.has(error) ? error : projectBackendError(error, \"projected\"),\n ir: settings.ir,\n upstreamErrors: settings.upstreamErrors,\n };\n // Preserve eager configuration validation for the single-ontology shorthand.\n if (\"kind\" in options && !options.authenticate) {\n const bound = yield* bind(\"\");\n // Configuration is a binding, not a live reference to mutable app state.\n options = { ...options, context: bound.options.context } as OntologyBindingOptions<R>;\n }\n return server;\n});\n\nexport interface MakeOntologyServer {\n <R = never, const Paths extends string = string>(\n options:\n | OntologyServerRoutes<R, Paths, Exclude<OpenedOntologyRoute<R>, ManagedReplicaRoute<R>>>\n | OntologyBindingOptions<R>\n ): Effect.Effect<OntologyServer<Exclude<R, Scope.Scope>>, BackendError, R | Scope.Scope>;\n <R = never, const Paths extends string = string>(\n options: OntologyServerRoutes<R, Paths>\n ): Effect.Effect<OntologyServer<Exclude<R, Scope.Scope>>, BackendError, R | Runtimes | Scope.Scope>;\n}\nexport const makeOntologyServer: MakeOntologyServer = constructServer as MakeOntologyServer;\n\n/** One RPC server dispatches all targets, including calls in the same HTTP batch. */\nexport const ontologyServerDispatch = <R = never>(router: OntologyServer<R>) => {\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 ontology =\n request.headers[ontologyHeader] ?? (yield* OntologyTransportTarget) ?? \"\";\n const existing = yield* OntologyTransportBinding;\n const bound =\n existing?.ontology === ontology\n ? (existing.bound as BoundOntology<R>)\n : yield* router.bind(ontology, yield* OntologyTransportRequest);\n const handler = yield* OntologyRpcs.accessHandler(tag as Rpcs[\"_tag\"]).pipe(\n Effect.provideContext(bound.handlers)\n );\n const result = handler(payload, request) as\n | Effect.Effect<unknown, BackendError, R>\n | Stream.Stream<unknown, BackendError, R>;\n const action = payload as { name?: string; invocation?: { name?: string } } | undefined;\n const project = (error: BackendError) =>\n projectBackendError(\n error,\n bound.options.errors,\n errorContext(bound.options, action?.name ?? action?.invocation?.name)\n );\n return RpcSchema.isStreamSchema(rpc.successSchema)\n ? (result as Stream.Stream<unknown, BackendError, R>).pipe(\n Stream.mapError(project),\n Stream.provideService(CurrentExecutionContext, bound.executionContext)\n )\n : (result as Effect.Effect<unknown, BackendError, R>).pipe(\n Effect.mapError(project),\n Effect.provideService(CurrentExecutionContext, bound.executionContext)\n );\n }).pipe(Effect.mapError((error) => projectBackendError(error, router.errors)));\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((result) => result as Stream.Stream<unknown, BackendError, R>)\n )\n )\n : (payload: never, request: Parameters<Handler>[1]) =>\n Effect.scoped(\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 })\n ) as unknown as {\n readonly [Procedure in Rpcs as Procedure[\"_tag\"]]: Rpc.ToHandlerFn<Procedure, R | Scope.Scope>;\n };\n // Errors have already been projected for the selected ontology. Keep the\n // outer middleware for defect conversion without projecting them a second time.\n return Layer.merge(OntologyRpcs.toLayer(handlers), errorProjectionLayer({ errors: \"forward\" }));\n};\n"],"mappings":";;;;;;;;;;;;;;AAoBA,MAAa,iBAAiB;AAC9B,MAAM,oBAAoB;AAC1B,MAAM,aAAa,OAAO,eAAe,MAAM,OAAO,YAAY,IAAI,CAAC;AACvE,MAAM,QAAQ,UACV,OAAO,oBAAoB,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,KAC1C,OAAO,eAEC,IAAI,aAAa;CACb,WAAW;CACX,MAAM;CACN,WAAW;CACX,SAAS;AACb,CAAC,CACT,CACJ;;AAOJ,SAAgB,eAAe,QAA2B,UAAqC;CAC3F,OAAO,OAAO,YACV,CAAC,GAAG,aAAa,SAAS,KAAK,CAAC,CAAC,CAAC,KAAK,QAAQ,CAC3C,MACC,SAAkB,aACf,QAAQ,MAAM,QAAQ,IAAI,Q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@ export declare const OntologyRpcs: RpcGroup.RpcGroup<Rpc.Rpc<"LoadSubset", Schem
1202
1202
  readonly watchSubset: Schema.optional<Schema.Boolean>;
1203
1203
  readonly actionParameterResolution: Schema.optional<Schema.Boolean>;
1204
1204
  readonly queries: Schema.optional<Schema.Boolean>;
1205
- readonly pins: Schema.optional<Schema.Boolean>;
1205
+ readonly system: Schema.optional<Schema.Boolean>;
1206
1206
  readonly meta: Schema.optional<Schema.Boolean>;
1207
1207
  readonly attachments: Schema.optional<Schema.Struct<{
1208
1208
  readonly stage: Schema.Boolean;
@@ -1405,7 +1405,7 @@ export declare const makeOntologyRpcClient: Effect.Effect<{
1405
1405
  readonly watchSubset?: boolean | undefined;
1406
1406
  readonly actionParameterResolution?: boolean | undefined;
1407
1407
  readonly queries?: boolean | undefined;
1408
- readonly pins?: boolean | undefined;
1408
+ readonly system?: boolean | undefined;
1409
1409
  readonly meta?: boolean | undefined;
1410
1410
  readonly attachments?: {
1411
1411
  readonly stage: boolean;
@@ -2898,6 +2898,9 @@ export declare const makeOntologyRpcClient: Effect.Effect<{
2898
2898
  } | undefined) => Effect.Effect<Discard extends true ? void : void, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced"> | import("effect/rpc/RpcClientError").RpcClientError | (Discard extends true ? never : BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">), never>;
2899
2899
  }, never, RpcClient.Protocol | Scope.Scope>;
2900
2900
  export interface OntologyClientOptions {
2901
+ /** @internal The networks the transport reaches the server on, for the client's backends
2902
+ * (`OntologyBackendService.networks`). A transport on the same device is on none. */
2903
+ readonly networks?: readonly string[];
2901
2904
  /** Previously accepted, public source binding; never inferred from cached rows. */
2902
2905
  readonly description?: OntologyDescription$1;
2903
2906
  /** The definition `description` was accepted with. Required with `description`; otherwise
@@ -2939,8 +2942,8 @@ export interface OntologyClient {
2939
2942
  readonly ir?: import("@party-stack/ontology-spec").OntologyIR;
2940
2943
  readonly context?: Record<string, unknown>;
2941
2944
  readonly operations: OntologyOperationsClient;
2942
- /** Ordinary ontology operations over the selected replica's download inventory. */
2943
- readonly pinBackend?: Effect.Effect<import("@party-stack/ontology-backend").OntologyBackendService, BackendError, Scope.Scope>;
2945
+ /** Ordinary ontology operations over the endpoint's system ontology: its downloads and replica status. */
2946
+ readonly systemBackend?: Effect.Effect<import("@party-stack/ontology-backend").OntologyBackendService, BackendError, Scope.Scope>;
2944
2947
  /** The endpoint's current definition as meta ontology rows (`@party-stack/ontology-spec/meta`).
2945
2948
  * It follows the endpoint: after a definition change it serves the new one. */
2946
2949
  readonly metaBackend?: Effect.Effect<import("@party-stack/ontology-backend").OntologyBackendService, BackendError, Scope.Scope>;
@@ -3022,7 +3025,7 @@ export interface OntologyRpcServerOptions<R = never> extends ErrorProjectionOpti
3022
3025
  /** Administrative resources use the same ontology RPCs and transport. Access is
3023
3026
  * still gated by the parent endpoint before the resource is acquired. */
3024
3027
  export declare const ontologyRpcHandlers: <R>(options: OntologyRpcServerOptions<R>) => Layer.Layer<Rpc.Handler<"Accept"> | Rpc.Handler<"AckDelivery"> | Rpc.Handler<"Acknowledge"> | Rpc.Handler<"ApplyAction"> | Rpc.Handler<"AttachmentMetadata"> | Rpc.Handler<"Changes"> | Rpc.Handler<"ControlOutbox"> | Rpc.Handler<"CreateAttachment"> | Rpc.Handler<"Decrypt"> | Rpc.Handler<"DeleteLocalData"> | Rpc.Handler<"Demand"> | Rpc.Handler<"Describe"> | Rpc.Handler<"LoadSubset"> | Rpc.Handler<"OpenClient"> | Rpc.Handler<"PullChanges"> | Rpc.Handler<"Query"> | Rpc.Handler<"QueryFunction"> | Rpc.Handler<"Read"> | Rpc.Handler<"ReadAttachment"> | Rpc.Handler<"ReleaseOwner"> | Rpc.Handler<"ReplicaStatus"> | Rpc.Handler<"ResolveActionParameters"> | Rpc.Handler<"Submit"> | Rpc.Handler<"SubscribeSelection"> | Rpc.Handler<"SubscribeState"> | Rpc.Handler<"Traces"> | Rpc.Handler<"UpdateView"> | Rpc.Handler<"ValidateAction"> | Rpc.Handler<"WatchChanges"> | Rpc.Handler<"WatchSubset"> | Rpc.Handler<"WriteAttachmentChunk"> | OntologyErrorProjection, never, Exclude<Exclude<R, never>, Scope.Scope> | Exclude<Exclude<Exclude<R, never>, Scope.Scope>, Scope.Scope>>;
3025
- export type OntologyResource = "pins" | "meta";
3028
+ export type OntologyResource = "system" | "meta";
3026
3029
  export type OntologyRpcClient = Effect.Success<ReturnType<typeof RpcClient.make<RpcGroup.Rpcs<typeof OntologyRpcs>>>>;
3027
3030
  /** HTTP byte operations use the same incompatibility notification as typed RPC. */
3028
3031
  export declare const observeOntologyClientFailure: <A, R>(client: OntologyClient, work: Effect.Effect<A, BackendError, R>) => Effect.Effect<A, BackendError<"Conflict" | "Forbidden" | "HistoryExpired" | "Internal" | "InvalidConfiguration" | "InvalidRequest" | "InvalidResponse" | "NotFound" | "NotImplemented" | "RateLimited" | "ResultExpired" | "SchemaMismatch" | "SessionExpired" | "SessionReplaced" | "SourceMismatch" | "Unauthenticated" | "Unavailable" | "ValidationFailed" | "ViewReplaced">, R>;
package/lib/rpc.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"rpc.d.ts","names":["OntologyDescription"],"sources":["../src/rpc.ts"],"mappings":";;;;;;;;;;;;;;cAsEM,kBAAgB,OAAA;qBA0DT,cAAY,SAAA,SAAA,IAAA,kBAAA,OAAA,iDAAA,qCAAA,OAAA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oQ9B,6BAA0B,QAVvB,mBAAiB,UACf,0BACT,OAAO,OAAO,gBAAgB,cAAc,MAAM;;;;;;qBAc9C,oCAAiC,QAhB9B,mBAAiB,UACf,0BACT,OAAO,OAAO,gBAAgB,cAAc,MAAM"}
package/lib/rpc.js CHANGED
@@ -9,7 +9,7 @@ import { Cause, Context, Deferred, Effect, Exit, Layer, PubSub, Random, Schedule
9
9
  import { Rpc, RpcClient, RpcGroup, RpcMiddleware, RpcSchema } from "effect/rpc";
10
10
  import { ontologyDefinitionContractHash, ontologyDefinitionHash, ontologyDefinitionSignature } from "@party-stack/ontology-storage";
11
11
  import { Table } from "@party-stack/ontology-storage/tables";
12
- import { pinOntology } from "@party-stack/ontology-replica";
12
+ import { systemOntology } from "@party-stack/ontology-replica";
13
13
  import { objectSubset } from "@party-stack/ontology-backend/subset";
14
14
  import { ClientLeaseSchema, ClientSessionSchema, ClientTokenSchema } from "@party-stack/ontology-backend/clients";
15
15
  import { DeliveryFrameCodec, DeliveryPositionSchema } from "@party-stack/ontology-backend/delivery";
@@ -213,7 +213,7 @@ const baseOntologyRpcHandlers = (options) => {
213
213
  watchSubset: clientSync && Boolean(operationOptions.backend?.watchSubset || options.ir?.objectTypes.some((type) => typeof operationOptions.backend?.refresh?.(objectSubset(type.name))?.pollIntervalMs === "number")),
214
214
  actionParameterResolution: Boolean(options.backend?.resolveActionParameters || options.replica),
215
215
  queries: Boolean(options.backend),
216
- pins: Boolean(options.replica),
216
+ system: Boolean(options.replica),
217
217
  meta: Boolean(options.ir),
218
218
  attachments: options.backend ? options.backend.attachments && { stage: Boolean(options.backend.attachments.stage) } : options.replica ? { stage: true } : void 0,
219
219
  encrypted: Boolean(options.backend ? options.backend.encrypted : options.replica)
@@ -328,9 +328,9 @@ const resourceHeader = "x-party-stack-resource";
328
328
  const ontologyRpcHandlers = (options) => Layer.unwrap(Effect.gen(function* () {
329
329
  const scope = yield* Effect.scope;
330
330
  const ordinary = yield* Layer.buildWithScope(baseOntologyRpcHandlers(options), scope);
331
- const pins = yield* Effect.cached(Effect.gen(function* () {
331
+ const system = yield* Effect.cached(Effect.gen(function* () {
332
332
  if (!options.replica) return yield* new BackendError({
333
- operation: "pins",
333
+ operation: "system",
334
334
  kind: "NotImplemented",
335
335
  retryable: false,
336
336
  message: "This endpoint does not own downloads."
@@ -338,11 +338,11 @@ const ontologyRpcHandlers = (options) => Layer.unwrap(Effect.gen(function* () {
338
338
  const backend = yield* options.replica.demand.pins.backend;
339
339
  return yield* Layer.buildWithScope(baseOntologyRpcHandlers({
340
340
  backend,
341
- ir: pinOntology,
341
+ ir: systemOntology,
342
342
  context: options.context,
343
343
  enableRealtime: options.enableRealtime,
344
344
  errors: options.errors,
345
- authorize: (_, headers) => options.authorize({ operation: "Pins" }, headers)
345
+ authorize: (_, headers) => options.authorize({ operation: "System" }, headers)
346
346
  }), scope);
347
347
  }));
348
348
  const describeAccess = (headers) => options.authorize({ operation: "Describe" }, headers);
@@ -366,14 +366,14 @@ const ontologyRpcHandlers = (options) => Layer.unwrap(Effect.gen(function* () {
366
366
  const handlers = Object.fromEntries([...OntologyRpcs.requests].map(([tag, rpc]) => {
367
367
  const invoke = (payload, request) => Effect.gen(function* () {
368
368
  const resource = request.headers[resourceHeader];
369
- if (resource !== void 0 && resource !== "pins" && resource !== "meta") return yield* new BackendError({
369
+ if (resource !== void 0 && resource !== "system" && resource !== "meta") return yield* new BackendError({
370
370
  operation: "ontology.resource",
371
371
  kind: "NotFound",
372
372
  retryable: false,
373
373
  message: "Unknown ontology resource."
374
374
  });
375
- if (resource === "pins") yield* options.authorize({ operation: "Pins" }, request.headers);
376
- const context = resource === "pins" ? yield* pins : resource === "meta" ? yield* meta : ordinary;
375
+ if (resource === "system") yield* options.authorize({ operation: "System" }, request.headers);
376
+ const context = resource === "system" ? yield* system : resource === "meta" ? yield* meta : ordinary;
377
377
  return (yield* OntologyRpcs.accessHandler(tag).pipe(Effect.provideContext(context)))(payload, request);
378
378
  });
379
379
  return [tag, RpcSchema.isStreamSchema(rpc.successSchema) ? (payload, request) => Stream.unwrap(invoke(payload, request).pipe(Effect.map((result) => result))) : (payload, request) => Effect.flatten(invoke(payload, request).pipe(Effect.map((result) => result)))];
@@ -381,7 +381,7 @@ const ontologyRpcHandlers = (options) => Layer.unwrap(Effect.gen(function* () {
381
381
  return Layer.merge(OntologyRpcs.toLayer(handlers), errorProjectionLayer(options));
382
382
  }));
383
383
  const resourceDefinitions = {
384
- pins: pinOntology,
384
+ system: systemOntology,
385
385
  meta: metaOntology
386
386
  };
387
387
  const selectResource = (client, resource) => Object.fromEntries([...OntologyRpcs.requests.keys()].map((tag) => [tag, (payload, settings) => Reflect.apply(Reflect.get(client, tag), client, [payload, {
@@ -423,7 +423,7 @@ const protocolIdentity = (description) => ({
423
423
  watchSubset: Boolean(description.watchSubset),
424
424
  actionParameterResolution: Boolean(description.actionParameterResolution),
425
425
  queries: Boolean(description.queries),
426
- pins: Boolean(description.pins),
426
+ system: Boolean(description.system),
427
427
  meta: Boolean(description.meta),
428
428
  attachments: Boolean(description.attachments),
429
429
  stageAttachments: Boolean(description.attachments?.stage),
@@ -615,21 +615,30 @@ const openProtocolClient = Effect.fnUntraced(function* (client, options, accept,
615
615
  });
616
616
  if (!ir && description.meta) ({description, ir} = yield* readDefinition(client, description, open));
617
617
  const described = yield* makeDefinitionClient(client, description, ir, options);
618
- const pinBackend = description.pins && !options?.resource ? open(base, { resource: "pins" }).pipe(Effect.map((resource) => resource.backend)) : void 0;
619
- const metaBackend = description.meta && !options?.resource ? open(base, { resource: "meta" }).pipe(Effect.map((resource) => resource.backend)) : void 0;
618
+ const systemBackend = description.system && !options?.resource ? open(base, {
619
+ resource: "system",
620
+ networks: options?.networks
621
+ }).pipe(Effect.map((resource) => resource.backend)) : void 0;
622
+ const metaBackend = description.meta && !options?.resource ? open(base, {
623
+ resource: "meta",
624
+ networks: options?.networks
625
+ }).pipe(Effect.map((resource) => resource.backend)) : void 0;
620
626
  client = described.client;
621
627
  const operations = yield* makeOntologyOperationsClient(client);
622
628
  const common = {
623
629
  description,
624
630
  definition: metaBackend && !options?.resource ? watchDefinition(described.definition, metaBackend) : described.definition,
625
631
  operations,
626
- pinBackend,
632
+ systemBackend,
627
633
  metaBackend,
628
634
  sourceId: description.sourceId,
629
635
  definitionHash: description.definitionHash,
630
636
  ir,
631
637
  context: description.context,
632
- backend: makeRpcBackend(client, description, operations)
638
+ backend: {
639
+ ...makeRpcBackend(client, description, operations),
640
+ ...options?.networks && { networks: options.networks }
641
+ }
633
642
  };
634
643
  if (description.replication === "committed") return {
635
644
  ...common,