@voltro/runtime 0.85.0 → 0.87.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 (184) hide show
  1. package/CHANGELOG.md +5987 -0
  2. package/README.md +43 -0
  3. package/THIRD-PARTY-NOTICES.md +864 -253
  4. package/dist/aggregate.js +42 -0
  5. package/dist/aggregateExtrema.js +80 -0
  6. package/dist/aggregateIvm.js +115 -0
  7. package/dist/analyticsMirror.js +228 -0
  8. package/dist/analyticsSink.js +32 -0
  9. package/dist/apiKeyUsage.js +33 -0
  10. package/dist/apiKeys.js +227 -0
  11. package/dist/apiKeysWiring.js +114 -0
  12. package/dist/apiRoleBucketSampler.js +64 -0
  13. package/dist/apiRoleWorkloadHistory.js +56 -0
  14. package/dist/apiRoleWorkloadMetrics.js +78 -0
  15. package/dist/apiRoleWorkloadStorage.js +95 -0
  16. package/dist/approvalBuiltins.js +10 -0
  17. package/dist/approvals.js +262 -0
  18. package/dist/authMiddlewareLayer.js +48 -0
  19. package/dist/bindEvent.js +92 -0
  20. package/dist/bootListener.js +143 -0
  21. package/dist/bootRefusal.js +7 -0
  22. package/dist/bootStoreCodec.js +71 -0
  23. package/dist/businessRules.js +67 -0
  24. package/dist/changeClaimsTable.js +12 -0
  25. package/dist/circuitBreaker.js +1 -0
  26. package/dist/columnOnUpdate.js +23 -0
  27. package/dist/composeAnalytics.js +129 -0
  28. package/dist/computedQuery.js +4 -0
  29. package/dist/computedQueryCache.js +231 -0
  30. package/dist/connectionBuiltins.js +81 -0
  31. package/dist/connectionCredentials.js +66 -0
  32. package/dist/connectionState.js +34 -0
  33. package/dist/connectionVault.js +410 -0
  34. package/dist/connectionsFacade.js +56 -0
  35. package/dist/coordinatedSchedule.js +145 -0
  36. package/dist/crdtHistory.js +138 -0
  37. package/dist/crdtMerge.js +179 -0
  38. package/dist/crdtVersionsTable.js +25 -0
  39. package/dist/credentialBound.js +12 -0
  40. package/dist/crud.js +72 -0
  41. package/dist/dataStore.js +712 -0
  42. package/dist/dataloader.js +61 -0
  43. package/dist/declaredTablesGuard.js +49 -0
  44. package/dist/defineExecutor.js +4 -0
  45. package/dist/dependencyGraph.js +32 -0
  46. package/dist/devices.js +228 -0
  47. package/dist/devicesWiring.js +168 -0
  48. package/dist/dialectReplicationAdapter.js +29 -0
  49. package/dist/dispatcher.js +522 -0
  50. package/dist/effectStore.js +71 -0
  51. package/dist/engineClients.js +24 -0
  52. package/dist/eventBus.js +260 -0
  53. package/dist/eventPublish.js +49 -0
  54. package/dist/events.js +193 -0
  55. package/dist/expectation.js +52 -0
  56. package/dist/expectationEvaluator.js +308 -0
  57. package/dist/experiment.js +96 -0
  58. package/dist/experimentEvaluator.js +245 -0
  59. package/dist/externalizedTasks.js +38 -0
  60. package/dist/fieldCipher.js +130 -0
  61. package/dist/fieldKeyRegistry.js +295 -0
  62. package/dist/fieldKeyRekey.js +286 -0
  63. package/dist/fieldKeyScan.js +136 -0
  64. package/dist/fieldKeyring.js +77 -0
  65. package/dist/fingerprint.js +21 -0
  66. package/dist/finops.js +42 -0
  67. package/dist/finopsAccountant.js +216 -0
  68. package/dist/handlerBody.js +8 -0
  69. package/dist/healthProbes.js +55 -0
  70. package/dist/hot.d.ts +56 -0
  71. package/dist/hot.js +3 -0
  72. package/dist/hotDataStore.js +148 -0
  73. package/dist/hotDataStoreSnapshot.js +98 -0
  74. package/dist/hotDataStoreTables.js +18 -0
  75. package/dist/http-range.d.ts +53 -0
  76. package/dist/http-range.js +52 -0
  77. package/dist/httpClientSsrf.js +24 -0
  78. package/dist/httpClientTracing.js +14 -0
  79. package/dist/httpCompression.js +76 -0
  80. package/dist/httpInputStream.js +82 -0
  81. package/dist/httpKeepAlive.js +12 -0
  82. package/dist/httpRouteMounts.js +48 -0
  83. package/dist/idempotencyStore.js +110 -0
  84. package/dist/idleDetector.js +21 -0
  85. package/dist/index.d.ts +1249 -517
  86. package/dist/index.js +155 -15292
  87. package/dist/insertRequiredColumns.js +19 -0
  88. package/dist/inspectWorkflow.js +1 -0
  89. package/dist/instanceMembership.js +98 -0
  90. package/dist/ivm.js +125 -0
  91. package/dist/kvDataStore.js +86 -0
  92. package/dist/kvFacade.js +38 -0
  93. package/dist/matcher.js +304 -0
  94. package/dist/memoryColumnDefaults.js +11 -0
  95. package/dist/memoryQueryJoins.js +114 -0
  96. package/dist/memorySetOperations.js +43 -0
  97. package/dist/metrics.js +175 -0
  98. package/dist/observability.js +123 -0
  99. package/dist/observedGraph.js +52 -0
  100. package/dist/originGuard.js +116 -0
  101. package/dist/outbox.js +352 -0
  102. package/dist/pluginRefRules.js +65 -0
  103. package/dist/policyGuardResolver.js +55 -0
  104. package/dist/preview.js +62 -0
  105. package/dist/projectedRows.js +12 -0
  106. package/dist/provenance.js +63 -0
  107. package/dist/rangeIndex.js +89 -0
  108. package/dist/rawReadScope.js +17 -0
  109. package/dist/reaction.js +85 -0
  110. package/dist/reactiveConfig.js +11 -0
  111. package/dist/readClassification.js +57 -0
  112. package/dist/readRecorder.js +67 -0
  113. package/dist/readScopePredicate.js +12 -0
  114. package/dist/rebac.js +104 -0
  115. package/dist/rebacInterceptor.js +81 -0
  116. package/dist/registry.js +29 -0
  117. package/dist/relevantFields.js +65 -0
  118. package/dist/replicaHealth.js +42 -0
  119. package/dist/replicaLocality.js +44 -0
  120. package/dist/replicaObservations.js +121 -0
  121. package/dist/replicaSelection.js +32 -0
  122. package/dist/replicatedDataStore.js +257 -0
  123. package/dist/requestLoader.js +7 -0
  124. package/dist/resumeCensus.js +28 -0
  125. package/dist/revalidation.js +22 -0
  126. package/dist/rowFilter.js +82 -0
  127. package/dist/rowStateBytes.js +45 -0
  128. package/dist/rpcBodyCap.js +63 -0
  129. package/dist/rpcConnections.js +83 -0
  130. package/dist/rpcDefectDiagnostics.js +15 -0
  131. package/dist/rpcServer.js +1065 -0
  132. package/dist/rpcWorkloadAdmission.js +50 -0
  133. package/dist/runAsSystem.js +23 -0
  134. package/dist/rywPositionStore.js +119 -0
  135. package/dist/schedule.js +23 -0
  136. package/dist/scheduleBackfillRequests.js +151 -0
  137. package/dist/scheduleClaimsTable.js +11 -0
  138. package/dist/scheduleRunsTable.js +37 -0
  139. package/dist/scheduler.js +840 -0
  140. package/dist/schemaRegistry.js +65 -0
  141. package/dist/secretsResolver.js +35 -0
  142. package/dist/securityHeaders.js +33 -0
  143. package/dist/servePipeline.js +374 -0
  144. package/dist/serverOnlyAudit.js +66 -0
  145. package/dist/serverTracer.js +15 -0
  146. package/dist/serviceCredentials.js +40 -0
  147. package/dist/setReadScopes.js +28 -0
  148. package/dist/singleNodeOrchestrator.js +91 -0
  149. package/dist/snapshotValueCodec.js +46 -0
  150. package/dist/sourceResolution.js +52 -0
  151. package/dist/storeMiddleware.js +882 -0
  152. package/dist/storeQuery.js +204 -0
  153. package/dist/storeRead.js +10 -0
  154. package/dist/subscriber.js +8 -0
  155. package/dist/subscriptionOutbox.js +139 -0
  156. package/dist/subscriptionRegistry.js +82 -0
  157. package/dist/subscriptionResume.js +132 -0
  158. package/dist/subscriptionSocketMetrics.js +65 -0
  159. package/dist/systemSubject.js +5 -0
  160. package/dist/tenantScope.js +11 -0
  161. package/dist/tenantSelection.js +27 -0
  162. package/dist/timeline.js +105 -0
  163. package/dist/traceContext.js +5 -0
  164. package/dist/traceSink.js +63 -0
  165. package/dist/traceSpansTable.js +29 -0
  166. package/dist/traceparent.js +23 -0
  167. package/dist/transactionSubject.js +12 -0
  168. package/dist/trustedProxy.js +155 -0
  169. package/dist/undo.js +129 -0
  170. package/dist/undoBuiltins.js +69 -0
  171. package/dist/undoCapture.js +74 -0
  172. package/dist/undoLogTable.js +16 -0
  173. package/dist/upsertBinding.js +20 -0
  174. package/dist/wakeOrchestrator.js +34 -0
  175. package/dist/wakeRegistry.js +71 -0
  176. package/dist/wakeRouter.js +63 -0
  177. package/dist/wakeSupervisor.js +62 -0
  178. package/dist/wakeupsTable.js +12 -0
  179. package/dist/webSocketGatewayRuntime.js +154 -0
  180. package/dist/webhookVerification.js +18 -0
  181. package/dist/wireColumnStrip.js +84 -0
  182. package/dist/workflowReadBuiltins.js +87 -0
  183. package/dist/workflowRuntime.js +708 -0
  184. package/package.json +19 -7
