@plitzi/sdk-server 0.38.20 → 0.38.21

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 (238) hide show
  1. package/CHANGELOG.md +117 -0
  2. package/README.md +2 -2
  3. package/dist/actions.d.ts +6 -0
  4. package/dist/actions.js +2 -1
  5. package/dist/core/configSeam.js +2 -2
  6. package/dist/core/services/functionRoutes.js +7 -2
  7. package/dist/core/services/realtime.js +5 -2
  8. package/dist/functions-api.d.ts +155 -0
  9. package/dist/functions.d.ts +3 -1
  10. package/dist/functions.js +2 -1
  11. package/dist/helpers/serverLog.d.ts +1 -1
  12. package/dist/helpers/serverLog.js +1 -1
  13. package/dist/hosts/project/plugins.js +20 -3
  14. package/dist/modules/actions/index.js +16 -3
  15. package/dist/modules/actions/jobs/index.d.ts +4 -3
  16. package/dist/modules/actions/jobs/index.js +2 -1
  17. package/dist/modules/actions/jobs/later.d.ts +2 -2
  18. package/dist/modules/actions/jobs/later.js +5 -2
  19. package/dist/modules/actions/jobs/memoryQueue.d.ts +4 -4
  20. package/dist/modules/actions/jobs/memoryQueue.js +69 -25
  21. package/dist/modules/actions/jobs/scheduler.d.ts +2 -2
  22. package/dist/modules/actions/jobs/scheduler.js +5 -2
  23. package/dist/modules/actions/jobs/worker.d.ts +6 -3
  24. package/dist/modules/actions/jobs/worker.js +104 -10
  25. package/dist/modules/actions/runtime/runAction.d.ts +5 -2
  26. package/dist/modules/actions/runtime/runAction.js +5 -3
  27. package/dist/modules/actions/runtime/taskContext.d.ts +12 -3
  28. package/dist/modules/actions/runtime/taskContext.js +7 -1
  29. package/dist/modules/actions/types.d.ts +18 -4
  30. package/dist/modules/functions/capabilities.js +59 -1
  31. package/dist/modules/functions/config.d.ts +9 -0
  32. package/dist/modules/functions/context.d.ts +2 -2
  33. package/dist/modules/functions/context.js +14 -1
  34. package/dist/modules/functions/contract.d.ts +84 -1
  35. package/dist/modules/functions/driver.js +94 -2
  36. package/dist/modules/functions/jobControl.d.ts +21 -0
  37. package/dist/modules/functions/jobControl.js +43 -0
  38. package/dist/modules/functions/jobs.d.ts +98 -0
  39. package/dist/modules/functions/jobs.js +438 -0
  40. package/dist/modules/functions/manifest.js +36 -3
  41. package/dist/modules/functions/native.js +2 -1
  42. package/dist/modules/functions/oauth.d.ts +2 -1
  43. package/dist/modules/functions/oauth.js +15 -2
  44. package/dist/modules/functions/protocol.d.ts +71 -4
  45. package/dist/modules/functions/protocol.js +2 -1
  46. package/dist/modules/functions/routes.d.ts +9 -1
  47. package/dist/modules/functions/routes.js +48 -23
  48. package/dist/modules/functions/runner/messages.d.ts +0 -1
  49. package/dist/modules/functions/runner/messages.js +40 -2
  50. package/dist/modules/functions/runner/remote.js +58 -3
  51. package/dist/modules/functions/runner/service.js +53 -7
  52. package/dist/modules/functions/sandbox/isolate.js +5 -3
  53. package/dist/modules/functions/space.js +4 -4
  54. package/dist/modules/mongo/jobQueue.d.ts +3 -3
  55. package/dist/modules/mongo/jobQueue.js +137 -26
  56. package/dist/modules/mysql/jobs/jobQueue.d.ts +3 -3
  57. package/dist/modules/mysql/jobs/jobQueue.js +97 -33
  58. package/dist/modules/mysql/jobs/schema.js +38 -11
  59. package/dist/modules/realtime/handlers.d.ts +5 -2
  60. package/dist/modules/realtime/handlers.js +15 -4
  61. package/dist/modules/realtime/index.d.ts +11 -1
  62. package/dist/modules/realtime/index.js +8 -1
  63. package/dist/modules/realtime/jobs.d.ts +20 -0
  64. package/dist/modules/realtime/jobs.js +41 -0
  65. package/dist/modules/realtime/retained.d.ts +3 -2
  66. package/dist/modules/realtime/retained.js +2 -2
  67. package/dist/modules/realtime/socket.d.ts +4 -1
  68. package/dist/modules/realtime/socket.js +2 -2
  69. package/dist/modules/rsc/resolveRscData.js +2 -1
  70. package/dist/modules/runtime/host.js +1 -1
  71. package/dist/modules/runtime/runner.d.ts +1 -1
  72. package/dist/modules/runtime/runner.js +12 -2
  73. package/dist/modules/runtime/stages.js +1 -1
  74. package/dist/modules/ssr/applySSRResult.d.ts +5 -0
  75. package/dist/modules/ssr/applySSRResult.js +8 -1
  76. package/dist/modules/ssr/buildBody.js +2 -1
  77. package/dist/modules/ssr/prepareRender.d.ts +3 -0
  78. package/dist/modules/ssr/prepareRender.js +17 -5
  79. package/dist/modules/ssr/spaceDocument.d.ts +2 -1
  80. package/dist/modules/ssr/spaceDocument.js +14 -5
  81. package/dist/modules/ssr/streamBody.js +2 -1
  82. package/package.json +3 -3
  83. package/skills/plitzi-authoring/reference/auth.md +6 -0
  84. package/skills/plitzi-authoring/reference/authoring-errors.md +1 -0
  85. package/skills/plitzi-authoring/reference/plugin-reach.md +3 -0
  86. package/skills/plitzi-authoring/reference/realtime.md +4 -0
  87. package/dist/adapters/cloudAdapters.test.d.ts +0 -1
  88. package/dist/adapters/jsonAdapters.test.d.ts +0 -1
  89. package/dist/adapters/space/space.test.d.ts +0 -1
  90. package/dist/core/auth/api.test.d.ts +0 -1
  91. package/dist/core/auth/authorize.test.d.ts +0 -1
  92. package/dist/core/auth/createAuth.test.d.ts +0 -1
  93. package/dist/core/auth/csrf.test.d.ts +0 -1
  94. package/dist/core/auth/domains.test.d.ts +0 -1
  95. package/dist/core/auth/identity.test.d.ts +0 -1
  96. package/dist/core/auth/lifecycle.test.d.ts +0 -1
  97. package/dist/core/auth/oauth/oauth.test.d.ts +0 -1
  98. package/dist/core/auth/redirects.test.d.ts +0 -1
  99. package/dist/core/auth/routes.test.d.ts +0 -1
  100. package/dist/core/auth/session.test.d.ts +0 -1
  101. package/dist/core/auth/spaceTokens.test.d.ts +0 -1
  102. package/dist/core/auth/throttle.test.d.ts +0 -1
  103. package/dist/core/auth/tokens.test.d.ts +0 -1
  104. package/dist/core/auth/totp.test.d.ts +0 -1
  105. package/dist/core/configSeam.test.d.ts +0 -1
  106. package/dist/core/createServer.actions.test.d.ts +0 -1
  107. package/dist/core/createServer.functions.test.d.ts +0 -1
  108. package/dist/core/createServer.livePages.test.d.ts +0 -1
  109. package/dist/core/createServer.notFound.test.d.ts +0 -1
  110. package/dist/core/createServer.oauth.test.d.ts +0 -1
  111. package/dist/core/createServer.publicData.test.d.ts +0 -1
  112. package/dist/core/createServer.test.d.ts +0 -1
  113. package/dist/core/fontStore.test.d.ts +0 -1
  114. package/dist/core/freePort.test.d.ts +0 -1
  115. package/dist/core/handlers/csrfMiddleware.test.d.ts +0 -1
  116. package/dist/core/handlers/handlers.test.d.ts +0 -1
  117. package/dist/core/handlers/socialRouteHandlers.test.d.ts +0 -1
  118. package/dist/core/http/dispatcher.test.d.ts +0 -1
  119. package/dist/core/http/stages/crossSiteWrites.test.d.ts +0 -1
  120. package/dist/core/http/stages/exchangeRoute.test.d.ts +0 -1
  121. package/dist/core/http/stages/images.test.d.ts +0 -1
  122. package/dist/core/http/stages/middlewares.test.d.ts +0 -1
  123. package/dist/core/http/stages/sessionRenewal.test.d.ts +0 -1
  124. package/dist/core/http/stages/signInRoute.test.d.ts +0 -1
  125. package/dist/core/oauth/authorize.test.d.ts +0 -1
  126. package/dist/core/oauth/register.test.d.ts +0 -1
  127. package/dist/core/oauth/token.test.d.ts +0 -1
  128. package/dist/core/requestParser.test.d.ts +0 -1
  129. package/dist/core/server/baseServer.test.d.ts +0 -1
  130. package/dist/core/server/closeOnSignals.test.d.ts +0 -1
  131. package/dist/core/server/drain.test.d.ts +0 -1
  132. package/dist/core/server/fleet/channel.test.d.ts +0 -1
  133. package/dist/core/server/fleet/fixtures/fleetServer.d.ts +0 -1
  134. package/dist/core/server/fleet/fleet.integration.test.d.ts +0 -1
  135. package/dist/core/server/fleet/relay.test.d.ts +0 -1
  136. package/dist/core/server/fleet/role.test.d.ts +0 -1
  137. package/dist/core/server/fleet/supervisor.test.d.ts +0 -1
  138. package/dist/core/services/resolve.test.d.ts +0 -1
  139. package/dist/core/staticFiles.test.d.ts +0 -1
  140. package/dist/env.test.d.ts +0 -1
  141. package/dist/helpers/atomicFile.test.d.ts +0 -1
  142. package/dist/helpers/buildResponseHelpers.test.d.ts +0 -1
  143. package/dist/helpers/buildServerInfo.test.d.ts +0 -1
  144. package/dist/helpers/cache/CompressedFileCache.test.d.ts +0 -1
  145. package/dist/helpers/cache/cacheManager.test.d.ts +0 -1
  146. package/dist/helpers/cache/keys.test.d.ts +0 -1
  147. package/dist/helpers/compress.test.d.ts +0 -1
  148. package/dist/helpers/hydrationPayload.test.d.ts +0 -1
  149. package/dist/helpers/offlineDataLoader.test.d.ts +0 -1
  150. package/dist/helpers/onAbort.test.d.ts +0 -1
  151. package/dist/helpers/outboundGuard.test.d.ts +0 -1
  152. package/dist/helpers/reportReactBuild.test.d.ts +0 -1
  153. package/dist/helpers/resolveDebugMode.test.d.ts +0 -1
  154. package/dist/helpers/serverLog.test.d.ts +0 -1
  155. package/dist/hosts/authoringHost/index.test.d.ts +0 -1
  156. package/dist/hosts/project/serveProject.test.d.ts +0 -1
  157. package/dist/layers.test.d.ts +0 -1
  158. package/dist/middlewares/spaceDeployment.test.d.ts +0 -1
  159. package/dist/modules/actions/connectorWrite.test.d.ts +0 -1
  160. package/dist/modules/actions/jobs/failureStreak.test.d.ts +0 -1
  161. package/dist/modules/actions/jobs/later.test.d.ts +0 -1
  162. package/dist/modules/actions/jobs/memoryStores.test.d.ts +0 -1
  163. package/dist/modules/actions/jobs/scheduler.test.d.ts +0 -1
  164. package/dist/modules/actions/jobs/testing/jobQueueContract.d.ts +0 -25
  165. package/dist/modules/actions/jobs/worker.test.d.ts +0 -1
  166. package/dist/modules/actions/moduleFor.test.d.ts +0 -1
  167. package/dist/modules/actions/runtime/check.test.d.ts +0 -1
  168. package/dist/modules/actions/runtime/credentials.test.d.ts +0 -1
  169. package/dist/modules/actions/runtime/email.test.d.ts +0 -1
  170. package/dist/modules/actions/runtime/fileKv.test.d.ts +0 -1
  171. package/dist/modules/actions/runtime/flags.test.d.ts +0 -1
  172. package/dist/modules/actions/runtime/guards.test.d.ts +0 -1
  173. package/dist/modules/actions/runtime/kvStore.test.d.ts +0 -1
  174. package/dist/modules/actions/runtime/namespaceKv.test.d.ts +0 -1
  175. package/dist/modules/actions/runtime/redisKv.integration.test.d.ts +0 -1
  176. package/dist/modules/actions/runtime/renderResolver.test.d.ts +0 -1
  177. package/dist/modules/actions/runtime/renderShare.test.d.ts +0 -1
  178. package/dist/modules/actions/runtime/runAction.test.d.ts +0 -1
  179. package/dist/modules/actions/runtime/runLogger.test.d.ts +0 -1
  180. package/dist/modules/actions/runtime/signing.test.d.ts +0 -1
  181. package/dist/modules/actions/taskCatalog.test.d.ts +0 -1
  182. package/dist/modules/actions/tasks/db.test.d.ts +0 -1
  183. package/dist/modules/actions/tasks/email.test.d.ts +0 -1
  184. package/dist/modules/actions/tasks/http.test.d.ts +0 -1
  185. package/dist/modules/actions/tasks/kv.test.d.ts +0 -1
  186. package/dist/modules/actions/transport/callHandler.test.d.ts +0 -1
  187. package/dist/modules/actions/transport/webhookHandler.test.d.ts +0 -1
  188. package/dist/modules/connectors/engine.test.d.ts +0 -1
  189. package/dist/modules/connectors/projection.test.d.ts +0 -1
  190. package/dist/modules/connectors/resolver.test.d.ts +0 -1
  191. package/dist/modules/functions/build.test.d.ts +0 -1
  192. package/dist/modules/functions/load.test.d.ts +0 -1
  193. package/dist/modules/functions/local.test.d.ts +0 -1
  194. package/dist/modules/functions/manifest.test.d.ts +0 -1
  195. package/dist/modules/functions/native.test.d.ts +0 -1
  196. package/dist/modules/functions/oauth.test.d.ts +0 -1
  197. package/dist/modules/functions/plugins.test.d.ts +0 -1
  198. package/dist/modules/functions/routes.test.d.ts +0 -1
  199. package/dist/modules/functions/runner/remote.test.d.ts +0 -1
  200. package/dist/modules/functions/sandbox/isolate.test.d.ts +0 -1
  201. package/dist/modules/functions/testing/tasksOf.d.ts +0 -4
  202. package/dist/modules/images/imageProxy.test.d.ts +0 -1
  203. package/dist/modules/images/transform.test.d.ts +0 -1
  204. package/dist/modules/mongo/stores.integration.test.d.ts +0 -1
  205. package/dist/modules/mysql/accounts.test.d.ts +0 -1
  206. package/dist/modules/mysql/jobs/stores.integration.test.d.ts +0 -1
  207. package/dist/modules/mysql/schema.test.d.ts +0 -1
  208. package/dist/modules/mysql/store.integration.test.d.ts +0 -1
  209. package/dist/modules/realtime/realtime.test.d.ts +0 -1
  210. package/dist/modules/realtime/redisPubSub.test.d.ts +0 -1
  211. package/dist/modules/realtime/retained.test.d.ts +0 -1
  212. package/dist/modules/realtime/socket.test.d.ts +0 -1
  213. package/dist/modules/rsc/connectorRscData.test.d.ts +0 -1
  214. package/dist/modules/rsc/handler.test.d.ts +0 -1
  215. package/dist/modules/rsc/publicFileResolver.test.d.ts +0 -1
  216. package/dist/modules/rsc/resolveRscData.test.d.ts +0 -1
  217. package/dist/modules/runtime/elsewhere.test.d.ts +0 -1
  218. package/dist/modules/runtime/entry.test.d.ts +0 -1
  219. package/dist/modules/runtime/inside.test.d.ts +0 -1
  220. package/dist/modules/runtime/ownServer.test.d.ts +0 -1
  221. package/dist/modules/runtime/runtime.test.d.ts +0 -1
  222. package/dist/modules/sqlite/kv.test.d.ts +0 -1
  223. package/dist/modules/ssr/draftSession.test.d.ts +0 -1
  224. package/dist/modules/ssr/loadPluginComponents.test.d.ts +0 -1
  225. package/dist/modules/ssr/metering.test.d.ts +0 -1
  226. package/dist/modules/ssr/prepareRender.test.d.ts +0 -1
  227. package/dist/modules/ssr/redirect.test.d.ts +0 -1
  228. package/dist/modules/ssr/registerExternalPlugins.test.d.ts +0 -1
  229. package/dist/modules/ssr/reportMissingPlugins.test.d.ts +0 -1
  230. package/dist/modules/ssr/resolvePageSeo.test.d.ts +0 -1
  231. package/dist/modules/ssr/spaceDocument.test.d.ts +0 -1
  232. package/dist/modules/ssr/template.test.d.ts +0 -1
  233. package/dist/modules/ssr/testing/offlineData.d.ts +0 -5
  234. package/dist/modules/ssr/vendor.test.d.ts +0 -1
  235. package/dist/plugins/compile.test.d.ts +0 -1
  236. package/dist/plugins/copy.test.d.ts +0 -1
  237. package/dist/plugins/manager.test.d.ts +0 -1
  238. package/dist/plugins/validate.test.d.ts +0 -1
