@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,260 @@
1
+ import { recordEventDropped as e, recordEventPublished as t, recordEventSubscribers as n } from "./metrics.js";
2
+ import { eventRoute as r, parseEventRoute as i } from "@voltro/protocol";
3
+ import { createLogger as a } from "@voltro/logger";
4
+ //#region src/eventBus.ts
5
+ var o = a({ scope: "voltro:events" }), s = 64, c = 3e5, l = 1e4, u = class {
6
+ routes = /* @__PURE__ */ new Map();
7
+ origin;
8
+ ringSize;
9
+ ringTtlMs;
10
+ maxRoutes;
11
+ publishRemote;
12
+ deliveryOf;
13
+ interest = /* @__PURE__ */ new Map();
14
+ interestListeners = /* @__PURE__ */ new Set();
15
+ now;
16
+ constructor(e) {
17
+ this.origin = e.origin, this.ringSize = e.ringSize ?? s, this.ringTtlMs = e.ringTtlMs ?? c, this.maxRoutes = e.maxRoutes ?? l, this.publishRemote = e.publishRemote, this.deliveryOf = e.deliveryOf, this.now = e.now ?? Date.now;
18
+ }
19
+ get instanceOrigin() {
20
+ return this.origin;
21
+ }
22
+ onInterestChange(e) {
23
+ this.interestListeners.add(e);
24
+ for (let [t, n] of this.interest) n > 0 && e(t, !0);
25
+ return () => {
26
+ this.interestListeners.delete(e);
27
+ };
28
+ }
29
+ shiftInterest(e, t) {
30
+ let n = this.interest.get(e) ?? 0, r = n + t;
31
+ r <= 0 ? this.interest.delete(e) : this.interest.set(e, r), n === 0 && r === 1 ? this.notifyInterest(e, !0) : n === 1 && r === 0 && this.notifyInterest(e, !1);
32
+ }
33
+ notifyInterest(e, t) {
34
+ for (let n of this.interestListeners) try {
35
+ n(e, t);
36
+ } catch (n) {
37
+ o.warn("event interest listener threw", {
38
+ event: e,
39
+ active: t,
40
+ cause: n
41
+ });
42
+ }
43
+ }
44
+ activeEvents() {
45
+ return [...this.interest.keys()];
46
+ }
47
+ deliveryFor(e) {
48
+ return this.deliveryOf?.(e) ?? "each";
49
+ }
50
+ state(e) {
51
+ let t = this.routes.get(e);
52
+ if (t !== void 0) return t.lastTouched = this.now(), t;
53
+ this.evictIfOverCapacity();
54
+ let n = {
55
+ latest: this.deliveryOf?.(i(e).event) === "latest",
56
+ listeners: /* @__PURE__ */ new Set(),
57
+ watermark: /* @__PURE__ */ new Map(),
58
+ localNext: 1,
59
+ ring: [],
60
+ lastTouched: this.now()
61
+ };
62
+ return this.routes.set(e, n), n;
63
+ }
64
+ evictIfOverCapacity() {
65
+ if (this.routes.size < this.maxRoutes) return;
66
+ let e = Math.max(1, Math.floor(this.maxRoutes / 10)), t = this.coldestIdleRoutes(e), n = 0;
67
+ for (let r of t) {
68
+ if (n >= e) break;
69
+ this.routes.delete(r), n += 1;
70
+ }
71
+ if (n === 0) {
72
+ o.warn("event ring capacity reached with all routes live — replay buffers cleared", {
73
+ routes: this.routes.size,
74
+ maxRoutes: this.maxRoutes
75
+ });
76
+ for (let e of this.routes.values()) e.ring = [];
77
+ }
78
+ }
79
+ coldestIdleRoutes(e) {
80
+ let t = [], n = -Infinity, r = !0, i = Number.isFinite(e);
81
+ if (this.routes.forEach((a, o) => {
82
+ if (a.listeners.size !== 0) return;
83
+ let s = a.lastTouched;
84
+ Number.isFinite(s) || (i = !1), s < n && (r = !1), n = s, t.length < e && t.push(o);
85
+ }), !i) return [...this.routes.entries()].filter(([, e]) => e.listeners.size === 0).sort((e, t) => e[1].lastTouched - t[1].lastTouched).map(([e]) => e);
86
+ if (r) return t;
87
+ let a = [], o = (e, t) => e.at > t.at || e.at === t.at && e.order > t.order, s = () => {
88
+ let e = 0;
89
+ for (; e * 2 + 1 < a.length;) {
90
+ let t = e * 2 + 1;
91
+ if (t + 1 < a.length && o(a[t + 1], a[t]) && t++, !o(a[t], a[e])) break;
92
+ let n = a[e];
93
+ a[e] = a[t], a[t] = n, e = t;
94
+ }
95
+ }, c = 0;
96
+ return this.routes.forEach((t, n) => {
97
+ if (t.listeners.size !== 0) return;
98
+ let r = c++;
99
+ if (a.length < e) {
100
+ a.push({
101
+ route: n,
102
+ at: t.lastTouched,
103
+ order: r
104
+ });
105
+ let e = a.length - 1;
106
+ for (; e > 0;) {
107
+ let t = e - 1 >> 1;
108
+ if (!o(a[e], a[t])) break;
109
+ let n = a[t];
110
+ a[t] = a[e], a[e] = n, e = t;
111
+ }
112
+ } else {
113
+ let e = a[0];
114
+ if (t.lastTouched > e.at || t.lastTouched === e.at && r >= e.order) return;
115
+ e.route = n, e.at = t.lastTouched, e.order = r, s();
116
+ }
117
+ }), a.map((e) => e.route);
118
+ }
119
+ pruneRing(e) {
120
+ let t = this.now() - this.ringTtlMs, n = 0;
121
+ for (; n < e.ring.length && e.ring[n].at < t;) n += 1;
122
+ let r = Math.max(0, e.ring.length - n - this.ringSize), i = n + r;
123
+ i > 0 && e.ring.splice(0, i);
124
+ }
125
+ publish(e) {
126
+ let n = r(e.tenantId, e.event, e.key), i = this.state(n), a = {
127
+ route: n,
128
+ event: e.event,
129
+ origin: this.origin,
130
+ n: i.localNext,
131
+ emittedAt: this.now(),
132
+ payload: e.payload
133
+ };
134
+ if (i.localNext += 1, this.accept(i, a), t(e.event), this.publishRemote !== void 0) try {
135
+ this.publishRemote(a);
136
+ } catch (t) {
137
+ o.warn("event broadcast publish failed — local delivery unaffected", {
138
+ event: e.event,
139
+ cause: t
140
+ });
141
+ }
142
+ return a;
143
+ }
144
+ injectRemote(e) {
145
+ e.origin !== this.origin && this.accept(this.state(e.route), e);
146
+ }
147
+ accept(e, t) {
148
+ let n = e.watermark.get(t.origin) ?? 0;
149
+ t.n > n && e.watermark.set(t.origin, t.n);
150
+ let r = n;
151
+ e.latest ? e.ring = [{
152
+ envelope: t,
153
+ at: this.now()
154
+ }] : (e.ring.push({
155
+ envelope: t,
156
+ at: this.now()
157
+ }), this.pruneRing(e));
158
+ let i = {
159
+ kind: "event",
160
+ envelope: t,
161
+ prior: r
162
+ };
163
+ for (let n of e.listeners) try {
164
+ n(i);
165
+ } catch (e) {
166
+ o.warn("event listener threw — other subscribers unaffected", {
167
+ event: t.event,
168
+ cause: e
169
+ });
170
+ }
171
+ }
172
+ subscribe(e) {
173
+ let t = r(e.tenantId, e.event, e.key), i = this.state(t);
174
+ e.onAttach?.(new Map(i.watermark));
175
+ let a = !0, o = [], s = (t) => {
176
+ a ? o.push(t) : e.listener(t);
177
+ };
178
+ i.listeners.add(s), n(e.event, 1), this.shiftInterest(e.event, 1);
179
+ let c = e.options?.resume;
180
+ if (c !== void 0) this.replayForResume(i, c, e.listener);
181
+ else if (e.options?.rewind === !0) {
182
+ this.pruneRing(i);
183
+ for (let t of i.ring) e.listener({
184
+ kind: "event",
185
+ envelope: t.envelope,
186
+ prior: t.envelope.n - 1
187
+ });
188
+ }
189
+ a = !1;
190
+ for (let t of o) e.listener(t);
191
+ o.length = 0;
192
+ let l = !0;
193
+ return () => {
194
+ l && (l = !1, i.listeners.delete(s), n(e.event, -1), this.shiftInterest(e.event, -1));
195
+ };
196
+ }
197
+ replayForResume(t, n, r) {
198
+ if (t.latest) {
199
+ let e = t.ring[t.ring.length - 1];
200
+ if (e === void 0 || (n.find((t) => t.origin === e.envelope.origin)?.n ?? 0) >= e.envelope.n) return;
201
+ r({
202
+ kind: "event",
203
+ envelope: e.envelope,
204
+ prior: e.envelope.n - 1
205
+ });
206
+ return;
207
+ }
208
+ this.pruneRing(t);
209
+ let i = new Map(n.map((e) => [e.origin, e.n])), a = [];
210
+ for (let e of t.ring) {
211
+ let t = e.envelope;
212
+ t.n > (i.get(t.origin) ?? 0) && a.push(t);
213
+ }
214
+ a.sort((e, t) => e.origin === t.origin ? e.n - t.n : e.emittedAt - t.emittedAt);
215
+ let o = /* @__PURE__ */ new Map();
216
+ for (let e of a) o.set(e.origin, (o.get(e.origin) ?? 0) + 1);
217
+ let s = 0;
218
+ for (let [e, n] of t.watermark) {
219
+ let t = i.get(e) ?? 0, r = Math.max(0, n - t), a = o.get(e) ?? 0;
220
+ s += Math.max(0, r - a);
221
+ }
222
+ s > 0 && (r({
223
+ kind: "gap",
224
+ missed: s,
225
+ reason: "resume"
226
+ }), e(t.ring[0]?.envelope.event ?? "unknown", "resume", s));
227
+ for (let e of a) r({
228
+ kind: "event",
229
+ envelope: e,
230
+ prior: e.n - 1
231
+ });
232
+ }
233
+ stats() {
234
+ let e = 0, t = 0;
235
+ for (let n of this.routes.values()) e += n.listeners.size, t += n.ring.length;
236
+ return {
237
+ routes: this.routes.size,
238
+ subscribers: e,
239
+ buffered: t
240
+ };
241
+ }
242
+ snapshot() {
243
+ let e = [];
244
+ return this.routes.forEach((t, n) => {
245
+ let r = t.ring[t.ring.length - 1]?.envelope;
246
+ e.push({
247
+ route: n,
248
+ event: r?.event ?? i(n).event,
249
+ subscribers: t.listeners.size,
250
+ buffered: t.ring.length,
251
+ lastEmittedAt: r?.emittedAt
252
+ });
253
+ }), e;
254
+ }
255
+ clear() {
256
+ this.routes.clear();
257
+ }
258
+ };
259
+ //#endregion
260
+ export { u as EventBus };
@@ -0,0 +1,49 @@
1
+ import { Context as e, Effect as t, Schema as n } from "effect";
2
+ import { EventKeyInvalid as r, EventPayloadInvalid as i, EventPayloadTooLarge as a, MAX_EVENT_ENVELOPE_BYTES as o } from "@voltro/protocol";
3
+ //#region src/eventPublish.ts
4
+ var s = (e) => e instanceof Error ? e.message : String(e), c = (e, c, l, u) => t.gen(function* () {
5
+ let d = n.encodeEffect(c.key), f = n.encodeEffect(c.payload), p = yield* d(l).pipe(t.mapError((e) => new r({
6
+ event: c.name,
7
+ message: s(e)
8
+ }))), m = yield* f(u).pipe(t.mapError((e) => new i({
9
+ event: c.name,
10
+ message: s(e)
11
+ }))), h = Buffer.byteLength(JSON.stringify({
12
+ event: c.name,
13
+ key: p,
14
+ payload: m
15
+ }), "utf8");
16
+ if (h > o) return yield* t.fail(new a({
17
+ event: c.name,
18
+ bytes: h,
19
+ limit: o
20
+ }));
21
+ let g = () => e.bus.publish({
22
+ tenantId: e.tenantId,
23
+ event: c.name,
24
+ key: p,
25
+ payload: m
26
+ }).n;
27
+ if (e.deferToCommit === void 0 && e.onPublished === void 0) return {
28
+ n: g(),
29
+ deferred: !1
30
+ };
31
+ let _ = t.gen(function* () {
32
+ let n = e.onPublished;
33
+ return n !== void 0 && (yield* t.promise(async () => {
34
+ await n(c.name, m, c);
35
+ })), g();
36
+ });
37
+ return e.deferToCommit === void 0 ? {
38
+ n: yield* _,
39
+ deferred: !1
40
+ } : (e.deferToCommit(() => t.runPromise(t.asVoid(_))), {
41
+ n: -1,
42
+ deferred: !0
43
+ });
44
+ }), l = class extends e.Service()("@voltro/OutboxEventPublisher") {}, u = (e) => {
45
+ let n;
46
+ return Object.assign(e, { then: (r, i) => (n ??= t.runPromise(e), n.then(r, i)) });
47
+ }, d = (e) => ({ publish: (t, n, r) => u(c(e, t, n, r)) });
48
+ //#endregion
49
+ export { l as OutboxEventPublisher, d as makeEventPublisher, c as publishEvent };
package/dist/events.js ADDED
@@ -0,0 +1,193 @@
1
+ import { boolean as e, eq as t, id as n, json as r, table as i, text as a, timestamp as o } from "@voltro/database";
2
+ //#region src/events.ts
3
+ var s = (e) => {
4
+ if ("on" in e) {
5
+ let { on: t, ...n } = e;
6
+ return {
7
+ _tag: "workflowEventTrigger",
8
+ event: t.name,
9
+ ...n
10
+ };
11
+ }
12
+ return {
13
+ _tag: "workflowEventTrigger",
14
+ ...e
15
+ };
16
+ }, c = s, l = (e) => typeof e == "object" && !!e && e._tag === "workflowEventTrigger", u = () => {
17
+ let e = globalThis.crypto;
18
+ return typeof e?.randomUUID == "function" ? e.randomUUID() : `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;
19
+ }, d = (e) => `${e}_${u()}`, f = (e) => e.id ?? `${e.event}->${e.workflow}`, p = i("_voltro_workflow_events", {
20
+ id: n({ prefix: "wfe" }),
21
+ name: a(),
22
+ payload: r(),
23
+ source: a(),
24
+ subject: r().nullable(),
25
+ traceId: a().nullable(),
26
+ occurredAt: o().default("now")
27
+ }).index(["name"]).index(["source"]).index(["occurredAt"]), m = i("_voltro_workflow_event_deliveries", {
28
+ id: n({ prefix: "wfed" }),
29
+ eventId: a(),
30
+ eventName: a(),
31
+ triggerId: a(),
32
+ workflowName: a(),
33
+ executionId: a().nullable(),
34
+ status: a().oneOf([
35
+ "starting",
36
+ "started",
37
+ "skipped",
38
+ "failed"
39
+ ]).default("starting"),
40
+ idempotencyKey: a().unique(),
41
+ skipped: e().default(!1),
42
+ errorMessage: a().nullable(),
43
+ createdAt: o().default("now"),
44
+ completedAt: o().nullable()
45
+ }).index(["eventId"]).index(["eventName"]).index(["triggerId"]).index(["workflowName"]).index(["status"]), h = (e) => {
46
+ let n = e.makeId ?? d, r = /* @__PURE__ */ new Map();
47
+ for (let t of e.triggers) {
48
+ let e = r.get(t.event);
49
+ e ? e.push(t) : r.set(t.event, [t]);
50
+ }
51
+ let i = (t, n, r) => {
52
+ e.emit?.(t, {
53
+ op: n,
54
+ row: r
55
+ });
56
+ }, a = async (t, n, r) => {
57
+ let a = await e.store.insert(t, r);
58
+ return i(n, "insert", typeof a == "object" && a ? a : r), a;
59
+ }, o = async (t, n, r, a) => {
60
+ let o = await e.store.update(t, r, a);
61
+ return typeof o == "object" && o && i(n, "update", o), o;
62
+ }, s = (e) => {
63
+ let t = r.get(e) ?? [], n = e === "*" ? [] : r.get("*") ?? [];
64
+ return t.length === 0 ? n : [...t, ...n];
65
+ };
66
+ return { emit: async (r, i, c) => {
67
+ let l = c?.id ?? n("wfe"), u = /* @__PURE__ */ new Date(), d = c?.source ?? e.source, p = {
68
+ id: l,
69
+ name: r,
70
+ data: i,
71
+ occurredAt: u,
72
+ source: d,
73
+ ...e.subject === void 0 ? {} : { subject: e.subject },
74
+ ...e.traceId === void 0 ? {} : { traceId: e.traceId }
75
+ };
76
+ await a("_voltro_workflow_events", "workflowDomainEvents", {
77
+ id: l,
78
+ name: r,
79
+ payload: i,
80
+ source: d,
81
+ subject: e.subject ?? null,
82
+ traceId: e.traceId ?? null,
83
+ occurredAt: u
84
+ });
85
+ let m = s(r), h = [];
86
+ for (let s of m) {
87
+ let c = f(s), u = s.workflow, d, m = async (e) => {
88
+ let t = n("wfed");
89
+ await a("_voltro_workflow_event_deliveries", "workflowEventDeliveries", {
90
+ id: t,
91
+ eventId: l,
92
+ eventName: r,
93
+ triggerId: c,
94
+ workflowName: u,
95
+ executionId: null,
96
+ status: "skipped",
97
+ idempotencyKey: `${l}:${c}:skipped:${t}`,
98
+ skipped: !0,
99
+ errorMessage: e,
100
+ createdAt: /* @__PURE__ */ new Date(),
101
+ completedAt: /* @__PURE__ */ new Date()
102
+ }), h.push({
103
+ triggerId: c,
104
+ workflowName: u,
105
+ status: "skipped",
106
+ reason: e
107
+ });
108
+ };
109
+ try {
110
+ let f = s.idempotencyKey?.(p) ?? `${l}:${c}`;
111
+ if (s.filter && !await s.filter(p)) {
112
+ await m("filter");
113
+ continue;
114
+ }
115
+ if ((await e.store.query({
116
+ table: "_voltro_workflow_event_deliveries",
117
+ order: [],
118
+ predicate: t("idempotencyKey", f),
119
+ projection: ["id"],
120
+ skip: void 0,
121
+ take: 1
122
+ }))[0] !== void 0) {
123
+ await m("duplicate");
124
+ continue;
125
+ }
126
+ d = (await a("_voltro_workflow_event_deliveries", "workflowEventDeliveries", {
127
+ id: n("wfed"),
128
+ eventId: l,
129
+ eventName: r,
130
+ triggerId: c,
131
+ workflowName: u,
132
+ executionId: null,
133
+ status: "starting",
134
+ idempotencyKey: f,
135
+ skipped: !1,
136
+ errorMessage: null,
137
+ createdAt: /* @__PURE__ */ new Date(),
138
+ completedAt: null
139
+ })).id;
140
+ let g = s.payload ? await s.payload(p) : i, _ = await e.startWorkflow(u, g, {
141
+ ...e.subject === void 0 ? {} : { subject: e.subject },
142
+ ...e.traceId === void 0 ? {} : { traceId: e.traceId },
143
+ source: `event:${r}`,
144
+ ...e.parentExecutionId !== void 0 && e.parentExecutionId !== null ? {
145
+ parentExecutionId: e.parentExecutionId,
146
+ parentGeneration: e.parentGeneration ?? null
147
+ } : {}
148
+ });
149
+ d !== void 0 && await o("_voltro_workflow_event_deliveries", "workflowEventDeliveries", d, {
150
+ executionId: _.executionId,
151
+ status: "started",
152
+ completedAt: /* @__PURE__ */ new Date()
153
+ }), h.push({
154
+ triggerId: c,
155
+ workflowName: u,
156
+ status: "started",
157
+ run: _
158
+ });
159
+ } catch (e) {
160
+ let t = e?.message ?? String(e);
161
+ d === void 0 ? await a("_voltro_workflow_event_deliveries", "workflowEventDeliveries", {
162
+ id: n("wfed"),
163
+ eventId: l,
164
+ eventName: r,
165
+ triggerId: c,
166
+ workflowName: u,
167
+ executionId: null,
168
+ status: "failed",
169
+ idempotencyKey: `${l}:${c}:failed:${n("wfed")}`,
170
+ skipped: !1,
171
+ errorMessage: t,
172
+ createdAt: /* @__PURE__ */ new Date(),
173
+ completedAt: /* @__PURE__ */ new Date()
174
+ }).catch(() => void 0) : await o("_voltro_workflow_event_deliveries", "workflowEventDeliveries", d, {
175
+ status: "failed",
176
+ errorMessage: t,
177
+ completedAt: /* @__PURE__ */ new Date()
178
+ }).catch(() => void 0), h.push({
179
+ triggerId: c,
180
+ workflowName: u,
181
+ status: "failed",
182
+ reason: t
183
+ });
184
+ }
185
+ }
186
+ return {
187
+ eventId: l,
188
+ triggered: h
189
+ };
190
+ } };
191
+ };
192
+ //#endregion
193
+ export { m as _voltroWorkflowEventDeliveriesTable, p as _voltroWorkflowEventsTable, c as defineEventTrigger, l as isWorkflowEventTriggerDefinition, h as makeEventsFacade, s as triggerWorkflow };
@@ -0,0 +1,52 @@
1
+ import { Context as e, Effect as t } from "effect";
2
+ //#region src/expectation.ts
3
+ var n = /* @__PURE__ */ new Set([
4
+ "info",
5
+ "warn",
6
+ "critical"
7
+ ]), r = (e, t) => /* @__PURE__ */ Error(`defineExpectation(${JSON.stringify(e)}): ${t}`), i = (e) => {
8
+ let t = e.name;
9
+ if (typeof t != "string" || t.length === 0) throw Error("defineExpectation: a non-empty `name` is required");
10
+ if (e.on === void 0 || typeof e.on.table != "string" || e.on.table.length === 0) throw r(t, "on.table is required — the table whose writes drive the expectation");
11
+ if (e.on.where !== void 0 && typeof e.on.where != "function") throw r(t, "on.where, when present, must be a predicate function");
12
+ let i = e.invariant;
13
+ if (i === void 0 || typeof i.kind != "string") throw r(t, "invariant is required");
14
+ switch (i.kind) {
15
+ case "freshness":
16
+ if (typeof i.column != "string" || i.column.length === 0) throw r(t, "freshness invariant requires a `column` (the timestamp column)");
17
+ if (!(typeof i.maxAgeMs == "number" && i.maxAgeMs > 0)) throw r(t, "freshness invariant requires a positive `maxAgeMs`");
18
+ break;
19
+ case "nullRate":
20
+ if (typeof i.column != "string" || i.column.length === 0) throw r(t, "nullRate invariant requires a `column`");
21
+ if (!(typeof i.maxRate == "number" && i.maxRate >= 0 && i.maxRate <= 1)) throw r(t, "nullRate invariant requires `maxRate` in [0, 1]");
22
+ break;
23
+ case "rowCount":
24
+ if (i.min === void 0 && i.max === void 0) throw r(t, "rowCount invariant requires at least one of `min` / `max`");
25
+ if (i.min !== void 0 && i.max !== void 0 && i.min > i.max) throw r(t, "rowCount invariant: `min` must not exceed `max`");
26
+ break;
27
+ case "valueBounds":
28
+ if (typeof i.column != "string" || i.column.length === 0) throw r(t, "valueBounds invariant requires a `column`");
29
+ if (i.min === void 0 && i.max === void 0) throw r(t, "valueBounds invariant requires at least one of `min` / `max`");
30
+ if (i.min !== void 0 && i.max !== void 0 && i.min > i.max) throw r(t, "valueBounds invariant: `min` must not exceed `max`");
31
+ if (i.maxViolationRate !== void 0 && !(typeof i.maxViolationRate == "number" && i.maxViolationRate >= 0 && i.maxViolationRate <= 1)) throw r(t, "valueBounds invariant: `maxViolationRate`, when set, must be in [0, 1]");
32
+ break;
33
+ default: throw r(t, `unknown invariant kind ${JSON.stringify(i.kind)}`);
34
+ }
35
+ let a = e.severity ?? "warn";
36
+ if (!n.has(a)) throw r(t, `severity must be one of info | warn | critical (got ${JSON.stringify(a)})`);
37
+ return {
38
+ _voltroExpectation: !0,
39
+ name: t,
40
+ on: e.on.where === void 0 ? { table: e.on.table } : {
41
+ table: e.on.table,
42
+ where: e.on.where
43
+ },
44
+ invariant: i,
45
+ severity: a,
46
+ ...e.description === void 0 ? {} : { description: e.description }
47
+ };
48
+ }, a = (e) => typeof e == "object" && !!e && e._voltroExpectation === !0, o = class extends e.Service()("@voltro/ExpectationRegistry") {}, s = (e) => t.gen(function* () {
49
+ return (yield* o).get(e.name);
50
+ });
51
+ //#endregion
52
+ export { o as ExpectationRegistry, i as defineExpectation, a as isExpectationDefinition, s as useExpectation };