@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
@@ -0,0 +1,438 @@
1
+ import { serverLog } from "../../helpers/serverLog.js";
2
+ import { ActionRefusal, isActionRefusal } from "../actions/runtime/errors.js";
3
+ import { functionContextFor } from "./context.js";
4
+ import { answerCall, readCall } from "./capabilities.js";
5
+ import { functionLimitsFor } from "./config.js";
6
+ import { FunctionFailure } from "./protocol.js";
7
+ import { isTerminalJobStatus } from "@plitzi/sdk-shared/actions";
8
+ import { isRecord } from "@plitzi/sdk-shared/helpers";
9
+ import { createHash, randomUUID } from "node:crypto";
10
+ //#region src/modules/functions/jobs.ts
11
+ var DEFAULT_FUNCTION_JOB_LIMITS = {
12
+ running: 10,
13
+ waiting: 1e3,
14
+ maxSeconds: 21600,
15
+ sliceMs: 3e5,
16
+ sliceCpuMs: 3e4,
17
+ sliceCalls: 1e4,
18
+ stateBytes: 1e6
19
+ };
20
+ /** How long a slice asked to end has to save and return before it is cut. */
21
+ var JOB_GRACE_MS = 5e3;
22
+ /** The least time between two reports a watcher hears: what a loop reporting every iteration costs nothing more than. */
23
+ var REPORT_EVERY_MS = 250;
24
+ /** How long a job over its account's running jobs waits before it is looked at again. */
25
+ var BUSY_WAIT_MS = 5e3;
26
+ /** The most running jobs read to decide which of them go on: past it, every one but the oldest waits. */
27
+ var RUNNING_READ = 1e3;
28
+ /** A name a keyed job is known by, as a topic is written. */
29
+ var KEY = /^[A-Za-z0-9:_.-]{1,128}$/;
30
+ var STOPS = [
31
+ "pause",
32
+ "cancel",
33
+ "limit",
34
+ "shutdown"
35
+ ];
36
+ var isStop = (value) => STOPS.some((stop) => stop === value);
37
+ var bytesOf = (value) => value === void 0 ? 4 : Buffer.byteLength(JSON.stringify(value));
38
+ var messageOf = (error) => error instanceof Error ? error.message : String(error);
39
+ /** What a job's declaration says besides its code, as a manifest holds it. */
40
+ var jobsManifestOf = (definition) => Object.fromEntries(Object.entries(definition.jobs ?? {}).map(([name, job]) => [name, {
41
+ ...job.watch ? { watch: job.watch } : {},
42
+ ...job.maxSeconds === void 0 ? {} : { maxSeconds: job.maxSeconds }
43
+ }]));
44
+ /**
45
+ * 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
46
+ * — anything else it threw can carry what a visitor must not read, and stays in the Queue for an operator.
47
+ */
48
+ var jobViewOf = (job) => {
49
+ const last = job.history.at(-1);
50
+ const failed = job.status === "failed" || job.status === "dead";
51
+ return {
52
+ id: job.id,
53
+ name: job.target.name,
54
+ status: job.status,
55
+ ...job.progress ? { progress: job.progress.fraction } : {},
56
+ ...job.progress?.step ? { step: job.progress.step } : {},
57
+ ...job.status === "succeeded" && job.result !== void 0 ? { result: job.result } : {},
58
+ ...failed ? { error: last?.refused && last.error ? last.error : "The job failed" } : {},
59
+ createdAt: job.createdAt,
60
+ updatedAt: job.updatedAt
61
+ };
62
+ };
63
+ var createFunctionJobs = ({ queue, config, getFunctions, taskContext, publish, maxAttempts }) => {
64
+ const queueOrThrow = () => {
65
+ const found = queue();
66
+ if (!found) throw new Error("This server runs no jobs — its actions have no queue (`jobs: false`, or no way to list actions)");
67
+ return found;
68
+ };
69
+ const limitsOf = async (spaceId) => ({
70
+ ...DEFAULT_FUNCTION_JOB_LIMITS,
71
+ ...await config.jobs?.limitsFor?.(spaceId)
72
+ });
73
+ const announce = async (spaceId, jobId) => {
74
+ if (!publish) return;
75
+ try {
76
+ const job = await queue()?.getJob([spaceId], jobId);
77
+ if (job?.target.kind === "function") await publish({
78
+ spaceId,
79
+ environment: job.environment
80
+ }, jobId, jobViewOf(job));
81
+ } catch (error) {
82
+ serverLog.warn("Functions", `job ${jobId} of space ${String(spaceId)}: its watchers were not told`, error);
83
+ }
84
+ };
85
+ /** A job of this space's functions by id — a run of an action under the same id is not one `ctx.jobs` reaches. */
86
+ const ownJob = async (spaceId, id) => {
87
+ const job = typeof id === "string" && id !== "" ? await queueOrThrow().getJob([spaceId], id) : void 0;
88
+ return job?.target.kind === "function" ? job : void 0;
89
+ };
90
+ const forRun = (run, declared) => {
91
+ const { spaceId } = run;
92
+ /** A stop or a resume, said to the job's watchers when it changed something. */
93
+ const changed = async (id, change) => {
94
+ const jobs = queueOrThrow();
95
+ if (!await ownJob(spaceId, id) || !await change(jobs)) return false;
96
+ await announce(spaceId, id);
97
+ return true;
98
+ };
99
+ return {
100
+ start: async (name, input = {}, { key } = {}) => {
101
+ const jobs = queueOrThrow();
102
+ const declaration = Object.hasOwn(declared, name) ? declared[name] : void 0;
103
+ if (!declaration) {
104
+ const names = Object.keys(declared);
105
+ throw new Error(`No job "${name}": ${names.length ? `this code declares ${names.join(", ")}` : "declare it in jobs of defineFunctions"}`);
106
+ }
107
+ if (!isRecord(input)) throw new Error("A job is handed an object as its input");
108
+ if (key !== void 0 && (typeof key !== "string" || !KEY.test(key))) throw new Error("A key is 1 to 128 letters, digits and `:_.-` — `train:model-7`");
109
+ const limits = await limitsOf(spaceId);
110
+ if (bytesOf(input) > limits.stateBytes) throw new Error(`A job's input is ${String(bytesOf(input))} bytes, over the ${String(limits.stateBytes)} a job keeps: hand it an id to read the rest by`);
111
+ const waiting = (await Promise.all(["pending", "paused"].map(async (status) => (await jobs.listJobs({
112
+ spaceIds: [spaceId],
113
+ kind: "function",
114
+ status,
115
+ limit: 1,
116
+ offset: 0
117
+ })).total))).reduce((sum, count) => sum + count, 0);
118
+ if (waiting >= limits.waiting) throw new ActionRefusal(`This space has ${String(waiting)} jobs waiting, the most it may: let some of them finish first`);
119
+ const id = key === void 0 ? `job:${String(spaceId)}:${randomUUID()}` : `job:${String(spaceId)}:${name}:${createHash("sha256").update(key).digest("hex").slice(0, 24)}`;
120
+ if (!await jobs.enqueue({
121
+ id,
122
+ spaceId,
123
+ environment: run.environment,
124
+ target: {
125
+ kind: "function",
126
+ name,
127
+ ...run.user ? { user: run.user } : {},
128
+ ...declaration.watch ? { watch: declaration.watch } : {},
129
+ ...run.at ? { at: run.at } : {}
130
+ },
131
+ input,
132
+ dueAt: (await jobs.now()).getTime(),
133
+ maxAttempts,
134
+ ...key === void 0 ? {} : { key }
135
+ })) {
136
+ const existing = await jobs.getJob([spaceId], id);
137
+ if (existing && isTerminalJobStatus(existing.status)) await jobs.requeue([spaceId], id, {
138
+ input,
139
+ fresh: true
140
+ });
141
+ }
142
+ await announce(spaceId, id);
143
+ const job = await jobs.getJob([spaceId], id);
144
+ if (!job) throw new Error(`Job "${name}" was started and is not in the queue: the queue lost it`);
145
+ return jobViewOf(job);
146
+ },
147
+ get: async (id) => {
148
+ const job = await ownJob(spaceId, id);
149
+ return job ? jobViewOf(job) : void 0;
150
+ },
151
+ pause: (id) => changed(id, (jobs) => jobs.pause([spaceId], id)),
152
+ resume: (id) => changed(id, (jobs) => jobs.resume([spaceId], id)),
153
+ cancel: (id) => changed(id, (jobs) => jobs.cancel([spaceId], id))
154
+ };
155
+ };
156
+ const find = async (spaceId, target) => {
157
+ const definition = (config.native ?? []).find((each) => Object.hasOwn(each.jobs ?? {}, target.name));
158
+ if (definition) return {
159
+ native: true,
160
+ definition
161
+ };
162
+ const functions = await getFunctions?.(spaceId, target.at);
163
+ const declaration = functions?.manifest.jobs?.[target.name];
164
+ return functions && declaration ? {
165
+ native: false,
166
+ functions,
167
+ declaration
168
+ } : void 0;
169
+ };
170
+ const slice = async (job, signal, workerId) => {
171
+ const jobs = queueOrThrow();
172
+ const startedAt = Date.now();
173
+ const spent = () => Date.now() - startedAt;
174
+ const { target } = job;
175
+ if (target.kind !== "function") return {
176
+ kind: "failed",
177
+ error: "A run of an action is not a job of functions",
178
+ final: true,
179
+ refused: false,
180
+ spentMs: 0
181
+ };
182
+ const found = await find(job.spaceId, target);
183
+ if (!found) return {
184
+ kind: "failed",
185
+ error: `This space's functions declare no job "${target.name}" any more`,
186
+ final: true,
187
+ refused: false,
188
+ spentMs: 0
189
+ };
190
+ const limits = await limitsOf(job.spaceId);
191
+ const { jobs: running } = await jobs.listJobs({
192
+ spaceIds: limits.pool ?? [job.spaceId],
193
+ kind: "function",
194
+ status: "running",
195
+ limit: RUNNING_READ,
196
+ offset: 0
197
+ });
198
+ const order = running.sort((a, b) => a.createdAt - b.createdAt || (a.id < b.id ? -1 : 1)).findIndex((each) => each.id === job.id);
199
+ if (order === -1 || order >= limits.running) return {
200
+ kind: "wait",
201
+ delayMs: BUSY_WAIT_MS + Math.floor(Math.random() * BUSY_WAIT_MS),
202
+ why: `waiting: ${String(Math.min(running.length - 1, limits.running))} jobs of this account run at once, the most it may`
203
+ };
204
+ const refusal = found.native ? void 0 : await config.admit?.(job.spaceId);
205
+ if (refusal) return {
206
+ kind: "wait",
207
+ delayMs: BUSY_WAIT_MS,
208
+ why: `waiting: ${refusal}`
209
+ };
210
+ const declared = found.native ? jobsManifestOf(found.definition)[target.name] : found.declaration;
211
+ const maxMs = Math.min(limits.maxSeconds, declared.maxSeconds ?? limits.maxSeconds) * 1e3;
212
+ const remainingMs = maxMs - (job.activeMs ?? 0);
213
+ if (remainingMs <= 0) return {
214
+ kind: "failed",
215
+ error: `ran for ${String(Math.round(maxMs / 1e3))} s, the most a job may`,
216
+ final: true,
217
+ refused: false,
218
+ spentMs: 0
219
+ };
220
+ const sandboxed = !found.native && !found.functions.runner;
221
+ const boundMs = sandboxed ? Math.min(limits.sliceMs, remainingMs) : remainingMs;
222
+ const lastSlice = boundMs >= remainingMs;
223
+ const stopper = new AbortController();
224
+ const forward = () => stopper.abort(isStop(signal.reason) ? signal.reason : "cancel");
225
+ signal.addEventListener("abort", forward, { once: true });
226
+ if (signal.aborted) forward();
227
+ const timer = setTimeout(() => stopper.abort("limit"), boundMs);
228
+ let saved = false;
229
+ let reported;
230
+ let reportTimer;
231
+ let reportedAt = 0;
232
+ /** A write the worker no longer holds the job for: the job is somebody else's now, and this slice stops. */
233
+ const held = (written) => {
234
+ if (!written) stopper.abort("shutdown");
235
+ };
236
+ const flushReport = async () => {
237
+ clearTimeout(reportTimer);
238
+ reportTimer = void 0;
239
+ const progress = reported;
240
+ reported = void 0;
241
+ if (!progress) return;
242
+ reportedAt = Date.now();
243
+ held(await jobs.write({
244
+ jobId: job.id,
245
+ workerId,
246
+ progress
247
+ }));
248
+ await announce(job.spaceId, job.id);
249
+ };
250
+ const save = async (state) => {
251
+ const bytes = bytesOf(state);
252
+ if (bytes > limits.stateBytes) throw new Error(`job.save: the state is ${String(bytes)} bytes, over the ${String(limits.stateBytes)} a job keeps — save where it is, not what it made`);
253
+ const written = await jobs.write({
254
+ jobId: job.id,
255
+ workerId,
256
+ state
257
+ });
258
+ held(written);
259
+ if (!written) throw new Error("job.save: this server no longer holds the job — another one took it over");
260
+ saved = true;
261
+ };
262
+ const report = (fraction, step) => {
263
+ reported = {
264
+ fraction: Math.min(1, Math.max(0, Number.isFinite(fraction) ? fraction : 0)),
265
+ ...step ? { step: step.slice(0, 200) } : {}
266
+ };
267
+ if (reportTimer) return;
268
+ reportTimer = setTimeout(() => {
269
+ flushReport().catch((error) => {
270
+ serverLog.warn("Functions", `job ${job.id}: a report was not kept`, error);
271
+ });
272
+ }, Math.max(0, REPORT_EVERY_MS - (Date.now() - reportedAt)));
273
+ };
274
+ const user = target.user;
275
+ const ctx = taskContext()({
276
+ runId: randomUUID(),
277
+ spaceId: job.spaceId,
278
+ environment: job.environment,
279
+ trigger: "call",
280
+ callerId: user ? `user:${String(user.id)}` : "job",
281
+ ...user ? { user } : {},
282
+ ...target.at ? { at: target.at } : {}
283
+ }, stopper.signal, [`job:${target.name}`]);
284
+ const log = (line) => {
285
+ serverLog.info("Functions", `job ${target.name} ${job.id} of space ${String(job.spaceId)}: ${line}`);
286
+ };
287
+ const contextOf = (hosts, definition, manifest = {}) => ({
288
+ ...functionContextFor({
289
+ ...ctx,
290
+ log
291
+ }, hosts, void 0, definition.oauth, manifest),
292
+ trigger: "job"
293
+ });
294
+ /** How the code ended, read with why it was asked to: returning once asked to stop is stopping, not finishing. */
295
+ const outcomeOf = (ended) => {
296
+ const stop = stopper.signal.aborted && isStop(stopper.signal.reason) ? stopper.signal.reason : void 0;
297
+ if (stop === "limit" && lastSlice) return {
298
+ kind: "failed",
299
+ error: `ran for ${String(Math.round(maxMs / 1e3))} s, the most a job may`,
300
+ final: true,
301
+ refused: false,
302
+ spentMs: spent()
303
+ };
304
+ if (stop && "value" in ended) return {
305
+ kind: "stopped",
306
+ stop,
307
+ saved,
308
+ spentMs: spent()
309
+ };
310
+ if ("value" in ended) return {
311
+ kind: "done",
312
+ result: ended.value,
313
+ spentMs: spent()
314
+ };
315
+ const { error } = ended;
316
+ if (isActionRefusal(error) || error instanceof FunctionFailure && error.reason === "refused") return {
317
+ kind: "failed",
318
+ error: messageOf(error),
319
+ final: true,
320
+ refused: true,
321
+ spentMs: spent()
322
+ };
323
+ if (stop) return {
324
+ kind: "stopped",
325
+ stop,
326
+ saved,
327
+ spentMs: spent()
328
+ };
329
+ return {
330
+ kind: "failed",
331
+ error: messageOf(error),
332
+ final: false,
333
+ refused: false,
334
+ spentMs: spent()
335
+ };
336
+ };
337
+ const slicePart = {
338
+ id: job.id,
339
+ attempt: job.attempts,
340
+ ...job.state === void 0 ? {} : { state: job.state }
341
+ };
342
+ try {
343
+ if (found.native) {
344
+ const { definition } = found;
345
+ const declaredJob = definition.jobs?.[target.name];
346
+ if (!declaredJob) throw new Error(`This server's functions declare no job "${target.name}"`);
347
+ const fnCtx = contextOf(definition.allow?.hosts ?? [], definition, jobsManifestOf(definition));
348
+ const handle = {
349
+ id: job.id,
350
+ name: target.name,
351
+ state: job.state,
352
+ attempt: job.attempts,
353
+ save,
354
+ report,
355
+ get stopping() {
356
+ const reason = stopper.signal.reason;
357
+ return stopper.signal.aborted && isStop(reason) ? reason : void 0;
358
+ },
359
+ signal: stopper.signal
360
+ };
361
+ const value = await declaredJob.run(job.input, handle, fnCtx);
362
+ return outcomeOf({ value: value === void 0 ? null : value });
363
+ }
364
+ const { functions } = found;
365
+ const runner = functions.runner ?? config.runner;
366
+ if (!runner) throw new Error("This server runs no space functions");
367
+ const fnCtx = contextOf(functions.manifest.hosts, functions.manifest, functions.manifest.jobs);
368
+ const limitsForSlice = {
369
+ ...functionLimitsFor(config.limits, functions.limits, functions.manifest.limits),
370
+ cpuMs: sandboxed ? limits.sliceCpuMs : boundMs,
371
+ wallMs: boundMs + JOB_GRACE_MS,
372
+ calls: sandboxed ? limits.sliceCalls : Number.MAX_SAFE_INTEGER
373
+ };
374
+ const answer = async (raw) => {
375
+ const call = readCall(raw);
376
+ if (call.op !== "job") return answerCall(fnCtx, call);
377
+ if (call.method === "save") {
378
+ await save(call.state);
379
+ return null;
380
+ }
381
+ report(call.fraction, call.step);
382
+ return null;
383
+ };
384
+ let usage;
385
+ let ok = false;
386
+ try {
387
+ const value = await runner.invoke({
388
+ bundle: functions.bundle,
389
+ invocation: {
390
+ kind: "job",
391
+ name: target.name,
392
+ input: job.input,
393
+ job: slicePart,
394
+ context: {
395
+ spaceId: fnCtx.spaceId,
396
+ environment: fnCtx.environment,
397
+ runId: fnCtx.runId,
398
+ trigger: fnCtx.trigger,
399
+ callerId: fnCtx.callerId,
400
+ ...fnCtx.user ? { user: fnCtx.user } : {}
401
+ },
402
+ graceMs: JOB_GRACE_MS
403
+ },
404
+ limits: limitsForSlice,
405
+ answer,
406
+ signal: stopper.signal,
407
+ onUsage: (spentNow) => {
408
+ usage = spentNow;
409
+ }
410
+ });
411
+ ok = true;
412
+ return outcomeOf({ value });
413
+ } finally {
414
+ if (usage) config.onUsage?.({
415
+ spaceId: job.spaceId,
416
+ task: `job ${target.name}`,
417
+ ok,
418
+ usage
419
+ });
420
+ }
421
+ } catch (error) {
422
+ return outcomeOf({ error });
423
+ } finally {
424
+ clearTimeout(timer);
425
+ signal.removeEventListener("abort", forward);
426
+ await flushReport().catch((error) => {
427
+ serverLog.warn("Functions", `job ${job.id}: its last report was not kept`, error);
428
+ });
429
+ }
430
+ };
431
+ return {
432
+ forRun,
433
+ slice,
434
+ announce
435
+ };
436
+ };
437
+ //#endregion
438
+ export { DEFAULT_FUNCTION_JOB_LIMITS, JOB_GRACE_MS, createFunctionJobs, jobViewOf, jobsManifestOf };
@@ -14,6 +14,8 @@ export declare const reservedRouteProblem: (route: string) => string;
14
14
  * wildcard, `..` — is not a key, so what a space may answer is only ever a path it spelled out.