@@ -0,0 +1,1065 @@
1
+ import { crdtFoldCell as e, crdtIncrementalCell as t } from "./crdtMerge.js";
2
+ import { resolveDependentTables as n } from "./dependencyGraph.js";
3
+ import { buildSubjectKey as r } from "./rywPositionStore.js";
4
+ import { runWithRoutingContext as i, runWithRoutingContextEffect as a } from "./replicatedDataStore.js";
5
+ import { makeDefaultRefilter as o, rowFilterMayNarrow as s } from "./rowFilter.js";
6
+ import { captureRpcWorkloadAdmission as c, selectRpcWorkloadGroup as l } from "./rpcWorkloadAdmission.js";
7
+ import { applyKeepAlive as u, resolveKeepAlive as d } from "./httpKeepAlive.js";
8
+ import { rpcFrameDefects as f } from "./rpcDefectDiagnostics.js";
9
+ import { makeHttpRouteGroupFinder as p, makeUnmatchedGroupFinder as m, planHttpRouteMounts as h } from "./httpRouteMounts.js";
10
+ import { isComputedQuery as g } from "./computedQuery.js";
11
+ import { registerConnectionStream as _ } from "./connectionCredentials.js";
12
+ import { getRpcConnection as v, withRpcClientAddress as y, withRpcConnectionIdentity as b } from "./rpcConnections.js";
13
+ import { makeSubscriptionOutbox as x, pumpOutbox as S, reactiveSocketTunables as C } from "./subscriptionOutbox.js";
14
+ import { adoptDetached as ee, canonicalInputKey as te, detachForResume as ne, recordForResume as re } from "./subscriptionResume.js";
15
+ import { externalSpanFromTraceparent as ie, newTraceId as w, parseTraceparent as T } from "./traceparent.js";
16
+ import { runWithTraceContext as E } from "./traceContext.js";
17
+ import { runWithObservedProcedure as D } from "./observedGraph.js";
18
+ import { actingUserId as O } from "./storeMiddleware.js";
19
+ import { readCappedBody as ae, withBufferedBody as oe } from "./rpcBodyCap.js";
20
+ import { dispatchHttpInputStream as se } from "./httpInputStream.js";
21
+ import { maybeCompress as ce, mergeCompressionHeaders as le } from "./httpCompression.js";
22
+ import { runWebSocketGateway as ue } from "./webSocketGatewayRuntime.js";
23
+ import { noteResumeVerdict as de } from "./resumeCensus.js";
24
+ import { publishServerTracerLayer as fe } from "./serverTracer.js";
25
+ import { boundByCredential as pe } from "./credentialBound.js";
26
+ import { classifyRequestOrigin as me, isStateChangingMethod as he, makeOriginGuardExemption as ge, resolveOriginGuardConfig as _e } from "./originGuard.js";
27
+ import { resolveRequestClientAddress as ve, resolveRequestIsHttps as ye, resolveTrustedProxies as be } from "./trustedProxy.js";
28
+ import { resolveSecurityHeaders as xe, securityHeadersFor as Se } from "./securityHeaders.js";
29
+ import { assertWebhookRoutesDeclareVerification as Ce } from "./webhookVerification.js";
30
+ import { Cause as k, Context as we, Deferred as A, Effect as j, Fiber as Te, Layer as M, Queue as N, Schema as P, Stream as F } from "effect";
31
+ import { extractDbCause as Ee, hasEagerLoads as I, runWithWriteAttribution as L } from "@voltro/database";
32
+ import { randomUUID as De } from "node:crypto";
33
+ import { ConnectionInfo as R, MUTATION_IN_FLIGHT_RETRY_AFTER_MS as Oe, MutationConnectionRequired as z, MutationIdempotencyRefused as ke, MutationInFlight as Ae, SubjectService as je, Unauthenticated as Me, beginIdempotent as Ne, currentSubjectAuthority as Pe, defineWebSocket as Fe, failIdempotent as Ie, finishIdempotent as Le, groupShapeDigests as Re, holdIdempotentClaim as ze, prepareIdempotentInput as Be, recheckGuardsEffect as Ve, validateHttpStreamMaxDuration as He, wsMutationIdempotencyScope as Ue } from "@voltro/protocol";
34
+ import { LoggerLayer as We, createLogger as B } from "@voltro/logger";
35
+ import { RpcSerialization as Ge, RpcServer as V } from "effect/rpc";
36
+ import { Server as Ke, createServer as qe } from "node:http";
37
+ import { HttpRouter as H, HttpServer as Je, HttpServerError as Ye, HttpServerRequest as U, HttpServerResponse as W } from "effect/http";
38
+ import { NodeHttpServer as Xe, NodeHttpServerRequest as Ze, NodeServices as Qe } from "@effect/platform-node";
39
+ import { dispatchSharedPath as $e, restCorsHeaders as et, restCorsPreflight as tt, routeAcceptsPath as nt } from "@voltro/protocol/rest";
40
+ import { instanceId as rt, replicaId as it } from "@voltro/protocol/identity";
41
+ //#region src/rpcServer.ts
42
+ var at = (e) => {
43
+ let t = e.indexOf(".");
44
+ if (t <= 0) return;
45
+ let n = e.slice(0, t), r = e.slice(t + 1);
46
+ if (r !== "" && r.includes(".")) {
47
+ if (n === "subscription") return {
48
+ tag: r,
49
+ kind: "query"
50
+ };
51
+ if (n === "query" || n === "mutation" || n === "action" || n === "stream") return {
52
+ tag: r,
53
+ kind: n
54
+ };
55
+ }
56
+ }, G = (e, t) => {
57
+ let n = at(e);
58
+ return n === void 0 ? t() : D(n, t);
59
+ }, ot = (e, t, n, r) => e === "subject" ? `${t}:s:${n}` : e === "global" ? `${t}:global` : r.tenantId == null ? void 0 : `${t}:t:${r.tenantId}`, st = We({}), K = (e, t) => j.callback((n) => {
60
+ let r = L(t, () => j.runFork(e.pipe(j.provide(st))));
61
+ return r.addObserver((e) => {
62
+ n(e);
63
+ }), j.asVoid(Te.interrupt(r));
64
+ }), ct = (e, t, n, r) => {
65
+ let i = n === void 0 ? void 0 : v(n);
66
+ return {
67
+ subject: e,
68
+ traceId: t?.traceId ?? w(),
69
+ ...r === void 0 ? {} : { cookieHeader: r },
70
+ ...t?.spanId === void 0 ? {} : { spanId: t.spanId },
71
+ ...n === void 0 ? {} : { clientId: n },
72
+ ...i === void 0 ? {} : { connection: i },
73
+ ...i?.remoteAddr === void 0 ? {} : { remoteAddr: i.remoteAddr }
74
+ };
75
+ }, lt = j.currentSpan.pipe(j.catch(() => j.succeed(void 0))), ut = (e) => ({
76
+ traceId: e.traceId,
77
+ ...e.spanId === void 0 ? {} : { spanId: e.spanId }
78
+ }), dt = (e, t, n) => {
79
+ e !== void 0 && (e.attribute("rpc.tag", t), e.attribute("subject.type", n.type), n.tenantId !== void 0 && n.tenantId !== null && e.attribute("tenant.id", n.tenantId));
80
+ }, ft = (e) => o(e, (e) => {
81
+ J.error("row filter failed to load — subscription", {}, e instanceof Error ? e : Error(String(e)));
82
+ }), q = (e) => ({
83
+ single: (t) => j.runPromise(N.offer(e, t)),
84
+ end: () => N.endUnsafe(e)
85
+ }), pt = (r, i, a, o, c, l, u, d, f, p) => F.callback((m) => j.gen(function* () {
86
+ let h = f ?? C(), g = i.crdtColumnsFor(r.table), v = x({
87
+ maxBufferedBytes: h.maxBufferedBytes,
88
+ overrunAfterMs: h.overrunAfterMs,
89
+ oversizedEventBytes: h.oversizedEventBytes,
90
+ label: c,
91
+ ...g.size > 0 ? { crdt: {
92
+ columns: g,
93
+ merge: e,
94
+ incremental: t
95
+ } } : {}
96
+ });
97
+ yield* j.addFinalizer(() => j.sync(() => v.close()));
98
+ let y = s([...n(r)]), b = d !== void 0 && (I(r) || y), ie = p !== void 0 && !b, w = ie ? te(p.input) : "unused", T = ie && w !== "uncanonical" ? {
99
+ label: c,
100
+ inputKey: w,
101
+ subjectId: a.subject.id ?? "anonymous",
102
+ tenantId: a.subject.tenantId ?? ""
103
+ } : void 0;
104
+ de(c, p === void 0 ? "not-offered" : b ? y ? "row-filter" : "eager-load" : w !== "uncanonical" || "uncanonical-input");
105
+ let E = { current: (e) => {
106
+ T !== void 0 && re(T, e), v.push(e);
107
+ } };
108
+ if (T !== void 0 && p?.fromRevision !== void 0 && p.reconcile === void 0) {
109
+ let e = u !== void 0 && (yield* j.tryPromise(() => u()).pipe(j.match({
110
+ onFailure: () => !0,
111
+ onSuccess: (e) => !!e
112
+ }))) ? void 0 : ee(T, p.fromRevision);
113
+ if (e !== void 0) {
114
+ for (let t of e.deltas) v.push({
115
+ _tag: "delta",
116
+ revision: t.revision,
117
+ emittedAt: t.emittedAt,
118
+ patch: t.patch
119
+ });
120
+ e.sink.current = E.current;
121
+ let t = e.unsubscribe;
122
+ if (yield* j.addFinalizer(() => j.sync(() => {
123
+ e.sink.current = () => {}, ne(T, {
124
+ sink: e.sink,
125
+ unsubscribe: t
126
+ });
127
+ })), yield* j.forkScoped(j.promise(() => S(v, q(m), c))), a.clientId !== void 0) {
128
+ let e = _(a.clientId, () => {
129
+ N.endUnsafe(m);
130
+ });
131
+ yield* j.addFinalizer(() => j.sync(() => e()));
132
+ }
133
+ return;
134
+ }
135
+ }
136
+ let D = yield* j.tryPromise(() => i.subscribe(r, (e) => {
137
+ E.current(e);
138
+ }, a, o, c, p?.reconcile === void 0 ? l : void 0, u, d, p?.reconcile !== void 0)).pipe(j.matchCause({
139
+ onFailure: (e) => (X(`subscription.${c}`, a.traceId, e), {
140
+ ok: !1,
141
+ error: Tt(e)
142
+ }),
143
+ onSuccess: (e) => ({
144
+ ok: !0,
145
+ unsubscribe: e
146
+ })
147
+ }));
148
+ if (!D.ok) {
149
+ N.offerUnsafe(m, {
150
+ _tag: "error",
151
+ error: D.error
152
+ }), N.endUnsafe(m);
153
+ return;
154
+ }
155
+ let O = D.unsubscribe;
156
+ if (yield* j.addFinalizer(() => j.sync(() => {
157
+ T === void 0 ? O() : (E.current = () => {}, ne(T, {
158
+ sink: E,
159
+ unsubscribe: O
160
+ }));
161
+ })), yield* j.forkScoped(j.promise(() => S(v, q(m), c))), a.clientId !== void 0) {
162
+ let e = _(a.clientId, () => {
163
+ N.endUnsafe(m);
164
+ });
165
+ yield* j.addFinalizer(() => j.sync(() => e()));
166
+ }
167
+ }), { bufferSize: 1 }), mt = (e, t, n, r, i) => F.callback((a) => j.gen(function* () {
168
+ let o = i ?? C(), s = x({
169
+ maxBufferedBytes: o.maxBufferedBytes,
170
+ overrunAfterMs: o.overrunAfterMs,
171
+ oversizedEventBytes: o.oversizedEventBytes,
172
+ label: r
173
+ });
174
+ yield* j.addFinalizer(() => j.sync(() => s.close()));
175
+ let c = yield* j.tryPromise(() => t.subscribeComputed(e, (e) => {
176
+ s.push(e._tag === "snapshot" ? {
177
+ ...e,
178
+ computed: !0
179
+ } : e);
180
+ }, n, r)).pipe(j.matchCause({
181
+ onFailure: (e) => (X(`subscription.${r}`, n.traceId, e), {
182
+ ok: !1,
183
+ error: Tt(e)
184
+ }),
185
+ onSuccess: (e) => ({
186
+ ok: !0,
187
+ unsubscribe: e
188
+ })
189
+ }));
190
+ if (!c.ok) {
191
+ N.offerUnsafe(a, {
192
+ _tag: "error",
193
+ error: c.error
194
+ }), N.endUnsafe(a);
195
+ return;
196
+ }
197
+ let l = c.unsubscribe;
198
+ if (de(r, "computed"), yield* j.addFinalizer(() => j.sync(() => l())), yield* j.forkScoped(j.promise(() => S(s, q(a), r))), n.clientId !== void 0) {
199
+ let e = _(n.clientId, () => {
200
+ N.endUnsafe(a);
201
+ });
202
+ yield* j.addFinalizer(() => j.sync(() => e()));
203
+ }
204
+ }), { bufferSize: 1 }), ht = (e, t, n = "rpc.subscription", o, s, c, l) => F.unwrap(j.gen(function* () {
205
+ let u = yield* je, d = yield* R, f = (e) => {
206
+ let t = F.make({
207
+ _tag: "error",
208
+ error: new Me({ reason: "The session has expired. Sign in again." })
209
+ });
210
+ return pe(e, d.credentialExpiresAt, t, t);
211
+ }, p = yield* lt;
212
+ dt(p, n, u);
213
+ let m = ct(u, p, d.clientId, d.cookieHeader), h = r(u.id, d.clientId), _ = {
214
+ subjectKey: h,
215
+ ...d.reconcile === void 0 ? {} : { forcePrimary: !0 }
216
+ }, v = i(_, () => E({
217
+ traceId: m.traceId,
218
+ ...m.spanId === void 0 ? {} : { spanId: m.spanId }
219
+ }, () => G(n, () => e(m)))), y = j.isEffect(v) ? yield* a(_, v).pipe(j.matchCause({
220
+ onFailure: (e) => (X(`subscription.${n}`, m.traceId, e), {
221
+ ok: !1,
222
+ error: Tt(e)
223
+ }),
224
+ onSuccess: (e) => ({
225
+ ok: !0,
226
+ value: e
227
+ })
228
+ })) : {
229
+ ok: !0,
230
+ value: v
231
+ };
232
+ if (!y.ok) return F.make({
233
+ _tag: "error",
234
+ error: y.error
235
+ });
236
+ let b = y.value;
237
+ if (g(b)) return f(gt(mt(d.reconcile === void 0 ? b : {
238
+ ...b,
239
+ recompute: () => i(_, b.recompute)
240
+ }, t, m, n), d.reconcile));
241
+ let x = b, S = o?.(x), C = s === void 0 ? void 0 : ot(s.scope, s.baseKey, h, u);
242
+ return f(gt(pt(x, t, m, S, n, s === void 0 || C === void 0 ? void 0 : {
243
+ key: C,
244
+ ttlMs: s.ttlMs,
245
+ swrMs: s.swrMs,
246
+ label: n.replace(/^subscription\./, "")
247
+ }, c?.(u), l?.(u) ?? ft(u), void 0, {
248
+ input: x,
249
+ ...d.resumeFrom === void 0 ? {} : { fromRevision: d.resumeFrom },
250
+ ...d.reconcile === void 0 ? {} : { reconcile: d.reconcile }
251
+ }), d.reconcile));
252
+ }).pipe(j.withSpan(n, { attributes: { "framework.kind": "subscription" } }))), gt = (e, t) => t === void 0 ? e : e.pipe(F.mapAccum(() => !1, (e, n) => !e && n._tag === "snapshot" ? [!0, [{
253
+ ...n,
254
+ reconciles: t
255
+ }]] : [e, [n]])), _t = (e, t = "rpc.stream", n, r, i) => F.unwrap(j.gen(function* () {
256
+ let a = yield* je, o = yield* R, s = yield* lt;
257
+ dt(s, t, a);
258
+ let c = ct(a, s, o.clientId, o.cookieHeader), l = n ?? [], u = () => Ve(a, l, r), d = j.gen(function* () {
259
+ let n = yield* u();
260
+ if (n) return yield* j.fail(n);
261
+ let r = G(t, () => e(c));
262
+ return j.isEffect(r) ? yield* r : r;
263
+ }), f = yield* (i?.interceptor ? i.interceptor(d, {
264
+ tag: i.tag,
265
+ kind: "stream",
266
+ input: r,
267
+ subject: a,
268
+ traceId: c.traceId,
269
+ ...c.spanId === void 0 ? {} : { spanId: c.spanId },
270
+ ...c.remoteAddr === void 0 ? {} : { remoteAddr: c.remoteAddr }
271
+ }) : d).pipe(j.catchCause((e) => j.succeed(F.failCause(e)))), p = F.flatMap(f, (e) => F.unwrap(u().pipe(j.map((t) => t ? F.fail(t) : F.make(e))))), m = pe(p, o.credentialExpiresAt, F.empty);
272
+ if (c.clientId === void 0) return m;
273
+ let h = c.clientId;
274
+ return F.unwrap(j.gen(function* () {
275
+ let e = yield* A.make(), t = _(h, () => {
276
+ A.doneUnsafe(e, j.void);
277
+ });
278
+ return yield* j.addFinalizer(() => j.sync(() => t())), m.pipe(F.interruptWhen(A.await(e)));
279
+ }));
280
+ }).pipe(j.withSpan(t, { attributes: { "framework.kind": "stream" } }))), J = B({ scope: "voltro:rpc" }), vt = B({ scope: "voltro:http" }), Y = B({ scope: "voltro:shutdown" }), yt = (e) => {
281
+ if (e instanceof Error) {
282
+ let t = e._tag;
283
+ return {
284
+ name: e.name,
285
+ message: e.message,
286
+ ...typeof t == "string" ? { tag: t } : {},
287
+ ...e.stack === void 0 ? {} : { stack: e.stack.split("\n").slice(1, 4).map((e) => e.trim()) }
288
+ };
289
+ }
290
+ if (typeof e == "object" && e) {
291
+ let t = e._tag;
292
+ return {
293
+ ...typeof t == "string" ? { tag: t } : {},
294
+ value: String(e).slice(0, 300)
295
+ };
296
+ }
297
+ return { value: String(e).slice(0, 300) };
298
+ }, X = (e, t, n) => {
299
+ if (k.hasInterruptsOnly(n)) return;
300
+ let r = k.squash(n), i = r?._tag, a = r instanceof Error ? r.message : r?.message ?? String(r), o = k.hasDies(n), s = Ee(r), c = {
301
+ traceId: t,
302
+ ...i === void 0 ? {} : { errorTag: i },
303
+ ...s
304
+ }, l = a === "Failed to execute statement" && typeof s.dbMessage == "string" ? s.dbMessage : a;
305
+ o ? J.error(`${e} failed: ${l}`, c) : J.warn(`${e} failed: ${l}`, c);
306
+ }, bt = /* @__PURE__ */ new Set([
307
+ "SqlError",
308
+ "ResultLengthMismatch",
309
+ "FieldDecryptionError"
310
+ ]), Z = (e) => typeof e == "object" && !!e && typeof e._tag == "string" && bt.has(e._tag), xt = (e, t) => {
311
+ try {
312
+ return P.is(e)(t);
313
+ } catch {
314
+ return !0;
315
+ }
316
+ }, St = /* @__PURE__ */ new Set(), Ct = (e, t) => {
317
+ let n = `${e}\u0000${t}`;
318
+ St.has(n) || (St.size >= 1e3 && St.clear(), St.add(n), J.warn(`${e} failed with '${t}', which is undeclared on its wire union — the client received InternalError instead. Add ${t} to the descriptor's \`error:\`, register it app-wide through a plugin's \`errorSchemas\`, or map it to a declared error (\`Effect.orDie\` if it is a defect). \`defineExecutor\` reports this at compile time.`, {
319
+ procedure: e,
320
+ errorTag: t
321
+ }));
322
+ }, wt = (e, t = "internal server error") => ({
323
+ _tag: "InternalError",
324
+ message: t,
325
+ traceId: e
326
+ }), Q = (e) => {
327
+ let t = e instanceof Error ? e.message : e?.message, n = typeof t == "string" && t.length > 0 ? t : String(e), r = e?._tag, i = typeof r == "string" && r.length > 0 && !n.startsWith(r) ? `${r}: ${n}` : n;
328
+ return i.length <= 500 ? i : `${i.slice(0, 500)}…`;
329
+ }, Tt = (e) => {
330
+ let t = k.squash(e);
331
+ if (t && typeof t == "object" && t._tag === "UnknownError" && (t = t.error ?? t.cause ?? t), Z(t)) return {
332
+ _tag: "InternalError",
333
+ message: "internal server error"
334
+ };
335
+ let n = t && typeof t == "object" ? t : {}, r = {};
336
+ for (let [e, t] of Object.entries(n)) e !== "cause" && e !== "stack" && e !== "message" && (t === null || typeof t == "string" || typeof t == "number" || typeof t == "boolean") && (r[e] = t);
337
+ let i = t?._tag, a = t instanceof Error ? t.message : t?.message;
338
+ return {
339
+ ...r,
340
+ ...typeof i == "string" ? { _tag: i } : {},
341
+ message: typeof a == "string" ? a : String(t)
342
+ };
343
+ }, Et = (e, t, n) => {
344
+ let r = P.encodeUnknownSync(t), i = P.decodeUnknownSync(t);
345
+ return {
346
+ input: e,
347
+ admit: n,
348
+ encode: (e) => {
349
+ try {
350
+ return r(e);
351
+ } catch {
352
+ throw Error("Mutation output cannot be recorded for replay");
353
+ }
354
+ },
355
+ decode: (e) => {
356
+ try {
357
+ return i(e);
358
+ } catch {
359
+ throw Error("Stored mutation response is incompatible with the current output contract");
360
+ }
361
+ }
362
+ };
363
+ }, Dt = (e) => {
364
+ let t = {}, n;
365
+ for (let [r, i] of Object.entries(e ?? {})) Array.isArray(i) ? r.toLowerCase() === "set-cookie" ? n = i : t[r] = i.join(", ") : t[r] = i;
366
+ return {
367
+ headers: t,
368
+ setCookie: n
369
+ };
370
+ }, Ot = (e, t, n = "rpc.mutation", a, o, s, c = "subject") => j.gen(function* () {
371
+ let l = t, u = yield* je, d = yield* R, f = yield* lt;
372
+ dt(f, n, u);
373
+ let p = ct(u, f, d.clientId, d.cookieHeader), m = async () => {
374
+ if (typeof a?.admit != "function") throw Error("Missing current mutation admission");
375
+ await a.admit(l, p);
376
+ }, h = () => j.tryPromise({
377
+ try: m,
378
+ catch: (e) => e
379
+ }), g = c === "connection";
380
+ if (g && (p.connection?.transport !== "websocket" || p.connection.signal.aborted)) return yield* j.fail(new z({ traceId: p.traceId }));
381
+ let _ = o && d.idempotencyKey ? {
382
+ store: o.store,
383
+ ttlMs: o.ttlMs,
384
+ key: d.idempotencyKey,
385
+ scope: Ue(u.tenantId, O(u), n, g ? p.connection?.id : void 0)
386
+ } : null, v = r(u.id, d.clientId), y = {
387
+ traceId: p.traceId,
388
+ subjectId: O(u),
389
+ procedure: n
390
+ }, b = (t = (e) => e) => j.suspend(() => {
391
+ let r = i({ subjectKey: v }, () => E({
392
+ traceId: p.traceId,
393
+ ...p.spanId === void 0 ? {} : { spanId: p.spanId }
394
+ }, () => L(y, () => G(n, () => e(l, {
395
+ ...p,
396
+ subject: Pe(u)
397
+ })))));
398
+ return j.isEffect(r) ? t(K(r, y)) : j.tryPromise({
399
+ try: () => Promise.resolve(r),
400
+ catch: (e) => e
401
+ });
402
+ }), x = !1, S;
403
+ return yield* (_ ? j.acquireUseRelease(j.tryPromise({
404
+ try: async () => {
405
+ let e;
406
+ try {
407
+ if (!a) throw Error("Missing declared mutation codec");
408
+ let n = await Be(a.input, t, u);
409
+ l = n.input, e = n.fingerprint;
410
+ } catch {
411
+ throw new ke({
412
+ traceId: p.traceId,
413
+ reason: "input-unavailable"
414
+ });
415
+ }
416
+ await m();
417
+ let n = await Ne(_.store, _.scope, _.key, e, _.ttlMs, Date.now());
418
+ return n.kind === "fresh" && (S = ze(_.store, n.claim)), n;
419
+ },
420
+ catch: (e) => e
421
+ }), (e) => j.gen(function* () {
422
+ if (yield* j.yieldNow, yield* h(), g && p.connection?.signal.aborted) return yield* j.fail(new z({ traceId: p.traceId }));
423
+ if (e.kind === "replay") {
424
+ if (e.response.status !== 200) throw Error("Stored mutation response is unavailable");
425
+ try {
426
+ return a ? a.decode(e.response.body) : e.response.body;
427
+ } catch {
428
+ throw Error("Stored mutation response is incompatible with the current output contract");
429
+ }
430
+ }
431
+ return e.kind === "input-conflict" || e.kind === "input-unbound" ? yield* j.fail(new ke({
432
+ traceId: p.traceId,
433
+ reason: e.kind
434
+ })) : e.kind === "conflict" ? yield* j.fail(new Ae({
435
+ traceId: p.traceId,
436
+ retryAfterMs: Oe
437
+ })) : yield* j.uninterruptibleMask((t) => t(j.void).pipe(j.flatMap(() => b(t)), j.tap((t) => {
438
+ x = !0;
439
+ let n;
440
+ try {
441
+ n = {
442
+ status: 200,
443
+ body: a ? a.encode(t) : t
444
+ };
445
+ } catch {
446
+ n = {
447
+ status: 500,
448
+ body: null
449
+ };
450
+ }
451
+ return j.promise(async () => {
452
+ try {
453
+ if (!await Le(_.store, e.claim, n, Date.now())) throw Error("Original mutation claim is no longer owned");
454
+ } catch {
455
+ throw Error("Mutation replay receipt could not be retained");
456
+ }
457
+ if (n.status !== 200) throw Error("Mutation output cannot be recorded for replay");
458
+ });
459
+ })));
460
+ }), (e) => j.sync(() => S?.()).pipe(j.andThen(e.kind === "fresh" && !x ? j.promise(() => Ie(_.store, e.claim)).pipe(j.ignore) : j.void))) : a ? h().pipe(j.flatMap(() => b())) : b()).pipe(j.tapCause((e) => j.sync(() => X(n, p.traceId, e))), j.catchIf(Z, () => j.die(wt(p.traceId))), j.catchIf((e) => e instanceof Error && typeof e._tag != "string", (e) => j.die(wt(p.traceId, Q(e)))), j.catchIf((e) => s !== void 0 && typeof e?._tag == "string" && !xt(s, e), (e) => j.sync(() => Ct(n, e._tag)).pipe(j.andThen(j.die(wt(p.traceId, Q(e)))))), j.catchDefect((e) => e?._tag === "InternalError" ? j.die(e) : j.die(wt(p.traceId, Q(e)))), j.annotateLogs(ut(p)));
461
+ }).pipe(j.withSpan(n, { attributes: { "framework.kind": "mutation" } })), kt = 8388608, At = (e) => {
462
+ let t = c(e.workloadAdmission), n = l(e.group, t, "http"), r = l(e.group, t, "websocket"), i = e.port ?? 4e3, a = e.host, o = e.path ?? "/ws", s = o, g = e.replicaId ?? it();
463
+ Ce(e.webhookRoutes);
464
+ let _ = e.listener, x = _?.server ?? qe(), S = /* @__PURE__ */ new Set();
465
+ x.on("connection", (e) => {
466
+ S.add(e), e.once("close", () => {
467
+ S.delete(e);
468
+ });
469
+ }), u(x, d(e));
470
+ let C = (t) => U.HttpServerRequest.pipe(j.flatMap((t) => j.gen(function* () {
471
+ if (!e.inspectRoute) return W.text("inspect route not configured", { status: 404 });
472
+ let n = {};
473
+ for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
474
+ let r = e.inspectRoute, i = r.binary?.[new URL(t.url, "http://inspect.invalid").pathname], a;
475
+ !i && t.method !== "GET" && t.method !== "HEAD" && t.method !== "OPTIONS" && (a = yield* t.text.pipe(j.orElseSucceed(() => "")));
476
+ let o = yield* j.promise(async (e) => {
477
+ if (!i) return r.handle(t.url, n, t.method, a, e);
478
+ let o = F.toReadableStream(t.stream);
479
+ return i(t.url, n, t.method, o, e);
480
+ });
481
+ if (o === null) return W.text("inspect route not found", { status: 404 });
482
+ if (o.byteStream !== void 0) {
483
+ let e = {
484
+ ...o.headers,
485
+ ...o.byteStream.contentLength === void 0 ? {} : { "content-length": String(o.byteStream.contentLength) },
486
+ ...o.byteStream.contentDisposition === void 0 ? {} : { "content-disposition": o.byteStream.contentDisposition }
487
+ };
488
+ if (t.method === "HEAD") return W.empty({
489
+ status: o.status,
490
+ headers: {
491
+ ...e,
492
+ "content-type": o.contentType
493
+ }
494
+ });
495
+ let n = o.byteStream.stream;
496
+ return W.stream(F.fromReadableStream({
497
+ evaluate: () => typeof n == "function" ? n() : n,
498
+ onError: (e) => e
499
+ }), {
500
+ status: o.status,
501
+ contentType: o.contentType,
502
+ headers: e
503
+ });
504
+ }
505
+ return W.text(o.body, {
506
+ status: o.status,
507
+ contentType: o.contentType,
508
+ headers: o.headers ?? {}
509
+ });
510
+ }))), ee = () => U.HttpServerRequest.pipe(j.flatMap((t) => {
511
+ let n = e.inspectStream;
512
+ if (!n) return j.succeed(W.text("inspect stream not configured", { status: 404 }));
513
+ let r = {};
514
+ for (let [e, n] of Object.entries(t.headers)) n !== void 0 && (r[e.toLowerCase()] = Array.isArray(n) ? n.join(", ") : n);
515
+ let i = n.corsHeaders(r.origin);
516
+ if (n.isDisabled()) return j.succeed(W.text(JSON.stringify({ error: "inspect disabled (VOLTRO_INSPECT=off)" }), {
517
+ status: 503,
518
+ contentType: "application/json; charset=utf-8",
519
+ headers: i
520
+ }));
521
+ let a = n.authorize(r);
522
+ return a.ok ? (n.select?.(t.url, r) ?? j.succeed(void 0)).pipe(j.flatMap((e) => {
523
+ if (e?.kind === "stream") return j.succeed(W.stream(e.stream, {
524
+ status: 200,
525
+ headers: {
526
+ ...i,
527
+ "content-type": "text/event-stream; charset=utf-8",
528
+ "cache-control": "no-cache, no-transform",
529
+ "x-accel-buffering": "no"
530
+ }
531
+ }));
532
+ if (e?.kind === "refused") return j.succeed(W.text(JSON.stringify(e.body), {
533
+ status: e.status,
534
+ contentType: "application/json; charset=utf-8",
535
+ headers: i
536
+ }));
537
+ let r = new TextEncoder(), a = n.keepAliveMs ?? 15e3, o = t.url.indexOf("?"), s = o === -1 ? new URLSearchParams() : new URLSearchParams(t.url.slice(o + 1)), c = s.get("live") === "1", l = s.get("channels"), u = l ? new Set(l.split(",").map((e) => e.trim()).filter((e) => e.length > 0)) : void 0, d = (e) => {
538
+ if (!u || e.indexOf("event: ") !== 0) return !0;
539
+ let t = e.indexOf("\n", 7);
540
+ return t < 0 || u.has(e.slice(7, t).trim());
541
+ }, f = F.callback((e) => j.gen(function* () {
542
+ if (N.offerUnsafe(e, r.encode("retry: 5000\n\n")), !c) for (let t of n.replay()) d(t) && N.offerUnsafe(e, r.encode(t));
543
+ let t = n.subscribe((t) => {
544
+ d(t) && N.offerUnsafe(e, r.encode(t));
545
+ }), i = setInterval(() => {
546
+ N.offerUnsafe(e, r.encode(n.keepAlive()));
547
+ }, a);
548
+ yield* j.addFinalizer(() => j.sync(() => {
549
+ clearInterval(i), t();
550
+ }));
551
+ }));
552
+ return j.succeed(W.stream(f, {
553
+ status: 200,
554
+ headers: {
555
+ "content-type": "text/event-stream; charset=utf-8",
556
+ ...n.replicaId ? { "x-voltro-replica-id": n.replicaId } : {},
557
+ "cache-control": "no-cache, no-transform",
558
+ connection: "keep-alive",
559
+ "x-accel-buffering": "no",
560
+ ...i
561
+ }
562
+ }));
563
+ })) : j.succeed(W.text(JSON.stringify({
564
+ error: "unauthorized",
565
+ reason: a.reason
566
+ }), {
567
+ status: 401,
568
+ contentType: "application/json; charset=utf-8",
569
+ headers: i
570
+ }));
571
+ })), te = C(!0), ne = C(!1), re = H.add("*", "/_voltro/inspect/*", U.HttpServerRequest.pipe(j.flatMap((e) => e.url.split("?")[0] === "/_voltro/inspect" ? te : ne))), E = M.empty;
572
+ e.inspectRoute !== void 0 && (E = e.inspectStream === void 0 ? re : M.mergeAll(H.add("GET", "/_voltro/inspect/stream", ee()), re));
573
+ let D = e.publishSurfaceDigest === !0 ? Re(e.group) : void 0, O = e.serviceSurfaceTags ?? /* @__PURE__ */ new Set(), de = (e) => {
574
+ let t = Object.entries(D), n = 0;
575
+ for (let r of t) (e ? O.has(r[0]) : !O.has(r[0])) && (t[n++] = r);
576
+ return t.length = n, Object.fromEntries(t);
577
+ }, pe = D === void 0 ? void 0 : de(!1), A = D === void 0 || O.size === 0 ? void 0 : de(!0), P = j.succeed(W.text(JSON.stringify({
578
+ protocol: 1,
579
+ mutationReplay: e.mutationReplay === !0,
580
+ ...pe === void 0 ? {} : { surface: pe },
581
+ ...A === void 0 ? {} : { serviceSurface: A }
582
+ }), {
583
+ status: 200,
584
+ contentType: "application/json; charset=utf-8",
585
+ headers: {
586
+ "cache-control": "no-store",
587
+ "access-control-allow-origin": "*"
588
+ }
589
+ })), I = "/_voltro/runtime-capabilities", L = `${s.slice(0, s.lastIndexOf("/"))}/_voltro/runtime-capabilities`, R = L === I ? H.add("GET", I, P) : M.mergeAll(H.add("GET", I, P), H.add("GET", L, P)), Oe = M.empty;
590
+ if (e.webhookRoutes !== void 0 && e.webhookRoutes.size > 0) {
591
+ let t = (t) => U.HttpServerRequest.pipe(j.flatMap((n) => j.gen(function* () {
592
+ let r = {};
593
+ for (let [e, t] of Object.entries(n.headers)) t !== void 0 && (r[e.toLowerCase()] = Array.isArray(t) ? t.join(", ") : t);
594
+ let i = n.url.split("?")[0], a = t.maxBodyBytes ?? ot, o = /* @__PURE__ */ new Uint8Array();
595
+ if (n.method !== "GET" && n.method !== "HEAD") {
596
+ let e = Number(r["content-length"]);
597
+ if (Number.isFinite(e) && e > a) return W.text("payload too large", { status: 413 });
598
+ let t = yield* ae(n.source, a);
599
+ if (t._tag === "aborted") return W.text("request aborted", { status: 400 });
600
+ if (t._tag === "too-large") return W.text("payload too large", { status: 413 });
601
+ o = new Uint8Array(t.bytes);
602
+ }
603
+ let s = ie(r.traceparent), c = yield* j.promise(() => t.handle({
604
+ method: n.method,
605
+ path: i,
606
+ headers: r,
607
+ rawBody: o
608
+ })).pipe(j.withSpan(`webhook${i}`, {
609
+ attributes: {
610
+ "framework.kind": "webhook",
611
+ "http.route": i
612
+ },
613
+ ...s ? { parent: s } : {}
614
+ })), l = new TextEncoder().encode(c.body), u = ce({
615
+ body: l,
616
+ contentType: c.contentType,
617
+ acceptEncoding: r["accept-encoding"],
618
+ options: e.compression
619
+ });
620
+ return u.compressed ? W.uint8Array(u.bytes, {
621
+ status: c.status,
622
+ contentType: c.contentType,
623
+ headers: u.headers
624
+ }) : W.text(c.body, {
625
+ status: c.status,
626
+ contentType: c.contentType
627
+ });
628
+ }))), n = Array.from(e.webhookRoutes.entries()).map(([e, n]) => H.add("*", e, t(n)));
629
+ Oe = M.mergeAll(...n);
630
+ }
631
+ let z = be(e.security?.trustedProxies, process.env, e.security?.clientAddressHeader), ke = M.empty, Ae = () => void 0;
632
+ if (e.httpRoutes !== void 0 && e.httpRoutes.length > 0) {
633
+ let t = (t) => U.HttpServerRequest.pipe(j.flatMap((n) => j.gen(function* () {
634
+ let r = {};
635
+ for (let [e, t] of Object.entries(n.headers)) t !== void 0 && (r[e.toLowerCase()] = Array.isArray(t) ? t.join(", ") : t);
636
+ let i = n.url.indexOf("?"), a = i >= 0 ? n.url.slice(0, i) : n.url, o = i >= 0 ? n.url.slice(i + 1) : "";
637
+ if (!t.some((e) => nt(e, a))) return W.text("not found", { status: 404 });
638
+ let s = t.reduce((e, t) => Math.max(e, t.maxBodyBytes ?? ot), 0), c = t[0]?.handleStream, l = /* @__PURE__ */ new Uint8Array();
639
+ if (c !== void 0 || n.method !== "GET" && n.method !== "HEAD") {
640
+ let e = Number(r["content-length"]);
641
+ if (Number.isFinite(e) && e > s) return W.text("payload too large", { status: 413 });
642
+ if (c === void 0) {
643
+ let e = yield* ae(n.source, s);
644
+ if (e._tag === "aborted") return W.text("request aborted", { status: 400 });
645
+ if (e._tag === "too-large") return W.text("payload too large", { status: 413 });
646
+ l = new Uint8Array(e.bytes);
647
+ }
648
+ }
649
+ let u = e.getStore?.(), d;
650
+ try {
651
+ d = n.source?.socket?.remoteAddress;
652
+ } catch {
653
+ d = void 0;
654
+ }
655
+ let f = ve({
656
+ socketAddress: d,
657
+ headers: r,
658
+ config: z
659
+ }), p = {
660
+ method: n.method,
661
+ path: a,
662
+ query: o,
663
+ headers: r,
664
+ ...u === void 0 ? {} : { store: u },
665
+ ...f === void 0 ? {} : { remoteAddr: f }
666
+ }, m = Date.now(), h = yield* j.promise((e) => c === void 0 ? $e(t, {
667
+ ...p,
668
+ rawBody: l
669
+ }) : se(n.source, s, p, c, e));
670
+ if (e.onHttpRoute !== void 0) try {
671
+ e.onHttpRoute({
672
+ method: n.method,
673
+ path: a,
674
+ status: h.status,
675
+ durationMs: Date.now() - m,
676
+ traceId: T(r.traceparent)?.traceId ?? w()
677
+ });
678
+ } catch {}
679
+ h.status >= 500 && vt.warn(`${n.method} ${a} → ${h.status}`, {
680
+ method: n.method,
681
+ path: a,
682
+ status: h.status,
683
+ ...typeof h.body == "string" && h.body.length > 0 ? { body: h.body.slice(0, 1e3) } : {},
684
+ ...h.cause === void 0 ? {} : { cause: yt(h.cause) }
685
+ });
686
+ let g = Dt(h.headers), _ = g.headers, v = (e) => (g.setCookie !== void 0 && Ze.toServerResponse(n).setHeader("set-cookie", [...g.setCookie]), e), y = {
687
+ status: h.status,
688
+ ...h.contentType ? { contentType: h.contentType } : {},
689
+ headers: _
690
+ };
691
+ if (h.byteStream !== void 0) {
692
+ let e = h.byteStream.stream, t = typeof e == "function" ? e() : e;
693
+ return v(W.stream(F.fromReadableStream({
694
+ evaluate: () => t,
695
+ onError: (e) => e
696
+ }), {
697
+ status: h.status,
698
+ contentType: h.contentType ?? "application/octet-stream",
699
+ headers: {
700
+ ..._,
701
+ ...h.byteStream.contentLength === void 0 ? {} : { "content-length": String(h.byteStream.contentLength) },
702
+ ...h.byteStream.contentDisposition === void 0 ? {} : { "content-disposition": h.byteStream.contentDisposition }
703
+ }
704
+ }));
705
+ }
706
+ if (h.stream !== void 0) {
707
+ let { subscribe: e, keepAliveMs: t } = h.stream, n = He(h.stream.maxDurationMs), r = new TextEncoder(), i = t ?? 15e3, a = F.callback((t) => j.gen(function* () {
708
+ let n, a, o = !1;
709
+ yield* j.addFinalizer(() => j.sync(() => {
710
+ o = !0, a !== void 0 && clearInterval(a), n?.();
711
+ })), N.offerUnsafe(t, r.encode("retry: 5000\n\n"));
712
+ let s = e((e) => {
713
+ o || N.offerUnsafe(t, r.encode(e));
714
+ });
715
+ o ? s() : n = s, a = !o && i > 0 ? setInterval(() => {
716
+ N.offerUnsafe(t, r.encode(": keep-alive\n\n"));
717
+ }, i) : void 0;
718
+ })), o = n === void 0 ? a : a.pipe(F.interruptWhen(j.sleep(n)));
719
+ return v(W.stream(o, {
720
+ status: h.status,
721
+ headers: {
722
+ ..._,
723
+ "content-type": "text/event-stream; charset=utf-8",
724
+ "cache-control": "no-cache, no-transform",
725
+ connection: "keep-alive",
726
+ "x-accel-buffering": "no"
727
+ }
728
+ }));
729
+ }
730
+ if (n.method === "HEAD") return v(W.empty({
731
+ status: y.status,
732
+ headers: _
733
+ }));
734
+ let b = h.body instanceof Uint8Array ? h.body : new TextEncoder().encode(h.body ?? ""), x = ce({
735
+ body: b,
736
+ contentType: h.contentType,
737
+ acceptEncoding: r["accept-encoding"],
738
+ options: e.compression
739
+ });
740
+ return v(W.uint8Array(x.bytes, {
741
+ ...y,
742
+ headers: le(_, x.headers)
743
+ }));
744
+ })), j.tapCause((e) => k.hasInterruptsOnly(e) ? j.void : j.sync(() => vt.error(`${t.map((e) => e.method).join("|")} ${t[0].path} threw`, { path: t[0].path }, k.squash(e))))), n = h(e.httpRoutes), r = new Map(n.map((e) => [e, t(e.routes)])), i = m(n);
745
+ Ae = (e) => {
746
+ let t = i(e);
747
+ return t === void 0 ? void 0 : { effect: r.get(t) };
748
+ };
749
+ let a = n.flatMap((e) => {
750
+ let t = r.get(e);
751
+ return e.methods.map((n) => H.add(n, `${e.mountPath}/*`, t));
752
+ });
753
+ ke = M.mergeAll(...a);
754
+ }
755
+ let je = V.layerProtocolWebsocket({ path: o }), Me = (e) => {
756
+ let t = B({ scope: e }), n = /* @__PURE__ */ new Map();
757
+ return (e) => M.flatMap(e, (e) => {
758
+ let r = we.get(e, V.Protocol);
759
+ return M.succeedContext(we.make(V.Protocol, {
760
+ ...r,
761
+ run: (e) => r.run((t, r) => j.suspend(() => {
762
+ if (r._tag === "Request") {
763
+ let e = n.get(t);
764
+ e === void 0 && (n.set(t, e = /* @__PURE__ */ new Map()), v(t)?.signal.addEventListener("abort", () => {
765
+ n.delete(t);
766
+ }, { once: !0 })), e.set(String(r.id), r.tag);
767
+ }
768
+ return e(t, r);
769
+ })),
770
+ end: (e) => (n.delete(e), r.end(e)),
771
+ send: (e, i, a) => j.suspend(() => {
772
+ let o = n.get(e), s = "requestId" in i ? String(i.requestId) : void 0, c = s === void 0 ? o?.size === 1 ? o.values().next().value : void 0 : o?.get(s);
773
+ i._tag === "Exit" && s !== void 0 && o?.delete(s);
774
+ for (let n of f(i)) {
775
+ let r = Ee(n), i = typeof r.dbMessage == "string" ? r.dbMessage : void 0;
776
+ t.error(i === void 0 ? "rpc defect sent to client" : `rpc defect sent to client: ${i}`, {
777
+ clientId: e,
778
+ defect: n,
779
+ ...s === void 0 ? {} : { requestId: s },
780
+ ...c === void 0 ? {} : { rpcTag: c },
781
+ ...c === void 0 && o !== void 0 ? { rpcTags: [...new Set(o.values())] } : {},
782
+ ...String(n).includes("Expected JSON value") ? { outputHint: "Schema.Unknown outputs must contain JSON values; declare date conversion in the output schema." } : {},
783
+ ...r,
784
+ ...i === void 0 ? {} : { hint: "the failing statement is in `_voltro_traces` (attributes.db.query.text) for this trace" }
785
+ });
786
+ }
787
+ return r.send(e, i, a);
788
+ })
789
+ }));
790
+ });
791
+ }, Ne = { disableFatalDefects: !0 }, Pe = V.layer(r, Ne), Ie = V.layer(n, Ne).pipe(M.provide(Me("voltro:rpc:http")(b(V.layerProtocolHttp({ path: "/rpc" }), "http"))), M.provide(Ge.layerJson), M.provide(e.httpHandlersLayer ?? e.handlersLayer)), Le = Pe.pipe(M.provide(Me("voltro:rpc")(b(je, "websocket"))), M.provide(Ge.layerJson), M.provide(e.handlersLayer)), ze = new Set((e.webSocketGateways ?? []).map((e) => e.path)), Be;
792
+ if (e.webSocketGateways !== void 0 && e.webSocketGateways.length > 0) {
793
+ let t = B({ scope: "voltro:gateway" }), n = e.webSocketGateways.map(Fe).map((n) => H.add("GET", n.path, U.HttpServerRequest.pipe(j.flatMap((r) => j.gen(function* () {
794
+ let i = {};
795
+ for (let [e, t] of Object.entries(r.headers)) t !== void 0 && (i[e.toLowerCase()] = Array.isArray(t) ? t.join(", ") : t);
796
+ if (!gt(r.method, i)) return W.text("upgrade required", {
797
+ status: 426,
798
+ headers: { upgrade: "websocket" }
799
+ });
800
+ let a = null, o;
801
+ if (n.auth === "subject") {
802
+ let r = e.resolveGatewaySubject;
803
+ if (r === void 0) return t.error("gateway declares auth: subject but the boot passed no resolveGatewaySubject", { path: n.path }), W.text("gateway auth unavailable", { status: 500 });
804
+ let s = yield* j.promise(() => r(i).catch(() => null));
805
+ if (s === null) return W.text("unauthorized", { status: 401 });
806
+ a = s.subject, o = s.credentialExpiresAt;
807
+ }
808
+ let s = yield* r.upgrade;
809
+ return yield* ue(s, r.source.socket, n, a, i, o, (e) => t.error("gateway handler failed", { path: n.path }, e)), W.empty({ status: 200 });
810
+ })))));
811
+ Be = M.mergeAll(...n);
812
+ }
813
+ let Ve = H.make.pipe(j.provideService(H.RouterConfig, {
814
+ caseSensitive: !0,
815
+ ignoreTrailingSlash: !1,
816
+ ignoreDuplicateSlashes: !1
817
+ })), Ue = M.mergeAll(R, ...t === void 0 || r.requests.size > 0 ? [Le] : [], ...t === void 0 || n.requests.size > 0 ? [Ie] : [], E, Oe, ke, ...Be === void 0 ? [] : [Be]), We = e.pluginHttpInterceptor, Ke = Number(process.env.VOLTRO_MAX_RPC_BODY_BYTES), at = e.maxRpcBodyBytes ?? (Number.isFinite(Ke) && Ke > 0 ? Ke : 8388608), G = Number(process.env.VOLTRO_MAX_BODY_BYTES), ot = e.maxBodyBytes ?? (Number.isFinite(G) && G > 0 ? G : 8388608), K = { "cache-control": "no-store" }, ct = e.httpRoutes?.some((e) => e.cors !== void 0 || e.credentials !== void 0) ? p(h(e.httpRoutes)) : () => void 0, lt = _e({
818
+ ...e.security?.originGuard === void 0 ? {} : { mode: e.security.originGuard },
819
+ ...e.security?.allowedOrigins === void 0 ? {} : { allowedOrigins: e.security.allowedOrigins }
820
+ }), ut = ge({
821
+ ...e.webhookRoutes === void 0 ? {} : { webhookPaths: e.webhookRoutes.keys() },
822
+ ...e.httpRoutes === void 0 ? {} : { httpRoutes: e.httpRoutes }
823
+ }), dt = xe(e.security?.headers), ft = B({ scope: "voltro:security" }), q = B({ scope: "voltro:rpc" }), pt = (e) => {
824
+ try {
825
+ let t = new URL(e, "http://voltro.invalid").searchParams.get("voltro-socket-id");
826
+ return t !== null && /^[A-Za-z0-9-]{1,80}$/.test(t) ? t : void 0;
827
+ } catch {
828
+ return;
829
+ }
830
+ }, mt = (e) => {
831
+ let t = Object.create(e);
832
+ return Object.defineProperty(t, "upgrade", {
833
+ configurable: !0,
834
+ get: () => j.gen(function* () {
835
+ let t = yield* e.upgrade, n = De(), r = pt(e.url), i = Date.now();
836
+ return q.info("rpc websocket opened", {
837
+ replicaId: g,
838
+ instanceId: rt(),
839
+ connectionId: n,
840
+ ...r === void 0 ? {} : { clientSocketId: r }
841
+ }), yield* j.addFinalizer(() => j.sync(() => {
842
+ q.info("rpc websocket closed", {
843
+ replicaId: g,
844
+ instanceId: rt(),
845
+ connectionId: n,
846
+ ...r === void 0 ? {} : { clientSocketId: r },
847
+ durationMs: Date.now() - i
848
+ });
849
+ })), t;
850
+ })
851
+ }), t;
852
+ }, ht = (e, t) => {
853
+ let n = e.headers, r = Se(dt, {
854
+ contentType: n["content-type"],
855
+ https: t
856
+ }), i = {};
857
+ for (let [e, t] of Object.entries(r)) n[e] === void 0 && (i[e] = t);
858
+ return Object.keys(i).length === 0 ? e : W.setHeaders(e, i);
859
+ }, gt = (e, t) => e.toUpperCase() === "GET" && (t.upgrade ?? "").toLowerCase().includes("websocket"), _t = (e) => j.gen(function* () {
860
+ let t = yield* U.HttpServerRequest, n = {};
861
+ for (let [e, r] of Object.entries(t.headers)) r !== void 0 && (n[e.toLowerCase()] = Array.isArray(r) ? r.join(", ") : r);
862
+ let r = t.url.indexOf("?"), i = r === -1 ? t.url : t.url.slice(0, r), a, o = !1;
863
+ try {
864
+ let e = t.source?.socket;
865
+ a = e?.remoteAddress, o = e?.encrypted === !0;
866
+ } catch {
867
+ a = void 0;
868
+ }
869
+ let c = ye({
870
+ socketEncrypted: o,
871
+ socketAddress: a,
872
+ xForwardedProto: n["x-forwarded-proto"],
873
+ config: z
874
+ }), l = ve({
875
+ socketAddress: a,
876
+ headers: n,
877
+ config: z
878
+ }), u = t.method === "OPTIONS" ? n["access-control-request-method"] ?? t.method : t.method, d = (ct(i)?.routes ?? []).filter((e) => nt(e, i)), f = d.find((e) => e.method === u || e.method === "*" || u === "HEAD" && e.method === "GET"), p = f ?? d[0], m = et(p?.cors, n.origin), h = (e) => {
879
+ let t = e.headers.vary, n = p?.cors !== void 0 && t !== void 0 ? {
880
+ ...m,
881
+ vary: [...new Set(`${t}, Origin`.split(",").map((e) => e.trim()))].join(", ")
882
+ } : m;
883
+ return ht(W.setHeaders(e, n), c);
884
+ };
885
+ if (t.method === "OPTIONS" && f?.cors !== void 0 && n["access-control-request-method"] !== void 0) {
886
+ let e = tt(f.cors, f.method, n);
887
+ return h(W.empty({
888
+ status: e.status,
889
+ headers: e.headers
890
+ }));
891
+ }
892
+ if (t.method === "POST" && i === "/rpc") {
893
+ let e = n["content-length"];
894
+ if (e !== void 0 && Number(e) > at) return h(W.text("rpc payload too large", {
895
+ status: 413,
896
+ headers: K
897
+ }));
898
+ }
899
+ let g = i === "/rpc" && he(t.method), _ = (i === s || ze.has(i)) && gt(t.method, n);
900
+ if (he(t.method) && !ut(i) && f?.credentials !== "bearer" || _) {
901
+ let e = me({
902
+ headers: n,
903
+ config: lt
904
+ });
905
+ if (!e.allowed) return ft.warn("refused cross-site request", {
906
+ path: i,
907
+ method: t.method,
908
+ reason: e.reason,
909
+ origin: e.origin,
910
+ surface: _ ? "websocket-upgrade" : g ? "rpc" : "http-route"
911
+ }), h(W.text("origin not allowed", {
912
+ status: 403,
913
+ headers: K
914
+ }));
915
+ }
916
+ let v = g ? j.gen(function* () {
917
+ let r = yield* ae(t.source, at);
918
+ return r._tag === "aborted" ? h(W.text("rpc request body incomplete", {
919
+ status: 400,
920
+ headers: K
921
+ })) : r._tag === "too-large" ? (ft.warn("refused an over-cap rpc body", {
922
+ path: i,
923
+ cap: at,
924
+ receivedAtLeast: r.received,
925
+ declaredLength: n["content-length"] ?? null
926
+ }), h(W.text("rpc payload too large", {
927
+ status: 413,
928
+ headers: K
929
+ }))) : yield* j.provideService(e, U.HttpServerRequest, oe(y(t, l), r.bytes));
930
+ }) : e, b = _ && i === s ? mt(y(t, l)) : t, x = b === t ? v : j.provideService(v, U.HttpServerRequest, b);
931
+ if (!We) {
932
+ let e = yield* x;
933
+ return W.isHttpServerResponse(e) ? h(e) : e;
934
+ }
935
+ let S = yield* j.tryPromise(() => We(async () => null, {
936
+ method: t.method,
937
+ path: i,
938
+ headers: n,
939
+ remoteAddr: l
940
+ })).pipe(j.catch((e) => j.sync(() => (vt.error("http interceptor threw — request REFUSED (fail-closed)", {
941
+ method: t.method,
942
+ path: i
943
+ }, e), {
944
+ status: 500,
945
+ body: "internal error",
946
+ headers: void 0
947
+ }))));
948
+ if (S !== null) return h(W.text(S.body ?? "", {
949
+ status: S.status,
950
+ ...S.headers ? { headers: S.headers } : {}
951
+ }));
952
+ let C = yield* x;
953
+ return W.isHttpServerResponse(C) ? h(C) : C;
954
+ }), J = _ === void 0 ? void 0 : new jt(x);
955
+ if (_ !== void 0 && J !== void 0) {
956
+ let e = new Promise((e) => {
957
+ let t = (n) => {
958
+ n === "request" && (J.removeListener("newListener", t), e());
959
+ };
960
+ J.on("newListener", t);
961
+ });
962
+ Mt.set(x, e), e.then(() => {
963
+ _.delegate({
964
+ request: (e, t) => {
965
+ J.emit("request", e, t);
966
+ },
967
+ upgrade: (e, t, n) => {
968
+ J.emit("upgrade", e, t, n);
969
+ }
970
+ });
971
+ });
972
+ }
973
+ let Y = M.unwrap(j.gen(function* () {
974
+ let e = yield* Ve;
975
+ return yield* M.build(M.provide(Ue, M.succeed(H.HttpRouter, e))), e.asHttpEffect();
976
+ }).pipe(j.map((e) => Je.serve(_t(e.pipe(j.catchIf((e) => Ye.isHttpServerError(e) && e.reason._tag === "RouteNotFound", (e) => {
977
+ let t = Ae(e.request.url.split("?")[0]);
978
+ return t === void 0 ? j.fail(e) : t.effect;
979
+ }))))))).pipe(M.provide(Xe.layer(() => J ?? x, a === void 0 ? { port: i } : {
980
+ port: i,
981
+ host: a
982
+ })), M.provide(Qe.layer), M.provide(st));
983
+ e.tracerLayer && (Y = Y.pipe(M.provide(fe), M.provide(e.tracerLayer)));
984
+ let X = B({ scope: "voltro:rpc" }), bt = M.launch(Y).pipe(j.catchCause((e) => j.sync(() => {
985
+ X.error("rpc server crashed", {}, k.squash(e)), process.exit(1);
986
+ }))), Z = j.runFork(bt);
987
+ return $.add(Z), Vt(), {
988
+ server: x,
989
+ shutdown: async () => {
990
+ $.delete(Z);
991
+ let e = j.runPromise(Te.interrupt(Z)).then(() => void 0, () => void 0);
992
+ for (let e of S) e.destroy();
993
+ x.closeIdleConnections(), await e, _ !== void 0 && await _.close();
994
+ }
995
+ };
996
+ }, jt = class extends Ke {
997
+ bound;
998
+ constructor(e) {
999
+ super(), this.bound = e;
1000
+ }
1001
+ listen(...e) {
1002
+ let t = e.find((e) => typeof e == "function");
1003
+ return t !== void 0 && process.nextTick(t), this;
1004
+ }
1005
+ address() {
1006
+ return this.bound.address();
1007
+ }
1008
+ }, Mt = /* @__PURE__ */ new WeakMap(), $ = /* @__PURE__ */ new Set(), Nt = /* @__PURE__ */ new Set(), Pt = !1, Ft = (e) => (Nt.add(e), () => {
1009
+ Nt.delete(e);
1010
+ }), It = 1e4, Lt = 1e3, Rt = 3e5, zt = () => {
1011
+ let e = process.env.VOLTRO_SHUTDOWN_GRACE_MS;
1012
+ if (e === void 0 || e === "") return It;
1013
+ let t = Number(e);
1014
+ return !Number.isFinite(t) || t <= 0 ? It : Math.min(Rt, Math.max(Lt, Math.trunc(t)));
1015
+ }, Bt = (e) => {
1016
+ let t = Date.now(), n = !1, r = (r) => () => {
1017
+ n || (n = !0, clearTimeout(i), e.onOutcome?.({
1018
+ reason: r,
1019
+ ms: Date.now() - t
1020
+ }), e.exit());
1021
+ }, i = setTimeout(r("deadline"), e.deadlineMs);
1022
+ i.unref?.(), Promise.all(e.hooks.map((e) => Promise.resolve().then(e).then(() => void 0, () => void 0))).then(() => Promise.all(e.fibers.map((e) => j.runPromise(Te.interrupt(e)).then(() => void 0, () => void 0)))).then(r("drained"), r("drained"));
1023
+ }, Vt = () => {
1024
+ if (Pt) return;
1025
+ Pt = !0;
1026
+ let e = () => {
1027
+ let e = [...$], t = [...Nt];
1028
+ $.clear(), Nt.clear(), Bt({
1029
+ fibers: e,
1030
+ hooks: t,
1031
+ deadlineMs: zt(),
1032
+ exit: () => process.exit(0),
1033
+ onOutcome: ({ reason: e, ms: t }) => {
1034
+ e === "drained" ? Y.info(`drained in ${t}ms`) : Y.error(`drain deadline exceeded — cut at ${t}ms`, { hint: "a shutdown hook or a pool drain did not complete; whatever had not finished did not happen" });
1035
+ }
1036
+ });
1037
+ };
1038
+ process.once("SIGINT", e), process.once("SIGTERM", e);
1039
+ }, Ht = (e, t = 1e4) => new Promise((n, r) => {
1040
+ if (e.listening) {
1041
+ let i = Mt.get(e);
1042
+ if (i === void 0) {
1043
+ n();
1044
+ return;
1045
+ }
1046
+ let a = setTimeout(() => r(/* @__PURE__ */ Error(`rpc server did not bind within ${t}ms`)), t);
1047
+ i.then(() => {
1048
+ clearTimeout(a), n();
1049
+ });
1050
+ return;
1051
+ }
1052
+ let i = !1, a;
1053
+ function o(t) {
1054
+ i || (i = !0, clearTimeout(a), e.removeListener("listening", s), e.removeListener("error", c), t ? r(t) : n());
1055
+ }
1056
+ function s() {
1057
+ o();
1058
+ }
1059
+ function c(e) {
1060
+ o(e);
1061
+ }
1062
+ a = setTimeout(() => o(/* @__PURE__ */ Error(`rpc server did not bind within ${t}ms`)), t), e.on("listening", s), e.on("error", c);
1063
+ });
1064
+ //#endregion
1065
+ export { kt as DEFAULT_MAX_RPC_BODY_BYTES, Ht as awaitServerListening, mt as bindComputedUntyped, Ot as bindMutation, _t as bindStream, ht as bindSubscription, pt as bindSubscriptionUntyped, Q as defectMessage, Bt as drainForShutdown, Z as isInfraError, Et as makeMutationCodec, Ft as onProcessShutdown, zt as shutdownGraceMsFromEnv, At as startRpcServer };