@plitzi/sdk-server 0.38.20 → 0.38.22

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 (245) hide show
  1. package/CHANGELOG.md +141 -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/auth/createAuth.d.ts +1 -1
  6. package/dist/core/auth/tokens.d.ts +1 -1
  7. package/dist/core/configSeam.js +12 -2
  8. package/dist/core/services/functionRoutes.js +7 -2
  9. package/dist/core/services/realtime.js +5 -2
  10. package/dist/functions-api.d.ts +176 -3
  11. package/dist/functions.d.ts +3 -1
  12. package/dist/functions.js +2 -1
  13. package/dist/helpers/serverLog.d.ts +1 -1
  14. package/dist/helpers/serverLog.js +1 -1
  15. package/dist/hosts/project/plugins.js +20 -3
  16. package/dist/hosts/project/serveProject.js +16 -1
  17. package/dist/modules/actions/index.js +17 -4
  18. package/dist/modules/actions/jobs/index.d.ts +4 -3
  19. package/dist/modules/actions/jobs/index.js +2 -1
  20. package/dist/modules/actions/jobs/later.d.ts +2 -2
  21. package/dist/modules/actions/jobs/later.js +5 -2
  22. package/dist/modules/actions/jobs/memoryQueue.d.ts +4 -4
  23. package/dist/modules/actions/jobs/memoryQueue.js +69 -25
  24. package/dist/modules/actions/jobs/scheduler.d.ts +2 -2
  25. package/dist/modules/actions/jobs/scheduler.js +5 -2
  26. package/dist/modules/actions/jobs/worker.d.ts +6 -3
  27. package/dist/modules/actions/jobs/worker.js +104 -10
  28. package/dist/modules/actions/runtime/errors.d.ts +9 -1
  29. package/dist/modules/actions/runtime/errors.js +12 -2
  30. package/dist/modules/actions/runtime/runAction.d.ts +5 -2
  31. package/dist/modules/actions/runtime/runAction.js +5 -3
  32. package/dist/modules/actions/runtime/taskContext.d.ts +12 -3
  33. package/dist/modules/actions/runtime/taskContext.js +9 -1
  34. package/dist/modules/actions/types.d.ts +22 -6
  35. package/dist/modules/functions/capabilities.js +124 -13
  36. package/dist/modules/functions/config.d.ts +20 -0
  37. package/dist/modules/functions/context.d.ts +2 -2
  38. package/dist/modules/functions/context.js +16 -3
  39. package/dist/modules/functions/contract.d.ts +97 -3
  40. package/dist/modules/functions/driver.js +136 -9
  41. package/dist/modules/functions/jobControl.d.ts +21 -0
  42. package/dist/modules/functions/jobControl.js +43 -0
  43. package/dist/modules/functions/jobs.d.ts +98 -0
  44. package/dist/modules/functions/jobs.js +438 -0
  45. package/dist/modules/functions/manifest.d.ts +2 -0
  46. package/dist/modules/functions/manifest.js +37 -4
  47. package/dist/modules/functions/native.js +2 -1
  48. package/dist/modules/functions/oauth.d.ts +3 -2
  49. package/dist/modules/functions/oauth.js +53 -19
  50. package/dist/modules/functions/protocol.d.ts +98 -7
  51. package/dist/modules/functions/protocol.js +15 -1
  52. package/dist/modules/functions/routes.d.ts +9 -1
  53. package/dist/modules/functions/routes.js +50 -25
  54. package/dist/modules/functions/runner/messages.d.ts +0 -1
  55. package/dist/modules/functions/runner/messages.js +46 -5
  56. package/dist/modules/functions/runner/remote.js +60 -8
  57. package/dist/modules/functions/runner/service.js +54 -8
  58. package/dist/modules/functions/sandbox/guest.js +5 -3
  59. package/dist/modules/functions/sandbox/isolate.js +7 -8
  60. package/dist/modules/functions/space.js +4 -4
  61. package/dist/modules/mongo/jobQueue.d.ts +3 -3
  62. package/dist/modules/mongo/jobQueue.js +137 -26
  63. package/dist/modules/mysql/jobs/jobQueue.d.ts +3 -3
  64. package/dist/modules/mysql/jobs/jobQueue.js +97 -33
  65. package/dist/modules/mysql/jobs/schema.js +38 -11
  66. package/dist/modules/realtime/handlers.d.ts +5 -2
  67. package/dist/modules/realtime/handlers.js +15 -4
  68. package/dist/modules/realtime/index.d.ts +11 -1
  69. package/dist/modules/realtime/index.js +8 -1
  70. package/dist/modules/realtime/jobs.d.ts +20 -0
  71. package/dist/modules/realtime/jobs.js +41 -0
  72. package/dist/modules/realtime/retained.d.ts +3 -2
  73. package/dist/modules/realtime/retained.js +2 -2
  74. package/dist/modules/realtime/socket.d.ts +4 -1
  75. package/dist/modules/realtime/socket.js +2 -2
  76. package/dist/modules/rsc/resolveRscData.js +2 -1
  77. package/dist/modules/runtime/host.js +1 -1
  78. package/dist/modules/runtime/runner.d.ts +1 -1
  79. package/dist/modules/runtime/runner.js +12 -2
  80. package/dist/modules/runtime/stages.js +1 -1
  81. package/dist/modules/ssr/applySSRResult.d.ts +5 -0
  82. package/dist/modules/ssr/applySSRResult.js +8 -1
  83. package/dist/modules/ssr/buildBody.js +2 -1
  84. package/dist/modules/ssr/prepareRender.d.ts +3 -0
  85. package/dist/modules/ssr/prepareRender.js +17 -5
  86. package/dist/modules/ssr/spaceDocument.d.ts +2 -1
  87. package/dist/modules/ssr/spaceDocument.js +14 -5
  88. package/dist/modules/ssr/streamBody.js +2 -1
  89. package/package.json +3 -3
  90. package/skills/plitzi-authoring/reference/auth.md +6 -0
  91. package/skills/plitzi-authoring/reference/authoring-errors.md +1 -0
  92. package/skills/plitzi-authoring/reference/plugin-reach.md +3 -0
  93. package/skills/plitzi-authoring/reference/realtime.md +4 -0
  94. package/dist/adapters/cloudAdapters.test.d.ts +0 -1
  95. package/dist/adapters/jsonAdapters.test.d.ts +0 -1
  96. package/dist/adapters/space/space.test.d.ts +0 -1
  97. package/dist/core/auth/api.test.d.ts +0 -1
  98. package/dist/core/auth/authorize.test.d.ts +0 -1
  99. package/dist/core/auth/createAuth.test.d.ts +0 -1
  100. package/dist/core/auth/csrf.test.d.ts +0 -1
  101. package/dist/core/auth/domains.test.d.ts +0 -1
  102. package/dist/core/auth/identity.test.d.ts +0 -1
  103. package/dist/core/auth/lifecycle.test.d.ts +0 -1
  104. package/dist/core/auth/oauth/oauth.test.d.ts +0 -1
  105. package/dist/core/auth/redirects.test.d.ts +0 -1
  106. package/dist/core/auth/routes.test.d.ts +0 -1
  107. package/dist/core/auth/session.test.d.ts +0 -1
  108. package/dist/core/auth/spaceTokens.test.d.ts +0 -1
  109. package/dist/core/auth/throttle.test.d.ts +0 -1
  110. package/dist/core/auth/tokens.test.d.ts +0 -1
  111. package/dist/core/auth/totp.test.d.ts +0 -1
  112. package/dist/core/configSeam.test.d.ts +0 -1
  113. package/dist/core/createServer.actions.test.d.ts +0 -1
  114. package/dist/core/createServer.functions.test.d.ts +0 -1
  115. package/dist/core/createServer.livePages.test.d.ts +0 -1
  116. package/dist/core/createServer.notFound.test.d.ts +0 -1
  117. package/dist/core/createServer.oauth.test.d.ts +0 -1
  118. package/dist/core/createServer.publicData.test.d.ts +0 -1
  119. package/dist/core/createServer.test.d.ts +0 -1
  120. package/dist/core/fontStore.test.d.ts +0 -1
  121. package/dist/core/freePort.test.d.ts +0 -1
  122. package/dist/core/handlers/csrfMiddleware.test.d.ts +0 -1
  123. package/dist/core/handlers/handlers.test.d.ts +0 -1
  124. package/dist/core/handlers/socialRouteHandlers.test.d.ts +0 -1
  125. package/dist/core/http/dispatcher.test.d.ts +0 -1
  126. package/dist/core/http/stages/crossSiteWrites.test.d.ts +0 -1
  127. package/dist/core/http/stages/exchangeRoute.test.d.ts +0 -1
  128. package/dist/core/http/stages/images.test.d.ts +0 -1
  129. package/dist/core/http/stages/middlewares.test.d.ts +0 -1
  130. package/dist/core/http/stages/sessionRenewal.test.d.ts +0 -1
  131. package/dist/core/http/stages/signInRoute.test.d.ts +0 -1
  132. package/dist/core/oauth/authorize.test.d.ts +0 -1
  133. package/dist/core/oauth/register.test.d.ts +0 -1
  134. package/dist/core/oauth/token.test.d.ts +0 -1
  135. package/dist/core/requestParser.test.d.ts +0 -1
  136. package/dist/core/server/baseServer.test.d.ts +0 -1
  137. package/dist/core/server/closeOnSignals.test.d.ts +0 -1
  138. package/dist/core/server/drain.test.d.ts +0 -1
  139. package/dist/core/server/fleet/channel.test.d.ts +0 -1
  140. package/dist/core/server/fleet/fixtures/fleetServer.d.ts +0 -1
  141. package/dist/core/server/fleet/fleet.integration.test.d.ts +0 -1
  142. package/dist/core/server/fleet/relay.test.d.ts +0 -1
  143. package/dist/core/server/fleet/role.test.d.ts +0 -1
  144. package/dist/core/server/fleet/supervisor.test.d.ts +0 -1
  145. package/dist/core/services/resolve.test.d.ts +0 -1
  146. package/dist/core/staticFiles.test.d.ts +0 -1
  147. package/dist/env.test.d.ts +0 -1
  148. package/dist/helpers/atomicFile.test.d.ts +0 -1
  149. package/dist/helpers/buildResponseHelpers.test.d.ts +0 -1
  150. package/dist/helpers/buildServerInfo.test.d.ts +0 -1
  151. package/dist/helpers/cache/CompressedFileCache.test.d.ts +0 -1
  152. package/dist/helpers/cache/cacheManager.test.d.ts +0 -1
  153. package/dist/helpers/cache/keys.test.d.ts +0 -1
  154. package/dist/helpers/compress.test.d.ts +0 -1
  155. package/dist/helpers/hydrationPayload.test.d.ts +0 -1
  156. package/dist/helpers/offlineDataLoader.test.d.ts +0 -1
  157. package/dist/helpers/onAbort.test.d.ts +0 -1
  158. package/dist/helpers/outboundGuard.test.d.ts +0 -1
  159. package/dist/helpers/reportReactBuild.test.d.ts +0 -1
  160. package/dist/helpers/resolveDebugMode.test.d.ts +0 -1
  161. package/dist/helpers/serverLog.test.d.ts +0 -1
  162. package/dist/hosts/authoringHost/index.test.d.ts +0 -1
  163. package/dist/hosts/project/serveProject.test.d.ts +0 -1
  164. package/dist/layers.test.d.ts +0 -1
  165. package/dist/middlewares/spaceDeployment.test.d.ts +0 -1
  166. package/dist/modules/actions/connectorWrite.test.d.ts +0 -1
  167. package/dist/modules/actions/jobs/failureStreak.test.d.ts +0 -1
  168. package/dist/modules/actions/jobs/later.test.d.ts +0 -1
  169. package/dist/modules/actions/jobs/memoryStores.test.d.ts +0 -1
  170. package/dist/modules/actions/jobs/scheduler.test.d.ts +0 -1
  171. package/dist/modules/actions/jobs/testing/jobQueueContract.d.ts +0 -25
  172. package/dist/modules/actions/jobs/worker.test.d.ts +0 -1
  173. package/dist/modules/actions/moduleFor.test.d.ts +0 -1
  174. package/dist/modules/actions/runtime/check.test.d.ts +0 -1
  175. package/dist/modules/actions/runtime/credentials.test.d.ts +0 -1
  176. package/dist/modules/actions/runtime/email.test.d.ts +0 -1
  177. package/dist/modules/actions/runtime/fileKv.test.d.ts +0 -1
  178. package/dist/modules/actions/runtime/flags.test.d.ts +0 -1
  179. package/dist/modules/actions/runtime/guards.test.d.ts +0 -1
  180. package/dist/modules/actions/runtime/kvStore.test.d.ts +0 -1
  181. package/dist/modules/actions/runtime/namespaceKv.test.d.ts +0 -1
  182. package/dist/modules/actions/runtime/redisKv.integration.test.d.ts +0 -1
  183. package/dist/modules/actions/runtime/renderResolver.test.d.ts +0 -1
  184. package/dist/modules/actions/runtime/renderShare.test.d.ts +0 -1
  185. package/dist/modules/actions/runtime/runAction.test.d.ts +0 -1
  186. package/dist/modules/actions/runtime/runLogger.test.d.ts +0 -1
  187. package/dist/modules/actions/runtime/signing.test.d.ts +0 -1
  188. package/dist/modules/actions/taskCatalog.test.d.ts +0 -1
  189. package/dist/modules/actions/tasks/db.test.d.ts +0 -1
  190. package/dist/modules/actions/tasks/email.test.d.ts +0 -1
  191. package/dist/modules/actions/tasks/http.test.d.ts +0 -1
  192. package/dist/modules/actions/tasks/kv.test.d.ts +0 -1
  193. package/dist/modules/actions/transport/callHandler.test.d.ts +0 -1
  194. package/dist/modules/actions/transport/webhookHandler.test.d.ts +0 -1
  195. package/dist/modules/connectors/engine.test.d.ts +0 -1
  196. package/dist/modules/connectors/projection.test.d.ts +0 -1
  197. package/dist/modules/connectors/resolver.test.d.ts +0 -1
  198. package/dist/modules/functions/build.test.d.ts +0 -1
  199. package/dist/modules/functions/load.test.d.ts +0 -1
  200. package/dist/modules/functions/local.test.d.ts +0 -1
  201. package/dist/modules/functions/manifest.test.d.ts +0 -1
  202. package/dist/modules/functions/native.test.d.ts +0 -1
  203. package/dist/modules/functions/oauth.test.d.ts +0 -1
  204. package/dist/modules/functions/plugins.test.d.ts +0 -1
  205. package/dist/modules/functions/routes.test.d.ts +0 -1
  206. package/dist/modules/functions/runner/remote.test.d.ts +0 -1
  207. package/dist/modules/functions/sandbox/isolate.test.d.ts +0 -1
  208. package/dist/modules/functions/testing/tasksOf.d.ts +0 -4
  209. package/dist/modules/images/imageProxy.test.d.ts +0 -1
  210. package/dist/modules/images/transform.test.d.ts +0 -1
  211. package/dist/modules/mongo/stores.integration.test.d.ts +0 -1
  212. package/dist/modules/mysql/accounts.test.d.ts +0 -1
  213. package/dist/modules/mysql/jobs/stores.integration.test.d.ts +0 -1
  214. package/dist/modules/mysql/schema.test.d.ts +0 -1
  215. package/dist/modules/mysql/store.integration.test.d.ts +0 -1
  216. package/dist/modules/realtime/realtime.test.d.ts +0 -1
  217. package/dist/modules/realtime/redisPubSub.test.d.ts +0 -1
  218. package/dist/modules/realtime/retained.test.d.ts +0 -1
  219. package/dist/modules/realtime/socket.test.d.ts +0 -1
  220. package/dist/modules/rsc/connectorRscData.test.d.ts +0 -1
  221. package/dist/modules/rsc/handler.test.d.ts +0 -1
  222. package/dist/modules/rsc/publicFileResolver.test.d.ts +0 -1
  223. package/dist/modules/rsc/resolveRscData.test.d.ts +0 -1
  224. package/dist/modules/runtime/elsewhere.test.d.ts +0 -1
  225. package/dist/modules/runtime/entry.test.d.ts +0 -1
  226. package/dist/modules/runtime/inside.test.d.ts +0 -1
  227. package/dist/modules/runtime/ownServer.test.d.ts +0 -1
  228. package/dist/modules/runtime/runtime.test.d.ts +0 -1
  229. package/dist/modules/sqlite/kv.test.d.ts +0 -1
  230. package/dist/modules/ssr/draftSession.test.d.ts +0 -1
  231. package/dist/modules/ssr/loadPluginComponents.test.d.ts +0 -1
  232. package/dist/modules/ssr/metering.test.d.ts +0 -1
  233. package/dist/modules/ssr/prepareRender.test.d.ts +0 -1
  234. package/dist/modules/ssr/redirect.test.d.ts +0 -1
  235. package/dist/modules/ssr/registerExternalPlugins.test.d.ts +0 -1
  236. package/dist/modules/ssr/reportMissingPlugins.test.d.ts +0 -1
  237. package/dist/modules/ssr/resolvePageSeo.test.d.ts +0 -1
  238. package/dist/modules/ssr/spaceDocument.test.d.ts +0 -1
  239. package/dist/modules/ssr/template.test.d.ts +0 -1
  240. package/dist/modules/ssr/testing/offlineData.d.ts +0 -5
  241. package/dist/modules/ssr/vendor.test.d.ts +0 -1
  242. package/dist/plugins/compile.test.d.ts +0 -1
  243. package/dist/plugins/copy.test.d.ts +0 -1
  244. package/dist/plugins/manager.test.d.ts +0 -1
  245. package/dist/plugins/validate.test.d.ts +0 -1
