@plitzi/sdk-actions 0.0.0-stage → 0.39.3

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 (168) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +54 -2
  3. package/dist/chunks/credentials-DwxZeAvH.mjs +27 -0
  4. package/dist/chunks/errors-bCBfIe7c.mjs +54 -0
  5. package/dist/chunks/grants-BsD-WlLE.mjs +168 -0
  6. package/dist/chunks/load-DBWRZn7G.mjs +48 -0
  7. package/dist/chunks/module-WdDzbjHy.mjs +7032 -0
  8. package/dist/chunks/queueDocument-xYz-KZ5V.mjs +21 -0
  9. package/dist/chunks/queueRules-BCCVgeUE.mjs +487 -0
  10. package/dist/chunks/remote-DopPgCMK.mjs +404 -0
  11. package/dist/chunks/storeClock-Btm7EaVm.mjs +31 -0
  12. package/dist/chunks/taskCatalog-S1IozUTD.mjs +201 -0
  13. package/dist/connectors/connectors.d.ts +7 -0
  14. package/dist/connectors/engine.d.ts +47 -0
  15. package/dist/connectors/getByPath.d.ts +8 -0
  16. package/dist/connectors/projection.d.ts +18 -0
  17. package/dist/connectors/resolver.d.ts +27 -0
  18. package/dist/connectors/types.d.ts +19 -0
  19. package/dist/engine/configSeam.d.ts +10 -0
  20. package/dist/engine/connectorWrite.d.ts +12 -0
  21. package/dist/engine/fileStore.d.ts +60 -0
  22. package/dist/engine/fleet.d.ts +20 -0
  23. package/dist/engine/jobs/calls.d.ts +49 -0
  24. package/dist/engine/jobs/claimSpaces.d.ts +10 -0
  25. package/dist/engine/jobs/codeMarks.d.ts +10 -0
  26. package/dist/engine/jobs/endings.d.ts +42 -0
  27. package/dist/engine/jobs/failureStreak.d.ts +15 -0
  28. package/dist/engine/jobs/fileQueue.d.ts +34 -0
  29. package/dist/engine/jobs/flow.d.ts +11 -0
  30. package/dist/engine/jobs/jobs.d.ts +36 -0
  31. package/dist/engine/jobs/later.d.ts +27 -0
  32. package/dist/engine/jobs/memoryNeeds.d.ts +24 -0
  33. package/dist/engine/jobs/memoryQueue.d.ts +33 -0
  34. package/dist/engine/jobs/memoryWatch.d.ts +21 -0
  35. package/dist/engine/jobs/notNow.d.ts +39 -0
  36. package/dist/engine/jobs/queueDocument.d.ts +15 -0
  37. package/dist/engine/jobs/queueRules.d.ts +64 -0
  38. package/dist/engine/jobs/scheduler.d.ts +70 -0
  39. package/dist/engine/jobs/schedules.d.ts +24 -0
  40. package/dist/engine/jobs/storeClock.d.ts +16 -0
  41. package/dist/engine/jobs/wake.d.ts +6 -0
  42. package/dist/engine/jobs/worker.d.ts +99 -0
  43. package/dist/engine/module.d.ts +96 -0
  44. package/dist/engine/moduleFor.d.ts +3 -0
  45. package/dist/engine/runtime/check.d.ts +24 -0
  46. package/dist/engine/runtime/credentials.d.ts +8 -0
  47. package/dist/engine/runtime/deadline.d.ts +19 -0
  48. package/dist/engine/runtime/email.d.ts +38 -0
  49. package/dist/engine/runtime/errors.d.ts +28 -0
  50. package/dist/engine/runtime/fileKv.d.ts +35 -0
  51. package/dist/engine/runtime/flags.d.ts +16 -0
  52. package/dist/engine/runtime/guards.d.ts +190 -0
  53. package/dist/engine/runtime/kvList.d.ts +28 -0
  54. package/dist/engine/runtime/kvStore.d.ts +36 -0
  55. package/dist/engine/runtime/limits.d.ts +12 -0
  56. package/dist/engine/runtime/memoryKv.d.ts +28 -0
  57. package/dist/engine/runtime/namespaceKv.d.ts +9 -0
  58. package/dist/engine/runtime/precheck.d.ts +28 -0
  59. package/dist/engine/runtime/rateLimit.d.ts +9 -0
  60. package/dist/engine/runtime/redisKv.d.ts +27 -0
  61. package/dist/engine/runtime/renderFailure.d.ts +24 -0
  62. package/dist/engine/runtime/renderResolver.d.ts +16 -0
  63. package/dist/engine/runtime/renderShare.d.ts +12 -0
  64. package/dist/engine/runtime/report.d.ts +15 -0
  65. package/dist/engine/runtime/runAction.d.ts +26 -0
  66. package/dist/engine/runtime/runLogger.d.ts +37 -0
  67. package/dist/engine/runtime/runStats.d.ts +8 -0
  68. package/dist/engine/runtime/scope.d.ts +40 -0
  69. package/dist/engine/runtime/signing.d.ts +27 -0
  70. package/dist/engine/runtime/taskContext.d.ts +54 -0
  71. package/dist/engine/runtime/triggers.d.ts +12 -0
  72. package/dist/engine/taskCatalog.d.ts +28 -0
  73. package/dist/engine/tasks/auth.d.ts +2 -0
  74. package/dist/engine/tasks/builtins.d.ts +10 -0
  75. package/dist/engine/tasks/connector.d.ts +2 -0
  76. package/dist/engine/tasks/db.d.ts +2 -0
  77. package/dist/engine/tasks/email.d.ts +2 -0
  78. package/dist/engine/tasks/flow.d.ts +3 -0
  79. package/dist/engine/tasks/helpers.d.ts +16 -0
  80. package/dist/engine/tasks/http.d.ts +2 -0
  81. package/dist/engine/tasks/kv.d.ts +2 -0
  82. package/dist/engine/tasks/list.d.ts +2 -0
  83. package/dist/engine/tasks/names.d.ts +8 -0
  84. package/dist/engine/tasks/realtime.d.ts +3 -0
  85. package/dist/engine/tasks/registry.d.ts +19 -0
  86. package/dist/engine/tasks/transform.d.ts +2 -0
  87. package/dist/engine/transport/callHandler.d.ts +34 -0
  88. package/dist/engine/transport/cancelHandler.d.ts +23 -0
  89. package/dist/engine/transport/catalogHandler.d.ts +22 -0
  90. package/dist/engine/transport/stream.d.ts +22 -0
  91. package/dist/engine/transport/verifySignature.d.ts +16 -0
  92. package/dist/engine/transport/webhookHandler.d.ts +26 -0
  93. package/dist/engine/types.d.ts +442 -0
  94. package/dist/functions/build.d.ts +27 -0
  95. package/dist/functions/capabilities.d.ts +11 -0
  96. package/dist/functions/config.d.ts +111 -0
  97. package/dist/functions/context.d.ts +15 -0
  98. package/dist/functions/index.d.ts +17 -0
  99. package/dist/functions/index.mjs +461 -0
  100. package/dist/functions/jobControl.d.ts +22 -0
  101. package/dist/functions/jobs.d.ts +104 -0
  102. package/dist/functions/load.d.ts +22 -0
  103. package/dist/functions/local.d.ts +36 -0
  104. package/dist/functions/manifest.d.ts +32 -0
  105. package/dist/functions/native.d.ts +13 -0
  106. package/dist/functions/oauth.d.ts +33 -0
  107. package/dist/functions/routes.d.ts +50 -0
  108. package/dist/functions/runner/remote.d.ts +26 -0
  109. package/dist/functions/scope.d.ts +28 -0
  110. package/dist/functions/space.d.ts +41 -0
  111. package/dist/functions/tryEntry.d.ts +9 -0
  112. package/dist/index.d.ts +47 -0
  113. package/dist/index.mjs +545 -0
  114. package/dist/mongo/claimable.d.ts +5 -0
  115. package/dist/mongo/index.d.ts +4 -0
  116. package/dist/mongo/index.mjs +779 -0
  117. package/dist/mongo/jobQueue.d.ts +38 -0
  118. package/dist/mongo/kv.d.ts +15 -0
  119. package/dist/mysql/index.d.ts +5 -0
  120. package/dist/mysql/index.mjs +808 -0
  121. package/dist/mysql/jobQueue.d.ts +40 -0
  122. package/dist/mysql/kv.d.ts +18 -0
  123. package/dist/mysql/rows.d.ts +64 -0
  124. package/dist/mysql/schema.d.ts +28 -0
  125. package/dist/mysql/summary.d.ts +7 -0
  126. package/dist/realtime/declarations.d.ts +11 -0
  127. package/dist/realtime/failure.d.ts +6 -0
  128. package/dist/realtime/grants.d.ts +22 -0
  129. package/dist/realtime/handlers.d.ts +86 -0
  130. package/dist/realtime/hub.d.ts +71 -0
  131. package/dist/realtime/index.d.ts +105 -0
  132. package/dist/realtime/index.mjs +824 -0
  133. package/dist/realtime/jobs.d.ts +18 -0
  134. package/dist/realtime/message.d.ts +3 -0
  135. package/dist/realtime/presence.d.ts +33 -0
  136. package/dist/realtime/retained.d.ts +21 -0
  137. package/dist/realtime/socket.d.ts +30 -0
  138. package/dist/render/index.d.ts +10 -0
  139. package/dist/render/index.mjs +1 -0
  140. package/dist/render/protocol.d.ts +47 -0
  141. package/dist/render/remote.d.ts +16 -0
  142. package/dist/runtimes/bundle.d.ts +29 -0
  143. package/dist/runtimes/index.d.ts +3 -0
  144. package/dist/runtimes/index.mjs +229 -0
  145. package/dist/runtimes/stages.d.ts +52 -0
  146. package/dist/sqlite/index.d.ts +4 -0
  147. package/dist/sqlite/index.mjs +160 -0
  148. package/dist/sqlite/jobQueue.d.ts +35 -0
  149. package/dist/sqlite/kv.d.ts +34 -0
  150. package/dist/sqlite/open.d.ts +3 -0
  151. package/dist/types/config.d.ts +293 -0
  152. package/dist/types/index.d.ts +2 -0
  153. package/dist/types/index.mjs +1 -0
  154. package/dist/types/jobs.d.ts +317 -0
  155. package/dist/worker/elsewhere.d.ts +16 -0
  156. package/dist/worker/index.d.ts +5 -0
  157. package/dist/worker/index.mjs +1703 -0
  158. package/dist/worker/origin.d.ts +12 -0
  159. package/dist/worker/pageEngine.d.ts +11 -0
  160. package/dist/worker/stages/action.d.ts +24 -0
  161. package/dist/worker/stages/cors.d.ts +9 -0
  162. package/dist/worker/stages/forward.d.ts +12 -0
  163. package/dist/worker/stages/functionRoutes.d.ts +10 -0
  164. package/dist/worker/stages/queuedCalls.d.ts +15 -0
  165. package/dist/worker/stages/realtime.d.ts +9 -0
  166. package/dist/worker/stages/render.d.ts +9 -0
  167. package/dist/worker/worker.d.ts +39 -0
  168. package/package.json +76 -3
