@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.
- package/CHANGELOG.md +141 -0
- package/README.md +2 -2
- package/dist/actions.d.ts +6 -0
- package/dist/actions.js +2 -1
- package/dist/core/auth/createAuth.d.ts +1 -1
- package/dist/core/auth/tokens.d.ts +1 -1
- package/dist/core/configSeam.js +12 -2
- package/dist/core/services/functionRoutes.js +7 -2
- package/dist/core/services/realtime.js +5 -2
- package/dist/functions-api.d.ts +176 -3
- package/dist/functions.d.ts +3 -1
- package/dist/functions.js +2 -1
- package/dist/helpers/serverLog.d.ts +1 -1
- package/dist/helpers/serverLog.js +1 -1
- package/dist/hosts/project/plugins.js +20 -3
- package/dist/hosts/project/serveProject.js +16 -1
- package/dist/modules/actions/index.js +17 -4
- package/dist/modules/actions/jobs/index.d.ts +4 -3
- package/dist/modules/actions/jobs/index.js +2 -1
- package/dist/modules/actions/jobs/later.d.ts +2 -2
- package/dist/modules/actions/jobs/later.js +5 -2
- package/dist/modules/actions/jobs/memoryQueue.d.ts +4 -4
- package/dist/modules/actions/jobs/memoryQueue.js +69 -25
- package/dist/modules/actions/jobs/scheduler.d.ts +2 -2
- package/dist/modules/actions/jobs/scheduler.js +5 -2
- package/dist/modules/actions/jobs/worker.d.ts +6 -3
- package/dist/modules/actions/jobs/worker.js +104 -10
- package/dist/modules/actions/runtime/errors.d.ts +9 -1
- package/dist/modules/actions/runtime/errors.js +12 -2
- package/dist/modules/actions/runtime/runAction.d.ts +5 -2
- package/dist/modules/actions/runtime/runAction.js +5 -3
- package/dist/modules/actions/runtime/taskContext.d.ts +12 -3
- package/dist/modules/actions/runtime/taskContext.js +9 -1
- package/dist/modules/actions/types.d.ts +22 -6
- package/dist/modules/functions/capabilities.js +124 -13
- package/dist/modules/functions/config.d.ts +20 -0
- package/dist/modules/functions/context.d.ts +2 -2
- package/dist/modules/functions/context.js +16 -3
- package/dist/modules/functions/contract.d.ts +97 -3
- package/dist/modules/functions/driver.js +136 -9
- package/dist/modules/functions/jobControl.d.ts +21 -0
- package/dist/modules/functions/jobControl.js +43 -0
- package/dist/modules/functions/jobs.d.ts +98 -0
- package/dist/modules/functions/jobs.js +438 -0
- package/dist/modules/functions/manifest.d.ts +2 -0
- package/dist/modules/functions/manifest.js +37 -4
- package/dist/modules/functions/native.js +2 -1
- package/dist/modules/functions/oauth.d.ts +3 -2
- package/dist/modules/functions/oauth.js +53 -19
- package/dist/modules/functions/protocol.d.ts +98 -7
- package/dist/modules/functions/protocol.js +15 -1
- package/dist/modules/functions/routes.d.ts +9 -1
- package/dist/modules/functions/routes.js +50 -25
- package/dist/modules/functions/runner/messages.d.ts +0 -1
- package/dist/modules/functions/runner/messages.js +46 -5
- package/dist/modules/functions/runner/remote.js +60 -8
- package/dist/modules/functions/runner/service.js +54 -8
- package/dist/modules/functions/sandbox/guest.js +5 -3
- package/dist/modules/functions/sandbox/isolate.js +7 -8
- package/dist/modules/functions/space.js +4 -4
- package/dist/modules/mongo/jobQueue.d.ts +3 -3
- package/dist/modules/mongo/jobQueue.js +137 -26
- package/dist/modules/mysql/jobs/jobQueue.d.ts +3 -3
- package/dist/modules/mysql/jobs/jobQueue.js +97 -33
- package/dist/modules/mysql/jobs/schema.js +38 -11
- package/dist/modules/realtime/handlers.d.ts +5 -2
- package/dist/modules/realtime/handlers.js +15 -4
- package/dist/modules/realtime/index.d.ts +11 -1
- package/dist/modules/realtime/index.js +8 -1
- package/dist/modules/realtime/jobs.d.ts +20 -0
- package/dist/modules/realtime/jobs.js +41 -0
- package/dist/modules/realtime/retained.d.ts +3 -2
- package/dist/modules/realtime/retained.js +2 -2
- package/dist/modules/realtime/socket.d.ts +4 -1
- package/dist/modules/realtime/socket.js +2 -2
- package/dist/modules/rsc/resolveRscData.js +2 -1
- package/dist/modules/runtime/host.js +1 -1
- package/dist/modules/runtime/runner.d.ts +1 -1
- package/dist/modules/runtime/runner.js +12 -2
- package/dist/modules/runtime/stages.js +1 -1
- package/dist/modules/ssr/applySSRResult.d.ts +5 -0
- package/dist/modules/ssr/applySSRResult.js +8 -1
- package/dist/modules/ssr/buildBody.js +2 -1
- package/dist/modules/ssr/prepareRender.d.ts +3 -0
- package/dist/modules/ssr/prepareRender.js +17 -5
- package/dist/modules/ssr/spaceDocument.d.ts +2 -1
- package/dist/modules/ssr/spaceDocument.js +14 -5
- package/dist/modules/ssr/streamBody.js +2 -1
- package/package.json +3 -3
- package/skills/plitzi-authoring/reference/auth.md +6 -0
- package/skills/plitzi-authoring/reference/authoring-errors.md +1 -0
- package/skills/plitzi-authoring/reference/plugin-reach.md +3 -0
- package/skills/plitzi-authoring/reference/realtime.md +4 -0
- package/dist/adapters/cloudAdapters.test.d.ts +0 -1
- package/dist/adapters/jsonAdapters.test.d.ts +0 -1
- package/dist/adapters/space/space.test.d.ts +0 -1
- package/dist/core/auth/api.test.d.ts +0 -1
- package/dist/core/auth/authorize.test.d.ts +0 -1
- package/dist/core/auth/createAuth.test.d.ts +0 -1
- package/dist/core/auth/csrf.test.d.ts +0 -1
- package/dist/core/auth/domains.test.d.ts +0 -1
- package/dist/core/auth/identity.test.d.ts +0 -1
- package/dist/core/auth/lifecycle.test.d.ts +0 -1
- package/dist/core/auth/oauth/oauth.test.d.ts +0 -1
- package/dist/core/auth/redirects.test.d.ts +0 -1
- package/dist/core/auth/routes.test.d.ts +0 -1
- package/dist/core/auth/session.test.d.ts +0 -1
- package/dist/core/auth/spaceTokens.test.d.ts +0 -1
- package/dist/core/auth/throttle.test.d.ts +0 -1
- package/dist/core/auth/tokens.test.d.ts +0 -1
- package/dist/core/auth/totp.test.d.ts +0 -1
- package/dist/core/configSeam.test.d.ts +0 -1
- package/dist/core/createServer.actions.test.d.ts +0 -1
- package/dist/core/createServer.functions.test.d.ts +0 -1
- package/dist/core/createServer.livePages.test.d.ts +0 -1
- package/dist/core/createServer.notFound.test.d.ts +0 -1
- package/dist/core/createServer.oauth.test.d.ts +0 -1
- package/dist/core/createServer.publicData.test.d.ts +0 -1
- package/dist/core/createServer.test.d.ts +0 -1
- package/dist/core/fontStore.test.d.ts +0 -1
- package/dist/core/freePort.test.d.ts +0 -1
- package/dist/core/handlers/csrfMiddleware.test.d.ts +0 -1
- package/dist/core/handlers/handlers.test.d.ts +0 -1
- package/dist/core/handlers/socialRouteHandlers.test.d.ts +0 -1
- package/dist/core/http/dispatcher.test.d.ts +0 -1
- package/dist/core/http/stages/crossSiteWrites.test.d.ts +0 -1
- package/dist/core/http/stages/exchangeRoute.test.d.ts +0 -1
- package/dist/core/http/stages/images.test.d.ts +0 -1
- package/dist/core/http/stages/middlewares.test.d.ts +0 -1
- package/dist/core/http/stages/sessionRenewal.test.d.ts +0 -1
- package/dist/core/http/stages/signInRoute.test.d.ts +0 -1
- package/dist/core/oauth/authorize.test.d.ts +0 -1
- package/dist/core/oauth/register.test.d.ts +0 -1
- package/dist/core/oauth/token.test.d.ts +0 -1
- package/dist/core/requestParser.test.d.ts +0 -1
- package/dist/core/server/baseServer.test.d.ts +0 -1
- package/dist/core/server/closeOnSignals.test.d.ts +0 -1
- package/dist/core/server/drain.test.d.ts +0 -1
- package/dist/core/server/fleet/channel.test.d.ts +0 -1
- package/dist/core/server/fleet/fixtures/fleetServer.d.ts +0 -1
- package/dist/core/server/fleet/fleet.integration.test.d.ts +0 -1
- package/dist/core/server/fleet/relay.test.d.ts +0 -1
- package/dist/core/server/fleet/role.test.d.ts +0 -1
- package/dist/core/server/fleet/supervisor.test.d.ts +0 -1
- package/dist/core/services/resolve.test.d.ts +0 -1
- package/dist/core/staticFiles.test.d.ts +0 -1
- package/dist/env.test.d.ts +0 -1
- package/dist/helpers/atomicFile.test.d.ts +0 -1
- package/dist/helpers/buildResponseHelpers.test.d.ts +0 -1
- package/dist/helpers/buildServerInfo.test.d.ts +0 -1
- package/dist/helpers/cache/CompressedFileCache.test.d.ts +0 -1
- package/dist/helpers/cache/cacheManager.test.d.ts +0 -1
- package/dist/helpers/cache/keys.test.d.ts +0 -1
- package/dist/helpers/compress.test.d.ts +0 -1
- package/dist/helpers/hydrationPayload.test.d.ts +0 -1
- package/dist/helpers/offlineDataLoader.test.d.ts +0 -1
- package/dist/helpers/onAbort.test.d.ts +0 -1
- package/dist/helpers/outboundGuard.test.d.ts +0 -1
- package/dist/helpers/reportReactBuild.test.d.ts +0 -1
- package/dist/helpers/resolveDebugMode.test.d.ts +0 -1
- package/dist/helpers/serverLog.test.d.ts +0 -1
- package/dist/hosts/authoringHost/index.test.d.ts +0 -1
- package/dist/hosts/project/serveProject.test.d.ts +0 -1
- package/dist/layers.test.d.ts +0 -1
- package/dist/middlewares/spaceDeployment.test.d.ts +0 -1
- package/dist/modules/actions/connectorWrite.test.d.ts +0 -1
- package/dist/modules/actions/jobs/failureStreak.test.d.ts +0 -1
- package/dist/modules/actions/jobs/later.test.d.ts +0 -1
- package/dist/modules/actions/jobs/memoryStores.test.d.ts +0 -1
- package/dist/modules/actions/jobs/scheduler.test.d.ts +0 -1
- package/dist/modules/actions/jobs/testing/jobQueueContract.d.ts +0 -25
- package/dist/modules/actions/jobs/worker.test.d.ts +0 -1
- package/dist/modules/actions/moduleFor.test.d.ts +0 -1
- package/dist/modules/actions/runtime/check.test.d.ts +0 -1
- package/dist/modules/actions/runtime/credentials.test.d.ts +0 -1
- package/dist/modules/actions/runtime/email.test.d.ts +0 -1
- package/dist/modules/actions/runtime/fileKv.test.d.ts +0 -1
- package/dist/modules/actions/runtime/flags.test.d.ts +0 -1
- package/dist/modules/actions/runtime/guards.test.d.ts +0 -1
- package/dist/modules/actions/runtime/kvStore.test.d.ts +0 -1
- package/dist/modules/actions/runtime/namespaceKv.test.d.ts +0 -1
- package/dist/modules/actions/runtime/redisKv.integration.test.d.ts +0 -1
- package/dist/modules/actions/runtime/renderResolver.test.d.ts +0 -1
- package/dist/modules/actions/runtime/renderShare.test.d.ts +0 -1
- package/dist/modules/actions/runtime/runAction.test.d.ts +0 -1
- package/dist/modules/actions/runtime/runLogger.test.d.ts +0 -1
- package/dist/modules/actions/runtime/signing.test.d.ts +0 -1
- package/dist/modules/actions/taskCatalog.test.d.ts +0 -1
- package/dist/modules/actions/tasks/db.test.d.ts +0 -1
- package/dist/modules/actions/tasks/email.test.d.ts +0 -1
- package/dist/modules/actions/tasks/http.test.d.ts +0 -1
- package/dist/modules/actions/tasks/kv.test.d.ts +0 -1
- package/dist/modules/actions/transport/callHandler.test.d.ts +0 -1
- package/dist/modules/actions/transport/webhookHandler.test.d.ts +0 -1
- package/dist/modules/connectors/engine.test.d.ts +0 -1
- package/dist/modules/connectors/projection.test.d.ts +0 -1
- package/dist/modules/connectors/resolver.test.d.ts +0 -1
- package/dist/modules/functions/build.test.d.ts +0 -1
- package/dist/modules/functions/load.test.d.ts +0 -1
- package/dist/modules/functions/local.test.d.ts +0 -1
- package/dist/modules/functions/manifest.test.d.ts +0 -1
- package/dist/modules/functions/native.test.d.ts +0 -1
- package/dist/modules/functions/oauth.test.d.ts +0 -1
- package/dist/modules/functions/plugins.test.d.ts +0 -1
- package/dist/modules/functions/routes.test.d.ts +0 -1
- package/dist/modules/functions/runner/remote.test.d.ts +0 -1
- package/dist/modules/functions/sandbox/isolate.test.d.ts +0 -1
- package/dist/modules/functions/testing/tasksOf.d.ts +0 -4
- package/dist/modules/images/imageProxy.test.d.ts +0 -1
- package/dist/modules/images/transform.test.d.ts +0 -1
- package/dist/modules/mongo/stores.integration.test.d.ts +0 -1
- package/dist/modules/mysql/accounts.test.d.ts +0 -1
- package/dist/modules/mysql/jobs/stores.integration.test.d.ts +0 -1
- package/dist/modules/mysql/schema.test.d.ts +0 -1
- package/dist/modules/mysql/store.integration.test.d.ts +0 -1
- package/dist/modules/realtime/realtime.test.d.ts +0 -1
- package/dist/modules/realtime/redisPubSub.test.d.ts +0 -1
- package/dist/modules/realtime/retained.test.d.ts +0 -1
- package/dist/modules/realtime/socket.test.d.ts +0 -1
- package/dist/modules/rsc/connectorRscData.test.d.ts +0 -1
- package/dist/modules/rsc/handler.test.d.ts +0 -1
- package/dist/modules/rsc/publicFileResolver.test.d.ts +0 -1
- package/dist/modules/rsc/resolveRscData.test.d.ts +0 -1
- package/dist/modules/runtime/elsewhere.test.d.ts +0 -1
- package/dist/modules/runtime/entry.test.d.ts +0 -1
- package/dist/modules/runtime/inside.test.d.ts +0 -1
- package/dist/modules/runtime/ownServer.test.d.ts +0 -1
- package/dist/modules/runtime/runtime.test.d.ts +0 -1
- package/dist/modules/sqlite/kv.test.d.ts +0 -1
- package/dist/modules/ssr/draftSession.test.d.ts +0 -1
- package/dist/modules/ssr/loadPluginComponents.test.d.ts +0 -1
- package/dist/modules/ssr/metering.test.d.ts +0 -1
- package/dist/modules/ssr/prepareRender.test.d.ts +0 -1
- package/dist/modules/ssr/redirect.test.d.ts +0 -1
- package/dist/modules/ssr/registerExternalPlugins.test.d.ts +0 -1
- package/dist/modules/ssr/reportMissingPlugins.test.d.ts +0 -1
- package/dist/modules/ssr/resolvePageSeo.test.d.ts +0 -1
- package/dist/modules/ssr/spaceDocument.test.d.ts +0 -1
- package/dist/modules/ssr/template.test.d.ts +0 -1
- package/dist/modules/ssr/testing/offlineData.d.ts +0 -5
- package/dist/modules/ssr/vendor.test.d.ts +0 -1
- package/dist/plugins/compile.test.d.ts +0 -1
- package/dist/plugins/copy.test.d.ts +0 -1
- package/dist/plugins/manager.test.d.ts +0 -1
- package/dist/plugins/validate.test.d.ts +0 -1
|
@@ -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
|
-
|
|
6
|
-
|
|
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
|
-
|
|
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
|
|
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,
|
|
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.
|
|
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'
|
|
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
|
|
239
|
-
const 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 =
|
|
242
|
-
|
|
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
|
-
|
|
275
|
+
settled === "pending" ? at + (delayMs ?? 0) : job.runAt,
|
|
276
|
+
waiting ? null : workerId,
|
|
248
277
|
attempts,
|
|
249
278
|
JSON.stringify(history),
|
|
250
|
-
TERMINAL.includes(
|
|
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,
|
|
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
|
-
...
|
|
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
|
-
...
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
93
|
-
|
|
94
|
-
|
|
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
|
-
|
|
97
|
-
|
|
98
|
-
|
|
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;
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import onAbort from "../../helpers/onAbort.js";
|
|
2
2
|
import { openEventStream } from "../../core/http/sse.js";
|
|
3
3
|
import { warnRealtime } from "./failure.js";
|
|
4
|
+
import { JOB_CHANNEL, jobRefusal } from "./jobs.js";
|
|
4
5
|
import { readCookies } from "../../core/auth/credentials.js";
|
|
5
6
|
import { accessRefusal } from "@plitzi/sdk-shared/actions";
|
|
6
7
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
7
|
-
import { OBSERVER_COOKIE_NAME, PRESENCE_TYPE, channelLimits, matchChannel } from "@plitzi/sdk-shared/realtime";
|
|
8
|
+
import { OBSERVER_COOKIE_NAME, PRESENCE_TYPE, channelLimits, jobOfTopic, matchChannel } from "@plitzi/sdk-shared/realtime";
|
|
8
9
|
//#region src/modules/realtime/handlers.ts
|
|
9
10
|
/** Topics one connection may hold. A page shows a handful; past this it is somebody enumerating. */
|
|
10
11
|
var MAX_TOPICS = 8;
|
|
@@ -28,7 +29,7 @@ var grantFor = async (grants, space, topic, offered) => {
|
|
|
28
29
|
* declares and against the visitor's access. One that fails is reported, not a reason to refuse the rest; all failing
|
|
29
30
|
* is a `403`.
|
|
30
31
|
*/
|
|
31
|
-
var admit = async (req, resolveChannels, grants) => {
|
|
32
|
+
var admit = async (req, resolveChannels, grants, jobs) => {
|
|
32
33
|
const { environment = "main", spaceId, revision } = req.ctx.spaceDeployment ?? {};
|
|
33
34
|
if (typeof spaceId !== "number") return {
|
|
34
35
|
ok: false,
|
|
@@ -57,6 +58,16 @@ var admit = async (req, resolveChannels, grants) => {
|
|
|
57
58
|
environment
|
|
58
59
|
};
|
|
59
60
|
for (const topic of requested) {
|
|
61
|
+
const jobId = jobOfTopic(topic);
|
|
62
|
+
if (jobId !== void 0) {
|
|
63
|
+
const refusal = await jobRefusal(jobs, spaceId, jobId, req.ctx.user);
|
|
64
|
+
if (refusal) refused.push({
|
|
65
|
+
topic,
|
|
66
|
+
reason: refusal
|
|
67
|
+
});
|
|
68
|
+
else accepted.set(topic, JOB_CHANNEL);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
60
71
|
const match = matchChannel(topic, channels);
|
|
61
72
|
const refusal = match ? accessRefusal(match.declaration.access, req.ctx.user) : "undeclared";
|
|
62
73
|
const grant = match && !refusal && match.declaration.grant === true ? await grantFor(grants, space, topic, offered) : void 0;
|
|
@@ -178,8 +189,8 @@ var publishFrom = async (hub, connection, { topic, type, data, echo }) => {
|
|
|
178
189
|
* The first event, `ready`, tells the page its public name (`from`) and the secret its publishes carry. Resolves when
|
|
179
190
|
* the page goes.
|
|
180
191
|
*/
|
|
181
|
-
var handleRealtimeSubscribe = async ({ req, res, raw, signal, hub, resolveChannels, grants }) => {
|
|
182
|
-
const admission = await admit(req, resolveChannels, grants);
|
|
192
|
+
var handleRealtimeSubscribe = async ({ req, res, raw, signal, hub, resolveChannels, grants, jobs }) => {
|
|
193
|
+
const admission = await admit(req, resolveChannels, grants, jobs);
|
|
183
194
|
if (!admission.ok) {
|
|
184
195
|
answer(res, admission.answer);
|
|
185
196
|
return;
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { ChannelResolver } from './declarations';
|
|
2
2
|
import { RealtimeGrants } from './grants';
|
|
3
3
|
import { RealtimeHub } from './hub';
|
|
4
|
-
import {
|
|
4
|
+
import { JobLookup } from './jobs';
|
|
5
|
+
import { FunctionJobView, RealtimeTransport, SSRServerConfig } from '@plitzi/sdk-shared';
|
|
5
6
|
export { createMemoryPubSub } from './memoryPubSub';
|
|
6
7
|
export { handleRealtimePublish, handleRealtimeSubscribe } from './handlers';
|
|
7
8
|
export { handleRealtimeSocket } from './socket';
|
|
@@ -43,6 +44,15 @@ export type RealtimeModule = {
|
|
|
43
44
|
spaceId: number;
|
|
44
45
|
environment: string;
|
|
45
46
|
}, topic: string, grant?: string) => Promise<void>;
|
|
47
|
+
/** Says a job of the space's functions as it is now on its topic (`$job:<id>`), kept for a page that joins later. */
|
|
48
|
+
publishJob: (space: {
|
|
49
|
+
spaceId: number;
|
|
50
|
+
environment: string;
|
|
51
|
+
}, jobId: string, view: FunctionJobView) => Promise<void>;
|
|
52
|
+
/** Hands the realtime the way to a job, which the actions module holds: what the door of `$job:<id>` reads. */
|
|
53
|
+
watchJobs: (lookup: JobLookup) => void;
|
|
54
|
+
/** The way to a job, once the actions module handed it — what a subscription to `$job:<id>` is decided by. */
|
|
55
|
+
jobs: () => JobLookup | undefined;
|
|
46
56
|
};
|
|
47
57
|
/**
|
|
48
58
|
* The server's realtime channels, built once per config — or `undefined` when they are off or cannot be: without the
|
|
@@ -3,6 +3,7 @@ import { KV_METHODS, createMemoryKv } from "../actions/runtime/memoryKv.js";
|
|
|
3
3
|
import { createRealtimeGrants } from "./grants.js";
|
|
4
4
|
import { createChannelResolver } from "./declarations.js";
|
|
5
5
|
import { createRealtimeHub } from "./hub.js";
|
|
6
|
+
import { publishJobView } from "./jobs.js";
|
|
6
7
|
import { createMemoryPubSub } from "./memoryPubSub.js";
|
|
7
8
|
import { createRealtimeRetained } from "./retained.js";
|
|
8
9
|
import { handleRealtimePublish, handleRealtimeSubscribe } from "./handlers.js";
|
|
@@ -26,6 +27,7 @@ var realtimeModuleFor = (config) => {
|
|
|
26
27
|
const hub = createRealtimeHub(config.realtime?.pubsub ?? createMemoryPubSub(), retained);
|
|
27
28
|
const resolveChannels = createChannelResolver(getOfflineData);
|
|
28
29
|
const grants = createRealtimeGrants(kv);
|
|
30
|
+
let jobLookup;
|
|
29
31
|
const module = {
|
|
30
32
|
hub,
|
|
31
33
|
path: config.realtime?.path ?? "/_realtime",
|
|
@@ -60,7 +62,12 @@ var realtimeModuleFor = (config) => {
|
|
|
60
62
|
if (matchChannel(topic, await resolveChannels(space.spaceId, space.environment))?.declaration.grant !== true) throw new Error(`"${topic}" is not a topic of a private (\`grant: true\`) channel of this space: it has no grants to revoke`);
|
|
61
63
|
await grants.revoke(space, topic, grant);
|
|
62
64
|
await hub.revoke(space, topic, grant);
|
|
63
|
-
}
|
|
65
|
+
},
|
|
66
|
+
publishJob: (space, jobId, view) => publishJobView(hub, retained, space, jobId, view),
|
|
67
|
+
watchJobs: (lookup) => {
|
|
68
|
+
jobLookup = lookup;
|
|
69
|
+
},
|
|
70
|
+
jobs: () => jobLookup
|
|
64
71
|
};
|
|
65
72
|
modules.set(config, module);
|
|
66
73
|
return module;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { RealtimeHub, RealtimeSpace } from './hub';
|
|
2
|
+
import { RealtimeRetained } from './retained';
|
|
3
|
+
import { Job, ChannelDeclaration, FunctionJobView, SSRUser } from '@plitzi/sdk-shared';
|
|
4
|
+
/** How the realtime reaches a job, once the actions module hands it the way (`watchJobs`). */
|
|
5
|
+
export type JobLookup = (spaceId: number, jobId: string) => Promise<Job | undefined>;
|
|
6
|
+
/** A job's topic, as a channel: the server alone says how the job goes, and a page that joins hears the latest. */
|
|
7
|
+
export declare const JOB_CHANNEL: ChannelDeclaration;
|
|
8
|
+
/** How long a job's topic is kept after it last changed: as long as the queue keeps a finished job readable. */
|
|
9
|
+
export declare const JOB_RETAINED_SECONDS: number;
|
|
10
|
+
/**
|
|
11
|
+
* Why a page may not watch a job, or nothing when it may: whoever started it always does, and anyone else as the
|
|
12
|
+
* job's `watch` says — a channel's access, read against the visitor's permissions in the space. A job of another space,
|
|
13
|
+
* or none by that id, is no topic at all.
|
|
14
|
+
*/
|
|
15
|
+
export declare const jobRefusal: (lookup: JobLookup | undefined, spaceId: number, jobId: string, user: SSRUser | undefined) => Promise<"undeclared" | "unauthenticated" | "forbidden" | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* Says a job as it is now on its topic, kept for a page that joins later — the one way it is said, by the page server's
|
|
18
|
+
* realtime and by an operator's panel in a process of its own alike.
|
|
19
|
+
*/
|
|
20
|
+
export declare const publishJobView: (hub: Pick<RealtimeHub, "publish">, retained: RealtimeRetained, space: RealtimeSpace, jobId: string, view: FunctionJobView) => Promise<void>;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { accessRefusal } from "@plitzi/sdk-shared/actions";
|
|
2
|
+
import { JOB_TYPE, jobTopic } from "@plitzi/sdk-shared/realtime";
|
|
3
|
+
//#region src/modules/realtime/jobs.ts
|
|
4
|
+
/** A job's topic, as a channel: the server alone says how the job goes, and a page that joins hears the latest. */
|
|
5
|
+
var JOB_CHANNEL = {
|
|
6
|
+
access: { mode: "session" },
|
|
7
|
+
publish: "server",
|
|
8
|
+
retain: true
|
|
9
|
+
};
|
|
10
|
+
/** How long a job's topic is kept after it last changed: as long as the queue keeps a finished job readable. */
|
|
11
|
+
var JOB_RETAINED_SECONDS = 2592e3;
|
|
12
|
+
/**
|
|
13
|
+
* Why a page may not watch a job, or nothing when it may: whoever started it always does, and anyone else as the
|
|
14
|
+
* job's `watch` says — a channel's access, read against the visitor's permissions in the space. A job of another space,
|
|
15
|
+
* or none by that id, is no topic at all.
|
|
16
|
+
*/
|
|
17
|
+
var jobRefusal = async (lookup, spaceId, jobId, user) => {
|
|
18
|
+
const target = (lookup ? await lookup(spaceId, jobId) : void 0)?.target;
|
|
19
|
+
if (target?.kind !== "function") return "undeclared";
|
|
20
|
+
if (user && target.user?.id === user.id) return;
|
|
21
|
+
if (!target.watch) return user ? "forbidden" : "unauthenticated";
|
|
22
|
+
return accessRefusal(target.watch, user);
|
|
23
|
+
};
|
|
24
|
+
/**
|
|
25
|
+
* Says a job as it is now on its topic, kept for a page that joins later — the one way it is said, by the page server's
|
|
26
|
+
* realtime and by an operator's panel in a process of its own alike.
|
|
27
|
+
*/
|
|
28
|
+
var publishJobView = async (hub, retained, space, jobId, view) => {
|
|
29
|
+
const message = {
|
|
30
|
+
topic: jobTopic(jobId),
|
|
31
|
+
type: JOB_TYPE,
|
|
32
|
+
data: view,
|
|
33
|
+
from: "server",
|
|
34
|
+
at: Date.now(),
|
|
35
|
+
retained: true
|
|
36
|
+
};
|
|
37
|
+
await retained.keep(space, message, JOB_RETAINED_SECONDS);
|
|
38
|
+
await hub.publish(space, message);
|
|
39
|
+
};
|
|
40
|
+
//#endregion
|
|
41
|
+
export { JOB_CHANNEL, JOB_RETAINED_SECONDS, jobRefusal, publishJobView };
|
|
@@ -8,9 +8,10 @@ export declare const MAX_RETAINED_BYTES: number;
|
|
|
8
8
|
export type RealtimeRetained = {
|
|
9
9
|
/**
|
|
10
10
|
* Keeps `message` as its topic's latest of its type — or, with `null` data, forgets the type. Refused, before anything
|
|
11
|
-
* is sent, past {@link MAX_RETAINED_TYPES} types or {@link MAX_RETAINED_BYTES} for the topic.
|
|
11
|
+
* is sent, past {@link MAX_RETAINED_TYPES} types or {@link MAX_RETAINED_BYTES} for the topic. With `ttlSeconds`, the
|
|
12
|
+
* topic is forgotten that long after it last changed — a job's, which ends.
|
|
12
13
|
*/
|
|
13
|
-
keep: (space: RealtimeSpace, message: RealtimeMessage) => Promise<void>;
|
|
14
|
+
keep: (space: RealtimeSpace, message: RealtimeMessage, ttlSeconds?: number) => Promise<void>;
|
|
14
15
|
/** What a topic keeps: the latest message of each type, oldest first. */
|
|
15
16
|
of: (space: RealtimeSpace, topic: string) => Promise<RealtimeMessage[]>;
|
|
16
17
|
};
|
|
@@ -23,7 +23,7 @@ var parseKept = (raw) => {
|
|
|
23
23
|
var createRealtimeRetained = (store) => {
|
|
24
24
|
const key = ({ spaceId, environment }, topic) => `realtime-retained:${String(spaceId)}:${environment}:${topic}`;
|
|
25
25
|
return {
|
|
26
|
-
keep: async (space, message) => {
|
|
26
|
+
keep: async (space, message, ttlSeconds) => {
|
|
27
27
|
const at = key(space, message.topic);
|
|
28
28
|
for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) {
|
|
29
29
|
const raw = await store.get(at);
|
|
@@ -36,7 +36,7 @@ var createRealtimeRetained = (store) => {
|
|
|
36
36
|
if (Object.keys(next).length > 64) throw new Error(`"${message.topic}" keeps at most ${String(64)} types of message: keep fewer, larger ones (one \`lists\` holding every list), or forget one with null`);
|
|
37
37
|
const written = JSON.stringify(next);
|
|
38
38
|
if (Buffer.byteLength(written) > 524288) throw new Error(`"${message.topic}" keeps at most ${String(MAX_RETAINED_BYTES / 1024)} KB, and "${message.type}" would take it past that: every page that joins is sent all of it — keep there what the screens show, the rest in kv`);
|
|
39
|
-
if (await store.swap(at, raw, written)) return;
|
|
39
|
+
if (await store.swap(at, raw, written, ttlSeconds)) return;
|
|
40
40
|
}
|
|
41
41
|
throw new Error(`"${message.topic}" changed under ${String(ATTEMPTS)} writes in a row, so "${message.type}" was not kept: publish it again`);
|
|
42
42
|
},
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ChannelResolver } from './declarations';
|
|
2
2
|
import { RealtimeGrants } from './grants';
|
|
3
3
|
import { RealtimeHub } from './hub';
|
|
4
|
+
import { JobLookup } from './jobs';
|
|
4
5
|
import { UpgradeRequest } from '../../core/http/socketResponse';
|
|
5
6
|
import { SSRRequest, SSRResponseHelpers } from '@plitzi/sdk-shared';
|
|
6
7
|
import { IncomingMessage } from 'node:http';
|
|
@@ -13,6 +14,8 @@ export type SocketDeps = {
|
|
|
13
14
|
resolveChannels: ChannelResolver;
|
|
14
15
|
grants: RealtimeGrants;
|
|
15
16
|
allowedOrigins: readonly string[];
|
|
17
|
+
/** The way to the jobs `$job:<id>` is about — absent where the server runs none. */
|
|
18
|
+
jobs?: JobLookup;
|
|
16
19
|
};
|
|
17
20
|
/**
|
|
18
21
|
* A page's realtime connection as a WebSocket: the same topics, rules and messages as the Server-Sent Events one, in
|
|
@@ -22,4 +25,4 @@ export type SocketDeps = {
|
|
|
22
25
|
* Refused the way the stream is — a `403` or a `422`, in HTTP, before anything switches — so a page falls back or
|
|
23
26
|
* reports it exactly as it would there.
|
|
24
27
|
*/
|
|
25
|
-
export declare const handleRealtimeSocket: ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins }: SocketDeps) => Promise<void>;
|
|
28
|
+
export declare const handleRealtimeSocket: ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs }: SocketDeps) => Promise<void>;
|
|
@@ -50,7 +50,7 @@ var ackId = (id) => typeof id === "number" && Number.isInteger(id) || typeof id
|
|
|
50
50
|
* Refused the way the stream is — a `403` or a `422`, in HTTP, before anything switches — so a page falls back or
|
|
51
51
|
* reports it exactly as it would there.
|
|
52
52
|
*/
|
|
53
|
-
var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins }) => {
|
|
53
|
+
var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels, grants, allowedOrigins, jobs }) => {
|
|
54
54
|
if (!originAllowed(raw, req, allowedOrigins)) {
|
|
55
55
|
answer(res, {
|
|
56
56
|
status: 403,
|
|
@@ -59,7 +59,7 @@ var handleRealtimeSocket = async ({ req, res, raw, upgrade, hub, resolveChannels
|
|
|
59
59
|
});
|
|
60
60
|
return;
|
|
61
61
|
}
|
|
62
|
-
const admission = await admit(req, resolveChannels, grants);
|
|
62
|
+
const admission = await admit(req, resolveChannels, grants, jobs);
|
|
63
63
|
if (!admission.ok) {
|
|
64
64
|
answer(res, admission.answer);
|
|
65
65
|
return;
|
|
@@ -2,7 +2,7 @@ import { serverLog } from "../../helpers/serverLog.js";
|
|
|
2
2
|
import onAbort from "../../helpers/onAbort.js";
|
|
3
3
|
import { matchRscPage } from "./matchRscPage.js";
|
|
4
4
|
import { flagUserFromSSR, flagValues, resolveFlags } from "@plitzi/sdk-shared/flags";
|
|
5
|
-
import { collectServerElements } from "@plitzi/sdk-shared/schema";
|
|
5
|
+
import { collectServerElements, pageAccessOf, pageAccessRefusal } from "@plitzi/sdk-shared/schema";
|
|
6
6
|
//#region src/modules/rsc/resolveRscData.ts
|
|
7
7
|
var DEFAULT_ELEMENT_TIMEOUT_MS = 5e3;
|
|
8
8
|
/**
|
|
@@ -40,6 +40,7 @@ var resolveRscData = async ({ schema, req, spaceId, environment, user, ids, reso
|
|
|
40
40
|
const match = matchRscPage(schema, req.path, user);
|
|
41
41
|
if (!match) return { serverData: {} };
|
|
42
42
|
const { pageId, routeParams } = match;
|
|
43
|
+
if (pageAccessRefusal(pageAccessOf(schema.flat[pageId].attributes), user) !== void 0) return { serverData: {} };
|
|
43
44
|
const flags = flagValues(resolveFlags(schema.flags, {
|
|
44
45
|
environment,
|
|
45
46
|
hostname: req.hostname,
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
+
import { webRequestOf, writeWebResponse } from "../../core/http/webExchange.js";
|
|
1
2
|
import { describeFunctions } from "../functions/driver.js";
|
|
2
3
|
import { startFunctionsRunnerService } from "../functions/runner/service.js";
|
|
3
4
|
import { endpointFor, endpointProblem } from "./contract.js";
|
|
4
5
|
import { reachSpaceInside } from "./inside.js";
|
|
5
6
|
import { createRuntimeRunner } from "./runner.js";
|
|
6
|
-
import { webRequestOf, writeWebResponse } from "../../core/http/webExchange.js";
|
|
7
7
|
//#region src/modules/runtime/host.ts
|
|
8
8
|
/** Where a started runtime says what it serves — under `/_`, which no endpoint may take. */
|
|
9
9
|
var RUNTIME_DESCRIBE_PATH = "/_describe";
|
|
@@ -5,7 +5,7 @@ import { FunctionRunner } from '../functions/protocol';
|
|
|
5
5
|
* A runtime's functions as a runner: the same protocol as the sandbox's, answered by code loaded in this process. The
|
|
6
6
|
* driver is the sandbox's own (`createFunctionsDriver`), so a task behaves the same in both — its `ctx` is calls to the
|
|
7
7
|
* platform, `ctx.kv.change` the same loop, a refusal the same answer. What it does not share is the isolate: there are
|
|
8
|
-
* no limits here but the platform's clock, since this process is the space's alone.
|
|
8
|
+
* no limits here but the platform's clock, since this process is the space's alone — and a route's answer streams.
|
|
9
9
|
*
|
|
10
10
|
* The bundle a request names is not asked for: the code is the one this runtime was started with.
|
|
11
11
|
*/
|