@@ -1,4 +1,4 @@
1
- import { FunctionFailure } from "../protocol.js";
1
+ import { FunctionFailure, failedAnswerOf } from "../protocol.js";
2
2
  import { frameText } from "../../../helpers/wsFrame.js";
3
3
  import { readResponseMessage } from "./messages.js";
4
4
  import { WebSocket } from "ws";
@@ -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);
@@ -65,23 +78,62 @@ var createRemoteRunner = ({ url, secret, connectTimeoutMs = 5e3, graceMs = 5e3 }
65
78
  }), (error) => send({
66
79
  type: "answer",
67
80
  id: message.id,
68
- answer: {
69
- ok: false,
70
- error: error instanceof Error ? error.message : String(error)
71
- }
81
+ answer: failedAnswerOf(error)
72
82
  }));
73
83
  return;
84
+ case "head": {
85
+ if (settled) return;
86
+ settled = true;
87
+ clearTimeout(deadline);
88
+ const stream = new ReadableStream({
89
+ start: (controller) => {
90
+ body = controller;
91
+ },
92
+ cancel: () => {
93
+ bodyEnded = true;
94
+ send({ type: "abort" });
95
+ socket.close(1e3);
96
+ }
97
+ });
98
+ resolve({
99
+ streamed: true,
100
+ status: message.status,
101
+ statusText: message.statusText,
102
+ headers: message.headers,
103
+ body: stream
104
+ });
105
+ return;
106
+ }
107
+ case "chunk":
108
+ if (body && !bodyEnded) body.enqueue("base64" in message.chunk ? new Uint8Array(Buffer.from(message.chunk.base64, "base64")) : new TextEncoder().encode(message.chunk.text));
109
+ return;
74
110
  case "done":