@@ -55,13 +55,43 @@ export type WireResponse = {
55
55
  headers: WireHeaders;
56
56
  body: WireBody | null;
57
57
  };
58
+ /**
59
+ * A route's answer as it is written rather than once it is done — what a space's runtime answers, so a route there
60
+ * streams as an endpoint does, with the platform's `ctx` all the same: its head at once, its body as the code writes it.
61
+ * Never JSON: it lives in the process that holds the run, its body fed by the runner's `chunk` messages.
62
+ */
63
+ export type StreamedRouteAnswer = {
64
+ streamed: true;
65
+ status: number;
66
+ statusText: string;
67
+ headers: WireHeaders;
68
+ body: ReadableStream<Uint8Array>;
69
+ };
70
+ export declare const isStreamedRouteAnswer: (value: unknown) => value is StreamedRouteAnswer;
58
71
  /** Who and what an invocation is for: the facts a {@link FunctionContext} carries, sent with it rather than asked for. */
59
72
  export type FunctionInvocationContext = Pick<FunctionContext, 'spaceId' | 'environment' | 'runId' | 'trigger' | 'callerId' | 'user'>;
73
+ /** The slice of a job an invocation runs: which job, what it saved so far, and which attempt this is. */
74
+ export type FunctionJobSlice = {
75
+ id: string;
76
+ state?: unknown;
77
+ attempt: number;
78
+ };
60
79
  export type FunctionInvocation = {
61
80
  kind: 'task';
62
81
  name: string;
63
82
  params: Record<string, unknown>;
64
83
  context: FunctionInvocationContext;
84
+ } | {
85
+ kind: 'job';
86
+ name: string;
87
+ input: Record<string, unknown>;
88
+ job: FunctionJobSlice;
89
+ context: FunctionInvocationContext;
90
+ /**
91
+ * How long the code gets to save and return once the slice is asked to end (`signal` aborting with why: the
92
+ * `FunctionJobStop`), before the runner cuts it.
93
+ */
94
+ graceMs: number;
65
95
  } | {
66
96
  kind: 'route';
67
97
  key: string;
@@ -122,7 +152,7 @@ export type FunctionCall = {
122
152
  owner?: string;
123
153
  } | {
124
154
  op: 'oauth';
125
- method: 'status' | 'disconnect';
155
+ method: 'status' | 'disconnect' | 'token';
126
156
  connection: string;
127
157
  owner?: string;
128
158
  } | {
@@ -133,6 +163,29 @@ export type FunctionCall = {
133
163
  init: Omit<FunctionFetchInit, 'credential'>;
134
164
  owner?: string;
135
165
  }
166
+ /** `ctx.jobs`: the space's jobs, started and stopped by its code. */
167
+ | {
168
+ op: 'jobs';
169
+ method: 'start';
170
+ name: string;
171
+ input: Record<string, unknown>;
172
+ key?: string;
173
+ } | {
174
+ op: 'jobs';
175
+ method: 'get' | 'pause' | 'resume' | 'cancel';
176
+ id: string;
177
+ }
178
+ /** A job's `save` and `report`: what its slice keeps, and how far it is. */
179
+ | {
180
+ op: 'job';
181
+ method: 'save';
182
+ state: unknown;
183
+ } | {
184
+ op: 'job';
185
+ method: 'report';
186
+ fraction: number;
187
+ step?: string;
188
+ }
136
189
  /** Each value as the guest could send it: JSON, with what JSON cannot say already said as text. */
137
190
  | {
138
191
  op: 'log';
@@ -156,8 +209,9 @@ export type FunctionRunner = {
156
209
  /** Loads a bundle and answers what it declares — when the space's functions are saved, never on a run. */
157
210
  describe: (bundle: FunctionsBundle) => Promise<unknown>;
158
211
  /**
159
- * Runs one task or route of a bundle. Each call the code makes is handed to `answer`, whose result goes back to it;
160
- * `signal` aborting ends the invocation. Resolves with what the code returned, and rejects with a
212
+ * Runs one task, route or slice of a job of a bundle. Each call the code makes is handed to `answer`, whose result
213
+ * goes back to it; `signal` aborting ends the invocation — its `reason` handed to the code as the signal's, and a
214
+ * job's slice given its `graceMs` to save before it is cut. Resolves with what the code returned, and rejects with a
161
215
  * {@link FunctionFailure}.
162
216
  */
163
217
  invoke: (request: FunctionInvokeRequest) => Promise<unknown>;
@@ -221,12 +275,25 @@ export type RunnerRequestMessage = {
221
275
  type: 'answer';
222
276
  id: number;
223
277
  answer: FunctionAnswer;
224
- } | {
278
+ }
279
+ /** The invocation is asked to end — for a job's slice, with why (a `FunctionJobStop`). */
280
+ | {
225
281
  type: 'abort';
282
+ reason?: string;
226
283
  };
227
284
  export type RunnerResponseMessage = {
228
285
  type: 'needBundle';
229
286
  }
287
+ /** A route answering as it writes: its head, then each `chunk` of its body, then `done`. */
288
+ | {
289
+ type: 'head';
290
+ status: number;
291
+ statusText: string;
292
+ headers: WireHeaders;
293
+ } | {
294
+ type: 'chunk';
295
+ chunk: WireBody;
296
+ }
230
297
  /** As the code sent it: the platform reads it, trusting no runner to have. */
231
298
  | {
232
299
  type: 'call';
@@ -5,6 +5,7 @@
5
5
  * platform that calls it.
6
6
  */
7
7
  var FUNCTIONS_PROTOCOL = 1;
8
+ var isStreamedRouteAnswer = (value) => typeof value === "object" && value !== null && "streamed" in value && value.streamed === true && "body" in value && value.body instanceof ReadableStream;
8
9
  /** An invocation that did not answer, and why ({@link FunctionFailureReason}). */
9
10
  var FunctionFailure = class extends Error {
10
11
  reason;
@@ -15,4 +16,4 @@ var FunctionFailure = class extends Error {
15
16
  }
16
17
  };
17
18
  //#endregion
18
- export { FUNCTIONS_PROTOCOL, FunctionFailure };
19
+ export { FUNCTIONS_PROTOCOL, FunctionFailure, isStreamedRouteAnswer };
@@ -15,9 +15,17 @@ export type RouteVisit = {
15
15
  origin?: string;
16
16
  signal: AbortSignal;
17
17
  };
18
+ /**
19
+ * What a route answered, and whether it is written as it comes: a runtime's route and the deployment's own code may
20
+ * stream, and are passed on as they are written; a sandbox's is whole, and sent as one.
21
+ */
22
+ export type RouteAnswer = {
23
+ response: Response;
24
+ streamed: boolean;
25
+ };
18
26
  export type RouteHandler = {
19
27
  key: string;
20
- handle: (request: Request) => Promise<Response>;
28
+ handle: (request: Request) => Promise<RouteAnswer>;
21
29
  };
22
30
  /** The first of `keys` that answers the request, with its params — declared order, as a space reads them. */
23
31
  export declare const matchRoute: (keys: readonly string[], method: string, path: string) => {
@@ -3,13 +3,18 @@ import { isActionRefusal } from "../actions/runtime/errors.js";
3
3
  import { OAUTH_CALLBACK_PATH, oauthCallback } from "./oauth.js";
4
4
  import { pluginOfPath } from "./scope.js";
5
5
  import { functionContextFor } from "./context.js";
6
+ import { answerCall, readCall, responseOf, wireRequestOf, wireResponseFrom } from "./capabilities.js";
6
7
  import { functionLimitsFor } from "./config.js";
8
+ import { FunctionFailure, isStreamedRouteAnswer } from "./protocol.js";
9
+ import { jobsManifestOf } from "./jobs.js";
7
10
  import { parseRouteKey, reservedRouteProblem } from "./manifest.js";
8
- import { answerCall, readCall, responseOf, wireRequestOf, wireResponseFrom } from "./capabilities.js";
9
- import { FunctionFailure } from "./protocol.js";
10
11
  import { PLUGIN_ROUTES_SEGMENT } from "@plitzi/sdk-shared/actions";
11
12
  import { randomUUID } from "node:crypto";
12
13
  //#region src/modules/functions/routes.ts
14
+ var whole = (response) => ({
15
+ response,
16
+ streamed: false
17
+ });
13
18
  /** A route key's params from a path it answers, or nothing when it does not answer it. */
14
19
  var matchKey = (key, method, path) => {
15
20
  const segments = path.replace(/^\/+/, "").split("/");
@@ -80,7 +85,8 @@ var routesOf = (definition) => Object.entries(definition.routes ?? {}).map(([key
80
85
  key,
81
86
  handler,
82
87
  hosts: definition.allow?.hosts ?? [],
83
- ...definition.oauth ? { oauth: definition.oauth } : {}
88
+ ...definition.oauth ? { oauth: definition.oauth } : {},
89
+ jobs: jobsManifestOf(definition)
84
90
  }));
85
91
  /**
86
92
  * The route a request reaches, if one does: under `/plugins/<type>/`, that plugin's — this server's own, then the one
@@ -102,7 +108,7 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
102
108
  ...visit.at ? { at: visit.at } : {},
103
109
  ...visit.origin ? { origin: visit.origin } : {}
104
110
  }, visit.signal, [`route:${key}`]);
105
- const contextOf = (visit, key, hosts, scope, oauth) => {
111
+ const contextOf = (visit, key, hosts, scope, oauth, jobs) => {
106
112
  const ctx = runOf(visit, key);
107
113
  return {
108
114
  ...functionContextFor({
@@ -110,7 +116,7 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
110
116
  log: (line) => {
111
117
  serverLog.info("Functions", `route ${key} of space ${String(visit.spaceId)}: ${line}`);
112
118
  }
113
- }, hosts, scope, oauth),
119
+ }, hosts, scope, oauth, jobs),
114
120
  trigger: "route"
115
121
  };
116
122
  };
@@ -124,12 +130,15 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
124
130
  key: match.key,
125
131
  handle: async (request) => {
126
132
  try {
127
- return withoutCookies(await handler(withoutCredentials(request), {
128
- ...contextOf(visit, match.key, route.hosts, scope, route.oauth),
129
- params: match.params
130
- }));
133
+ return {
134
+ response: withoutCookies(await handler(withoutCredentials(request), {
135
+ ...contextOf(visit, match.key, route.hosts, scope, route.oauth, route.jobs),
136
+ params: match.params
137
+ })),
138
+ streamed: true
139
+ };
131
140
  } catch (error) {
132
- return failed(visit, match.key, error);
141
+ return whole(failed(visit, match.key, error));
133
142
  }
134
143
  }
135
144
  };
@@ -144,10 +153,19 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
144
153
  key: match.key,
145
154
  handle: async (request) => {
146
155
  const refusal = await config.admit?.(visit.spaceId);
147
- if (refusal) return Response.json({ error: refusal }, { status: 429 });
148
- const fnCtx = contextOf(visit, match.key, functions.manifest.hosts, scope, functions.manifest.oauth);
156
+ if (refusal) return whole(Response.json({ error: refusal }, { status: 429 }));
157
+ const fnCtx = contextOf(visit, match.key, functions.manifest.hosts, scope, functions.manifest.oauth, functions.manifest.jobs);
149
158
  let ok = false;
150
159
  let spent;
160
+ let streaming = false;
161
+ const meter = (usage, done) => {
162
+ config.onUsage?.({
163
+ spaceId: visit.spaceId,
164
+ task: usageName,
165
+ ok: done,
166
+ usage
167
+ });
168
+ };
151
169
  try {
152
170
  const value = await runner.invoke({
153
171
  bundle: functions.bundle,
@@ -169,20 +187,27 @@ var createRoutes = ({ config, plugins = () => new Map(Object.entries(config.plug
169
187
  answer: (call) => answerCall(fnCtx, readCall(call)),
170
188
  signal: visit.signal,
171
189
  onUsage: (usage) => {
172
- spent = usage;
190
+ if (streaming) meter(usage, true);
191
+ else spent = usage;
173
192
  }
174
193
  });
175
194
  ok = true;
176
- return withoutCookies(responseOf(wireResponseFrom(value)));
195
+ if (isStreamedRouteAnswer(value)) {
196
+ streaming = true;
197
+ return {
198
+ response: withoutCookies(new Response(value.body, {
199
+ status: value.status,
200
+ statusText: value.statusText,
201
+ headers: value.headers
202
+ })),
203
+ streamed: true
204
+ };
205
+ }
206
+ return whole(withoutCookies(responseOf(wireResponseFrom(value))));
177
207
  } catch (error) {
178
- return failed(visit, match.key, error);
208
+ return whole(failed(visit, match.key, error));
179
209
  } finally {
180
- if (spent) config.onUsage?.({
181
- spaceId: visit.spaceId,
182
- task: usageName,
183
- ok,
184
- usage: spent
185
- });
210
+ if (spent) meter(spent, ok);
186
211
  }
187
212
  }
188
213
  };
@@ -202,9 +227,9 @@ routeFor: async (visit, method, path) => {
202
227
  handle: async (request) => {
203
228
  const run = runOf(visit, `GET ${OAUTH_CALLBACK_PATH}`);
204
229
  try {
205
- return await oauthCallback(run, new URL(request.url).searchParams);
230
+ return whole(await oauthCallback(run, new URL(request.url).searchParams));
206
231
  } catch (error) {
207
- return failed(visit, `GET ${OAUTH_CALLBACK_PATH}`, error);
232
+ return whole(failed(visit, `GET ${OAUTH_CALLBACK_PATH}`, error));
208
233
  }
209
234
  }
210
235
  };
@@ -1,5 +1,4 @@
1
1
  import { RunnerRequestMessage, RunnerResponseMessage } from '../protocol';
2
2
  /** What the platform sent the runner, or nothing when it is not one of the protocol's messages. */
3
3
  export declare const readRequestMessage: (data: string) => RunnerRequestMessage | undefined;
4
- /** What the runner sent the platform, or nothing when it is not one of the protocol's messages. */
5
4
  export declare const readResponseMessage: (data: string) => RunnerResponseMessage | undefined;
@@ -40,7 +40,7 @@ var limitsOf = (value) => {
40
40
  * what is checked here is what the runner itself acts on.
41
41
  */
42
42
  var invocationOf = (value) => {
43
- if (!isRecord(value) || !isRecord(value.context) || value.kind !== "task" && value.kind !== "route") return;
43
+ if (!isRecord(value) || !isRecord(value.context) || value.kind !== "task" && value.kind !== "route" && value.kind !== "job") return;
44
44
  const { context } = value;
45
45
  if (typeof context.spaceId !== "number" || typeof context.runId !== "string" || typeof context.trigger !== "string" || typeof context.callerId !== "string" || !isEnvironment(context.environment)) return;
46
46
  const facts = {
@@ -68,6 +68,22 @@ var invocationOf = (value) => {
68
68
  params: value.params,
69
69
  context: withUser
70
70
  } : void 0;
71
+ if (value.kind === "job") {
72
+ const job = isRecord(value.job) ? value.job : void 0;
73
+ const graceMs = limitOf(value.graceMs);
74
+ return typeof value.name === "string" && isRecord(value.input) && job && typeof job.id === "string" && typeof job.attempt === "number" && graceMs !== void 0 ? {
75
+ kind: "job",
76
+ name: value.name,
77
+ input: value.input,
78
+ job: {
79
+ id: job.id,
80
+ attempt: job.attempt,
81
+ ...job.state === void 0 ? {} : { state: job.state }
82
+ },
83
+ context: withUser,
84
+ graceMs
85
+ } : void 0;
86
+ }
71
87
  const request = isRecord(value.request) ? value.request : void 0;
72
88
  if (!request || typeof value.key !== "string" || typeof request.method !== "string" || typeof request.url !== "string") return;
73
89
  const params = isRecord(value.params) ? value.params : {};
@@ -134,7 +150,10 @@ var readRequestMessage = (data) => {
134
150
  answer
135
151
  } : void 0;
136
152
  }
137
- case "abort": return { type: "abort" };
153
+ case "abort": return typeof message.reason === "string" ? {
154
+ type: "abort",
155
+ reason: message.reason
156
+ } : { type: "abort" };
138
157
  default: return;
139
158
  }
140
159
  };
@@ -161,10 +180,29 @@ var usageOf = (value) => {
161
180
  } } : {};
162
181
  };
163
182
  /** What the runner sent the platform, or nothing when it is not one of the protocol's messages. */
183
+ /** Headers as the wire carries them: name and value pairs, the rest left out. */
184
+ var headersOf = (value) => Array.isArray(value) ? value.flatMap((pair) => Array.isArray(pair) && typeof pair[0] === "string" && typeof pair[1] === "string" ? [[pair[0], pair[1]]] : []) : [];
164
185
  var readResponseMessage = (data) => {
165
186
  const message = parse(data);
166
187
  switch (message?.type) {
167
188
  case "needBundle": return { type: "needBundle" };
189
+ case "head": return typeof message.status === "number" ? {
190
+ type: "head",
191
+ status: message.status,
192
+ statusText: typeof message.statusText === "string" ? message.statusText : "",
193
+ headers: headersOf(message.headers)
194
+ } : void 0;
195
+ case "chunk": {
196
+ const chunk = isRecord(message.chunk) ? message.chunk : void 0;
197
+ if (typeof chunk?.base64 === "string") return {
198
+ type: "chunk",
199
+ chunk: { base64: chunk.base64 }
200
+ };
201
+ return typeof chunk?.text === "string" ? {
202
+ type: "chunk",
203
+ chunk: { text: chunk.text }
204
+ } : void 0;
205
+ }
168
206
  case "call": return typeof message.id === "number" ? {
169
207
  type: "call",
170
208
  id: message.id,
@@ -17,6 +17,16 @@ var createRemoteRunner = ({ url, secret, connectTimeoutMs = 5e3, graceMs = 5e3 }
17
17
  handshakeTimeout: connectTimeoutMs
18
18
  });
19
19
  let settled = false;
20
+ /** A route answering as it writes: the body handed out at its head, fed until `done`. */
21
+ let body;
22
+ let bodyEnded = false;
23
+ const endBody = (end) => {
24
+ if (body && !bodyEnded) {
25
+ bodyEnded = true;
26
+ end(body);
27
+ socket.close(1e3);
28
+ }
29
+ };
20
30
  const send = (message) => {
21
31
  if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify(message));
22
32
  };
@@ -32,7 +42,10 @@ var createRemoteRunner = ({ url, secret, connectTimeoutMs = 5e3, graceMs = 5e3 }
32
42
  settle(() => reject(new FunctionFailure("wall", `The functions runner did not answer within ${String(deadlineMs)} ms`)));
33
43
  socket.terminate();
34
44
  }, deadlineMs);
35
- const onAbort = () => send({ type: "abort" });
45
+ const onAbort = () => send(typeof signal?.reason === "string" ? {
46
+ type: "abort",
47
+ reason: signal.reason
48
+ } : { type: "abort" });
36
49
  signal?.addEventListener("abort", onAbort, { once: true });
37
50
  socket.on("open", () => {
38
51
  send(first);
@@ -71,17 +84,59 @@ var createRemoteRunner = ({ url, secret, connectTimeoutMs = 5e3, graceMs = 5e3 }
71
84
  }
72
85
  }));
73
86
  return;
87
+ case "head": {
88
+ if (settled) return;
89
+ settled = true;
90
+ clearTimeout(deadline);
91
+ const stream = new ReadableStream({
92
+ start: (controller) => {
93
+ body = controller;
94
+ },
95
+ cancel: () => {
96
+ bodyEnded = true;
97
+ send({ type: "abort" });
98
+ socket.close(1e3);
99
+ }
100
+ });
101
+ resolve({
102
+ streamed: true,
103
+ status: message.status,
104
+ statusText: message.statusText,
105
+ headers: message.headers,
106
+ body: stream
107
+ });
108
+ return;
109
+ }
110
+ case "chunk":
111
+ if (body && !bodyEnded) body.enqueue("base64" in message.chunk ? new Uint8Array(Buffer.from(message.chunk.base64, "base64")) : new TextEncoder().encode(message.chunk.text));
112
+ return;
74
113
  case "done":
75
114
  if (message.usage) onUsage?.(message.usage);
115
+ if (body) {
116
+ signal?.removeEventListener("abort", onAbort);
117
+ endBody((controller) => controller.close());
118
+ return;
119
+ }
76
120
  settle(() => resolve(message.value));
77
121
  return;
78
122
  case "failed":
79
123
  if (message.usage) onUsage?.(message.usage);
124
+ if (body) {
125
+ signal?.removeEventListener("abort", onAbort);
126
+ endBody((controller) => controller.error(new FunctionFailure(message.reason, message.error)));
127
+ return;
128
+ }
80
129
  settle(() => reject(new FunctionFailure(message.reason, message.error)));
81
130
  }
82
131
  });
83
- socket.on("error", (error) => settle(() => reject(unreachable(error.message))));
84
- socket.on("close", (code) => settle(() => reject(unreachable(`closed with ${String(code)}`))));
132
+ socket.on("error", (error) => {
133
+ endBody((controller) => controller.error(unreachable(error.message)));
134
+ settle(() => reject(unreachable(error.message)));
135
+ });
136
+ socket.on("close", (code) => {
137
+ endBody((controller) => controller.error(unreachable(`closed with ${String(code)}`)));
138
+ settle(() => reject(unreachable(`closed with ${String(code)}`)));
139
+ });
85
140
  });
