@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,227 @@
1
+ import { and as e, eq as t, generateId as n, inSet as r } from "@voltro/database";
2
+ import { createHash as i, randomBytes as a } from "node:crypto";
3
+ //#region src/apiKeys.ts
4
+ var o = "_voltro_api_keys", s = "actors", c = (e) => i("sha256").update(e, "utf8").digest("hex"), l = (e = "voltro_") => `${e}${a(30).toString("base64url")}`, u = (e) => ({
5
+ id: e.id,
6
+ name: e.name,
7
+ keyPrefix: e.keyPrefix,
8
+ tenantId: e.tenantId,
9
+ scopes: e.scopes ?? [],
10
+ lastUsedAt: e.lastUsedAt,
11
+ expiresAt: e.expiresAt,
12
+ revokedAt: e.revokedAt,
13
+ createdAt: e.createdAt,
14
+ createdBy: e.createdBy ?? null,
15
+ onBehalfOf: e.onBehalfOf ?? null,
16
+ ...e.metadata == null ? {} : { metadata: e.metadata }
17
+ }), d = (e, t) => e.revokedAt === null && (e.expiresAt === null || e.expiresAt > t), f = (e, t = {}) => {
18
+ let r = t.prefix ?? "voltro_", i = t.usage, a = async (t) => {
19
+ let i = l(r), a = n({
20
+ kind: "typeid",
21
+ prefix: "apikey"
22
+ }, o), s = t.scopes ?? [], u = t.expiresAt == null ? null : t.expiresAt instanceof Date ? t.expiresAt.getTime() : t.expiresAt;
23
+ return await e.ensureActor({
24
+ id: a,
25
+ displayName: t.name,
26
+ input: t
27
+ }), await e.insert({
28
+ id: a,
29
+ tenantId: t.tenantId ?? null,
30
+ name: t.name,
31
+ onBehalfOf: t.onBehalfOf ?? null,
32
+ hashedKey: c(i),
33
+ keyPrefix: i.slice(0, r.length + 6),
34
+ scopes: s,
35
+ lastUsedAt: null,
36
+ expiresAt: u,
37
+ revokedAt: null,
38
+ createdBy: t.createdBy ?? null,
39
+ createdAt: Date.now(),
40
+ ...t.metadata == null ? {} : { metadata: t.metadata }
41
+ }), {
42
+ id: a,
43
+ token: i,
44
+ keyPrefix: i.slice(0, r.length + 6),
45
+ name: t.name,
46
+ tenantId: t.tenantId ?? null,
47
+ scopes: s
48
+ };
49
+ }, s = async (t, n = Date.now()) => {
50
+ let r = await e.findByHash(t);
51
+ return !r || !d(r, n) ? null : (i === void 0 ? await e.patch(r.id, { lastUsedAt: n }) : i.touch(r.id, n), {
52
+ id: r.id,
53
+ tenantId: r.tenantId ?? "",
54
+ createdBy: r.createdBy ?? null,
55
+ onBehalfOf: r.onBehalfOf ?? null,
56
+ scopes: r.scopes ?? [],
57
+ ...r.metadata == null ? {} : { metadata: r.metadata }
58
+ });
59
+ };
60
+ return {
61
+ issue: a,
62
+ resolveByHash: s,
63
+ verify: (e, t) => s(c(e), t),
64
+ revoke: async (t, n, r = Date.now()) => {
65
+ let i = await e.findById(t);
66
+ return !i || (i.tenantId ?? null) !== n ? !1 : (await e.patch(t, { revokedAt: r }), !0);
67
+ },
68
+ rotate: async (t, n, r = Date.now()) => {
69
+ let i = await e.findById(t);
70
+ return !i || (i.tenantId ?? null) !== n ? null : (await e.patch(t, { revokedAt: r }), a({
71
+ tenantId: i.tenantId,
72
+ name: i.name,
73
+ scopes: i.scopes ?? [],
74
+ createdBy: i.createdBy,
75
+ onBehalfOf: i.onBehalfOf ?? null,
76
+ ...i.metadata == null ? {} : { metadata: i.metadata }
77
+ }));
78
+ },
79
+ list: async (t) => (await e.listByTenant(t)).map(u)
80
+ };
81
+ }, p = () => {
82
+ let e = /* @__PURE__ */ new Map(), t = /* @__PURE__ */ new Map();
83
+ return {
84
+ actors: t,
85
+ ensureActor: async (e) => {
86
+ t.has(e.id) || t.set(e.id, {
87
+ id: e.id,
88
+ kind: "apiKey",
89
+ displayName: e.displayName
90
+ });
91
+ },
92
+ insert: async (t) => {
93
+ e.set(t.id, t);
94
+ },
95
+ findByHash: async (t) => {
96
+ for (let n of e.values()) if (n.hashedKey === t) return n;
97
+ return null;
98
+ },
99
+ findById: async (t) => e.get(t) ?? null,
100
+ listByTenant: async (t) => {
101
+ let n = [...e.values()], r = 0;
102
+ for (let e of n) e.tenantId === t && (n[r++] = e);
103
+ return n.length = r, n;
104
+ },
105
+ patch: async (t, n) => {
106
+ let r = e.get(t);
107
+ r && e.set(t, {
108
+ ...r,
109
+ ...n
110
+ });
111
+ }
112
+ };
113
+ }, m = (e) => e == null ? null : e instanceof Date ? e.getTime() : typeof e == "number" ? e : typeof e == "string" ? new Date(e).getTime() : null, h = (e) => ({
114
+ id: String(e.id),
115
+ tenantId: e.tenantId ?? null,
116
+ name: String(e.name),
117
+ hashedKey: String(e.hashedKey),
118
+ keyPrefix: String(e.keyPrefix),
119
+ scopes: e.scopes ?? null,
120
+ lastUsedAt: m(e.lastUsedAt),
121
+ expiresAt: m(e.expiresAt),
122
+ revokedAt: m(e.revokedAt),
123
+ createdBy: e.createdBy ?? null,
124
+ onBehalfOf: e.onBehalfOf ?? null,
125
+ createdAt: m(e.createdAt) ?? 0,
126
+ ...e.metadata == null ? {} : { metadata: e.metadata }
127
+ }), g = async (e, t, n = !1) => await e.query({
128
+ table: o,
129
+ predicate: t,
130
+ order: [],
131
+ take: void 0,
132
+ skip: void 0,
133
+ projection: void 0,
134
+ ...n ? { lock: "update" } : {}
135
+ }), _ = async (n, r, i) => {
136
+ let a = await g(n, e(t("id", r), t("tenantId", i)), !0);
137
+ return a[0] ? h(a[0]) : null;
138
+ }, v = async (e) => {
139
+ let t = await e.keys();
140
+ if (t.length === 0) return {
141
+ keys: 0,
142
+ planted: 0,
143
+ failed: []
144
+ };
145
+ let n = /* @__PURE__ */ new Set();
146
+ for (let i = 0; i < t.length; i += 500) {
147
+ let a = t.slice(i, i + 500).map((e) => e.id), o = await e.store.query({
148
+ table: s,
149
+ predicate: r("id", a),
150
+ order: [],
151
+ take: void 0,
152
+ skip: void 0,
153
+ projection: void 0
154
+ });
155
+ for (let e of o) typeof e.id == "string" && n.add(e.id);
156
+ }
157
+ let i = 0, a = [];
158
+ for (let r of t) if (!n.has(r.id)) try {
159
+ await e.apiKeyStore.ensureActor({
160
+ id: r.id,
161
+ displayName: r.name,
162
+ input: {
163
+ tenantId: r.tenantId,
164
+ name: r.name,
165
+ scopes: r.scopes ?? [],
166
+ createdBy: r.createdBy,
167
+ onBehalfOf: r.onBehalfOf ?? null,
168
+ ...r.metadata == null ? {} : { metadata: r.metadata }
169
+ }
170
+ }), i++;
171
+ } catch (e) {
172
+ a.push({
173
+ id: r.id,
174
+ reason: e instanceof Error ? e.message : String(e)
175
+ });
176
+ }
177
+ return {
178
+ keys: t.length,
179
+ planted: i,
180
+ failed: a
181
+ };
182
+ }, y = (e) => async (t, n) => {
183
+ let r = await e.findById(t);
184
+ if (r === null) return;
185
+ let i = r.requestCount ?? 0, a = r.lastUsedAt ?? 0;
186
+ await e.patch(t, {
187
+ requestCount: i + n.requests,
188
+ lastUsedAt: Math.max(a, n.lastUsedAt)
189
+ });
190
+ }, b = (e, n = {}) => {
191
+ let r = n.ensureActor, i = (t) => g(e, t), a = (e) => {
192
+ let t = { ...e };
193
+ for (let e of [
194
+ "lastUsedAt",
195
+ "expiresAt",
196
+ "revokedAt",
197
+ "createdAt"
198
+ ]) e in t && typeof t[e] == "number" && (t[e] = new Date(t[e]));
199
+ return t;
200
+ };
201
+ return {
202
+ ensureActor: r === void 0 ? async (t) => {
203
+ await e.insertIgnore(s, {
204
+ id: t.id,
205
+ kind: "apiKey",
206
+ displayName: t.displayName
207
+ }, { conflictColumns: ["id"] });
208
+ } : (t) => r(t, e),
209
+ insert: async (t) => {
210
+ await e.insert(o, a(t));
211
+ },
212
+ findByHash: async (e) => {
213
+ let n = await i(t("hashedKey", e));
214
+ return n[0] ? h(n[0]) : null;
215
+ },
216
+ findById: async (e) => {
217
+ let n = await i(t("id", e));
218
+ return n[0] ? h(n[0]) : null;
219
+ },
220
+ listByTenant: async (e) => (await i(e === null ? void 0 : t("tenantId", e))).map(h).filter((t) => e === null || t.tenantId === e),
221
+ patch: async (t, n) => {
222
+ await e.update(o, t, a(n));
223
+ }
224
+ };
225
+ };
226
+ //#endregion
227
+ export { s as ACTORS_TABLE, o as API_KEYS_TABLE, b as dataStoreApiKeyStore, l as generateApiKeyToken, _ as lockApiKeyById, f as makeApiKeyService, y as makeApiKeyUsageFlusher, p as memoryApiKeyStore, v as plantMissingApiKeyActors, c as sha256Hex };
@@ -0,0 +1,114 @@
1
+ import { Schema as e } from "effect";
2
+ import { ADMIN_SCOPE as t, APIKEY_ISSUE_ORG_SCOPE as n, APIKEY_ISSUE_OTHER_SCOPE as r, APIKEY_ISSUE_SELF_SCOPE as i, ScopeError as a } from "@voltro/protocol";
3
+ import { defineRestRoute as o, requireAnyScope as s, requireScope as c } from "@voltro/protocol/rest";
4
+ import { apiKeyStrategy as l } from "@voltro/protocol/apikey";
5
+ //#region src/apiKeysWiring.ts
6
+ var u = (e, t = {}) => l({
7
+ id: "voltro-apikey",
8
+ ...t.prefix ? { prefix: t.prefix } : {},
9
+ resolveKey: (t) => e.resolveByHash(t)
10
+ }), d = (e) => {
11
+ let t = e.subject;
12
+ return {
13
+ id: t.id ?? null,
14
+ tenantId: t.tenantId ?? null,
15
+ scopes: t.scopes ?? []
16
+ };
17
+ }, f = (l, u = "/v1/api-keys") => {
18
+ let f = e.Struct({
19
+ id: e.String,
20
+ name: e.String,
21
+ keyPrefix: e.String,
22
+ tenantId: e.NullOr(e.String),
23
+ scopes: e.Array(e.String),
24
+ lastUsedAt: e.NullOr(e.Number),
25
+ expiresAt: e.NullOr(e.Number),
26
+ revokedAt: e.NullOr(e.Number),
27
+ createdAt: e.Number,
28
+ createdBy: e.NullOr(e.String),
29
+ onBehalfOf: e.NullOr(e.String),
30
+ metadata: e.optional(e.NullOr(e.Record(e.String, e.Unknown)))
31
+ });
32
+ return [
33
+ o({
34
+ method: "POST",
35
+ path: `${u}/issue`,
36
+ summary: "Issue an API key (the token is returned ONCE).",
37
+ guards: [s([
38
+ t,
39
+ i,
40
+ n,
41
+ r
42
+ ])],
43
+ input: e.Struct({ body: e.Struct({
44
+ name: e.String,
45
+ scopes: e.optional(e.Array(e.String)),
46
+ expiresInDays: e.optional(e.Number),
47
+ onBehalfOf: e.optional(e.NullOr(e.String))
48
+ }) }),
49
+ output: e.Struct({
50
+ id: e.String,
51
+ token: e.String,
52
+ keyPrefix: e.String
53
+ }),
54
+ handler: async (e, o) => {
55
+ let s = e.body, c = d(o), u = new Set(c.scopes), f = (e) => u.has(t) || u.has(e), p = s.onBehalfOf === void 0 ? c.id : s.onBehalfOf;
56
+ if (p === null) {
57
+ if (!f(n)) throw new a({
58
+ required: n,
59
+ message: "not allowed to issue an organization key"
60
+ });
61
+ } else if (p !== c.id) {
62
+ if (!f(r)) throw new a({
63
+ required: r,
64
+ message: "not allowed to issue a key on behalf of another user"
65
+ });
66
+ } else if (!f(i)) throw new a({
67
+ required: i,
68
+ message: "not allowed to issue an api key"
69
+ });
70
+ let m = s.scopes ?? [...u];
71
+ if (!u.has(t)) {
72
+ let e = m.filter((e) => !u.has(e));
73
+ if (e.length > 0) throw new a({
74
+ required: String(e[0]),
75
+ message: `cannot issue a key with scopes you do not hold: ${e.join(", ")}`
76
+ });
77
+ }
78
+ let h = await l.issue({
79
+ tenantId: c.tenantId,
80
+ name: s.name,
81
+ scopes: m,
82
+ ...s.expiresInDays ? { expiresAt: Date.now() + s.expiresInDays * 864e5 } : {},
83
+ createdBy: c.id,
84
+ onBehalfOf: p
85
+ });
86
+ return {
87
+ id: h.id,
88
+ token: h.token,
89
+ keyPrefix: h.keyPrefix
90
+ };
91
+ }
92
+ }),
93
+ o({
94
+ method: "GET",
95
+ path: u,
96
+ summary: "List the caller tenant's API keys (no secrets).",
97
+ guards: [c(t)],
98
+ input: e.Struct({}),
99
+ output: e.Struct({ keys: e.Array(f) }),
100
+ handler: async (e, t) => ({ keys: [...await l.list(d(t).tenantId)] })
101
+ }),
102
+ o({
103
+ method: "POST",
104
+ path: `${u}/revoke`,
105
+ summary: "Revoke an API key by id.",
106
+ guards: [c(t)],
107
+ input: e.Struct({ body: e.Struct({ id: e.String }) }),
108
+ output: e.Struct({ ok: e.Boolean }),
109
+ handler: async (e, t) => ({ ok: await l.revoke(e.body.id, d(t).tenantId) })
110
+ })
111
+ ];
112
+ };
113
+ //#endregion
114
+ export { f as apiKeyManagementRoutes, u as frameworkApiKeyStrategy };
@@ -0,0 +1,64 @@
1
+ import { API_ROLE_BUCKET_MS as e } from "./apiRoleWorkloadHistory.js";
2
+ import { API_WORKLOADS as t } from "@voltro/protocol";
3
+ //#region src/apiRoleBucketSampler.ts
4
+ var n = (n) => {
5
+ let r = [...new Set(n.workloads)];
6
+ if (!n.replicaId || n.replicaId.length > 191 || !n.role || n.role.length > 2080 || n.startedAt < 0 || n.epochNow < 0 || n.monotonicNow < 0 || !r.length || r.some((e) => !t.includes(e)) || !Number.isFinite(n.monotonicNow) || !Number.isSafeInteger(n.epochNow) || !Number.isSafeInteger(n.startedAt) || n.startedAt > n.epochNow) throw Error("Invalid role sampler configuration");
7
+ let i = n.epochNow - n.monotonicNow, a = (t) => Math.floor(t / e) * e, o = /* @__PURE__ */ new Map(), s = a(n.epochNow), c = n.epochNow, l = 0, u = 0, d = n.monotonicNow, f = (e) => {
8
+ let t = o.get(e);
9
+ return t || (t = {
10
+ from: e,
11
+ continuous: e >= n.epochNow,
12
+ seconds: /* @__PURE__ */ new Map()
13
+ }, o.set(e, t), o.size > 290 && (o.delete(Math.min(...o.keys())), l++)), t;
14
+ }, p = (t) => ({
15
+ replicaId: n.replicaId,
16
+ startedAt: n.startedAt,
17
+ role: n.role,
18
+ from: t.from,
19
+ until: t.from + e,
20
+ continuous: t.continuous,
21
+ workloads: Object.fromEntries(r.map((e) => [e, {
22
+ coverage: "partial",
23
+ seconds: t.seconds.get(e) ?? 0
24
+ }]))
25
+ });
26
+ return {
27
+ record(t) {
28
+ let n = i + t.from, o = i + t.until;
29
+ if (!r.includes(t.workload) || !Number.isFinite(n) || !Number.isFinite(o) || o <= n || t.from < d || n < s || o - n > 87e6) u++;
30
+ else {
31
+ d = t.until;
32
+ for (let r = a(n); r < o; r += e) {
33
+ let i = f(r), a = (Math.min(o, r + e) - Math.max(n, r)) / 1e3;
34
+ i.seconds.set(t.workload, (i.seconds.get(t.workload) ?? 0) + a);
35
+ }
36
+ }
37
+ },
38
+ advance(t, n) {
39
+ let r = i + t;
40
+ if (!Number.isFinite(r) || r < c || !Number.isFinite(n)) return;
41
+ let o = a(r), u = Math.max(s, o - 290 * e);
42
+ u > s && (l += (u - s) / e);
43
+ let d = r - c > 6e4 || Math.abs(n - r) > 1e3;
44
+ for (let t = u; t < o; t += e) {
45
+ let e = f(t);
46
+ d && (e.continuous = !1);
47
+ }
48
+ d && (f(o).continuous = !1), s = o, c = r;
49
+ },
50
+ pending() {
51
+ return [...o.values()].filter((t) => t.from + e <= s).sort((e, t) => e.from - t.from).map(p);
52
+ },
53
+ acknowledge(e) {
54
+ e + 3e5 <= s && o.delete(e);
55
+ },
56
+ status: () => ({
57
+ pendingBuckets: [...o.keys()].filter((t) => t + e <= s).length,
58
+ droppedBuckets: l,
59
+ rejectedSegments: u
60
+ })
61
+ };
62
+ };
63
+ //#endregion
64
+ export { n as makeApiRoleBucketSampler };
@@ -0,0 +1,56 @@
1
+ import { API_WORKLOADS as e } from "@voltro/protocol";
2
+ //#region src/apiRoleWorkloadHistory.ts
3
+ var t = 3e5, n = 864e5, r = (r) => {
4
+ if (!Number.isSafeInteger(r.startedAt) || r.startedAt < 0 || r.startedAt > r.now || !r.replicaId || !r.role || !Number.isSafeInteger(r.now) || r.now < 864e5) throw Error("Invalid role observation time");
5
+ let i = Math.floor(r.now / t) * t, a = i - n, o = n / t, s = [...new Set(r.requiredWorkloads)];
6
+ if (!s.length || s.some((t) => !e.includes(t))) throw Error("Invalid required workloads");
7
+ let c = (e, t, n = s) => ({
8
+ from: a,
9
+ until: i,
10
+ complete: !1,
11
+ reason: e,
12
+ missingBuckets: t,
13
+ incompleteWorkloads: n,
14
+ totals: [],
15
+ splitCandidates: []
16
+ });
17
+ if (r.buckets.length > 290) return c("invalid-observation", o);
18
+ let l = /* @__PURE__ */ new Map();
19
+ for (let t of r.buckets) {
20
+ if (t.replicaId !== r.replicaId || t.startedAt !== r.startedAt || t.role !== r.role || !Number.isSafeInteger(t.from) || t.from < 0 || t.from % 3e5 != 0 || t.until !== t.from + 3e5 || typeof t.continuous != "boolean") return c("invalid-observation", o);
21
+ let n = 0;
22
+ for (let [r, i] of Object.entries(t.workloads)) {
23
+ if (!e.includes(r) || !s.includes(r) || !i || !["partial", "complete"].includes(i.coverage) || !Number.isFinite(i.seconds) || i.seconds < 0) return c("invalid-observation", o);
24
+ n += i.seconds;
25
+ }
26
+ if (n > 300) return c("invalid-observation", o);
27
+ if (!(t.until <= a || t.from >= i)) {
28
+ if (l.has(t.from)) return c("invalid-observation", o);
29
+ l.set(t.from, t);
30
+ }
31
+ }
32
+ let u = /* @__PURE__ */ new Set(), d = new Map(s.map((e) => [e, 0]));
33
+ for (let e of l.values()) for (let t of s) {
34
+ let n = e.workloads[t];
35
+ (!e.continuous || e.from < r.startedAt || n?.coverage !== "complete") && u.add(t), n && d.set(t, d.get(t) + n.seconds);
36
+ }
37
+ let f = o - l.size;
38
+ if (f || u.size) return c("incomplete", f, [...u]);
39
+ let p = [...d.values()].reduce((e, t) => e + t, 0), m = [...d].map(([e, t]) => ({
40
+ workload: e,
41
+ seconds: t,
42
+ share: p === 0 ? 0 : t / p
43
+ })), h = m.filter((e) => e.share > .3).map((e) => e.workload);
44
+ return {
45
+ from: a,
46
+ until: i,
47
+ complete: !0,
48
+ missingBuckets: 0,
49
+ incompleteWorkloads: [],
50
+ reason: p === 0 ? "idle" : "observed",
51
+ totals: m,
52
+ splitCandidates: h.length >= 2 ? h : []
53
+ };
54
+ };
55
+ //#endregion
56
+ export { t as API_ROLE_BUCKET_MS, n as API_ROLE_WINDOW_MS, r as assessApiRoleWorkloadWindow };
@@ -0,0 +1,78 @@
1
+ import { Effect as e, Metric as t, Tracer as n } from "effect";
2
+ import { API_WORKLOADS as r } from "@voltro/protocol";
3
+ //#region src/apiRoleWorkloadMetrics.ts
4
+ var i = t.counter("api_role_workload_seconds_total", { description: "Measured active synchronous loop seconds by selected API role set and workload; excludes asynchronous waits." }), a = (e) => {
5
+ if (e.length === 0 || e.length > 32 || e.some((e) => !/^[a-z][a-z0-9-]{0,63}$/.test(e))) throw Error("Invalid API metric roles");
6
+ return [...new Set(e)].sort().join(",");
7
+ }, o = (o, s = {}) => {
8
+ let c = a(o), l = s.now ?? (() => performance.now()), u = new Map(r.map((e) => [e, i.pipe(t.withAttributes({
9
+ role: c,
10
+ workload: e
11
+ }))])), d = /* @__PURE__ */ new Map(), f = 0, p = [], m = (n, r) => {
12
+ let i = (r - n.since) / 1e3;
13
+ if (!(!Number.isFinite(i) || i <= 0)) {
14
+ try {
15
+ s.onSegment?.({
16
+ workload: n.workload,
17
+ from: n.since,
18
+ until: r
19
+ });
20
+ } catch {
21
+ f++;
22
+ }
23
+ d.set(n.workload, (d.get(n.workload) ?? 0) + i), e.runSync(t.update(u.get(n.workload), i));
24
+ }
25
+ }, h = (e) => {
26
+ if (!u.has(e)) throw Error("Unknown API metric workload");
27
+ let t = p[p.length - 1];
28
+ t && m(t, l());
29
+ let n = {
30
+ workload: e,
31
+ since: l()
32
+ };
33
+ return p.push(n), n;
34
+ }, g = (e) => {
35
+ let t = l();
36
+ p.pop(), m(e, t);
37
+ let n = p[p.length - 1];
38
+ n && (n.since = l());
39
+ };
40
+ return {
41
+ role: c,
42
+ observationErrors: () => f,
43
+ observeEffect(t, r) {
44
+ if (!u.has(r)) throw Error("Unknown API metric workload");
45
+ return e.withFiber((i) => {
46
+ let a = i.getRef(n.Tracer), o = n.make({
47
+ span: (e) => a.span(e),
48
+ context: (e, t) => {
49
+ let n = h(r);
50
+ try {
51
+ return a.context === void 0 ? e["~effect/Effect/evaluate"](t) : a.context(e, t);
52
+ } finally {
53
+ g(n);
54
+ }
55
+ }
56
+ });
57
+ return t.pipe(e.provideService(n.Tracer, o));
58
+ });
59
+ },
60
+ measureSync(e, t) {
61
+ let n = h(e);
62
+ try {
63
+ return t();
64
+ } finally {
65
+ g(n);
66
+ }
67
+ },
68
+ snapshot() {
69
+ return [...d].map(([e, t]) => ({
70
+ role: c,
71
+ workload: e,
72
+ seconds: t
73
+ }));
74
+ }
75
+ };
76
+ }, s = (e, t, n) => t.observeEffect(e, n);
77
+ //#endregion
78
+ export { a as apiRoleMetricLabel, o as makeApiRoleWorkloadMetrics, s as observeApiRoleEffect };
@@ -0,0 +1,95 @@
1
+ import { API_ROLE_BUCKET_MS as e, API_ROLE_WINDOW_MS as t, assessApiRoleWorkloadWindow as n } from "./apiRoleWorkloadHistory.js";
2
+ //#region src/apiRoleWorkloadStorage.ts
3
+ var r = "_voltro_api_role_workload_buckets", i = 16384, a = (e) => e instanceof Date ? e.getTime() : typeof e == "number" ? e : NaN, o = async (e, t) => {
4
+ let a = Object.keys(t.workloads);
5
+ if (n({
6
+ now: Math.max(864e5, t.until),
7
+ replicaId: t.replicaId,
8
+ startedAt: t.startedAt,
9
+ role: t.role,
10
+ requiredWorkloads: a,
11
+ buckets: [t]
12
+ }).reason === "invalid-observation" || !t.replicaId || t.replicaId.length > 191 || t.role.length > 2080) throw Error("Invalid API role history bucket");
13
+ let o = JSON.stringify({
14
+ version: 1,
15
+ continuous: t.continuous,
16
+ workloads: t.workloads
17
+ });
18
+ if (new TextEncoder().encode(o).byteLength > i) throw Error("API role history payload too large");
19
+ await e.upsert(r, {
20
+ replicaId: t.replicaId,
21
+ startedAt: new Date(t.startedAt),
22
+ role: t.role,
23
+ bucketFrom: new Date(t.from),
24
+ bucketUntil: new Date(t.until),
25
+ payload: o
26
+ }, { conflictColumns: [
27
+ "replicaId",
28
+ "startedAt",
29
+ "bucketFrom"
30
+ ] });
31
+ }, s = async (o, s) => {
32
+ let c = n({
33
+ ...s,
34
+ buckets: []
35
+ }), l = (await o.query({
36
+ table: r,
37
+ predicate: { and: [
38
+ {
39
+ column: "replicaId",
40
+ op: "eq",
41
+ value: s.replicaId
42
+ },
43
+ {
44
+ column: "startedAt",
45
+ op: "eq",
46
+ value: new Date(s.startedAt)
47
+ },
48
+ {
49
+ column: "role",
50
+ op: "eq",
51
+ value: s.role
52
+ },
53
+ {
54
+ column: "bucketFrom",
55
+ op: "gte",
56
+ value: new Date(c.from)
57
+ },
58
+ {
59
+ column: "bucketFrom",
60
+ op: "lt",
61
+ value: new Date(c.until)
62
+ }
63
+ ] },
64
+ order: [{
65
+ column: "bucketFrom",
66
+ direction: "asc"
67
+ }],
68
+ take: t / e + 1,
69
+ skip: void 0,
70
+ projection: void 0
71
+ })).map((e) => {
72
+ if (typeof e.payload != "string" || new TextEncoder().encode(e.payload).byteLength > i) throw Error("Invalid API role history payload");
73
+ let t = JSON.parse(e.payload);
74
+ if (!t || t.version !== 1 || typeof t.continuous != "boolean" || !t.workloads || typeof t.workloads != "object" || Array.isArray(t.workloads)) throw Error("Invalid API role history payload");
75
+ return {
76
+ replicaId: String(e.replicaId),
77
+ startedAt: a(e.startedAt),
78
+ role: String(e.role),
79
+ from: a(e.bucketFrom),
80
+ until: a(e.bucketUntil),
81
+ continuous: t.continuous,
82
+ workloads: t.workloads
83
+ };
84
+ }), u = n({
85
+ ...s,
86
+ buckets: l
87
+ });
88
+ if (u.reason === "invalid-observation") throw Error("Invalid API role history observations");
89
+ return {
90
+ buckets: l,
91
+ assessment: u
92
+ };
93
+ };
94
+ //#endregion
95
+ export { r as API_ROLE_WORKLOAD_BUCKETS_TABLE, s as readApiRoleWorkloadWindow, o as writeApiRoleWorkloadBucket };
@@ -0,0 +1,10 @@
1
+ import { decideApproval as e, pendingApprovalsFor as t } from "./approvals.js";
2
+ //#region src/approvalBuiltins.ts
3
+ var n = (e) => e.request?.subject ?? null, r = async (e, r) => t(r.store, n(r), { limit: e.limit ?? 50 }), i = async (t, r) => e(r.store, {
4
+ approvalId: t.approvalId,
5
+ decision: t.decision,
6
+ approver: n(r),
7
+ ...t.note === void 0 ? {} : { note: t.note }
8
+ });
9
+ //#endregion
10
+ export { r as approvalsPendingExecutor, i as decideApprovalInvocation };