75
111
  if (message.usage) onUsage?.(message.usage);
112
+ if (body) {
113
+ signal?.removeEventListener("abort", onAbort);
114
+ endBody((controller) => controller.close());
115
+ return;
116
+ }
76
117
  settle(() => resolve(message.value));
77
118
  return;
78
119
  case "failed":
79
120
  if (message.usage) onUsage?.(message.usage);
121
+ if (body) {
122
+ signal?.removeEventListener("abort", onAbort);
123
+ endBody((controller) => controller.error(new FunctionFailure(message.reason, message.error)));
124
+ return;
125
+ }
80
126
  settle(() => reject(new FunctionFailure(message.reason, message.error)));
81
127
  }
82
128
  });
83
- socket.on("error", (error) => settle(() => reject(unreachable(error.message))));
84
- socket.on("close", (code) => settle(() => reject(unreachable(`closed with ${String(code)}`))));
129
+ socket.on("error", (error) => {
130
+ endBody((controller) => controller.error(unreachable(error.message)));
131
+ settle(() => reject(unreachable(error.message)));
132
+ });
133
+ socket.on("close", (code) => {
134
+ endBody((controller) => controller.error(unreachable(`closed with ${String(code)}`)));
135
+ settle(() => reject(unreachable(`closed with ${String(code)}`)));
136
+ });
85
137
  });
