@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
@@ -1,5 +1,5 @@
1
1
  import { ActionLookups } from '../types';
2
- import { ActionJobQueue, Environment, SpaceRevision } from '@plitzi/sdk-shared';
2
+ import { JobQueue, Environment, SpaceRevision } from '@plitzi/sdk-shared';
3
3
  /** A month: past it, a run set for later is a schedule, and a cron says it better. */
4
4
  export declare const MAX_LATER_SECONDS: number;
5
5
  /** What a run asks to start later: one of the space's actions, in so many seconds, with its input — and a name. */
@@ -22,7 +22,7 @@ export type LaterAnswer = {
22
22
  };
23
23
  export type LaterDeps = {
24
24
  /** Read when asked: the queue is made after the runner, and a server may run none. */
25
- queue: () => ActionJobQueue | undefined;
25
+ queue: () => JobQueue | undefined;
26
26
  lookups: Pick<ActionLookups, 'getAction'>;
27
27
  maxAttempts: number;
28
28
  };
@@ -37,9 +37,12 @@ var laterFor = ({ queue, lookups, maxAttempts }, { spaceId, environment, at }) =
37
37
  await jobs.enqueue({
38
38
  id,
39
39
  spaceId,
40
- actionId: entry.id,
41
40
  environment,
42
- trigger: "later",
41
+ target: {
42
+ kind: "action",
43
+ name: entry.id,
44
+ trigger: "later"
45
+ },
43
46
  input,
44
47
  dueAt,
45
48
  maxAttempts,
@@ -1,5 +1,5 @@
1
1
  import { StoreMethods } from '../../../core/server/fleet/channel';
2
- import { ActionJobQueue } from '@plitzi/sdk-shared';
2
+ import { JobQueue } from '@plitzi/sdk-shared';
3
3
  export type MemoryJobQueueOptions = {
4
4
  /**
5
5
  * How many finished jobs to keep before the oldest are dropped.
@@ -18,16 +18,16 @@ export type MemoryJobQueueOptions = {
18
18
  clock?: () => number;
19
19
  };
20
20
  /** Every method of the queue, for the copy a server's workers share (see `fleet/stores.ts`). */
21
- export declare const JOB_QUEUE_METHODS: StoreMethods<ActionJobQueue>;
21
+ export declare const JOB_QUEUE_METHODS: StoreMethods<JobQueue>;
22
22
  /**
23
23
  * The default queue: one process's Maps.
24
24
  *
25
25
  * Correct for a deployment that runs ONE replica, which is most self-hosted ones, and honest about the rest — a
26
26
  * second replica running on this gets its own schedules and its own jobs, so a nightly digest goes out twice. The
27
- * cure is any store the replicas share, behind the same {@link ActionJobQueue} seam.
27
+ * cure is any store the replicas share, behind the same {@link JobQueue} seam.
28
28
  *
29
29
  * It keeps the contract exactly, rather than approximately: enqueue is idempotent by id, a claim reaps lapsed
30
30
  * leases, and every instant is read here rather than accepted from a caller. A test that passes against this one
31
31
  * is testing the rules a shared store has to keep too.
32
32
  */
33
- export declare const createMemoryJobQueue: ({ retainFinished, clock }?: MemoryJobQueueOptions) => ActionJobQueue;
33
+ export declare const createMemoryJobQueue: ({ retainFinished, clock }?: MemoryJobQueueOptions) => JobQueue;
@@ -1,10 +1,5 @@
1
+ import { isTerminalJobStatus } from "@plitzi/sdk-shared/actions";
1
2
  //#region src/modules/actions/jobs/memoryQueue.ts
2
- var TERMINAL = /* @__PURE__ */ new Set([
3
- "succeeded",
4
- "failed",
5
- "dead",
6
- "cancelled"
7
- ]);
8
3
  /** Every method of the queue, for the copy a server's workers share (see `fleet/stores.ts`). */
9
4
  var JOB_QUEUE_METHODS = {
10
5
  now: true,
@@ -12,6 +7,7 @@ var JOB_QUEUE_METHODS = {
12
7
  claim: true,
13
8
  heartbeat: true,
14
9
  settle: true,
10
+ write: true,
15
11
  dueSchedules: true,
16
12
  advanceSchedule: true,
17
13
  putSchedules: true,
@@ -20,6 +16,8 @@ var JOB_QUEUE_METHODS = {
20
16
  listSchedules: true,
21
17
  requeue: true,
22
18
  cancel: true,
19
+ pause: true,
20
+ resume: true,
23
21
  cancelPending: true
24
22
  };
25
23
  /**
@@ -27,7 +25,7 @@ var JOB_QUEUE_METHODS = {
27
25
  *
28
26
  * Correct for a deployment that runs ONE replica, which is most self-hosted ones, and honest about the rest — a
29
27
  * second replica running on this gets its own schedules and its own jobs, so a nightly digest goes out twice. The
30
- * cure is any store the replicas share, behind the same {@link ActionJobQueue} seam.
28
+ * cure is any store the replicas share, behind the same {@link JobQueue} seam.
31
29
  *
32
30
  * It keeps the contract exactly, rather than approximately: enqueue is idempotent by id, a claim reaps lapsed
33
31
  * leases, and every instant is read here rather than accepted from a caller. A test that passes against this one
@@ -40,7 +38,7 @@ var createMemoryJobQueue = ({ retainFinished = 500, clock = Date.now } = {}) =>
40
38
  const now = () => clock();
41
39
  /** Oldest finished jobs first, so the bound drops history rather than anything anybody is waiting on. */
42
40
  const evict = () => {
43
- const finished = [...jobs.values()].filter((job) => TERMINAL.has(job.status)).sort((a, b) => a.updatedAt - b.updatedAt);
41
+ const finished = [...jobs.values()].filter((job) => isTerminalJobStatus(job.status)).sort((a, b) => a.updatedAt - b.updatedAt);
44
42
  for (const job of finished.slice(0, finished.length - retainFinished)) jobs.delete(job.id);
45
43
  };
46
44
  const owned = (spaceIds, jobId) => {
@@ -95,16 +93,35 @@ var createMemoryJobQueue = ({ retainFinished = 500, clock = Date.now } = {}) =>
95
93
  },
96
94
  heartbeat: ({ jobIds, workerId, leaseMs }) => {
97
95
  const at = now();
98
- const cancelled = [];
96
+ const stops = [];
99
97
  for (const id of jobIds) {
100
98
  const job = jobs.get(id);
101
99
  if (!job || job.workerId !== workerId || job.status !== "running") continue;
102
100
  job.leaseUntil = at + leaseMs;
103
- if (job.cancelRequested) cancelled.push(id);
101
+ if (job.cancelRequested) stops.push({
102
+ jobId: id,
103
+ stop: "cancel"
104
+ });
105
+ else if (job.pauseRequested) stops.push({
106
+ jobId: id,
107
+ stop: "pause"
108
+ });
104
109
  }
105
- return Promise.resolve(cancelled);
110
+ return Promise.resolve(stops);
111
+ },
112
+ write: ({ jobId, workerId, state, progress }) => {
113
+ const job = jobs.get(jobId);
114
+ if (!job || job.workerId !== workerId || job.status !== "running") return Promise.resolve(false);
115
+ const at = now();
116
+ if (state !== void 0) job.state = state;
117
+ if (progress) job.progress = {
118
+ ...progress,
119
+ at
120
+ };
121
+ job.updatedAt = at;
122
+ return Promise.resolve(true);
106
123
  },
107
- settle: ({ jobId, workerId, status, delayMs, runId, error, attempt }) => {
124
+ settle: ({ jobId, workerId, status, delayMs, runId, error, attempt, result, spentMs, refund = status === "pending" && !attempt }) => {
108
125
  const job = jobs.get(jobId);
109
126
  if (!job || job.workerId !== workerId) return Promise.resolve();
110
127
  const at = now();
@@ -113,16 +130,18 @@ var createMemoryJobQueue = ({ retainFinished = 500, clock = Date.now } = {}) =>
113
130
  startedAt: job.updatedAt,
114
131
  endedAt: at
115
132
  });
116
- job.status = status;
133
+ job.status = status === "pending" && job.cancelRequested ? "cancelled" : status === "pending" && job.pauseRequested ? "paused" : status;
117
134
  job.updatedAt = at;
118
135
  job.leaseUntil = void 0;
119
136
  job.error = error;
137
+ job.cancelRequested = void 0;
138
+ job.pauseRequested = void 0;
120
139
  if (runId) job.runId = runId;
121
- if (status === "pending") {
122
- job.runAt = at + (delayMs ?? 0);
123
- job.workerId = void 0;
124
- if (!attempt) job.attempts = Math.max(0, job.attempts - 1);
125
- }
140
+ if (result !== void 0) job.result = result;
141
+ if (spentMs) job.activeMs = (job.activeMs ?? 0) + spentMs;
142
+ if (refund) job.attempts = Math.max(0, job.attempts - 1);
143
+ if (job.status === "pending") job.runAt = at + (delayMs ?? 0);
144
+ if (job.status === "pending" || job.status === "paused") job.workerId = void 0;
126
145
  evict();
127
146
  return Promise.resolve();
128
147
  },
@@ -157,8 +176,8 @@ var createMemoryJobQueue = ({ retainFinished = 500, clock = Date.now } = {}) =>
157
176
  }
158
177
  return Promise.resolve();
159
178
  },
160
- listJobs: ({ spaceIds, actionId, status, limit, offset }) => {
161
- const matching = [...jobs.values()].filter((job) => spaceIds.includes(job.spaceId) && (actionId === void 0 || job.actionId === actionId) && (status === void 0 || job.status === status)).sort((a, b) => b.updatedAt - a.updatedAt);
179
+ listJobs: ({ spaceIds, name, status, kind, limit, offset }) => {
180
+ const matching = [...jobs.values()].filter((job) => spaceIds.includes(job.spaceId) && (name === void 0 || job.target.name === name) && (status === void 0 || job.status === status) && (kind === void 0 || job.target.kind === kind)).sort((a, b) => b.updatedAt - a.updatedAt);
162
181
  return Promise.resolve({
163
182
  jobs: matching.slice(offset, offset + limit).map((job) => ({ ...job })),
164
183
  total: matching.length
@@ -166,29 +185,54 @@ var createMemoryJobQueue = ({ retainFinished = 500, clock = Date.now } = {}) =>
166
185
  },
167
186
  getJob: (spaceIds, jobId) => Promise.resolve(owned(spaceIds, jobId)),
168
187
  listSchedules: (spaceIds) => Promise.resolve([...schedules.values()].filter((schedule) => spaceIds.includes(schedule.spaceId))),
169
- requeue: (spaceIds, jobId) => {
188
+ requeue: (spaceIds, jobId, { input, fresh = false } = {}) => {
170
189
  const job = owned(spaceIds, jobId);
171
- if (!job || !TERMINAL.has(job.status)) return Promise.resolve(false);
190
+ if (!job || !isTerminalJobStatus(job.status)) return Promise.resolve(false);
172
191
  job.status = "pending";
173
192
  job.runAt = now();
174
193
  job.attempts = 0;
175
194
  job.workerId = void 0;
176
195
  job.leaseUntil = void 0;
177
- job.cancelRequested = false;
196
+ job.cancelRequested = void 0;
197
+ job.pauseRequested = void 0;
178
198
  job.error = void 0;
199
+ job.result = void 0;
200
+ if (input) job.input = input;
201
+ if (fresh) {
202
+ job.state = void 0;
203
+ job.progress = void 0;
204
+ job.activeMs = void 0;
205
+ }
179
206
  job.updatedAt = now();
180
207
  return Promise.resolve(true);
181
208
  },
182
209
  cancel: (spaceIds, jobId) => {
183
210
  const job = owned(spaceIds, jobId);
184
- if (!job || TERMINAL.has(job.status)) return Promise.resolve(false);
185
- if (job.status === "pending") {
211
+ if (!job || isTerminalJobStatus(job.status)) return Promise.resolve(false);
212
+ if (job.status === "pending" || job.status === "paused") {
186
213
  job.status = "cancelled";
187
214
  job.workerId = void 0;
215
+ job.pauseRequested = void 0;
188
216
  } else job.cancelRequested = true;
189
217
  job.updatedAt = now();
190
218
  return Promise.resolve(true);
191
219
  },
220
+ pause: (spaceIds, jobId) => {
221
+ const job = owned(spaceIds, jobId);
222
+ if (job?.target.kind !== "function" || job.status !== "pending" && job.status !== "running" || job.pauseRequested) return Promise.resolve(false);
223
+ if (job.status === "pending") job.status = "paused";
224
+ else job.pauseRequested = true;
225
+ job.updatedAt = now();
226
+ return Promise.resolve(true);
227
+ },
228
+ resume: (spaceIds, jobId) => {
229
+ const job = owned(spaceIds, jobId);
230
+ if (job?.status !== "paused") return Promise.resolve(false);
231
+ job.status = "pending";
232
+ job.runAt = now();
233
+ job.updatedAt = now();
234
+ return Promise.resolve(true);
235
+ },
192
236
  cancelPending: ({ spaceId, key, olderThan }) => {
193
237
  const newest = olderThan === void 0 ? void 0 : jobs.get(olderThan);
194
238
  const isOlder = (job) => newest === void 0 || job.createdAt < newest.createdAt || job.createdAt === newest.createdAt && job.id < newest.id;
@@ -1,7 +1,7 @@
1
1
  import { ActionLookups } from '../types';
2
- import { ActionJobQueue, Environment } from '@plitzi/sdk-shared';
2
+ import { JobQueue, Environment } from '@plitzi/sdk-shared';
3
3
  export type SchedulerOptions = {
4
- queue: ActionJobQueue;
4
+ queue: JobQueue;
5
5
  lookups: ActionLookups;
6
6
  /** Which environment scheduled runs execute in. Defaults to `main`, the document the builder edits. */
7
7
  environment?: Environment;
@@ -37,9 +37,12 @@ var createScheduler = ({ queue, lookups, environment = "main", pollMs = 15e3, ba
37
37
  (await queue.enqueue({
38
38
  id,
39
39
  spaceId,
40
- actionId,
41
40
  environment: schedule.environment,
42
- trigger: "schedule",
41
+ target: {
42
+ kind: "action",
43
+ name: actionId,
44
+ trigger: "schedule"
45
+ },
43
46
  input: {},
44
47
  dueAt: fireAt,
45
48
  maxAttempts: schedule.maxAttempts
@@ -1,10 +1,13 @@
1
+ import { FunctionJobsService } from '../../functions/jobs';
1
2
  import { ActionsModule } from '../index';
2
3
  import { ActionLookups } from '../types';
3
- import { ActionJobQueue } from '@plitzi/sdk-shared';
4
+ import { JobQueue } from '@plitzi/sdk-shared';
4
5
  export type JobWorkerOptions = {
5
- queue: ActionJobQueue;
6
+ queue: JobQueue;
6
7
  lookups: ActionLookups;
7
8
  module: ActionsModule;
9
+ /** What runs a job of a space's functions (`function` on the job), slice by slice. Absent, such a job waits. */
10
+ functionJobs?: FunctionJobsService;
8
11
  /**
9
12
  * How many jobs this replica runs AT ONCE.
10
13
  *
@@ -61,4 +64,4 @@ export type JobWorker = {
61
64
  stop: () => Promise<void>;
62
65
  inFlight: () => number;
63
66
  };
64
- export declare const createJobWorker: ({ queue, lookups, module, workers, pollMs, leaseMs, backoff, workerId, onError: customOnError }: JobWorkerOptions) => JobWorker;
67
+ export declare const createJobWorker: ({ queue, lookups, module, functionJobs, workers, pollMs, leaseMs, backoff, workerId, onError: customOnError }: JobWorkerOptions) => JobWorker;
@@ -33,12 +33,14 @@ var GIVE_UP = /* @__PURE__ */ new Set([
33
33
  "forbidden",
34
34
  "recursion"
35
35
  ]);
36
- var createJobWorker = ({ queue, lookups, module, workers = 4, pollMs = 1e3, leaseMs = 3e4, backoff = {}, workerId = `${process.pid}-${randomUUID().slice(0, 8)}`, onError: customOnError }) => {
36
+ var createJobWorker = ({ queue, lookups, module, functionJobs, workers = 4, pollMs = 1e3, leaseMs = 3e4, backoff = {}, workerId = `${process.pid}-${randomUUID().slice(0, 8)}`, onError: customOnError }) => {
37
37
  const onError = customOnError ?? ((error) => serverLog.error("Actions", "job worker failed", error));
38
38
  const claimFailures = createFailureStreak("Actions", "job claim");
39
39
  const heartbeatFailures = createFailureStreak("Actions", "job heartbeat");
40
40
  const { baseMs = 3e4, maxMs = 9e5 } = backoff;
41
41
  const active = /* @__PURE__ */ new Map();
42
+ /** Of `active`, the jobs of a space's functions: what a stop asks to save and hand back, rather than waits for. */
43
+ const slicing = /* @__PURE__ */ new Set();
42
44
  /** Every job this worker started, until it has settled — what `stop()` waits for. */
43
45
  const inFlight = /* @__PURE__ */ new Set();
44
46
  let timer;
@@ -66,7 +68,7 @@ var createJobWorker = ({ queue, lookups, module, workers = 4, pollMs = 1e3, leas
66
68
  delayMs,
67
69
  error
68
70
  });
69
- const fail = (job, runId, error) => {
71
+ const fail = (job, runId, error, { spentMs, refused = false } = {}) => {
70
72
  const exhausted = job.attempts >= job.maxAttempts;
71
73
  return settle({
72
74
  jobId: job.id,
@@ -74,17 +76,108 @@ var createJobWorker = ({ queue, lookups, module, workers = 4, pollMs = 1e3, leas
74
76
  status: exhausted ? "dead" : "pending",
75
77
  ...exhausted ? {} : { delayMs: retryDelay(job.attempts) },
76
78
  ...runId ? { runId } : {},
79
+ ...spentMs ? { spentMs } : {},
77
80
  error,
78
81
  attempt: {
79
82
  status: "failed",
80
83
  workerId,
81
84
  ...runId ? { runId } : {},
82
- error
85
+ error,
86
+ ...refused ? { refused } : {}
83
87
  }
84
88
  });
85
89
  };
90
+ /**
91
+ * One slice of a job of a space's functions, settled by how it ended: done, set aside, cancelled, handed back to go on
92
+ * in the next slice — or failed, to be tried again from what it saved.
93
+ */
94
+ const executeSlice = async (job, jobs) => {
95
+ const controller = new AbortController();
96
+ active.set(job.id, controller);
97
+ slicing.add(job.id);
98
+ try {
99
+ await jobs.announce(job.spaceId, job.id);
100
+ const outcome = await jobs.slice(job, controller.signal, workerId);
101
+ const base = {
102
+ jobId: job.id,
103
+ workerId
104
+ };
105
+ switch (outcome.kind) {
106
+ case "wait":
107
+ await release(job, outcome.delayMs, outcome.why);
108
+ break;
109
+ case "done":
110
+ await settle({
111
+ ...base,
112
+ status: "succeeded",
113
+ result: outcome.result,
114
+ spentMs: outcome.spentMs,
115
+ attempt: {
116
+ status: "succeeded",
117
+ workerId
118
+ }
119
+ });
120
+ break;
121
+ case "failed":
122
+ if (outcome.final) await settle({
123
+ ...base,
124
+ status: "failed",
125
+ spentMs: outcome.spentMs,
126
+ error: outcome.error,
127
+ attempt: {
128
+ status: "failed",
129
+ workerId,
130
+ error: outcome.error,
131
+ ...outcome.refused ? { refused: true } : {}
132
+ }
133
+ });
134
+ else await fail(job, void 0, outcome.error, { spentMs: outcome.spentMs });
135
+ break;
136
+ case "stopped": if (outcome.stop === "pause") await settle({
137
+ ...base,
138
+ status: "paused",
139
+ refund: true,
140
+ spentMs: outcome.spentMs,
141
+ attempt: {
142
+ status: "paused",
143
+ workerId
144
+ }
145
+ });
146
+ else if (outcome.stop === "cancel") await settle({
147
+ ...base,
148
+ status: "cancelled",
149
+ spentMs: outcome.spentMs,
150
+ attempt: {
151
+ status: "cancelled",
152
+ workerId
153
+ }
154
+ });
155
+ else if (outcome.stop === "shutdown" || outcome.saved) await settle({
156
+ ...base,
157
+ status: "pending",
158
+ delayMs: 0,
159
+ refund: true,
160
+ spentMs: outcome.spentMs
161
+ });
162
+ else await fail(job, void 0, "its slice ran out of time without saving progress — job.save where it is, to go on in the next one", { spentMs: outcome.spentMs });
163
+ }
164
+ } catch (error) {
165
+ await fail(job, void 0, messageOf(error));
166
+ } finally {
167
+ active.delete(job.id);
168
+ slicing.delete(job.id);
169
+ await jobs.announce(job.spaceId, job.id);
170
+ }
171
+ };
86
172
  const execute = async (job) => {
87
- const entry = await lookups.getAction(job.spaceId, job.actionId);
173
+ const { target } = job;
174
+ if (target.kind === "function") {
175
+ if (functionJobs) await executeSlice(job, functionJobs);
176
+ else await release(job, retryDelay(1), "not started: this replica runs no jobs of the spaces’ functions");
177
+ return;
178
+ }
179
+ const { name: actionId, trigger } = target;
180
+ const entry = await lookups.getAction(job.spaceId, actionId);
88
181
  if (!entry) {
89
182
  await settle({
90
183
  jobId: job.id,
@@ -103,8 +196,8 @@ var createJobWorker = ({ queue, lookups, module, workers = 4, pollMs = 1e3, leas
103
196
  try {
104
197
  run = await module.guards.begin({
105
198
  spaceId: job.spaceId,
106
- actionId: job.actionId,
107
- callerId: job.trigger,
199
+ actionId,
200
+ callerId: trigger,
108
201
  input: job.input,
109
202
  idempotencyKey: job.id,
110
203
  sharedKey: true,
@@ -138,8 +231,8 @@ var createJobWorker = ({ queue, lookups, module, workers = 4, pollMs = 1e3, leas
138
231
  input: job.input,
139
232
  spaceId: job.spaceId,
140
233
  environment: job.environment,
141
- trigger: job.trigger,
142
- callerId: job.trigger,
234
+ trigger,
235
+ callerId: trigger,
143
236
  runId: run.runId,
144
237
  signal: run.controller.signal
145
238
  });
@@ -219,11 +312,11 @@ var createJobWorker = ({ queue, lookups, module, workers = 4, pollMs = 1e3, leas
219
312
  const beat = async () => {
220
313
  const held = [...active.keys()];
221
314
  if (held.length === 0) return;
222
- for (const jobId of await queue.heartbeat({
315
+ for (const { jobId, stop } of await queue.heartbeat({
223
316
  jobIds: held,
224
317
  workerId,
225
318
  leaseMs
226
- })) active.get(jobId)?.abort();
319
+ })) active.get(jobId)?.abort(stop);
227
320
  };
228
321
  /** One pass at a time, and the one under way is kept so `stop()` can wait for the claim it may be making. */
229
322
  const guarded = async () => {
@@ -250,6 +343,7 @@ var createJobWorker = ({ queue, lookups, module, workers = 4, pollMs = 1e3, leas
250
343
  timer = void 0;
251
344
  await pass;
252
345
  if (inFlight.size > 0) serverLog.info("Actions", `waiting for ${inFlight.size} running job(s) to finish before stopping`);
346
+ for (const jobId of slicing) active.get(jobId)?.abort("shutdown");
253
347
  /**
254
348
  * Drained rather than abandoned: a deploy finishes the jobs it started instead of leaving them to be retried.
255
349
  *
@@ -1,6 +1,7 @@
1
1
  import { TaskContextRequest } from './taskContext';
2
+ import { FunctionJobsService } from '../../functions/jobs';
2
3
  import { ActionRunRequest, ActionRunResult, ActionsConfig, ActionTaskContext, ActionTaskRegistry } from '../types';
3
- import { ActionJobQueue } from '@plitzi/sdk-shared';
4
+ import { JobQueue } from '@plitzi/sdk-shared';
4
5
  export type ActionRunner = {
5
6
  runAction: (request: ActionRunRequest) => Promise<ActionRunResult>;
6
7
  };
@@ -18,6 +19,8 @@ export type TaskContextSource = (request: TaskContextRequest, signal: AbortSigna
18
19
  */
19
20
  export declare const createActionRunner: (config: ActionsConfig, registryFor: (request: ActionRunRequest) => ActionTaskRegistry | Promise<ActionTaskRegistry>, baseFetch?: typeof fetch,
20
21
  /** The queue runs set for later go into, read when asked: it is made after the runner, and a server may run none. */
21
- jobsQueue?: () => ActionJobQueue | undefined) => ActionRunner & {
22
+ jobsQueue?: () => JobQueue | undefined,
23
+ /** The space's jobs, for a function's `ctx.jobs` — made beside the runner, and reading back its `taskContext`. */
24
+ functionJobs?: FunctionJobsService) => ActionRunner & {
22
25
  taskContext: TaskContextSource;
23
26
  };
@@ -222,7 +222,7 @@ var runNode = async (node, scope, registry, buildContext) => {
222
222
  * input contract — lives HERE rather than in a transport, because a deployment mounting its own trigger calls this
223
223
  * directly. A check in the endpoint would be a check a custom trigger silently skips.
224
224
  */
225
- var createActionRunner = (config, registryFor, baseFetch = fetch, jobsQueue = () => void 0) => {
225
+ var createActionRunner = (config, registryFor, baseFetch = fetch, jobsQueue = () => void 0, functionJobs) => {
226
226
  const kv = createKvStore(config.kv ?? createMemoryKv());
227
227
  const emailSender = createEmailSender({
228
228
  ...config.email,
@@ -270,7 +270,8 @@ var createActionRunner = (config, registryFor, baseFetch = fetch, jobsQueue = ()
270
270
  email: emailSender,
271
271
  redactor,
272
272
  signing,
273
- later
273
+ later,
274
+ ...functionJobs ? { jobs: functionJobs } : {}
274
275
  }, request, signal, runFetch);
275
276
  /** The request budget ran out: said on the server's log at once, and in the step that hit it. */
276
277
  let budgetSpent;
@@ -583,7 +584,8 @@ var createActionRunner = (config, registryFor, baseFetch = fetch, jobsQueue = ()
583
584
  email: emailSender,
584
585
  redactor: createRedactor(),
585
586
  signing,
586
- later
587
+ later,
588
+ ...functionJobs ? { jobs: functionJobs } : {}
587
589
  }, contextRequest, signal, createRunFetch(baseFetch, signal, resolveLimits(config.limits, void 0), lineage))({});
588
590
  return {
589
591
  runAction,
@@ -1,8 +1,10 @@
1
1
  import { createEmailSender } from './email';
2
2
  import { createRedactor } from './scope';
3
3
  import { createSigning } from './signing';
4
+ import { FunctionJobsService } from '../../functions/jobs';
4
5
  import { LaterDeps } from '../jobs/later';
5
6
  import { ActionKvStore, ActionRunRequest, ActionsConfig, ActionTaskContext, ResolvedActionLimits } from '../types';
7
+ import { RunUser } from '@plitzi/sdk-shared';
6
8
  /**
7
9
  * Counts outbound calls, refuses past the budget, caps what one answer may carry back, and stamps the run's
8
10
  * lineage on every one of them.
@@ -31,12 +33,19 @@ export type TaskContextDeps = {
31
33
  signing?: ReturnType<typeof createSigning>;
32
34
  /** What runs set for later go through: the module's queue, read when asked. */
33
35
  later: LaterDeps;
36
+ /** The space's jobs, for a function's `ctx.jobs`. */
37
+ jobs?: FunctionJobsService;
38
+ };
39
+ /**
40
+ * Who and what the context is for — a run's request, or anything shaped like one (a function's route, a job's slice,
41
+ * whose user is who started it and holds no session).
42
+ */
43
+ export type TaskContextRequest = Pick<ActionRunRequest, 'runId' | 'spaceId' | 'environment' | 'trigger' | 'callerId' | 'at' | 'emit' | 'origin'> & {
44
+ user?: RunUser;
34
45
  };
35
- /** Who and what the context is for — a run's request, or anything shaped like one (a function's route). */
36
- export type TaskContextRequest = Pick<ActionRunRequest, 'runId' | 'spaceId' | 'environment' | 'trigger' | 'user' | 'callerId' | 'at' | 'emit' | 'origin'>;
37
46
  /**
38
47
  * What a task runs with — the one place it is made, for a step of a run and for a function answering a route alike:
39
48
  * every secret it resolves registered with the redactor, the space's `kv` namespace, the run's outbound budget, the
40
49
  * space's channels. Everything but `log`, which is the STEP's: each step keeps what it logged.
41
50
  */
42
- export declare const taskContextFor: (config: ActionsConfig, { kv, email, redactor, signing, later }: TaskContextDeps, request: TaskContextRequest, signal: AbortSignal, runFetch: typeof fetch) => ((scope: Record<string, unknown>) => Omit<ActionTaskContext, "log">);
51
+ export declare const taskContextFor: (config: ActionsConfig, { kv, email, redactor, signing, later, jobs }: TaskContextDeps, request: TaskContextRequest, signal: AbortSignal, runFetch: typeof fetch) => ((scope: Record<string, unknown>) => Omit<ActionTaskContext, "log">);
@@ -67,7 +67,7 @@ var createRunFetch = (base, signal, limits, lineage, onBudgetSpent) => {
67
67
  * every secret it resolves registered with the redactor, the space's `kv` namespace, the run's outbound budget, the
68
68
  * space's channels. Everything but `log`, which is the STEP's: each step keeps what it logged.
69
69
  */
70
- var taskContextFor = (config, { kv, email, redactor, signing, later }, request, signal, runFetch) => {
70
+ var taskContextFor = (config, { kv, email, redactor, signing, later, jobs }, request, signal, runFetch) => {
71
71
  const { realtime } = config;
72
72
  const readData = projectDataReader(config.lookups.getData, request.spaceId, request.at);
73
73
  return (scope) => ({
@@ -118,6 +118,12 @@ var taskContextFor = (config, { kv, email, redactor, signing, later }, request,
118
118
  environment: request.environment,
119
119
  ...request.at ? { at: request.at } : {}
120
120
  }) : {},
121
+ ...jobs ? { jobs: (declared) => jobs.forRun({
122
+ spaceId: request.spaceId,
123
+ environment: request.environment,
124
+ ...request.at ? { at: request.at } : {},
125
+ ...request.user ? { user: request.user } : {}
126
+ }, declared) } : {},
121
127
  ...realtime ? {
122
128
  publish: (topic, type, data) => realtime.publish({
123
129
  spaceId: request.spaceId,
@@ -1,11 +1,12 @@
1
1
  import { LaterAnswer, LaterRequest } from './jobs/later';
2
2
  import { ActionEmailSender } from './runtime/email';
3
3
  import { FunctionsConfig } from '../functions/config';
4
+ import { FunctionJobs } from '../functions/contract';
4
5
  import { SpaceFunctions } from '../functions/protocol';
5
6
  import { KvChangeLifetime } from './runtime/kvChange';
6
7
  import { KvListEntry, KvListPut, KvListPutOptions, KvListRange } from './runtime/kvList';
7
8
  import { SpaceSigning } from './runtime/signing';
8
- import { ActionEmailConfig, ActionJobQueue, ActionEntry, ActionLimits, ActionRejectRecord, ActionRunRecord, ActionRunStatus, ActionRunStep, ActionTriggerType, ConnectorManifest, Environment, InteractionCallbackParam, InteractionNode, InteractionNodeStatus, Schema, SpaceRevision, SSRServerConfig, SSRUser } from '@plitzi/sdk-shared';
9
+ import { ActionEmailConfig, Job, JobQueue, ActionEntry, ActionLimits, ActionRejectRecord, ActionRunRecord, ActionRunStatus, ActionRunStep, ActionTriggerType, ConnectorManifest, Environment, FunctionJobManifest, FunctionJobView, InteractionCallbackParam, InteractionNode, InteractionNodeStatus, RunUser, Schema, SpaceRevision, SSRServerConfig, SSRUser } from '@plitzi/sdk-shared';
9
10
  /** Resolved secret material, as the connector engine already models it. */
10
11
  export type ActionCredential = Record<string, string>;
11
12
  /**
@@ -152,7 +153,8 @@ export type ActionTaskContext = {
152
153
  spaceId: number;
153
154
  environment: Environment;
154
155
  trigger: ActionTriggerType;
155
- user?: SSRUser;
156
+ /** Who is asking, as the session named them — or, for a job's slice, who started it. Never the session itself. */
157
+ user?: RunUser;
156
158
  /**
157
159
  * Who is asking, as the transport identified them: `user:<id>` for a session, `ip:<address>` for everyone else,
158
160
  * and `render` or `schedule` for the runs no visitor started.
@@ -204,6 +206,11 @@ export type ActionTaskContext = {
204
206
  later?: (request: LaterRequest) => Promise<LaterAnswer>;
205
207
  /** Drops the runs waiting under `key`, and answers how many. */
206
208
  cancelLater?: (key: string) => Promise<number>;
209
+ /**
210
+ * The space's jobs, for code over the jobs it declares (`functions/jobs.ts`) — `undefined` when the server runs no
211
+ * jobs. What a function's `ctx.jobs` goes through.
212
+ */
213
+ jobs?: (declared: Readonly<Record<string, FunctionJobManifest>>) => FunctionJobs;
207
214
  /** Signs with the space's own key (`ActionsConfig.signingSecret`) — `undefined` when the deployment gave none. */
208
215
  sign?: SpaceSigning['sign'];
209
216
  verify?: SpaceSigning['verify'];
@@ -236,6 +243,13 @@ export type ActionRealtime = {
236
243
  spaceId: number;
237
244
  environment: string;
238
245
  }, topic: string, grant?: string) => Promise<void>;
246
+ /** Says a job of the space's functions as it is now, on its own topic (`$job:<id>`), kept for a page that joins. */
247
+ publishJob?: (space: {
248
+ spaceId: number;
249
+ environment: string;
250
+ }, jobId: string, view: FunctionJobView) => Promise<void>;
251
+ /** Hands the realtime the way to a job, for the door of its topic: who started it, and who its `watch` lets in. */
252
+ watchJobs?: (lookup: (spaceId: number, jobId: string) => Promise<Job | undefined>) => void;
239
253
  };
240
254
  /**
241
255
  * One step a server action can take.
@@ -353,14 +367,14 @@ export type ActionsConfig = {
353
367
  *
354
368
  * Supplying nothing still schedules — over an in-process queue, which is correct for one replica and silently
355
369
  * wrong for two, since each gets its own copy of every schedule. A deployment with more than one supplies a
356
- * {@link ActionJobQueue} over a store they share.
370
+ * {@link JobQueue} over a store they share.
357
371
  */
358
372
  export type ActionJobsConfig = {
359
373
  /**
360
374
  * Where jobs and schedules live. Omitted → this process's memory: nothing survives a restart, and a second
361
375
  * replica produces the same fires all over again.
362
376
  */
363
- queue?: ActionJobQueue;
377
+ queue?: JobQueue;
364
378
  /**
365
379
  * How many jobs this replica runs at once. Default 4; `0` makes it a producer that never consumes.
366
380
  *