@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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Robert Fidler
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,494 @@
1
- # Temporary Holding Version
1
+ # @party-stack/ontology-server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Transport bindings for native ontology backends and replicas, with policy-aware
4
+ describe/load/apply and structured errors. The server package does not depend on
5
+ the application SDK.
6
+
7
+ The package was renamed from `@party-stack/remote-ontology`. The replica-state RPC HTTP transport uses
8
+ streaming NDJSON over Fetch, rather than SSE/EventSource framing. The same Effect
9
+ RPC definition can run over worker ports.
10
+
11
+ ## Server roles
12
+
13
+ `makeOntologyServer` is a scoped, transport-neutral Effect. Configure one binding
14
+ or a table of routes. HTTP and worker helpers serve the same server. Choose the
15
+ role by where writes commit:
16
+
17
+ ```ts
18
+ import { makeOntologyServer } from "@party-stack/ontology-server";
19
+
20
+ // Authoritative storage; commits actions, receipts and journal atomically.
21
+ const ownedServer =
22
+ yield *
23
+ makeOntologyServer({
24
+ kind: "owned",
25
+ backend: owned,
26
+ authenticate,
27
+ });
28
+
29
+ // Direct forwarding, with no local outbox or client-session registry.
30
+ const proxyServer =
31
+ yield *
32
+ makeOntologyServer({
33
+ kind: "proxy",
34
+ backend: upstream,
35
+ ir,
36
+ authenticate,
37
+ });
38
+
39
+ // Confirmed read cache; writes still forward directly to upstream.
40
+ // Configure readCache with makeReplica({ ..., demand: { idleRetentionMs: 60_000, maxSubsets: 128 } }).
41
+ const cachedServer =
42
+ yield *
43
+ makeOntologyServer({
44
+ kind: "cached-proxy",
45
+ backend: upstream,
46
+ cache: readCache,
47
+ authenticate,
48
+ });
49
+
50
+ // Intermediate replica: accepts durable local actions into its own outbox.
51
+ const replicaServer =
52
+ yield *
53
+ makeOntologyServer({
54
+ enableRealtime: true,
55
+ kind: "replica",
56
+ backend: upstream,
57
+ replica,
58
+ dangerouslyAllowInternalAccess: true,
59
+ });
60
+ ```
61
+
62
+ Configure several targets with the same constructor:
63
+
64
+ ```ts
65
+ const server =
66
+ yield *
67
+ makeOntologyServer({
68
+ routes: {
69
+ issues: { kind: "owned", backend: owned, authenticate },
70
+ "forms/:formId": Effect.fnUntraced(function* ({ formId }: Readonly<Record<string, string>>) {
71
+ return { kind: "proxy" as const, backend: yield* openForm(formId!), ir, authenticate };
72
+ }),
73
+ },
74
+ idleRetentionMs: 60_000,
75
+ });
76
+ const handleRequest = yield * makeOntologyHttpHandler(server);
77
+ ```
78
+
79
+ Exact names use a map; parameter patterns are compiled at construction. Acquired
80
+ routes remain alive through active requests and streams, followed by the idle
81
+ retention interval. Each route binds authentication and policy independently.
82
+ `makeOntologyHttpClient` and `makeOntologyWorkerClient` open a shared root client;
83
+ `client.ontology(name)` acquires a selected handle without opening another transport.
84
+ For a single binding, use `client.ontology()`.
85
+
86
+ Managed replica routes return
87
+ `{ kind: "replica", ir, context, backend, ...replicaOptions }` from a route. The
88
+ server owns sharing and persistent partition inventory. `server.forget(name)`
89
+ deletes the stored partition even after its credentials expire. Direct and cached
90
+ proxy bindings do not acquire a replica catalog. Managed routes require the
91
+ `Runtimes` service; this requirement is inferred from the route declaration.
92
+ Omitting `replicas` and passing `replicas: {}` are equivalent.
93
+
94
+ An optional `replicas: { scope }` isolates both the inventory and data namespaces
95
+ when multiple servers share a runtime platform. Omitted scope preserves each
96
+ replica's configured namespace. Scope is storage isolation, not authorization.
97
+
98
+ There is no writes flag. IR policy controls read-only access. The role defines execution responsibility; it does not grant permission.
99
+ Only a private intermediate replica without a local IR policy exposes speculative
100
+ replica-state replication.
101
+ Owned, proxy and cached-proxy roles expose committed backend operations without
102
+ opening child replication sessions.
103
+
104
+ The read cache shares subset demand with scoped `RcMap` leases. Concurrent callers
105
+ share one demand. The idle timeout restarts after the last request releases its lease.
106
+ At capacity, the oldest idle demand is released first; RateLimited applies only when
107
+ every slot is in use. Active reads are never evicted. These configurable demand-count
108
+ bounds are independent from row GC and do not impose a byte budget. Forwarded
109
+ writes never enter the read cache's outbox. A successful receipt invalidates coverage
110
+ for its affected types; incomplete targets invalidate all types. The next read repairs
111
+ coverage. An invalidation IO failure cannot turn a committed action into a failed one.
112
+ Use a dedicated read-cache replica, bound to the same trusted upstream identity.
113
+
114
+ `kind: "replica"` publishes composed state through its speculative extension. Its
115
+ ordinary backend facet still serves committed upstream rows and journal. Protocol
116
+ `Submit` returns parent acceptance; stateless `ApplyAction` waits for upstream confirmation.
117
+ The replica's surrounding scope must own its synchronization loop.
118
+
119
+ ## Client synchronization
120
+
121
+ Finite queries and actions work by default. Opt into downstream watches, change-feed
122
+ reads, and replication sessions with `enableRealtime: true` on `makeOntologyServer`.
123
+ A routed server uses this as its default; an individual route can override it with
124
+ `enableRealtime: false`. Capabilities are advertised only when the backend and policy
125
+ support them, and no subscription is acquired until a client requests it. Disabled
126
+ synchronization calls are rejected, including direct RPC calls. Backend maintenance
127
+ and upstream sync are independent of this setting.
128
+
129
+ Error disclosure follows the route's IR policy automatically: policy-bound routes
130
+ project messages/issues; private no-policy routes forward the original typed error,
131
+ including its cause.
132
+ See the website's authorization boundaries guide for receipts and planned projected
133
+ change feeds.
134
+
135
+ ## Stateless backend operations
136
+
137
+ ```ts
138
+ import { objectSubset } from "@party-stack/ontology-backend/subset";
139
+ import { makeOntologyHttpBackend } from "@party-stack/ontology-server/rpc/http";
140
+
141
+ const backend = yield * makeOntologyHttpBackend({ url }).pipe(Effect.provide(FetchHttpClient.layer));
142
+ const snapshot = yield * backend.loadSubset(objectSubset("Issue", query));
143
+ const receipt = yield * backend.applyAction(invocation);
144
+ ```
145
+
146
+ Mount the endpoint so it accepts the trailing slash appended by Effect's HTTP
147
+ client (`/rpc/` as well as `/rpc`). These typed RPC calls do not open a replication client session. Describe advertises
148
+ whether incremental `PullChanges` and change hints are available; ordinary requests
149
+ need no session acknowledgment/bookkeeping. The same transport supports full/draft
150
+ validation, query functions and explicit attachment/decrypt operations.
151
+
152
+ `makeOntologyServer` automatically installs finite hierarchical Query execution
153
+ when an ontology definition is available (inferred for owned, cached-proxy and
154
+ replica roles; supplied as `ir` or through `ontology` for a direct proxy).
155
+ Call it through `client.operations.query(document, inputs)`. No custom Query
156
+ handler is required. Owned queries share one storage read transaction. Other roles
157
+ use their final backend read path, including cache hits; multiple provider calls
158
+ do not imply a provider-wide atomic snapshot. Incomplete source subsets are rejected.
159
+ Policy-projected servers use the authorized query executor. The low-level RPC
160
+ binding still permits endpoints without schema/query execution, and Describe
161
+ advertises whether finite queries are available.
162
+
163
+ Source identity is supplied by the server's backend/source in Describe. An owned
164
+ backend generates and persists a namespace-scoped identity on initialization; deleting
165
+ that state creates a new source. Adapter backends supply stable provider identities
166
+ (Foundry base URL + ontology RID, Salesforce instance URL). A cached proxy retains
167
+ its upstream identity, while an intermediate replica has its own persisted identity.
168
+ Clients learn it from Describe; it is independent from schema revisions and login/session IDs.
169
+
170
+ `changes.watch` acquires wake-up hints for `changes.pull(cursor)`, not row payloads.
171
+ `watchSubset` acquires subset invalidations independently of a journal. Both return
172
+ scoped Effects that establish and buffer the real subscription before returning its
173
+ stream. Policy composition establishes every dependency feed before it reports ready.
174
+ RPC sends its opening notification after acquisition; the remote backend client
175
+ consumes that notification as readiness rather than invalidating a just-started read.
176
+ Subsequent notifications still invalidate data or request reconnect repair.
177
+
178
+ Foundry uses `watchSubset`; Salesforce currently uses polling because its CDC client does not yet
179
+ report reconnect gaps/stream health. Neither currently exposes a resumable native journal.
180
+
181
+ ## Authorization and error disclosure
182
+
183
+ Supply `authenticate(request)` to resolve the IR context on each HTTP request.
184
+ The backend and HTTP owner are acquired once; request scopes own policy bindings,
185
+ active requests and streamed responses. `ir.policy` remains the domain permission
186
+ contract for objects, properties, actions and query functions.
187
+
188
+ ```ts
189
+ return (
190
+ yield *
191
+ makeOntologyServer({
192
+ kind: "owned",
193
+ backend,
194
+ ir,
195
+ authenticate: (request) => authenticatedContext(request),
196
+ })
197
+ );
198
+ ```
199
+
200
+ `authenticatedContext` is the application's Effect returning values matching the
201
+ IR context type, such as `{ userId, tenant }`. It fails with `Unauthenticated` for a
202
+ missing/invalid session. The server applies policy on the final read path, including
203
+ cache hits. Public endpoints deny internal replication, diagnostics and administration.
204
+ Already authenticated native bindings can instead supply a fixed `context`.
205
+
206
+ `dangerouslyAllowInternalAccess` adds diagnostics and administrative commands: replica
207
+ status, traces, outbox recovery, local-data deletion and owner release, where supplied.
208
+ These can inspect or change state outside the caller's policy; enable them only for
209
+ callers allowed to operate the whole endpoint. The setting never disables IR policy:
210
+ reads, schema projection, action checks, parameter bindings and attachment guards
211
+ still apply. Trace recording is configured separately.
212
+
213
+ Use `true` for a private endpoint, or a synchronous predicate over validated context:
214
+
215
+ ```ts
216
+ dangerouslyAllowInternalAccess: (context) => context.role === "internal-admin",
217
+ ```
218
+
219
+ Authentication still runs per request. A predicate must return a boolean; session
220
+ and database checks belong in `authenticate`. Worker helpers enable internal access
221
+ for private app ports. Without an IR policy, explicit internal access grants the raw
222
+ backend/replica protocol. With a policy, raw journals and selected/speculative state
223
+ remain unavailable because those streams are not yet policy-projected.
224
+
225
+ The low-level RPC guard is internal permission enforcement for transport binders;
226
+ normal server construction has no `authorize` callback. Authentication does not
227
+ replace the IR policy or grant domain permissions by itself.
228
+
229
+ Owned execution binds parameters and evaluates policy/reference checks in the same
230
+ transaction as mutator reads/writes, receipt and journal publication. Shape validation,
231
+ idempotency lookup and staging external bytes can precede that transaction. Adapted
232
+ providers have their own authoritative transaction; the proxy enforces its policy
233
+ before forwarding. Neither grants nor request snapshots are retained across calls.
234
+
235
+ Caller filters are rewritten into policy grant paths where safe. Caller pagination
236
+ runs after authorization; policy windows remain semantic barriers. The full-policy
237
+ eager evaluator is private oracle infrastructure, not a configuration switch. A
238
+ future eager sync/offline pin controls demand acquisition and retention instead.
239
+
240
+ Context-only conditional selections specialize the public definition. Row-dependent
241
+ properties remain potentially available and optional; returned rows omit denied
242
+ cells. Filtering/ordering on conditionally available fields is conservatively denied.
243
+ The context definition and bound values form one shared contract, returned by
244
+ `Describe` together with the projected definition, capabilities, definition hash and
245
+ source ID. Credentials and private authentication state belong in server services,
246
+ not context. Partition paths in `ir.context.partition` derive the local storage
247
+ partition from those same values.
248
+
249
+ A gateway can replace the upstream context definition and policy with its own:
250
+
251
+ ```ts
252
+ const tokenIR = {
253
+ ...upstreamIR,
254
+ context: {
255
+ type: o.struct({
256
+ fields: [
257
+ {
258
+ name: "approval",
259
+ displayName: "Approval",
260
+ type: o.objectReference({ objectType: "PostApproval" }),
261
+ },
262
+ ],
263
+ }),
264
+ partition: [["approval"]],
265
+ },
266
+ policy: tokenPolicy,
267
+ };
268
+ const server =
269
+ yield *
270
+ makeOntologyServer({
271
+ kind: "cached-proxy",
272
+ backend: upstream,
273
+ cache: trustedServiceAccountCache,
274
+ ir: tokenIR,
275
+ context: { approval: verifiedToken.approvalId },
276
+ });
277
+ ```
278
+
279
+ Each policy `bind` hides its parameter from the public action schema and replaces
280
+ caller input on the server. Compatible defaults and predictions are rewritten to
281
+ use the binding; predictions that cannot safely use the new context are omitted.
282
+ This gateway policy is enforced in addition to the provider's own permissions.
283
+ There is no separate `clientContext` option in the native constructor.
284
+
285
+ Projected attachments and decryption require an accessible source row/property and
286
+ re-find the exact attachment ID/ciphertext in that row. Checks happen before byte or
287
+ decryption providers are called. Standalone staging/eager-upload access is not granted;
288
+ action-associated HTTP uploads use the normal authorized action path.
289
+
290
+ Projected views omit raw journals, selected delivery and speculative state. Correct
291
+ visibility transitions for deletions/moves require a scoped delivery implementation.
292
+ Ordinary subset invalidation hints are available with `enableRealtime: true`, without row payloads.
293
+
294
+ Policy-bound routes project errors to safe normalized messages, exposed parameter
295
+ paths, and standard input constraints. Reference failures become a generic
296
+ invalid-reference issue; custom submission criteria remain hidden. Private routes
297
+ without a policy preserve the original typed errors, including causes. No separate
298
+ error-mode option is needed. An upstream connector authentication failure on a
299
+ policy-bound route becomes Unavailable for a downstream caller who cannot fix that
300
+ connector by signing in.
301
+
302
+ An action/function check authorizes its declared return value. Object grants do not
303
+ filter return values again. Affected receipt IDs are separately checked against the
304
+ base object policy: unconditional and primary-key/context-only grants can prove
305
+ visibility without a read; other rules use a policy-filtered read. Unproven IDs become
306
+ coarse type invalidations, without changing a committed action's success.
307
+
308
+ This projects stateless operations. Privileged replica-state access also exposes
309
+ outbox parameters and confirmed base, so it requires an explicitly trusted,
310
+ principal-bound source; this wrapper does not automatically secure that protocol.
311
+
312
+ ## Replica-state Effect RPC
313
+
314
+ The separate `./rpc` export defines typed client sessions, selected state reads,
315
+ ordered actions, applied acknowledgments, demand leases and invalidation streams.
316
+ It accepts `replicaStateSource(replica)` from an intermediate Replica. Authoritative
317
+ servers use the ordinary committed backend contract instead of speculative state.
318
+
319
+ `./rpc/http` composes the same contract with Fetch handlers and streaming NDJSON:
320
+
321
+ ```ts
322
+ import { makeOntologyHttpHandler } from "@party-stack/ontology-server/rpc/http";
323
+
324
+ // Inside the server's scoped Effect program:
325
+ const handleRequest =
326
+ yield *
327
+ makeOntologyHttpHandler({
328
+ backend: upstream,
329
+ source: replicaStateSource(replica),
330
+ ir,
331
+ authorize: authorizeRequest,
332
+ });
333
+ // Mount handleRequest at a dedicated HTTP route.
334
+ ```
335
+
336
+ ```ts
337
+ import { makeOntologyHttpClient } from "@party-stack/ontology-server/rpc/http";
338
+ import { Effect } from "effect";
339
+ import { FetchHttpClient } from "effect/http";
340
+
341
+ // Inside the client's scoped Effect program:
342
+ const client =
343
+ yield *
344
+ makeOntologyHttpClient({ url: "https://example.test/ontology/rpc" }).pipe(
345
+ Effect.provide(FetchHttpClient.layer)
346
+ );
347
+ // makeLiveOntology({ ir, client: Effect.succeed(client) }) composes
348
+ // the correct replica path with normal local row and blob storage.
349
+ ```
350
+
351
+ The HttpClient service supplies authentication/fetch behavior; its Layer constructs
352
+ that service. The surrounding Scope owns client/server fibers and subscription
353
+ leases. Cancelling a demand releases it; reconnecting a change stream invalidates
354
+ the view so missed hints are repaired. Incremental `SubscribeState` owns upstream
355
+ demand for its selected subsets; there is no parallel `Demand` RPC in that path.
356
+ Committed `SubscribeSelection` owns demand in the same way. The snapshot strategy
357
+ uses separate demand leases with finite state reads. Rich storage values retain their representation
358
+ through the shared codec.
359
+
360
+ Snapshot demand leases are streams: the first element confirms acquisition and later
361
+ failures remain observable. The protocol client performs one attempt; Replica's
362
+ shared watch supervisor owns retry/backoff, retry-after deadlines and credential
363
+ reactivation. Demand failures appear in `status.get.demands[].watchError`; failures
364
+ of the shared change-hint stream appear in `status.get.watchError`. Terminal failures
365
+ stop retrying, and closing the consumer closes its lease. A local parent remains
366
+ reachable independently of the device's upstream network status.
367
+
368
+ Authorization is mandatory per operation. Sources must belong to the authenticated
369
+ principal's partition. Ordinary owned/cached-proxy delivery sends selected committed
370
+ snapshots followed by atomic patches; the replica role also transfers speculative
371
+ state and action handoff. Returned-state projection for untrusted speculative clients
372
+ remains future work. Delivery resumes from a stored acknowledged position while
373
+ history remains available; expired history requires a snapshot without discarding
374
+ pending actions. Protocol children use normal local
375
+ row/blob retention, metadata pushdown and streaming cold-cache byte reads.
376
+
377
+ ## Worker transport
378
+
379
+ `./rpc/worker` uses Effect's platform worker services, without a generic service/
380
+ method envelope. Supply the browser platform Layer on each side:
381
+
382
+ ```ts
383
+ import * as BrowserWorker from "@effect/platform-browser/BrowserWorker";
384
+ import { makeOntologyWorkerClient } from "@party-stack/ontology-server/rpc/worker";
385
+
386
+ // Inside the tab's long-lived scoped program:
387
+ const source = yield * makeOntologyWorkerClient().pipe(Effect.provide(BrowserWorker.layer(() => worker)));
388
+ ```
389
+
390
+ ```ts
391
+ import * as BrowserWorkerRunner from "@effect/platform-browser/BrowserWorkerRunner";
392
+ import { serveOntologyWorker } from "@party-stack/ontology-server/rpc/worker";
393
+ import { Fiber } from "effect";
394
+
395
+ // Inside the owning worker's scoped program:
396
+ const server =
397
+ yield *
398
+ serveOntologyWorker({ source, authorize, enableRealtime: true }).pipe(
399
+ Effect.provide(BrowserWorkerRunner.layer)
400
+ );
401
+ yield * Fiber.join(server);
402
+ ```
403
+
404
+ The server fiber is owned by the calling Scope. Separate port servers may also use
405
+ `BrowserWorkerRunner.layerMessagePort(port)` with the same source. Closing a client
406
+ releases its streams without closing other clients or deleting accepted work.
407
+ The client handshake has a configurable timeout; startup failure can select an
408
+ explicit fallback before constructing the tab Replica. An active Replica must not
409
+ silently switch to a new source after submitting work.
410
+
411
+ ## Public API and migration
412
+
413
+ The deprecated per-operation HTTP endpoints and their Promise transport/client
414
+ wrappers have been removed. The package root exports `makeOntologyServer` and its
415
+ options. `./client` exports the native scoped LiveOntology client composition;
416
+ `./rpc`, `./rpc/http` and `./rpc/worker` expose Effect RPC bindings. The old `./http`
417
+ and `./server` exports no longer exist.
418
+
419
+ Use `makeOntologyServer` for owned/proxy/cached-proxy/replica roles, and
420
+ `makeOntologyHttpClient` or `makeOntologyHttpBackend` from `./rpc/http` for HTTP
421
+ clients. Native HTTP supports NDJSON subscriptions and streaming multipart action
422
+ uploads. Worker clients use `makeOntologyWorkerClient` with their platform Layer.
423
+ Describe provides the projected IR and shared context for dynamic clients.
424
+
425
+ Effect RPC preserves the common `BackendError` schema from ontology-backend.
426
+ There is no separate RemoteOntologyError envelope or legacy JSON parser.
427
+
428
+ ## Live view helpers
429
+
430
+ Connections additionally expose `.operations`: query functions, full/draft action
431
+ validation, attachment creation/metadata/bytes, owner outbox controls and trace
432
+ subscriptions. Supplying a native `replica` enables its local operations; data/action
433
+ capabilities come from `backend`. They use named, schema-validated RPCs and mandatory per-call
434
+ authorization. Servers supplying a `backend` also expose authorized stateless
435
+ subset reads, action commits and optional journal reads, without session allocation.
436
+
437
+ Trace snapshots use a sliding buffer and are subscribed only while the consumer
438
+ asks for them. Attachment downloads stream metadata followed by bounded byte frames.
439
+ Describe reports attachment access/staging and decryption capabilities; a protocol
440
+ backend does not manufacture absent capabilities or staging for read-only attachments.
441
+
442
+ The HTTP binding uses the same configured Effect HttpClient for RPC and binary IO.
443
+ Standalone attachment creation sends one streamed binary POST to the mounted URL;
444
+ actions carrying new bytes send a streamed multipart POST containing the portable
445
+ action request and files associated by attachment ID. Actions without new bytes
446
+ remain ordinary RPCs. A stateless proxy can consume those file streams directly in
447
+ its native backend's applyAction, without a staging registry or disk. The last file's
448
+ EOF is withheld until the complete multipart envelope and final authorization pass,
449
+ so provider action dispatch cannot precede upload validation. Files/metadata have
450
+ explicit per-request limits. HTTP does not use the multi-call chunk upload RPC.
451
+
452
+ Worker/MessagePort bindings use ordered, acknowledged 64 KiB chunk calls beneath a
453
+ scoped response stream. This host-local upload registry is bounded and expires on
454
+ idle/total deadlines; it is not a durable resumable session. Every chunk checks its
455
+ connection and authenticated upload owner. Full authorization runs on opening and
456
+ completion, rather than on every chunk. Closing the owning stream cancels incomplete
457
+ writes. Configure attachmentTransfers.uploadOwner for custom authentication or a
458
+ form/revision-scoped identity; the default fingerprints authorization/cookie headers.
459
+ Limits live under attachmentTransfers.limits (maxBytes, maxConcurrent, maxPerOwner,
460
+ maxReservedBytes, idleTimeoutMs, maxDurationMs). HTTP uses the size/deadline settings
461
+ per request; connection/owner admission applies to the message transport's host.
462
+
463
+ Both transports call the same attachment writer and native action executor. Owned
464
+ storage accepts one-shot bytes into its final byte store before fingerprinting or
465
+ committing rows; an intermediate replica needs its local attachment storage before
466
+ accepting uploads into an outbox. Parameters/outboxes persist attachment handles,
467
+ not stream objects. Provider-specific ID mappings return in the action receipt.
468
+ The application Blob convenience and memory store have explicit buffering limits;
469
+ the streaming storage/provider paths do not assemble a whole-file Blob.
470
+
471
+ Optional `ready` gates Describe and helper requests while a worker restores its
472
+ installation. Bootstrap failures retain their typed BackendError. Neither local
473
+ data deletion nor owner release is enabled by supplying a LiveOntology: those
474
+ require explicit `deleteLocalData` / `releaseOwner` callbacks and authorization.
475
+ Deletion acknowledgment and the optional owner-release notification are separate
476
+ so a transport failure during shutdown cannot turn an acknowledged deletion into
477
+ a reported deletion failure.
478
+
479
+ HTTP and MessagePort bindings do not schedule backend maintenance. The owned
480
+ backend's acquisition Scope owns its periodic sweep, or an external owner invokes
481
+ maintenance (the Alchemy DO resource uses its alarm). Mounting another transport
482
+ over the same backend therefore does not start another cleanup loop.
483
+
484
+ ## Framework Web handlers
485
+
486
+ `@party-stack/ontology-server/http` exports `OntologyHttpServer.layer(open)` and
487
+ `toWebHandler(layer)`. The latter uses Effect's native Web-handler Layer bridge
488
+ and returns `{ handler, dispose }`. The Layer owns backend resources and
489
+ maintenance; request/response scopes own active RPC and byte streams. Abort before
490
+ response headers cancels the RPC. Dispose the owner during shutdown or HMR.
491
+
492
+ Mount `handler(request)` in TanStack Start or export it as Next.js GET/POST. The
493
+ same handler signature fits a Worker with a Worker-compatible backend; a Node
494
+ SQLite Layer itself is not portable. See the [server guide](../../apps/website/content/docs/server.mdx).
@@ -0,0 +1,15 @@
1
+ import { OntologyOperationOptions, ProtocolAttachments } from "./operations.js";
2
+ import { ActionRequest, BackendError } from "@party-stack/ontology-backend";
3
+ import { Effect, Scope } from "effect";
4
+ import { HttpClient } from "effect/http";
5
+ //#region src/attachmentHttp.d.ts
6
+ export declare const isAttachmentHttpRequest: (request: Request) => boolean;
7
+ /** Byte bodies stay on one HTTP request. No upload registry or cross-request affinity is required. */
8
+ export declare const makeAttachmentHttpHandler: <R>(options: OntologyOperationOptions<R>) => Effect.Effect<(request: Request) => Promise<Response>, never, R | Scope.Scope>;
9
+ /** The HTTP transport shares its configured Effect HttpClient (credentials, tracing, cancellation). */
10
+ export declare const makeHttpAttachmentClient: (url: string) => Effect.Effect<{
11
+ readonly create: ProtocolAttachments["create"];
12
+ readonly applyAction: (request: ActionRequest) => Effect.Effect<import("@party-stack/ontology-backend").ActionReceipt, BackendError>;
13
+ }, never, HttpClient.HttpClient | Scope.Scope>;
14
+ //#endregion
15
+ //# sourceMappingURL=attachmentHttp.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachmentHttp.d.ts","names":[],"sources":["../src/attachmentHttp.ts"],"mappings":";;;;;qBAqDa,0BAAuB,SAAa;;qBAMpC,4BAAyD,GAAC,SAAA,yBAAA,OAAA,OAAA,QAAA,SA4LlD,YAAO,QAAA,kBAAA,IAAA,MAAA;;qBA6Df,2BAAwB,gBAAA,OAAA;WAEZ,QAAA;WACK,cAClB,SAAS,kBACR,OAAO,+CAA+C,eAAe;UAuFhF,WAAA,aAAA,MAAA"}