86
138
  return {
87
139
  describe: (bundle) => operate({
@@ -1,5 +1,5 @@
1
1
  import { serverLog } from "../../../helpers/serverLog.js";
2
- import { FunctionFailure } from "../protocol.js";
2
+ import { FunctionFailure, errorOfAnswer, 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,
@@ -50,7 +96,7 @@ var serveConnection = (socket, runner) => {
50
96
  };
51
97
  const answer = (call) => new Promise((resolve, reject) => {
52
98
  const id = nextCall++;
53
- pending.set(id, (reply) => reply.ok ? resolve(reply.value) : reject(new Error(reply.error)));
99
+ pending.set(id, (reply) => reply.ok ? resolve(reply.value) : reject(errorOfAnswer(reply)));
54
100
  send({
55
101
  type: "call",
56
102
  id,
@@ -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") {
@@ -17,7 +17,7 @@ var installGuest = (scope, host, shared) => {
17
17
  */
18
18
  const REFUSAL = "ActionRefusal";
19
19
  const isRefusal = (error) => error instanceof Error && error.name === REFUSAL;
20
- const refusal = (message) => Object.assign(new Error(message), { name: REFUSAL });
20
+ const refusal = (message, code) => Object.assign(new Error(message), { name: REFUSAL }, code === void 0 ? {} : { code });
21
21
  const encodeUtf8 = (text) => {
22
22
  const out = [];
23
23
  for (const char of text) {
@@ -561,8 +561,10 @@ var installGuest = (scope, host, shared) => {
561
561
  };
562
562
  const call = async (message) => {
563
563
  const answer = JSON.parse(await host.call(JSON.stringify(message)));
564
- if (!isRecord(answer) || answer.ok !== true) throw new Error(isRecord(answer) && typeof answer.error === "string" ? answer.error : "The platform refused the call");
565
- return answer.value;
564
+ if (isRecord(answer) && answer.ok === true) return answer.value;
565
+ const said = isRecord(answer) && typeof answer.error === "string" ? answer.error : "The platform refused the call";
566
+ if (isRecord(answer) && answer.refused === true) throw refusal(said, typeof answer.code === "string" ? answer.code : void 0);
567
+ throw new Error(said);
566
568
  };
567
569
  const run = new GuestAbortController();
568
570
  const driver = shared.createFunctionsDriver({
@@ -1,5 +1,5 @@
1
1
  import { changeKv } from "../../actions/runtime/kvChange.js";
2
- import { FunctionFailure } from "../protocol.js";
2
+ import { FunctionFailure, failedAnswerOf } from "../protocol.js";
3
3
  import { installGuest } from "./guest.js";
4
4
  import { guestPrelude } from "./prelude.js";
5
5
  import { createFunctionsDriver, describeFunctions } from "../driver.js";
@@ -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();
@@ -244,10 +245,7 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 67108864 } = {}) => {
244
245
  value: value ?? null
245
246
  });
246
247
  } catch (error) {
247
- return JSON.stringify({
248
- ok: false,
249
- error: messageOf(error)
250
- });
248
+ return JSON.stringify(failedAnswerOf(error));
251
249
  }
252
250
  }));
253
251
  global.setSync("__plitziSleep", new ivm.Reference((ms) => new Promise((resolve) => later(Math.min(Math.max(0, ms), limits.wallMs), resolve))));
@@ -321,6 +319,7 @@ var createIsolateRunner = ({ concurrency = 8, cacheBytes = 67108864 } = {}) => {
321
319
  limits,
322
320
  answer,
323
321
  signal,
322
+ ...invocation.kind === "job" ? { graceMs: invocation.graceMs } : {},
324
323
  onUsage,
325
324
  drive: async (driver, definition) => {
326
325
  const invoke = driver.getSync("invoke", { reference: true });
@@ -1,10 +1,10 @@
1
1
  import { ActionRefusal } from "../actions/runtime/errors.js";
2
- import { functionContextFor } from "./context.js";
3
- import { taskName } from "../actions/tasks/registry.js";
4
- import { functionLimitsFor } from "./config.js";
5
2
  import { readManifest } from "./manifest.js";
3
+ import { functionContextFor } from "./context.js";
6
4
  import { answerCall, readCall } from "./capabilities.js";
5
+ import { functionLimitsFor } from "./config.js";
7
6
  import { FunctionFailure } from "./protocol.js";
7
+ import { taskName } from "../actions/tasks/registry.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
@@ -1,14 +1,15 @@
1
1
  import { createStoreClock } from "../actions/jobs/storeClock.js";
2
+ import { TERMINAL_JOB_STATUSES } from "@plitzi/sdk-shared/actions";
2
3
  //#region src/modules/mongo/jobQueue.ts
3
4
  /** Mongo's code for a unique index that refused a second document with the same key. */
4
5
  var DUPLICATE_KEY = 11e3;
5
- var TERMINAL = [
6
- "succeeded",
7
- "failed",
8
- "dead",
9
- "cancelled"
10
- ];
6
+ /** Mongo's code for a collection that does not exist yet. */
7
+ var NAMESPACE_NOT_FOUND = 26;
8
+ /** Spread into a plain array: the queries take a mutable list. */
9
+ var TERMINAL = [...TERMINAL_JOB_STATUSES];
11
10
  var DAY_MS = 864e5;
11
+ /** The index jobs were looked up by their action with, before they had a target. */
12
+ var LEGACY_ACTION_INDEX = "spaceId_1_actionId_1_updatedAt_-1";
12
13
  var resolveDb = (source) => typeof source === "function" ? source() : source;
13
14
  var scheduleId = (spaceId, actionId) => `${spaceId}:${actionId}`;
14
15
  /**
@@ -33,7 +34,7 @@ var lostAttempt = (at) => ({ $concatArrays: ["$history", [{
33
34
  error: "the worker holding this job stopped reporting"
34
35
  }]] });
35
36
  /**
36
- * An {@link ActionJobQueue} over two collections of a Mongo database the deployment owns.
37
+ * An {@link JobQueue} over two collections of a Mongo database the deployment owns.
37
38
  *
38
39
  * The helper for a deployment that already runs Mongo: it holds no connection of its own and creates nothing but the
39
40
  * indexes its queries need, on first use. Every replica pointed at the same database shares the jobs and the
@@ -60,6 +61,15 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
60
61
  return localTime ? localTime.getTime() : Date.now();
61
62
  });
62
63
  let ready;
64
+ /** Whether the index jobs were found by before targets is there — on a collection not made yet, nothing is. */
65
+ const legacyIndexIsThere = async () => {
66
+ try {
67
+ return await jobsOf().indexExists(LEGACY_ACTION_INDEX);
68
+ } catch (error) {
69
+ if (error.code === NAMESPACE_NOT_FOUND) return false;
70
+ throw error;
71
+ }
72
+ };
63
73
  /**
64
74
  * The indexes the queue cannot work without, built once on first use.
65
75
  *
@@ -68,6 +78,12 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
68
78
  * index each and merged already sorted.
69
79
  */
70
80
  const build = async () => {
81
+ await jobsOf().updateMany({ target: { $exists: false } }, [{ $set: { target: {
82
+ kind: "action",
83
+ name: "$actionId",
84
+ trigger: "$trigger"
85
+ } } }, { $unset: ["actionId", "trigger"] }]);
86
+ if (await legacyIndexIsThere()) await jobsOf().dropIndex(LEGACY_ACTION_INDEX);
71
87
  await Promise.all([
72
88
  jobsOf().createIndex({
73
89
  status: 1,
@@ -83,7 +99,7 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
83
99
  }),
84
100
  jobsOf().createIndex({
85
101
  spaceId: 1,
86
- actionId: 1,
102
+ "target.name": 1,
87
103
  updatedAt: -1
88
104
  }),
89
105
  jobsOf().createIndex({
@@ -178,10 +194,32 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
178
194
  _id: { $in: jobIds },
179
195
  workerId,
180
196
  status: "running",
181
- cancelRequested: true
182
- }).project({ _id: 1 }).toArray()).map((job) => job._id);
197
+ $or: [{ cancelRequested: true }, { pauseRequested: true }]
198
+ }).project({
199
+ _id: 1,
200
+ cancelRequested: 1
201
+ }).toArray()).map((job) => ({
202
+ jobId: job._id,
203
+ stop: job.cancelRequested === true ? "cancel" : "pause"
204
+ }));
205
+ },
206
+ write: async ({ jobId, workerId, state, progress }) => {
207
+ const { jobs } = await collections();
208
+ const at = await clock.now();
209
+ return (await jobs.updateOne({
210
+ _id: jobId,
211
+ workerId,
212
+ status: "running"
213
+ }, { $set: {
214
+ updatedAt: at,
215
+ ...state === void 0 ? {} : { state },
216
+ ...progress ? { progress: {
217
+ ...progress,
218
+ at
219
+ } } : {}
220
+ } })).matchedCount === 1;
183
221
  },
184
- settle: async ({ jobId, workerId, status, delayMs, runId, error, attempt }) => {
222
+ settle: async ({ jobId, workerId, status, delayMs, runId, error, attempt, result, spentMs, refund = status === "pending" && !attempt }) => {
185
223
  const { jobs } = await collections();
186
224
  const at = await clock.now();
187
225
  const entry = {
@@ -190,22 +228,46 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
190
228
  endedAt: at,
191
229
  ...attempt
192
230
  };
231
+ const settled = status === "pending" ? { $cond: [
232
+ { $eq: ["$cancelRequested", true] },
233
+ "cancelled",
234
+ { $cond: [
235
+ { $eq: ["$pauseRequested", true] },
236
+ "paused",
237
+ "pending"
238
+ ] }
239
+ ] } : status;
193
240
  await jobs.updateOne({
194
241
  _id: jobId,
195
242
  workerId
196
243
  }, [{ $set: {
197
244
  ...attempt ? { history: { $concatArrays: ["$history", [entry]] } } : {},
198
- status,
245
+ status: settled,
199
246
  updatedAt: at,
200
247
  leaseUntil: null,
201
248
  error: error ?? null,
249
+ cancelRequested: null,
250
+ pauseRequested: null,
202
251
  ...runId ? { runId } : {},
203
- ...status === "pending" ? {
204
- runAt: at + (delayMs ?? 0),
205
- workerId: null,
206
- ...attempt ? {} : { attempts: { $max: [0, { $subtract: ["$attempts", 1] }] } }
207
- } : {},
208
- expiresAt: TERMINAL.includes(status) ? expiryOf(at) : null
252
+ ...result === void 0 ? {} : { result: { $literal: result } },
253
+ ...spentMs ? { activeMs: { $add: [{ $ifNull: ["$activeMs", 0] }, spentMs] } } : {},
254
+ ...refund ? { attempts: { $max: [0, { $subtract: ["$attempts", 1] }] } } : {}
255
+ } }, { $set: {
256
+ runAt: { $cond: [
257
+ { $eq: ["$status", "pending"] },
258
+ at + (delayMs ?? 0),
259
+ "$runAt"
260
+ ] },
261
+ workerId: { $cond: [
262
+ { $in: ["$status", ["pending", "paused"]] },
263
+ null,
264
+ "$workerId"
265
+ ] },
266
+ expiresAt: { $cond: [
267
+ { $in: ["$status", TERMINAL] },
268
+ expiryOf(at),
269
+ null
270
+ ] }
209
271
  } }]);
210
272
  },
211
273
  dueSchedules: async (limit) => {
@@ -259,12 +321,13 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
259
321
  actionId: { $nin: incoming.map((schedule) => schedule.actionId) }
260
322
  });
261
323
  },
262
- listJobs: async ({ spaceIds, actionId, status, limit, offset }) => {
324
+ listJobs: async ({ spaceIds, name, status, kind, limit, offset }) => {
263
325
  const { jobs } = await collections();
264
326
  const filter = {
265
327
  spaceId: { $in: spaceIds },
266
- ...actionId ? { actionId } : {},
267
- ...status ? { status } : {}
328
+ ...name ? { "target.name": name } : {},
329
+ ...status ? { status } : {},
330
+ ...kind ? { "target.kind": kind } : {}
268
331
  };
269
332
  const [found, total] = await Promise.all([jobs.find(filter).sort({
270
333
  updatedAt: -1,
@@ -287,7 +350,7 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
287
350
  const { schedules } = await collections();
288
351
  return (await schedules.find({ spaceId: { $in: spaceIds } }).sort({ nextRunAt: 1 }).toArray()).map(toSchedule);
289
352
  },
290
- requeue: async (spaceIds, jobId) => {
353
+ requeue: async (spaceIds, jobId, { input, fresh = false } = {}) => {
291
354
  const { jobs } = await collections();
292
355
  const at = await clock.now();
293
356
  return (await jobs.updateOne({
@@ -300,13 +363,21 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
300
363
  runAt: at,
301
364
  attempts: 0,
302
365
  updatedAt: at,
303
- cancelRequested: false
366
+ ...input ? { input } : {}
304
367
  },
305
368
  $unset: {
306
369
  workerId: "",
307
370
  leaseUntil: "",
308
371
  error: "",
309
- expiresAt: ""
372
+ expiresAt: "",
373
+ result: "",
374
+ cancelRequested: "",
375
+ pauseRequested: "",
376
+ ...fresh ? {
377
+ state: "",
378
+ progress: "",
379
+ activeMs: ""
380
+ } : {}
310
381
  }
311
382
  })).matchedCount === 1;
312
383
  },
@@ -316,14 +387,17 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
316
387
  if ((await jobs.updateOne({
317
388
  _id: jobId,
318
389
  spaceId: { $in: spaceIds },
319
- status: "pending"
390
+ status: { $in: ["pending", "paused"] }
320
391
  }, {
321
392
  $set: {
322
393
  status: "cancelled",
323
394
  updatedAt: at,
324
395
  expiresAt: expiryOf(at)
325
396
  },
326
- $unset: { workerId: "" }
397
+ $unset: {
398
+ workerId: "",
399
+ pauseRequested: ""
400
+ }
327
401
  })).matchedCount === 1) return true;
328
402
  return (await jobs.updateOne({
329
403
  _id: jobId,
@@ -334,6 +408,43 @@ var createMongoJobQueue = ({ db, collections: names = {}, retentionDays = 90 })
334
408
  updatedAt: at
335
409
  } })).matchedCount === 1;
336
410
  },
411
+ pause: async (spaceIds, jobId) => {
412
+ const { jobs } = await collections();
413
+ const at = await clock.now();
414
+ const own = {
415
+ _id: jobId,
416
+ spaceId: { $in: spaceIds },
417
+ "target.kind": "function"
418
+ };
419
+ if ((await jobs.updateOne({
420
+ ...own,
421
+ status: "pending"
422
+ }, { $set: {
423
+ status: "paused",
424
+ updatedAt: at
425
+ } })).matchedCount === 1) return true;
426
+ return (await jobs.updateOne({
427
+ ...own,
428
+ status: "running",
429
+ pauseRequested: { $ne: true }
430
+ }, { $set: {
431
+ pauseRequested: true,
432
+ updatedAt: at
433
+ } })).matchedCount === 1;
434
+ },
435
+ resume: async (spaceIds, jobId) => {
436
+ const { jobs } = await collections();
437
+ const at = await clock.now();
438
+ return (await jobs.updateOne({
439
+ _id: jobId,
440
+ spaceId: { $in: spaceIds },
441
+ status: "paused"
442
+ }, { $set: {
443
+ status: "pending",
444
+ runAt: at,
445
+ updatedAt: at
446
+ } })).matchedCount === 1;
447
+ },
337
448
  cancelPending: async ({ spaceId, key, olderThan }) => {
338
449
  const { jobs } = await collections();
339
450
  const newest = olderThan === void 0 ? void 0 : await jobs.findOne({ _id: olderThan });
@@ -1,4 +1,4 @@
1
- import { ActionJobQueue } from '@plitzi/sdk-shared';
1
+ import { JobQueue } from '@plitzi/sdk-shared';
2
2
  import { Pool } from 'mysql2/promise';
3
3
  export type MysqlJobQueueOptions = {
4
4
  /** A pool the deployment opened. The helper borrows connections from it and never ends it. */
@@ -13,12 +13,12 @@ export type MysqlJobQueueOptions = {
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 MysqlJobQueue = ActionJobQueue & {
16
+ export type MysqlJobQueue = 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 tables in a MySQL database the deployment owns. Tested on MySQL 8; nothing in it
21
+ * An {@link JobQueue} over tables in a MySQL database the deployment owns. Tested on MySQL 8; nothing in it
22
22
  * needs more than 5.7.
23
23
  *
24
24
  * The helper for a deployment that already runs MySQL: it borrows connections from the pool it is handed, and creates