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