@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,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
@@ -1,13 +1,10 @@
1
1
  import { execute, selectOne, selectRows } from "../query.js";
2
2
  import { NOW_MS, ensureJobTables, jobTables } from "./schema.js";
3
3
  import { createStoreClock } from "../../actions/jobs/storeClock.js";
4
+ import { TERMINAL_JOB_STATUSES } from "@plitzi/sdk-shared/actions";
4
5
  //#region src/modules/mysql/jobs/jobQueue.ts
5
- var TERMINAL = [
6
- "succeeded",
7
- "failed",
8
- "dead",
9
- "cancelled"
10
- ];
6
+ /** Spread into a plain array: the queries take a mutable list. */
7
+ var TERMINAL = [...TERMINAL_JOB_STATUSES];
11
8
  var DAY_MS = 864e5;
12
9
  /** How often finished jobs past their retention are removed — at most once a minute per process, on a write. */
13
10
  var PURGE_EVERY_MS = 6e4;
@@ -21,9 +18,8 @@ var PURGE_EVERY_MS = 6e4;
21
18
  var toJob = (row) => ({
22
19
  id: row.id,
23
20
  spaceId: Number(row.space_id),
24
- actionId: row.action_id,
21
+ target: JSON.parse(row.target),
25
22
  environment: row.environment,
26
- trigger: row.trigger_type,
27
23
  input: JSON.parse(row.input),
28
24
  dueAt: Number(row.due_at),
29
25
  maxAttempts: Number(row.max_attempts),
@@ -39,8 +35,15 @@ var toJob = (row) => ({
39
35
  createdAt: Number(row.created_at),
40
36
  updatedAt: Number(row.updated_at),
41
37
  ...row.error === null ? {} : { error: row.error },
42
- history: JSON.parse(row.history)
38
+ history: JSON.parse(row.history),
39
+ ...row.state === null ? {} : { state: JSON.parse(row.state) },
40
+ ...row.progress === null ? {} : { progress: JSON.parse(row.progress) },
41
+ ...row.result === null ? {} : { result: JSON.parse(row.result) },
42
+ ...Number(row.pause_requested) === 1 ? { pauseRequested: true } : {},
43
+ ...Number(row.active_ms) > 0 ? { activeMs: Number(row.active_ms) } : {}
43
44
  });
45
+ /** A value of a JSON column, or SQL's NULL for none. */
46
+ var jsonOrNull = (value) => value === void 0 ? null : JSON.stringify(value);
44
47
  var toSchedule = (row) => ({
45
48
  spaceId: Number(row.space_id),
46
49
  actionId: row.action_id,
@@ -83,7 +86,7 @@ var transaction = async (pool, work) => {
83
86
  /** MySQL's code for a primary key that refused a second row with the same value. */
84
87
  var DUPLICATE_ENTRY = "ER_DUP_ENTRY";
85
88
  /**
86
- * An {@link ActionJobQueue} over tables in a MySQL database the deployment owns. Tested on MySQL 8; nothing in it
89
+ * An {@link JobQueue} over tables in a MySQL database the deployment owns. Tested on MySQL 8; nothing in it
87
90
  * needs more than 5.7.
88
91
  *
89
92
  * The helper for a deployment that already runs MySQL: it borrows connections from the pool it is handed, and creates
@@ -128,14 +131,15 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
128
131
  const conn = await db();
129
132
  const at = await clock.now();
130
133
  try {
131
- await execute(conn, `INSERT INTO ${t.jobs} (id, space_id, action_id, environment, trigger_type, input, due_at, max_attempts,
132
- missed, job_key, status, run_at, attempts, created_at, updated_at, history)
133
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, 0, ?, ?, '[]')`, [
134
+ await execute(conn, `INSERT INTO ${t.jobs} (id, space_id, target_kind, target_name, target, environment, input, due_at,
135
+ max_attempts, missed, job_key, status, run_at, attempts, created_at, updated_at, history)
136
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, 0, ?, ?, '[]')`, [
134
137
  job.id,
135
138
  job.spaceId,
136
- job.actionId,
139
+ job.target.kind,
140
+ job.target.name,
141
+ JSON.stringify(job.target),
137
142
  job.environment,
138
- job.trigger,
139
143
  JSON.stringify(job.input),
140
144
  job.dueAt,
141
145
  job.maxAttempts,
@@ -220,9 +224,32 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
220
224
  jobIds,
221
225
  workerId
222
226
  ]);
223
- return (await selectRows(conn, `SELECT id FROM ${t.jobs} WHERE id IN (?) AND worker_id = ? AND status = 'running' AND cancel_requested = 1`, [jobIds, workerId])).map((row) => row.id);
227
+ return (await selectRows(conn, `SELECT id, cancel_requested FROM ${t.jobs} WHERE id IN (?) AND worker_id = ? AND status = 'running'
228
+ AND (cancel_requested = 1 OR pause_requested = 1)`, [jobIds, workerId])).map((row) => ({
229
+ jobId: row.id,
230
+ stop: Number(row.cancel_requested) === 1 ? "cancel" : "pause"
231
+ }));
232
+ },
233
+ write: async ({ jobId, workerId, state, progress }) => {
234
+ const conn = await db();
235
+ const at = await clock.now();
236
+ const sets = [
237
+ "updated_at = ?",
238
+ ...state === void 0 ? [] : ["state = ?"],
239
+ ...progress ? ["progress = ?"] : []
240
+ ];
241
+ return (await execute(conn, `UPDATE ${t.jobs} SET ${sets.join(", ")} WHERE id = ? AND worker_id = ? AND status = 'running'`, [
242
+ at,
243
+ ...state === void 0 ? [] : [JSON.stringify(state)],
244
+ ...progress ? [JSON.stringify({
245
+ ...progress,
246
+ at
247
+ })] : [],
248
+ jobId,
249
+ workerId
250
+ ])).affectedRows === 1;
224
251
  },
225
- settle: async ({ jobId, workerId, status, delayMs, runId, error, attempt }) => {
252
+ settle: async ({ jobId, workerId, status, delayMs, runId, error, attempt, result, spentMs, refund = status === "pending" && !attempt }) => {
226
253
  await db();
227
254
  const at = await clock.now();
228
255
  await transaction(pool, async (connection) => {
@@ -235,19 +262,23 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
235
262
  startedAt: job.updatedAt,
236
263
  endedAt: at
237
264
  }] : job.history;
238
- const pending = status === "pending";
239
- const attempts = pending && !attempt ? Math.max(0, job.attempts - 1) : job.attempts;
265
+ const settled = status === "pending" && job.cancelRequested ? "cancelled" : status === "pending" && job.pauseRequested ? "paused" : status;
266
+ const attempts = refund ? Math.max(0, job.attempts - 1) : job.attempts;
267
+ const waiting = settled === "pending" || settled === "paused";
240
268
  await execute(connection, `UPDATE ${t.jobs} SET status = ?, updated_at = ?, lease_until = NULL, error = ?, run_id = COALESCE(?, run_id),
241
- run_at = ?, worker_id = ?, attempts = ?, history = ?, expires_at = ? WHERE id = ?`, [
242
- status,
269
+ run_at = ?, worker_id = ?, attempts = ?, history = ?, expires_at = ?, cancel_requested = 0,
270
+ pause_requested = 0, result = COALESCE(?, result), active_ms = active_ms + ? WHERE id = ?`, [
271
+ settled,
243
272
  at,
244
273
  error ?? null,
245
274
  runId ?? null,
246
- pending ? at + (delayMs ?? 0) : job.runAt,
247
- pending ? null : workerId,
275
+ settled === "pending" ? at + (delayMs ?? 0) : job.runAt,
276
+ waiting ? null : workerId,
248
277
  attempts,
249
278
  JSON.stringify(history),
250
- TERMINAL.includes(status) ? expiryOf(at) : null,
279
+ TERMINAL.includes(settled) ? expiryOf(at) : null,
280
+ jsonOrNull(result),
281
+ spentMs ?? 0,
251
282
  jobId
252
283
  ]);
253
284
  });
@@ -305,7 +336,7 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
305
336
  await execute(connection, kept.length > 0 ? `DELETE FROM ${t.schedules} WHERE space_id = ? AND action_id NOT IN (?)` : `DELETE FROM ${t.schedules} WHERE space_id = ?`, kept.length > 0 ? [spaceId, kept] : [spaceId]);
306
337
  });
307
338
  },
308
- listJobs: async ({ spaceIds, actionId, status, limit, offset }) => {
339
+ listJobs: async ({ spaceIds, name, status, kind, limit, offset }) => {
309
340
  if (!inSpaces(spaceIds)) return {
310
341
  jobs: [],
311
342
  total: 0
@@ -313,13 +344,15 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
313
344
  const conn = await db();
314
345
  const where = [
315
346
  "space_id IN (?)",
316
- ...actionId ? ["action_id = ?"] : [],
317
- ...status ? ["status = ?"] : []
347
+ ...name ? ["target_name = ?"] : [],
348
+ ...status ? ["status = ?"] : [],
349
+ ...kind ? ["target_kind = ?"] : []
318
350
  ].join(" AND ");
319
351
  const params = [
320
352
  spaceIds,
321
- ...actionId ? [actionId] : [],
322
- ...status ? [status] : []
353
+ ...name ? [name] : [],
354
+ ...status ? [status] : [],
355
+ ...kind ? [kind] : []
323
356
  ];
324
357
  const [rows, count] = await Promise.all([selectRows(conn, `SELECT * FROM ${t.jobs} WHERE ${where} ORDER BY updated_at DESC, id DESC LIMIT ? OFFSET ?`, [
325
358
  ...params,
@@ -340,15 +373,17 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
340
373
  if (!inSpaces(spaceIds)) return [];
341
374
  return (await selectRows(await db(), `SELECT * FROM ${t.schedules} WHERE space_id IN (?) ORDER BY next_run_at`, [spaceIds])).map(toSchedule);
342
375
  },
343
- requeue: async (spaceIds, jobId) => {
376
+ requeue: async (spaceIds, jobId, { input, fresh = false } = {}) => {
344
377
  if (!inSpaces(spaceIds)) return false;
345
378
  const conn = await db();
346
379
  const at = await clock.now();
347
380
  return (await execute(conn, `UPDATE ${t.jobs} SET status = 'pending', run_at = ?, attempts = 0, updated_at = ?, cancel_requested = 0,
348
- worker_id = NULL, lease_until = NULL, error = NULL, expires_at = NULL
381
+ pause_requested = 0, worker_id = NULL, lease_until = NULL, error = NULL, expires_at = NULL, result = NULL
382
+ ${input ? ", input = ?" : ""}${fresh ? ", state = NULL, progress = NULL, active_ms = 0" : ""}
349
383
  WHERE id = ? AND space_id IN (?) AND status IN (?)`, [
350
384
  at,
351
385
  at,
386
+ ...input ? [JSON.stringify(input)] : [],
352
387
  jobId,
353
388
  spaceIds,
354
389
  TERMINAL
@@ -358,8 +393,8 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
358
393
  if (!inSpaces(spaceIds)) return false;
359
394
  const conn = await db();
360
395
  const at = await clock.now();
361
- if ((await execute(conn, `UPDATE ${t.jobs} SET status = 'cancelled', updated_at = ?, expires_at = ?, worker_id = NULL
362
- WHERE id = ? AND space_id IN (?) AND status = 'pending'`, [
396
+ if ((await execute(conn, `UPDATE ${t.jobs} SET status = 'cancelled', updated_at = ?, expires_at = ?, worker_id = NULL, pause_requested = 0
397
+ WHERE id = ? AND space_id IN (?) AND status IN ('pending', 'paused')`, [
363
398
  at,
364
399
  expiryOf(at),
365
400
  jobId,
@@ -371,6 +406,35 @@ var createMysqlJobQueue = ({ pool, tablePrefix = "", createTables = true, retent
371
406
  spaceIds
372
407
  ])).affectedRows === 1;
373
408
  },
409
+ pause: async (spaceIds, jobId) => {
410
+ if (!inSpaces(spaceIds)) return false;
411
+ const conn = await db();
412
+ const at = await clock.now();
413
+ if ((await execute(conn, `UPDATE ${t.jobs} SET status = 'paused', updated_at = ?
414
+ WHERE id = ? AND space_id IN (?) AND target_kind = 'function' AND status = 'pending'`, [
415
+ at,
416
+ jobId,
417
+ spaceIds
418
+ ])).affectedRows === 1) return true;
419
+ return (await execute(conn, `UPDATE ${t.jobs} SET pause_requested = 1, updated_at = ?
420
+ WHERE id = ? AND space_id IN (?) AND target_kind = 'function' AND status = 'running' AND pause_requested = 0`, [
421
+ at,
422
+ jobId,
423
+ spaceIds
424
+ ])).affectedRows === 1;
425
+ },
426
+ resume: async (spaceIds, jobId) => {
427
+ if (!inSpaces(spaceIds)) return false;
428
+ const conn = await db();
429
+ const at = await clock.now();
430
+ return (await execute(conn, `UPDATE ${t.jobs} SET status = 'pending', run_at = ?, updated_at = ?
431
+ WHERE id = ? AND space_id IN (?) AND status = 'paused'`, [
432
+ at,
433
+ at,
434
+ jobId,
435
+ spaceIds
436
+ ])).affectedRows === 1;
437
+ },
374
438
  cancelPending: async ({ spaceId, key, olderThan }) => {
375
439
  const conn = await db();
376
440
  const newest = olderThan === void 0 ? void 0 : await selectOne(conn, `SELECT id, created_at FROM ${t.jobs} WHERE id = ?`, [olderThan]);
@@ -31,9 +31,10 @@ var mysqlJobSchemaStatements = (prefix = "") => {
31
31
  `CREATE TABLE IF NOT EXISTS ${t.jobs} (
32
32
  id VARCHAR(191) NOT NULL,
33
33
  space_id BIGINT NOT NULL,
34
- action_id VARCHAR(191) NOT NULL,
34
+ target_kind VARCHAR(16) NOT NULL,
35
+ target_name VARCHAR(191) NOT NULL,
36
+ target MEDIUMTEXT NOT NULL,
35
37
  environment VARCHAR(64) NOT NULL,
36
- trigger_type VARCHAR(64) NOT NULL,
37
38
  input MEDIUMTEXT NOT NULL,
38
39
  due_at BIGINT NOT NULL,
39
40
  max_attempts INT NOT NULL,
@@ -51,10 +52,16 @@ var mysqlJobSchemaStatements = (prefix = "") => {
51
52
  error TEXT NULL,
52
53
  history MEDIUMTEXT NOT NULL,
53
54
  expires_at BIGINT NULL,
55
+ state MEDIUMTEXT NULL,
56
+ progress TEXT NULL,
57
+ result MEDIUMTEXT NULL,
58
+ pause_requested TINYINT(1) NOT NULL DEFAULT 0,
59
+ active_ms BIGINT NOT NULL DEFAULT 0,
54
60
  PRIMARY KEY (id),
55
61
  KEY action_jobs_pending (status, run_at),
56
62
  KEY action_jobs_lease (status, lease_until),
57
63
  KEY action_jobs_space (space_id, updated_at),
64
+ KEY action_jobs_target (space_id, target_name, updated_at),
58
65
  KEY action_jobs_key (space_id, job_key, status),
59
66
  KEY action_jobs_expires (expires_at)
60
67
  ) ${CHARSET}`,
@@ -88,17 +95,37 @@ var columnsOf = async (db, table) => {
88
95
  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?`, [table]);
89
96
  return new Map(columns.map((column) => [column.name, column.type.toLowerCase()]));
90
97
  };
91
- var UPGRADES = [{
92
- needed: async (db, prefix) => {
93
- const columns = await columnsOf(db, `${prefix}action_kv`);
94
- return columns.get("k") !== "varbinary" || columns.get("v") !== "mediumtext";
98
+ var UPGRADES = [
99
+ {
100
+ needed: async (db, prefix) => {
101
+ const columns = await columnsOf(db, `${prefix}action_kv`);
102
+ return columns.get("k") !== "varbinary" || columns.get("v") !== "mediumtext";
103
+ },
104
+ statements: (prefix) => [`ALTER TABLE ${jobTables(prefix).kv} MODIFY k VARBINARY(764) NOT NULL, MODIFY v MEDIUMTEXT NOT NULL`]
95
105
  },
96
- statements: (prefix) => [`ALTER TABLE ${jobTables(prefix).kv} MODIFY k VARBINARY(764) NOT NULL, MODIFY v MEDIUMTEXT NOT NULL`]
97
- }, {
98
- needed: async (db, prefix) => !(await columnsOf(db, `${prefix}action_jobs`)).has("job_key"),
99
- statements: (prefix) => [`ALTER TABLE ${jobTables(prefix).jobs} ADD COLUMN job_key VARCHAR(191) NULL AFTER missed,
106
+ {
107
+ needed: async (db, prefix) => !(await columnsOf(db, `${prefix}action_jobs`)).has("job_key"),
108
+ statements: (prefix) => [`ALTER TABLE ${jobTables(prefix).jobs} ADD COLUMN job_key VARCHAR(191) NULL AFTER missed,
100
109
  ADD KEY action_jobs_key (space_id, job_key, status)`]
101
- }];
110
+ },
111
+ {
112
+ needed: async (db, prefix) => !(await columnsOf(db, `${prefix}action_jobs`)).has("target_kind"),
113
+ statements: (prefix) => {
114
+ const { jobs } = jobTables(prefix);
115
+ return [
116
+ `ALTER TABLE ${jobs} ADD COLUMN target_kind VARCHAR(16) NULL AFTER space_id,
117
+ ADD COLUMN target_name VARCHAR(191) NULL AFTER target_kind, ADD COLUMN target MEDIUMTEXT NULL AFTER target_name,
118
+ ADD COLUMN state MEDIUMTEXT NULL, ADD COLUMN progress TEXT NULL, ADD COLUMN result MEDIUMTEXT NULL,
119
+ ADD COLUMN pause_requested TINYINT(1) NOT NULL DEFAULT 0, ADD COLUMN active_ms BIGINT NOT NULL DEFAULT 0`,
120
+ `UPDATE ${jobs} SET target_kind = 'action', target_name = action_id,
121
+ target = JSON_OBJECT('kind', 'action', 'name', action_id, 'trigger', trigger_type)`,
122
+ `ALTER TABLE ${jobs} MODIFY target_kind VARCHAR(16) NOT NULL, MODIFY target_name VARCHAR(191) NOT NULL,
123
+ MODIFY target MEDIUMTEXT NOT NULL, DROP COLUMN action_id, DROP COLUMN trigger_type,
124
+ ADD KEY action_jobs_target (space_id, target_name, updated_at)`
125
+ ];
126
+ }
127
+ }
128
+ ];
102
129
  /**
103
130
  * What brings tables made before the columns above up to them — for a deployment that runs its own migrations: each
104
131
  * statement once, the ones its tables still lack. `ensureJobTables` does it by itself, and only where a table needs
@@ -1,6 +1,7 @@
1
1
  import { ChannelResolver } from './declarations';
2
2
  import { RealtimeGrants } from './grants';
3
3
  import { RealtimeConnection, RealtimeHub, RealtimeSpace } from './hub';
4
+ import { JobLookup } from './jobs';
4
5
  import { RawResponse } from '../../helpers/buildResponseHelpers';
5
6
  import { ChannelDeclaration, RealtimeSender, SSRRequest, SSRResponseHelpers } from '@plitzi/sdk-shared';
6
7
  export type RealtimeRefusal = {
@@ -36,7 +37,7 @@ export type Admission = {
36
37
  * declares and against the visitor's access. One that fails is reported, not a reason to refuse the rest; all failing
37
38
  * is a `403`.
38
39
  */
39
- export declare const admit: (req: SSRRequest, resolveChannels: ChannelResolver, grants: RealtimeGrants) => Promise<Admission>;
40
+ export declare const admit: (req: SSRRequest, resolveChannels: ChannelResolver, grants: RealtimeGrants, jobs?: JobLookup) => Promise<Admission>;
40
41
  /** A new connection for what was admitted, speaking through `send`. */
41
42
  export declare const connectionFor: (admission: Extract<Admission, {
42
43
  ok: true;
@@ -60,6 +61,8 @@ export type SubscribeDeps = {
60
61
  hub: RealtimeHub;
61
62
  resolveChannels: ChannelResolver;
62
63
  grants: RealtimeGrants;
64
+ /** The way to the jobs `$job:<id>` is about — absent where the server runs none. */
65
+ jobs?: JobLookup;
63
66
  };
64
67
  /**
65
68
  * `GET /_realtime?topics=a,b` (and `&grants=g1,g2` for the topics of a `grant: true` channel) — one Server-Sent Events connection for every topic a page listens to.
@@ -67,7 +70,7 @@ export type SubscribeDeps = {
67
70
  * The first event, `ready`, tells the page its public name (`from`) and the secret its publishes carry. Resolves when
68
71
  * the page goes.
69
72
  */
70
- export declare const handleRealtimeSubscribe: ({ req, res, raw, signal, hub, resolveChannels, grants }: SubscribeDeps) => Promise<void>;
73
+ export declare const handleRealtimeSubscribe: ({ req, res, raw, signal, hub, resolveChannels, grants, jobs }: SubscribeDeps) => Promise<void>;
71
74
  export type PublishDeps = {
72
75
  req: SSRRequest;
73
76
  res: SSRResponseHelpers;