@@ -0,0 +1,461 @@
1
+ import { c as oauthCallbackUrlOn, d as DEFAULT_FUNCTION_LIMITS, i as buildFunctions, l as readManifest, n as functionsInHand, o as DEFAULT_FUNCTION_JOB_LIMITS, r as FunctionsBuildError, t as createActionsModule, u as DEFAULT_FUNCTION_CEILINGS } from "../chunks/module-WdDzbjHy.mjs";
2
+ import { i as readFunctionsDir, n as loadFunctions, r as loadFunctionsSource } from "../chunks/load-DBWRZn7G.mjs";
3
+ import { t as credentialsFromEnv } from "../chunks/credentials-DwxZeAvH.mjs";
4
+ import { randomUUID } from "node:crypto";
5
+ import { FUNCTIONS_PROTOCOL, FunctionFailure, failedAnswerOf, readResponseMessage } from "@plitzi/sdk-shared/functions";
6
+ import { frameText } from "@plitzi/sdk-kernel/http";
7
+ import { lookup } from "node:dns/promises";
8
+ import { dataDirLookup } from "@plitzi/sdk-kernel/data";
9
+ import { isIP } from "node:net";
10
+ import { WebSocket } from "ws";
11
+ // src/functions/tryEntry.ts
12
+ var step = (id, fields) => ({
13
+ id,
14
+ title: id,
15
+ type: "task",
16
+ action: "",
17
+ params: {},
18
+ preview: {},
19
+ elementId: null,
20
+ beforeNode: "",
21
+ afterNode: "",
22
+ flowId: "try",
23
+ enabled: true,
24
+ ...fields
25
+ });
26
+ /** The id of the step that runs the task in a {@link functionTryEntry}: where its value, logs and error are found. */
27
+ var TRY_STEP = "task";
28
+ /**
29
+ * One task as the smallest flow that runs it: a session call, the task, and its answer — so trying a function is an
30
+ * ordinary run, with every check, limit and record a run has, and nothing of its own to keep in step. The builder's
31
+ * Try, an agent's and `plitzi functions dev` are all this.
32
+ */
33
+ var functionTryEntry = (task, params) => ({
34
+ id: `try:${task}`,
35
+ document: {
36
+ name: `Try ${task}`,
37
+ output: { value: { type: "json" } },
38
+ nodes: {
39
+ start: step("start", {
40
+ type: "trigger",
41
+ action: "call",
42
+ params: { access: "session" },
43
+ afterNode: TRY_STEP
44
+ }),
45
+ [TRY_STEP]: step(TRY_STEP, {
46
+ title: task,
47
+ action: task,
48
+ params,
49
+ afterNode: "answer"
50
+ }),
51
+ answer: step("answer", {
52
+ action: "flow.output",
53
+ params: { values: `{"value": {{ ${TRY_STEP}|json_encode }}}` }
54
+ })
55
+ }
56
+ }
57
+ });
58
+ // src/functions/local.ts
59
+ /** Who a local run is for: somebody signed in, with nothing to forward. */
60
+ var LOCAL_USER = {
61
+ id: 0,
62
+ username: "local",
63
+ email: "local@localhost",
64
+ verified: true,
65
+ permissions: [],
66
+ roles: [],
67
+ token: ""
68
+ };
69
+ /**
70
+ * A space's functions run on this machine exactly as the platform runs them — the same build, the same checks, the same
71
+ * isolates and limits, `ctx` over the same actions module — so what works here works there. `kv` lives as long as this
72
+ * does. What `plitzi functions dev` is made of, with the isolate runner of `@plitzi/sdk-runtime`.
73
+ */
74
+ var createLocalFunctions = ({ runner, credentials = credentialsFromEnv(), limits, dataDir, fetchImpl }) => {
75
+ let loaded;
76
+ const module = createActionsModule({
77
+ lookups: {
78
+ getAction: () => Promise.resolve(void 0),
79
+ getCredential: (_spaceId, identifier) => Promise.resolve(Object.hasOwn(credentials, identifier) ? credentials[identifier] : void 0),
80
+ getFunctions: () => Promise.resolve(loaded),
81
+ ...dataDir ? { getData: dataDirLookup(dataDir) } : {}
82
+ },
83
+ functions: {
84
+ runner,
85
+ ...limits ? { limits } : {}
86
+ },
87
+ jobs: false,
88
+ ...fetchImpl ? { fetchImpl } : {}
89
+ });
90
+ return {
91
+ load: async (source) => {
92
+ const prepared = await module.prepareFunctions(source);
93
+ if (!prepared.ok) return prepared;
94
+ loaded = functionsInHand(prepared.functions);
95
+ return {
96
+ ok: true,
97
+ tasks: prepared.functions.manifest.tasks.map((task) => `${task.namespace}.${task.action}`)
98
+ };
99
+ },
100
+ tryTask: (task, params) => module.runAction({
101
+ entry: functionTryEntry(task, params),
102
+ input: {},
103
+ callerId: "local",
104
+ user: LOCAL_USER,
105
+ spaceId: 0,
106
+ environment: "main",
107
+ trigger: "call",
108
+ runId: randomUUID()
109
+ })
110
+ };
111
+ };
112
+ // src/functions/runner/remote.ts
113
+ /** What reading a bundle may take on the runner (its own ceiling is 5 s), and then some. */
114
+ var DESCRIBE_DEADLINE_MS = 1e4;
115
+ /** How long a runner has to take or turn away an invocation once connected: it answers at once, either way. */
116
+ var ACCEPT_MS = 5e3;
117
+ /** The waits between rounds while every runner is full and even the one asked to keep it turned it away (stopping). */
118
+ var FULL_WAITS_MS = [
119
+ 100,
120
+ 250,
121
+ 500,
122
+ 1e3
123
+ ];
124
+ /** How long the addresses a runner name resolves to are kept: a scale-up is seen within it. */
125
+ var RESOLVE_MS = 1e3;
126
+ /**
127
+ * A runner that went away while it ran the invocation — killed, crashed, its connection cut: the platform's, never the
128
+ * code's, but it may have run in part (a call made, a request sent), so nothing sends it again on its own.
129
+ */
130
+ var unreachable = (detail) => new FunctionFailure("lost", `The functions runner went away while it ran this (${detail}): it may have run in part`);
131
+ /** A runner that turned this platform away before it opened — its secret is another's: nothing ran, nor will by asking. */
132
+ var refusedBy = (detail) => new FunctionFailure("error", `The functions runner turned this platform away (${detail}): its secret is not this platform's`);
133
+ /** A runner that was never connected to: the invocation was not sent, so nothing of it ran and it may be sent again. */
134
+ var notReached = (detail) => new FunctionFailure("unreachable", `No functions runner could be reached (${detail})`);
135
+ /**
136
+ * How long a runner that could not be reached is taken to be away: calls that need it are queued meanwhile rather
137
+ * than started. The first invocation past it tries again, and says whether it is back.
138
+ */
139
+ var AWAY_MS = 15e3;
140
+ /** The waits between tries of a runner that could not be reached: a restart takes a few seconds, an outage longer. */
141
+ var RETRY_WAITS_MS = [
142
+ 500,
143
+ 1e3,
144
+ 2e3
145
+ ];
146
+ var wait = (ms, signal) => new Promise((resolve) => {
147
+ const timer = setTimeout(resolve, ms);
148
+ signal?.addEventListener("abort", () => {
149
+ clearTimeout(timer);
150
+ resolve();
151
+ }, { once: true });
152
+ });
153
+ /** How often a wait for the runners' capacity is said while it lasts. */
154
+ var TELL_WAIT_MS = 250;
155
+ /**
156
+ * The platform's side of the runner service: a {@link FunctionRunner} over one WebSocket per operation. Each call the
157
+ * code makes arrives on it and is answered on it, by this process — the one holding the run.
158
+ */
159
+ var createRemoteRunner = ({ url, secret, connectTimeoutMs = 5e3, graceMs = 5e3 }) => {
160
+ /** When none of the runners a name stands for could be reached: while recent, the calls that need them are kept. */
161
+ const away = /* @__PURE__ */ new Map();
162
+ /** Invocations asked of it that no runner took yet: placed, or kept in a runner's queue (`waitingForRoom`). */
163
+ let waitingForRoom = 0;
164
+ const addressOf = (spaceId) => typeof url === "function" ? url(spaceId) : url;
165
+ const resolved = /* @__PURE__ */ new Map();
166
+ /** Each runner a name stands for — every address it resolves to — in an order of its own each time. */
167
+ const runnersOf = (address) => {
168
+ const named = new URL(address);
169
+ if (isIP(named.hostname.replace(/^\[|\]$/g, "")) !== 0) return Promise.resolve([address]);
170
+ const kept = resolved.get(address);
171
+ if (!kept || Date.now() - kept.at > RESOLVE_MS) resolved.set(address, {
172
+ at: Date.now(),
173
+ addresses: lookup(named.hostname, { all: true }).then((found) => found.map(({ address: ip, family }) => {
174
+ const each = new URL(address);
175
+ each.hostname = family === 6 ? `[${ip}]` : ip;
176
+ return each.toString().replace(/\/$/, "");
177
+ }), () => [address])
178
+ });
179
+ return (resolved.get(address)?.addresses ?? Promise.resolve([address])).then((addresses) => [...addresses].sort(() => Math.random() - .5));
180
+ };
181
+ const operate = ({ first, load, bundleId, address, deadlineMs, answer, signal, onUsage, onWaited, tellWaited }) => new Promise((resolve, reject) => {
182
+ const socket = new WebSocket(address, {
183
+ headers: { authorization: `Bearer ${secret}` },
184
+ handshakeTimeout: connectTimeoutMs
185
+ });
186
+ let settled = false;
187
+ let opened = false;
188
+ /** A route answering as it writes: the body handed out at its head, fed until `done`. */
189
+ let body;
190
+ let bodyEnded = false;
191
+ const endBody = (end) => {
192
+ if (body && !bodyEnded) {
193
+ bodyEnded = true;
194
+ end(body);
195
+ socket.close(1e3);
196
+ }
197
+ };
198
+ const send = (message) => {
199
+ if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));
200
+ };
201
+ const settle = (outcome) => {
202
+ if (settled) return;
203
+ settled = true;
204
+ clearTimeout(deadline);
205
+ signal?.removeEventListener("abort", onAbort);
206
+ outcome();
207
+ socket.close(1e3);
208
+ };
209
+ const giveUp = (ms, words) => setTimeout(() => {
210
+ settle(() => reject(new FunctionFailure("wall", words)));
211
+ socket.terminate();
212
+ }, ms);
213
+ /** When the runner's answer is due: `deadlineMs` after it took it, and later by what it says it waited for its CPU. */
214
+ let dueAt = 0;
215
+ let waitedMs = 0;
216
+ const answerDeadline = () => giveUp(Math.max(0, dueAt - Date.now()), `The functions runner did not answer within ${String(deadlineMs)} ms of taking it` + (waitedMs > 0 ? `, and the ${String(waitedMs)} ms it waited for its CPU` : ""));
217
+ let accepted = first.type !== "invoke";
218
+ if (accepted) dueAt = Date.now() + deadlineMs;
219
+ let deadline = accepted ? answerDeadline() : giveUp(connectTimeoutMs + ACCEPT_MS, "The functions runner neither took nor turned away the invocation");
220
+ const accept = () => {
221
+ if (!accepted) {
222
+ accepted = true;
223
+ tellWaited?.(true);
224
+ dueAt = Date.now() + deadlineMs;
225
+ clearTimeout(deadline);
226
+ deadline = answerDeadline();
227
+ }
228
+ };
229
+ const onAbort = () => send(typeof signal?.reason === "string" ? {
230
+ type: "abort",
231
+ reason: signal.reason
232
+ } : { type: "abort" });
233
+ signal?.addEventListener("abort", onAbort, { once: true });
234
+ socket.on("open", () => {
235
+ opened = true;
236
+ send(first);
237
+ if (signal?.aborted) onAbort();
238
+ });
239
+ socket.on("message", (data) => {
240
+ const message = readResponseMessage(frameText(data));
241
+ if (!message) {
242
+ settle(() => reject(new FunctionFailure("error", "The functions runner answered outside the protocol")));
243
+ return;
244
+ }
245
+ if (!(message.type === "failed" && (message.reason === "busy" || message.reason === "too_large")) && message.type !== "queued") accept();
246
+ switch (message.type) {
247
+ case "accepted": return;
248
+ case "queued":
249
+ clearTimeout(deadline);
250
+ return;
251
+ case "waited":
252
+ if (!settled) {
253
+ onWaited?.(message.ms);
254
+ waitedMs += message.ms;
255
+ dueAt += message.ms;
256
+ clearTimeout(deadline);
257
+ deadline = answerDeadline();
258
+ }
259
+ return;
260
+ case "needBundle":
261
+ load().then((code) => send({
262
+ type: "bundle",
263
+ bundle: {
264
+ id: bundleId,
265
+ code
266
+ }
267
+ }), (error) => settle(() => reject(new FunctionFailure("error", `The functions could not be read: ${error instanceof Error ? error.message : String(error)}`))));
268
+ return;
269
+ case "call":
270
+ answer(message.call).then((value) => send({
271
+ type: "answer",
272
+ id: message.id,
273
+ answer: {
274
+ ok: true,
275
+ value: value ?? null
276
+ }
277
+ }), (error) => send({
278
+ type: "answer",
279
+ id: message.id,
280
+ answer: failedAnswerOf(error)
281
+ }));
282
+ return;
283
+ case "head": {
284
+ if (settled) return;
285
+ settled = true;
286
+ clearTimeout(deadline);
287
+ const stream = new ReadableStream({
288
+ start: (controller) => {
289
+ body = controller;
290
+ },
291
+ cancel: () => {
292
+ bodyEnded = true;
293
+ send({ type: "abort" });
294
+ socket.close(1e3);
295
+ }
296
+ });
297
+ resolve({
298
+ streamed: true,
299
+ status: message.status,
300
+ statusText: message.statusText,
301
+ headers: message.headers,
302
+ body: stream
303
+ });
304
+ return;
305
+ }
306
+ case "chunk":
307
+ if (body && !bodyEnded) body.enqueue("base64" in message.chunk ? new Uint8Array(Buffer.from(message.chunk.base64, "base64")) : new TextEncoder().encode(message.chunk.text));
308
+ return;
309
+ case "done":
310
+ if (message.usage) onUsage?.(message.usage);
311
+ if (body) {
312
+ signal?.removeEventListener("abort", onAbort);
313
+ endBody((controller) => controller.close());
314
+ return;
315
+ }
316
+ settle(() => resolve(message.value));
317
+ return;
318
+ case "failed":
319
+ if (message.usage) onUsage?.(message.usage);
320
+ if (body) {
321
+ signal?.removeEventListener("abort", onAbort);
322
+ endBody((controller) => controller.error(new FunctionFailure(message.reason, message.error)));
323
+ return;
324
+ }
325
+ settle(() => reject(new FunctionFailure(message.reason, message.error)));
326
+ }
327
+ });
328
+ socket.on("error", (error) => {
329
+ if (!opened && !/Unexpected server response: 4\d\d/.test(error.message)) {
330
+ settle(() => reject(notReached(error.message)));
331
+ return;
332
+ }
333
+ if (!opened) {
334
+ settle(() => reject(refusedBy(error.message)));
335
+ return;
336
+ }
337
+ endBody((controller) => controller.error(unreachable(error.message)));
338
+ settle(() => reject(unreachable(error.message)));
339
+ });
340
+ socket.on("close", (code) => {
341
+ const why = opened ? unreachable(`closed with ${String(code)}`) : notReached(`closed with ${String(code)}`);
342
+ endBody((controller) => controller.error(why));
343
+ settle(() => reject(why));
344
+ });
345
+ });
346
+ return {
347
+ describe: async (bundle) => operate({
348
+ first: {
349
+ type: "describe",
350
+ protocol: FUNCTIONS_PROTOCOL,
351
+ bundle
352
+ },
353
+ address: (await runnersOf(addressOf()))[0] ?? addressOf(),
354
+ load: () => Promise.resolve(bundle.code),
355
+ bundleId: bundle.id,
356
+ deadlineMs: DESCRIBE_DEADLINE_MS,
357
+ answer: () => Promise.reject(/* @__PURE__ */ new Error("Nothing is reachable while a bundle is read"))
358
+ }),
359
+ invoke: async ({ bundle, invocation, limits, answer, signal, onUsage, onWaited }) => {
360
+ let waitedSince = Date.now();
361
+ let taken = false;
362
+ waitingForRoom += 1;
363
+ let counted = true;
364
+ const uncount = () => {
365
+ if (counted) {
366
+ counted = false;
367
+ waitingForRoom -= 1;
368
+ }
369
+ };
370
+ const tellWaited = (tookIt) => {
371
+ if (taken) return;
372
+ const now = Date.now();
373
+ if (now > waitedSince) {
374
+ onWaited?.(now - waitedSince);
375
+ waitedSince = now;
376
+ }
377
+ if (tookIt) {
378
+ taken = true;
379
+ uncount();
380
+ clearInterval(waiting);
381
+ }
382
+ };
383
+ const waiting = onWaited ? setInterval(() => tellWaited(false), TELL_WAIT_MS) : void 0;
384
+ const attempt = (address, queue = false) => operate({
385
+ first: {
386
+ type: "invoke",
387
+ protocol: FUNCTIONS_PROTOCOL,
388
+ bundleId: bundle.id,
389
+ invocation,
390
+ limits,
391
+ ...queue ? { queue: true } : {}
392
+ },
393
+ load: bundle.load,
394
+ bundleId: bundle.id,
395
+ address,
396
+ deadlineMs: limits.wallMs + graceMs,
397
+ answer,
398
+ signal,
399
+ onUsage,
400
+ ...onWaited ? { onWaited } : {},
401
+ tellWaited
402
+ });
403
+ try {
404
+ const name = addressOf(invocation.context.spaceId);
405
+ let unreachableRounds = 0;
406
+ for (let round = 0;; round += 1) {
407
+ const tried = /* @__PURE__ */ new Set();
408
+ let last;
409
+ const full = [];
410
+ let tooLarge;
411
+ let unreachable = false;
412
+ for (;;) {
413
+ const next = (await runnersOf(addressOf(invocation.context.spaceId))).filter((each) => !tried.has(each)).at(0);
414
+ if (next === void 0) break;
415
+ tried.add(next);
416
+ try {
417
+ const value = await attempt(next);
418
+ away.delete(name);
419
+ return value;
420
+ } catch (error) {
421
+ const reason = error instanceof FunctionFailure ? error.reason : void 0;
422
+ if (reason !== "busy" && reason !== "unreachable" && reason !== "too_large") throw error;
423
+ if (reason === "busy") full.push(next);
424
+ else if (reason === "too_large" && error instanceof FunctionFailure) tooLarge = error;
425
+ else unreachable = true;
426
+ last = error;
427
+ }
428
+ }
429
+ if (signal.aborted) throw last;
430
+ if (full.length > 0) {
431
+ const keeper = full[Math.floor(Math.random() * full.length)];
432
+ try {
433
+ const value = await attempt(keeper, true);
434
+ away.delete(name);
435
+ return value;
436
+ } catch (error) {
437
+ if (!(error instanceof FunctionFailure && error.reason === "busy")) throw error;
438
+ }
439
+ await wait(FULL_WAITS_MS[Math.min(round, FULL_WAITS_MS.length - 1)] ?? 1e3, signal);
440
+ continue;
441
+ }
442
+ if (tooLarge && !unreachable) throw new FunctionFailure("too_large", `No functions runner here could hold it: ${tooLarge.message}. A deployment that runs tasks of this size gives its runners more memory (a larger class)`);
443
+ away.set(name, Date.now());
444
+ const pause = RETRY_WAITS_MS.at(unreachableRounds);
445
+ unreachableRounds += 1;
446
+ if (pause === void 0) throw last;
447
+ await wait(pause, signal);
448
+ }
449
+ } finally {
450
+ clearInterval(waiting);
451
+ uncount();
452
+ }
453
+ },
454
+ waitingForRoom: () => waitingForRoom,
455
+ reachable: (spaceId) => {
456
+ const since = away.get(addressOf(spaceId));
457
+ return since === void 0 || Date.now() - since > AWAY_MS;
458
+ }
459
+ };
460
+ };
461
+ export { DEFAULT_FUNCTION_CEILINGS, DEFAULT_FUNCTION_JOB_LIMITS, DEFAULT_FUNCTION_LIMITS, FunctionsBuildError, TRY_STEP, buildFunctions, createLocalFunctions, createRemoteRunner, functionTryEntry, functionsInHand, loadFunctions, loadFunctionsSource, oauthCallbackUrlOn, readFunctionsDir, readManifest };
@@ -0,0 +1,22 @@
1
+ import { ActionKvAdapter } from '../engine/types';
2
+ import { JobQueue } from '../types';
3
+ import { PubSubAdapter } from '@plitzi/sdk-shared';
4
+ export type JobControlOptions = {
5
+ queue: JobQueue;
6
+ /**
7
+ * The page server's realtime — the pub/sub its replicas listen on and the `kv` its retained messages are kept in — so
8
+ * whoever watches a job hears what an operator did to it. Absent, the queue changes and nobody is told until the job
9
+ * moves again.
10
+ */
11
+ realtime?: {
12
+ pubsub: PubSubAdapter;
13
+ kv: ActionKvAdapter;
14
+ };
15
+ };
16
+ export type JobControl = Pick<JobQueue, 'pause' | 'resume' | 'cancel' | 'requeue'>;
17
+ /**
18
+ * An operator's hold on the jobs, from a process that serves no pages — a deployment's API behind its Queue panel: the
19
+ * queue's own `pause`, `resume`, `cancel` and `requeue`, each said on `$job:<id>` when it changed a job of the spaces'
20
+ * functions, as the page server says it when its code does the same.
21
+ */
22
+ export declare const createJobControl: ({ queue, realtime }: JobControlOptions) => JobControl;
@@ -0,0 +1,104 @@
1
+ import { FunctionsConfig } from './config';
2
+ import { TaskContextSource } from '../engine/runtime/runAction';
3
+ import { JobQueue } from '../types';
4
+ import { Job, Environment, FunctionJobManifest, FunctionJobView, RunUser, SpaceRevision } from '@plitzi/sdk-shared';
5
+ import { FunctionJobs, FunctionJobStop, FunctionsDefinition, SpaceFunctions } from '@plitzi/sdk-shared/functions';
6
+ /**
7
+ * A space's jobs (`defineFunctions({ jobs })`): work longer than a request, kept in the actions' durable queue and run
8
+ * slice by slice — in the sandbox, in a space's runtime, or natively in a self-hosted server.
9
+ *
10
+ * A slice ends when the code returns (the job is done), throws (an attempt failed: the next starts from the last save),
11
+ * or is asked to stop: paused, cancelled, its time in one go up, the replica going away. `job.save` is the one
12
+ * checkpoint, and the rule that keeps a job from looping forever is that a slice cut by its time goes on only if it saved
13
+ * since it began.
14
+ */
15
+ /** What a server lets a space's jobs spend: a deployment sets it per space (its plan), each unset one the default's. */
16
+ export type FunctionJobLimits = {
17
+ /** Jobs running at once, across `pool`. */
18
+ running: number;
19
+ /** The spaces whose jobs `running` counts together — an account's. Default: the space alone. */
20
+ pool?: number[];
21
+ /** Jobs waiting (`pending` or `paused`) in one space. */
22
+ waiting: number;
23
+ /** How long one job may run, every slice together, in seconds. */
24
+ maxSeconds: number;
25
+ /** How long one slice runs in the sandbox before it is asked to save and go on in the next. */
26
+ sliceMs: number;
27
+ /** CPU one slice in the sandbox may use. */
28
+ sliceCpuMs: number;
29
+ /** Calls to `ctx` one slice in the sandbox may make. */
30
+ sliceCalls: number;
31
+ /** The most a job keeps of what it saves — and of its input — as JSON, in bytes. */
32
+ stateBytes: number;
33
+ };
34
+ export declare const DEFAULT_FUNCTION_JOB_LIMITS: Omit<FunctionJobLimits, 'pool'>;
35
+ /** How a slice ended, for the worker to settle the job by. */
36
+ export type JobSliceOutcome = {
37
+ kind: 'done';
38
+ result: unknown;
39
+ spentMs: number;
40
+ } | {
41
+ kind: 'stopped';
42
+ stop: FunctionJobStop;
43
+ saved: boolean;
44
+ spentMs: number;
45
+ }
46
+ /** `final`: no attempt would change it — a refusal, a job no code declares, a job out of its time. */
47
+ | {
48
+ kind: 'failed';
49
+ error: string;
50
+ final: boolean;
51
+ refused: boolean;
52
+ spentMs: number;
53
+ }
54
+ /** Not started: the account runs as many jobs as it may, or may not run code right now. */
55
+ | {
56
+ kind: 'wait';
57
+ delayMs: number;
58
+ why: string;
59
+ }
60
+ /**
61
+ * Not started, and would not be on any attempt: it asks for what its plan does not include (a size). Set aside, what it
62
+ * saved kept, for its owner to change it or the plan and resume it — never failed for good.
63
+ */
64
+ | {
65
+ kind: 'setAside';
66
+ why: string;
67
+ };
68
+ /** Who and where a run of a space's code is, as `ctx.jobs` starts a job from it. */
69
+ export type JobRunScope = {
70
+ spaceId: number;
71
+ environment: Environment;
72
+ at?: SpaceRevision;
73
+ user?: RunUser;
74
+ };
75
+ export type FunctionJobsService = {
76
+ /** `ctx.jobs` for one run of a space's code, over the jobs that code declares. */
77
+ forRun: (run: JobRunScope, declared: Readonly<Record<string, FunctionJobManifest>>) => FunctionJobs;
78
+ /** Runs one slice of `job`, `signal` aborting with why (`pause`, `cancel`, `shutdown`) when its worker is told to. */
79
+ slice: (job: Job, signal: AbortSignal, workerId: string) => Promise<JobSliceOutcome>;
80
+ /** Says how the job is now to whoever watches it (`$job:<id>`). Never fails: a watcher missing a beat is not a fault. */
81
+ announce: (spaceId: number, jobId: string) => Promise<void>;
82
+ };
83
+ export type FunctionJobsDeps = {
84
+ /** Read when asked: the queue is made after the runner, and a server may run none. */
85
+ queue: () => JobQueue | undefined;
86
+ config: FunctionsConfig;
87
+ getFunctions?: (spaceId: number, at?: SpaceRevision) => Promise<SpaceFunctions | undefined>;
88
+ /** Read when a slice runs: the runner that makes it is made after this. */
89
+ taskContext: () => TaskContextSource;
90
+ /** Says the job as it is on `$job:<id>` — absent when the server has no realtime channels. */
91
+ publish?: (space: {
92
+ spaceId: number;
93
+ environment: string;
94
+ }, jobId: string, view: FunctionJobView) => Promise<void>;
95
+ maxAttempts: number;
96
+ };
97
+ /** What a job's declaration says besides its code, as a manifest holds it. */
98
+ export declare const jobsManifestOf: (definition: FunctionsDefinition) => Record<string, FunctionJobManifest>;
99
+ /**
100
+ * A job as whoever may watch it sees it: never its input or what it saved, and of a failure only the code's own refusal
101
+ * — anything else it threw can carry what a visitor must not read, and stays in the Queue for an operator.
102
+ */
103
+ export declare const jobViewOf: (job: Job) => FunctionJobView;
104
+ export declare const createFunctionJobs: ({ queue, config, getFunctions, taskContext, publish, maxAttempts }: FunctionJobsDeps) => FunctionJobsService;
@@ -0,0 +1,22 @@
1
+ import { FunctionsSource } from './build';
2
+ import { FunctionsDefinition } from '@plitzi/sdk-shared/functions';
3
+ /** Whether a module's default export has a definition's shape: what a server can register without surprises. */
4
+ export declare const isFunctionsDefinition: (value: unknown) => value is FunctionsDefinition;
5
+ /**
6
+ * A `functions/` directory as a source — the files the platform's rule counts, by their path inside it: what a space's
7
+ * functions are saved as, and what `loadFunctions` builds.
8
+ */
9
+ export declare const readFunctionsDir: (dir: string | URL) => Promise<FunctionsSource>;
10
+ /**
11
+ * A server's own functions from a directory — a project's `src/functions/`, the working copy `plitzi functions` keeps —
12
+ * built exactly as the platform builds a space's (the same rules, one bundle) and loaded natively, for
13
+ * `createServer({ functions: { native } })`. The same on `node src/main.ts` and on a compiled server: nothing here
14
+ * depends on how the server itself runs. A directory with nothing in it is no functions; one that does not build, or
15
+ * none of whose top-level files exports a definition, stops the server with where it is wrong.
16
+ */
17
+ export declare const loadFunctions: (dir: string | URL) => Promise<FunctionsDefinition[]>;
18
+ /**
19
+ * The same, from the files themselves (`FunctionsSource`, by their path): what a packed plugin carries as
20
+ * `functions.source.json`, loaded by a server that runs the plugin as it was packed.
21
+ */
22
+ export declare const loadFunctionsSource: (source: FunctionsSource) => Promise<FunctionsDefinition[]>;
@@ -0,0 +1,36 @@
1
+ import { FunctionsSource } from './build';
2
+ import { ActionRunResult } from '../engine/module';
3
+ import { FunctionsProblem } from '@plitzi/sdk-shared';
4
+ import { FunctionLimits, FunctionRunner } from '@plitzi/sdk-shared/functions';
5
+ export type LocalFunctionsOptions = {
6
+ /**
7
+ * What runs the code: an isolate, as on the platform — `createIsolateRunner({ concurrency: 1 })` of
8
+ * `@plitzi/sdk-runtime/runner`. Handed in, so what holds the runs never loads what runs a space's code (RFC 0032, D8).
9
+ */
10
+ runner: FunctionRunner;
11
+ /** Credentials `ctx.fetch` may name, by id — by default the project's own, from its environment (`PLITZI_CREDENTIALS`). */
12
+ credentials?: Record<string, Record<string, string>>;
13
+ /** As the platform's: a plan's limits, for code that must fit them there. */
14
+ limits?: Partial<FunctionLimits>;
15
+ /** The project's data folder (`src/data/`), what `ctx.data` reads — as the project's server reads it. */
16
+ dataDir?: string;
17
+ fetchImpl?: typeof fetch;
18
+ };
19
+ export type LocalFunctions = {
20
+ /** Builds and checks the source as the platform does, and keeps it as what `tryTask` runs. */
21
+ load: (source: FunctionsSource) => Promise<{
22
+ ok: true;
23
+ tasks: string[];
24
+ } | {
25
+ ok: false;
26
+ problems: FunctionsProblem[];
27
+ }>;
28
+ /** One task of what was loaded, in an isolate, with its value, logs and error — the platform's Try, here. */
29
+ tryTask: (task: string, params: Record<string, unknown>) => Promise<ActionRunResult>;
30
+ };
31
+ /**
32
+ * A space's functions run on this machine exactly as the platform runs them — the same build, the same checks, the same
33
+ * isolates and limits, `ctx` over the same actions module — so what works here works there. `kv` lives as long as this
34
+ * does. What `plitzi functions dev` is made of, with the isolate runner of `@plitzi/sdk-runtime`.
35
+ */
36
+ export declare const createLocalFunctions: ({ runner, credentials, limits, dataDir, fetchImpl }: LocalFunctionsOptions) => LocalFunctions;
@@ -0,0 +1,32 @@
1
+ import { FunctionScope } from './scope';
2
+ import { FunctionsManifest } from '@plitzi/sdk-shared';
3
+ import { FunctionLimits } from '@plitzi/sdk-shared/functions';
4
+ declare const ROUTE_METHODS: readonly ["GET", "POST", "PUT", "PATCH", "DELETE"];
5
+ export type RouteMethod = (typeof ROUTE_METHODS)[number];
6
+ export type RouteKey = {
7
+ method: RouteMethod;
8
+ segments: string[];
9
+ };
10
+ /** Why a space's (or a deployment's) route is refused: `/fn/plugins/` is where plugins answer. */
11
+ export declare const reservedRouteProblem: (route: string) => string;
12
+ /**
13
+ * A route key, `'<METHOD> /<path>'`: literal segments and `:params`, served under `/fn/`. Anything else — a query, a
14
+ * wildcard, `..` — is not a key, so what a space may answer is only ever a path it spelled out.
15
+ */
16
+ export declare const parseRouteKey: (key: string) => RouteKey | undefined;
17
+ /** What the platform writes into the consent URL itself: `authorizeParams` may add to it, never change it. */
18
+ export declare const OWN_AUTHORIZE_PARAMS: ReadonlySet<string>;
19
+ export type ManifestReading = {
20
+ manifest: FunctionsManifest;
21
+ problems: string[];
22
+ };
23
+ /**
24
+ * Reads what a bundle said it declares, and every rule it must meet — the one validator, at save and nowhere else
25
+ * afterwards, because what is stored is only ever what passed it.
26
+ *
27
+ * `reserved` is every namespace this deployment's own tasks use: a space's task may take none of them, so a step that
28
+ * names a platform task always runs the platform's. `ceilings` is the most this deployment gives one invocation: what a
29
+ * task may ask for.
30
+ */
31
+ export declare const readManifest: (value: unknown, reserved: ReadonlySet<string>, ceilings: FunctionLimits, scope?: FunctionScope) => ManifestReading;
32
+ export {};