15
15
  */
16
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>;
17
19
  export type ManifestReading = {
18
20
  manifest: FunctionsManifest;
19
21
  problems: string[];
@@ -1,6 +1,6 @@
1
1
  import { pluginTaskProblem } from "./scope.js";
2
2
  import { taskName, taskNameProblem } from "../actions/tasks/registry.js";
3
- import { PLUGIN_ROUTES_SEGMENT } from "@plitzi/sdk-shared/actions";
3
+ import { PLUGIN_ROUTES_SEGMENT, actionAccessOf } from "@plitzi/sdk-shared/actions";
4
4
  import { isRecord } from "@plitzi/sdk-shared/helpers";
5
5
  //#region src/modules/functions/manifest.ts
6
6
  var ROUTE_METHODS = [
@@ -50,6 +50,35 @@ var httpsUrl = (value) => {
50
50
  return;
51
51
  }
52
52
  };
53
+ /** The jobs a bundle declares (`jobs`), by name: who may watch each, and how long it may run. */
54
+ var jobsOf = (value, problems, scope) => {
55
+ if (value === void 0 || value === null) return;
56
+ if (scope) {
57
+ problems.push("The functions of a plugin declare no jobs: only its space does (jobs)");
58
+ return;
59
+ }
60
+ if (!isRecord(value)) {
61
+ problems.push("jobs is an object of jobs, by the name the code starts them by");
62
+ return;
63
+ }
64
+ const jobs = {};
65
+ for (const [name, entry] of Object.entries(value)) {
66
+ const where = `Job "${name}"`;
67
+ const said = problems.length;
68
+ if (!CONNECTION_NAME.test(name)) problems.push(`${where}: a name is a letter, then letters, digits and "-", up to 64`);
69
+ const spec = isRecord(entry) ? entry : {};
70
+ const watch = spec.watch === void 0 ? void 0 : actionAccessOf(spec.watch);
71
+ if (spec.watch !== void 0 && !watch) problems.push(`${where}: watch is a channel's access — { mode: 'public' }, { mode: 'session' } or { mode: 'role', permissions: ['…'] }`);
72
+ const maxSeconds = spec.maxSeconds;
73
+ if (maxSeconds !== void 0 && (typeof maxSeconds !== "number" || !Number.isInteger(maxSeconds) || maxSeconds < 1)) problems.push(`${where}: maxSeconds is a whole number of seconds, from 1`);
74
+ if (problems.length > said) continue;
75
+ jobs[name] = {
76
+ ...watch ? { watch } : {},
77
+ ...typeof maxSeconds === "number" ? { maxSeconds } : {}
78
+ };
79
+ }
80
+ return Object.keys(jobs).length ? jobs : void 0;
81
+ };
53
82
  /**
54
83
  * The OAuth connections a definition declared, rebuilt field by field: each a provider's issuer or its endpoints (https),
55
84
  * the credential with the app's id and secret, the scopes. What is wrong is said by connection, and that one left out.
@@ -94,13 +123,15 @@ var oauthOf = (value, problems, scope) => {
94
123
  else if (typeof param === "string") authorizeParams[key] = param;
95
124
  else problems.push(`${where}: authorizeParams.${key} is a string`);
96
125
  if (spec.clientAuth !== void 0 && spec.clientAuth !== "body" && spec.clientAuth !== "basic") problems.push(`${where}: clientAuth is "body" or "basic"`);
126
+ if (spec.exposeToken !== void 0 && typeof spec.exposeToken !== "boolean") problems.push(`${where}: exposeToken is true or false`);
97
127
  if (problems.length > said || !credential) continue;
98
128
  connections[name] = {
99
129
  ...urls,
100
130
  credential,
101
131
  ...scopes.length ? { scopes: scopes.filter((each) => typeof each === "string") } : {},
102
132
  ...Object.keys(authorizeParams).length ? { authorizeParams } : {},
103
- ...spec.clientAuth === "basic" || spec.clientAuth === "body" ? { clientAuth: spec.clientAuth } : {}
133
+ ...spec.clientAuth === "basic" || spec.clientAuth === "body" ? { clientAuth: spec.clientAuth } : {},
134
+ ...spec.exposeToken === true ? { exposeToken: true } : {}
104
135
  };
105
136
  }
106
137
  return Object.keys(connections).length ? connections : void 0;
@@ -283,16 +314,18 @@ var readManifest = (value, reserved, ceilings, scope) => {
283
314
  });
284
315
  const limits = limitsOf(raw.limits, "The functions", ceilings, problems);
285
316
  const oauth = oauthOf(raw.oauth, problems, scope);
317
+ const jobs = jobsOf(raw.jobs, problems, scope);
286
318
  return {
287
319
  manifest: {
288
320
  hosts,
289
321
  tasks,
290
322
  routes,
291
323
  ...limits ? { limits } : {},
292
- ...oauth ? { oauth } : {}
324
+ ...oauth ? { oauth } : {},
325
+ ...jobs ? { jobs } : {}
293
326
  },
294
327
  problems
295
328
  };
296
329
  };
297
330
  //#endregion
298
- export { ROUTE_METHODS, parseRouteKey, readManifest, reservedRouteProblem };
331
+ export { OWN_AUTHORIZE_PARAMS, ROUTE_METHODS, parseRouteKey, readManifest, reservedRouteProblem };
@@ -1,4 +1,5 @@
1
1
  import { functionContextFor } from "./context.js";
2
+ import { jobsManifestOf } from "./jobs.js";
2
3
  //#region src/modules/functions/native.ts
3
4
  /**
4
5
  * A server's own functions, loaded as they are: trusted code the deployment ships — a self-hosted server's, or a
@@ -6,7 +7,7 @@ import { functionContextFor } from "./context.js";
6
7
  * space runs in the sandbox, loaded without one.
7
8
  */
8
9
  var nativeTasks = (definitions = [], scope) => definitions.flatMap((definition) => (definition.tasks ?? []).map((task) => {
9
- const contextFor = (ctx) => functionContextFor(ctx, definition.allow?.hosts ?? [], scope, definition.oauth);
10
+ const contextFor = (ctx) => functionContextFor(ctx, definition.allow?.hosts ?? [], scope, definition.oauth, jobsManifestOf(definition));
10
11
  const { run, params } = task;
11
12
  return {
12
13
  namespace: task.namespace,
@@ -9,12 +9,13 @@ import { FunctionOAuthConnection } from '@plitzi/sdk-shared';
9
9
  * exchanges the code with the app's id and secret (a credential of the space's, resolved here) and keeps the tokens
10
10
  * sealed under the connection and its owner; `fetch` writes the access token into a request, renewing it first when it
11
11
  * is about to lapse and once more on a 401. Sealed with the space's own key, which no signature of `ctx.sign` reaches:
12
- * the code reads only ciphertext, even with `ctx.kv`.
12
+ * the code reads only ciphertext, even with `ctx.kv`. The one way out is `token`, for a connection that declares
13
+ * `exposeToken`: the access token, for an SDK in the page — the refresh token never leaves.
13
14
  */
14
15
  /** Where the provider sends the visitor back, under `/fn` — the one address to register with every provider. */
15
16
  export declare const OAUTH_CALLBACK_PATH = "/oauth/callback";
16
17
  /** What the parts of a run `ctx.oauth` uses are: its fetch, its kv, its credentials, its sealing, who and where. */
17
- export type OAuthRun = Pick<ActionTaskContext, 'fetch' | 'kv' | 'credential' | 'seal' | 'open' | 'origin' | 'user' | 'signal'>;
18
+ export type OAuthRun = Pick<ActionTaskContext, 'fetch' | 'kv' | 'credential' | 'seal' | 'open' | 'origin' | 'oauthCallbackOrigin' | 'user' | 'signal'>;
18
19
  /**
19
20
  * `ctx.oauth` for one run, over the connections its code declared. `hosts` are where `fetch` may write the token — the
20
21
  * same `allow.hosts` every request of the code is held to.