86
141
  return {
87
142
  describe: (bundle) => operate({
@@ -1,5 +1,5 @@
1
1
  import { serverLog } from "../../../helpers/serverLog.js";
2
- import { FunctionFailure } from "../protocol.js";
2
+ import { FunctionFailure, isStreamedRouteAnswer } from "../protocol.js";
3
3
  import { frameText } from "../../../helpers/wsFrame.js";
4
4
  import { watchConnections } from "../../../core/server/drain.js";
5
5
  import { readRequestMessage } from "./messages.js";
@@ -31,12 +31,58 @@ var serveConnection = (socket, runner) => {
31
31
  socket.close(1e3);
32
32
  };
33
33
  let usage;
34
+ /** A route answering as it writes: its head now, each part of its body as it comes, and `done` once it ends. */
35
+ const stream = async (answer) => {
36
+ send({
37
+ type: "head",
38
+ status: answer.status,
39
+ statusText: answer.statusText,
40
+ headers: answer.headers
41
+ });
42
+ const reader = answer.body.getReader();
43
+ const stop = () => {
44
+ reader.cancel().catch(() => void 0);
45
+ };
46
+ controller.signal.addEventListener("abort", stop, { once: true });
47
+ try {
48
+ for (;;) {
49
+ const { done, value } = await reader.read();
50
+ if (done) break;
51
+ send({
52
+ type: "chunk",
53
+ chunk: { base64: Buffer.from(value).toString("base64") }
54
+ });
55
+ }
56
+ } finally {
57
+ controller.signal.removeEventListener("abort", stop);
58
+ }
59
+ };
34
60
  const settle = (work) => {
35
- work.then((value) => finish({
36
- type: "done",
37
- value,
38
- ...usage ? { usage } : {}
39
- }), (error) => finish({
61
+ work.then(async (value) => {
62
+ if (!isStreamedRouteAnswer(value)) {
63
+ finish({
64
+ type: "done",
65
+ value,
66
+ ...usage ? { usage } : {}
67
+ });
68
+ return;
69
+ }
70
+ try {
71
+ await stream(value);
72
+ finish({
73
+ type: "done",
74
+ value: null,
75
+ ...usage ? { usage } : {}
76
+ });
77
+ } catch (error) {
78
+ finish({
79
+ type: "failed",
80
+ reason: "error",
81
+ error: `The route's answer broke off: ${error instanceof Error ? error.message : String(error)}`,
82
+ ...usage ? { usage } : {}
83
+ });
84
+ }
85
+ }, (error) => finish({
40
86
  type: "failed",
41
87
  ...error instanceof FunctionFailure ? {
42
88
  reason: error.reason,
@@ -74,7 +120,7 @@ var serveConnection = (socket, runner) => {
74
120
  return;
75
121
  }
76
122
  if (message.type === "abort") {
77
- controller.abort();
123
+ controller.abort(message.reason);
78
124
  return;
79
125
  }
80
126
  if (message.type === "bundle") {
@@ -183,7 +183,7 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 67108864 } = {}) => {
183
183
  }]);
184
184
  return ivm;
185
185
  };
186
- const session = async ({ bundle, limits, answer, signal, onUsage, drive }) => {
186
+ const session = async ({ bundle, limits, answer, signal, graceMs = ABORT_GRACE_MS, onUsage, drive }) => {
187
187
  const ivm = await ready();
188
188
  const entry = await cached(bundle);
189
189
  await acquire();
@@ -221,8 +221,9 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 67108864 } = {}) => {
221
221
  later(limits.wallMs, () => stop("wall"));
222
222
  let driver;
223
223
  const onAbort = () => {
224
- driver?.get("abort", { reference: true }).then((abort) => abort.apply(void 0, ["The run was aborted"])).catch(() => void 0);
225
- later(ABORT_GRACE_MS, () => stop("aborted"));
224
+ const reason = typeof signal?.reason === "string" ? signal.reason : "The run was aborted";
225
+ driver?.get("abort", { reference: true }).then((abort) => abort.apply(void 0, [reason])).catch(() => void 0);
226
+ later(graceMs, () => stop("aborted"));
226
227
  };
227
228
  try {
228
229
  const context = isolate.createContextSync();
@@ -321,6 +322,7 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 67108864 } = {}) => {
321
322
  limits,
322
323
  answer,
323
324
  signal,
325
+ ...invocation.kind === "job" ? { graceMs: invocation.graceMs } : {},
324
326
  onUsage,
325
327
  drive: async (driver, definition) => {
326
328
  const invoke = driver.getSync("invoke", { reference: true });
@@ -1,10 +1,10 @@
1
1
  import { ActionRefusal } from "../actions/runtime/errors.js";
2
2
  import { functionContextFor } from "./context.js";
3
- import { taskName } from "../actions/tasks/registry.js";
4
- import { functionLimitsFor } from "./config.js";
5
- import { readManifest } from "./manifest.js";
6
3
  import { answerCall, readCall } from "./capabilities.js";
4
+ import { functionLimitsFor } from "./config.js";
7
5
  import { FunctionFailure } from "./protocol.js";
6
+ import { taskName } from "../actions/tasks/registry.js";
7
+ import { readManifest } from "./manifest.js";
8
8
  import { FunctionsBuildError, buildFunctions } from "./build.js";
9
9
  import { createHash } from "node:crypto";
10
10
  //#region src/modules/functions/space.ts
@@ -36,7 +36,7 @@ var spaceTasks = (functions, runner, limitsFor, { admit, onUsage } = {}, scope)
36
36
  run: async (params, ctx) => {
37
37
  const refusal = await admit?.(ctx.spaceId);
38
38
  if (refusal) throw new Error(refusal);
39
- const fnCtx = functionContextFor(ctx, functions.manifest.hosts, scope, functions.manifest.oauth);
39
+ const fnCtx = functionContextFor(ctx, functions.manifest.hosts, scope, functions.manifest.oauth, functions.manifest.jobs);
40
40
  let ok = false;
41
41
  let spent;
42
42
  try {
@@ -1,4 +1,4 @@
1
- import { ActionJobQueue } from '@plitzi/sdk-shared';
1
+ import { JobQueue } from '@plitzi/sdk-shared';
2
2
  import { Db } from 'mongodb';
3
3
  /** The database, or how to reach it — a getter for a deployment whose client is replaced when it reconnects. */
4
4
  export type MongoDbSource = Db | (() => Db);
@@ -13,12 +13,12 @@ export type MongoJobQueueOptions = {
13
13
  /** How long a finished job stays readable. A waiting or running one never expires. Default 90 days. */
14
14
  retentionDays?: number;
15
15
  };
16
- export type MongoJobQueue = ActionJobQueue & {
16
+ export type MongoJobQueue = JobQueue & {
17
17
  /** Takes the store's clock again on the next call — after a failover to another primary. */
18
18
  resyncClock: () => void;
19
19
  };
20
20
  /**
21
- * An {@link ActionJobQueue} over two collections of a Mongo database the deployment owns.
21
+ * An {@link JobQueue} over two collections of a Mongo database the deployment owns.
22
22
  *
23
23
  * The helper for a deployment that already runs Mongo: it holds no connection of its own and creates nothing but the
24
24
  * indexes its queries need, on first use. Every replica pointed at the same database shares the jobs and the