@plitzi/sdk-server 0.38.23 → 0.39.0
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 +172 -1
- package/README.md +55 -9
- package/dist/actions.d.ts +4 -1
- package/dist/actions.js +3 -2
- package/dist/auth.d.ts +2 -2
- package/dist/auth.js +5 -4
- package/dist/core/auth/api/accounts.d.ts +11 -0
- package/dist/core/auth/api/accounts.js +175 -0
- package/dist/core/auth/api/admin.d.ts +41 -0
- package/dist/core/auth/api/admin.js +146 -0
- package/dist/core/auth/api/context.d.ts +119 -0
- package/dist/core/auth/api/context.js +262 -0
- package/dist/core/auth/api/factors.d.ts +31 -0
- package/dist/core/auth/api/factors.js +209 -0
- package/dist/core/auth/api/index.d.ts +94 -0
- package/dist/core/auth/api/index.js +43 -0
- package/dist/core/auth/api/profile.d.ts +43 -0
- package/dist/core/auth/api/profile.js +243 -0
- package/dist/core/auth/api/session.d.ts +62 -0
- package/dist/core/auth/api/session.js +312 -0
- package/dist/core/auth/{api.d.ts → api/types.d.ts} +41 -195
- package/dist/core/auth/api/values.d.ts +67 -0
- package/dist/core/auth/api/values.js +90 -0
- package/dist/core/auth/createAuth.d.ts +49 -39
- package/dist/core/auth/createAuth.js +21 -1
- package/dist/core/auth/oauth/client.d.ts +2 -2
- package/dist/core/auth/oauth/client.js +6 -1
- package/dist/core/auth/oauth/index.d.ts +30 -7
- package/dist/core/auth/oauth/index.js +33 -14
- package/dist/core/auth/oauth/providers/github.js +1 -1
- package/dist/core/auth/oauth/providers/google.js +1 -1
- package/dist/core/auth/oauth/providers/oidc.d.ts +40 -0
- package/dist/core/auth/oauth/providers/oidc.js +197 -0
- package/dist/core/auth/oauth/state.d.ts +2 -0
- package/dist/core/auth/oauth/state.js +2 -0
- package/dist/core/auth/oauth/types.d.ts +21 -3
- package/dist/core/auth/oauth/types.js +4 -1
- package/dist/core/auth/routes.js +1 -1
- package/dist/core/auth/tokens.d.ts +3 -1
- package/dist/core/auth/tokens.js +2 -1
- package/dist/core/configSeam.d.ts +0 -4
- package/dist/core/configSeam.js +12 -1
- package/dist/core/createServer.js +16 -4
- package/dist/core/freePort.d.ts +10 -0
- package/dist/core/freePort.js +39 -1
- package/dist/core/handlers/socialRouteHandlers.d.ts +9 -1
- package/dist/core/handlers/socialRouteHandlers.js +46 -12
- package/dist/core/health.d.ts +1 -0
- package/dist/core/health.js +2 -1
- package/dist/core/http/stages/authRoutes.d.ts +6 -0
- package/dist/core/http/stages/authRoutes.js +42 -1
- package/dist/core/http/stages/images.js +5 -3
- package/dist/core/http/stages/livePages.js +1 -1
- package/dist/core/server/fleet/relay.js +9 -1
- package/dist/core/server/fleet/stores.d.ts +7 -0
- package/dist/core/server/fleet/stores.js +15 -2
- package/dist/core/server/pageServer.js +5 -1
- package/dist/core/services/realtime.js +4 -2
- package/dist/core/services/registry.js +7 -1
- package/dist/core/services/robotsTxt.d.ts +16 -0
- package/dist/core/services/robotsTxt.js +50 -0
- package/dist/core/services/servedSpace.d.ts +8 -0
- package/dist/core/services/servedSpace.js +16 -0
- package/dist/core/services/sitemapXml.d.ts +7 -0
- package/dist/core/services/sitemapXml.js +37 -0
- package/dist/functions-api.d.ts +75 -2
- package/dist/helpers/fileStore.d.ts +60 -0
- package/dist/helpers/fileStore.js +127 -0
- package/dist/helpers/outboundGuard.d.ts +32 -3
- package/dist/helpers/outboundGuard.js +50 -5
- package/dist/hosts/project/agentRuns.d.ts +24 -0
- package/dist/hosts/project/agentRuns.js +107 -0
- package/dist/hosts/project/laterAsks.d.ts +41 -0
- package/dist/hosts/project/laterAsks.js +117 -0
- package/dist/hosts/project/plugins.js +11 -4
- package/dist/hosts/project/serveProject.d.ts +11 -3
- package/dist/hosts/project/serveProject.js +94 -36
- package/dist/hosts/project/spaceFailure.d.ts +4 -0
- package/dist/hosts/project/spaceFailure.js +10 -0
- package/dist/hosts/project/watchSpace.d.ts +5 -5
- package/dist/hosts/project/watchSpace.js +15 -6
- package/dist/index.js +2 -2
- package/dist/kernel.js +1 -1
- package/dist/modules/actions/connectorWrite.js +3 -1
- package/dist/modules/actions/index.js +1 -1
- package/dist/modules/actions/jobs/fileQueue.d.ts +34 -0
- package/dist/modules/actions/jobs/fileQueue.js +72 -0
- package/dist/modules/actions/jobs/index.js +3 -3
- package/dist/modules/actions/jobs/memoryQueue.js +6 -215
- package/dist/modules/actions/jobs/queueDocument.d.ts +14 -0
- package/dist/modules/actions/jobs/queueDocument.js +22 -0
- package/dist/modules/actions/jobs/queueRules.d.ts +39 -0
- package/dist/modules/actions/jobs/queueRules.js +270 -0
- package/dist/modules/actions/moduleFor.js +2 -0
- package/dist/modules/actions/runtime/fileKv.d.ts +3 -1
- package/dist/modules/actions/runtime/fileKv.js +12 -98
- package/dist/modules/actions/runtime/guards.d.ts +19 -1
- package/dist/modules/actions/runtime/guards.js +10 -1
- package/dist/modules/actions/runtime/kvChange.d.ts +40 -0
- package/dist/modules/actions/runtime/kvChange.js +23 -1
- package/dist/modules/actions/runtime/kvList.d.ts +4 -0
- package/dist/modules/actions/runtime/kvList.js +5 -1
- package/dist/modules/actions/runtime/kvStore.js +15 -1
- package/dist/modules/actions/runtime/namespaceKv.js +2 -0
- package/dist/modules/actions/runtime/renderResolver.js +31 -5
- package/dist/modules/actions/runtime/runAction.js +16 -6
- package/dist/modules/actions/runtime/scope.js +11 -0
- package/dist/modules/actions/runtime/taskContext.js +11 -32
- package/dist/modules/actions/tasks/auth.js +2 -0
- package/dist/modules/actions/tasks/connector.js +6 -2
- package/dist/modules/actions/tasks/flow.js +5 -0
- package/dist/modules/actions/tasks/http.js +2 -1
- package/dist/modules/actions/tasks/kv.js +5 -0
- package/dist/modules/actions/tasks/list.js +11 -2
- package/dist/modules/actions/tasks/transform.js +2 -0
- package/dist/modules/actions/transport/callHandler.js +25 -4
- package/dist/modules/actions/types.d.ts +46 -1
- package/dist/modules/connectors/engine.d.ts +7 -2
- package/dist/modules/connectors/engine.js +4 -4
- package/dist/modules/connectors/resolver.d.ts +2 -1
- package/dist/modules/connectors/resolver.js +3 -2
- package/dist/modules/functions/build.d.ts +7 -2
- package/dist/modules/functions/build.js +90 -6
- package/dist/modules/functions/capabilities.js +21 -0
- package/dist/modules/functions/context.js +6 -2
- package/dist/modules/functions/contract.d.ts +45 -1
- package/dist/modules/functions/driver.d.ts +2 -1
- package/dist/modules/functions/driver.js +39 -0
- package/dist/modules/functions/load.d.ts +1 -1
- package/dist/modules/functions/load.js +2 -2
- package/dist/modules/functions/manifest.js +7 -1
- package/dist/modules/functions/oauth.d.ts +3 -1
- package/dist/modules/functions/oauth.js +20 -7
- package/dist/modules/functions/protocol.d.ts +9 -0
- package/dist/modules/functions/sandbox/guest/bytes.d.ts +27 -0
- package/dist/modules/functions/sandbox/guest/bytes.js +108 -0
- package/dist/modules/functions/sandbox/guest/crypto.d.ts +47 -0
- package/dist/modules/functions/sandbox/guest/crypto.js +144 -0
- package/dist/modules/functions/sandbox/guest/events.d.ts +152 -0
- package/dist/modules/functions/sandbox/guest/events.js +143 -0
- package/dist/modules/functions/sandbox/guest/fetch.d.ts +305 -0
- package/dist/modules/functions/sandbox/guest/fetch.js +237 -0
- package/dist/modules/functions/sandbox/guest/index.d.ts +28 -0
- package/dist/modules/functions/sandbox/guest/index.js +130 -0
- package/dist/modules/functions/sandbox/{guest.d.ts → guest/types.d.ts} +5 -12
- package/dist/modules/functions/sandbox/isolate.js +20 -6
- package/dist/modules/functions/space.js +2 -8
- package/dist/modules/images/imageProxy.d.ts +3 -2
- package/dist/modules/images/imageProxy.js +2 -2
- package/dist/modules/mongo/jobQueue.js +0 -19
- package/dist/modules/mysql/accounts.js +12 -5
- package/dist/modules/mysql/jobs/index.d.ts +1 -1
- package/dist/modules/mysql/jobs/schema.d.ts +0 -6
- package/dist/modules/mysql/jobs/schema.js +2 -46
- package/dist/modules/mysql/schema.js +26 -1
- package/dist/modules/mysql/sessions.js +2 -1
- package/dist/modules/realtime/handlers.d.ts +9 -4
- package/dist/modules/realtime/handlers.js +20 -3
- package/dist/modules/realtime/hub.d.ts +4 -2
- package/dist/modules/realtime/hub.js +36 -4
- package/dist/modules/realtime/index.d.ts +14 -0
- package/dist/modules/realtime/index.js +14 -1
- package/dist/modules/realtime/presence.d.ts +33 -0
- package/dist/modules/realtime/presence.js +56 -0
- package/dist/modules/realtime/socket.d.ts +3 -1
- package/dist/modules/realtime/socket.js +2 -2
- package/dist/modules/rsc/connectorRscData.d.ts +6 -1
- package/dist/modules/rsc/connectorRscData.js +27 -6
- package/dist/modules/rsc/externalQueryReader.d.ts +28 -0
- package/dist/modules/rsc/externalQueryReader.js +43 -0
- package/dist/modules/rsc/handler.js +1 -1
- package/dist/modules/rsc/resolveRscData.d.ts +11 -1
- package/dist/modules/rsc/resolveRscData.js +86 -16
- package/dist/modules/runtime/inside.js +1 -1
- package/dist/modules/runtime/runner.js +2 -1
- package/dist/modules/sqlite/jobQueue.d.ts +35 -0
- package/dist/modules/sqlite/jobQueue.js +56 -0
- package/dist/modules/sqlite/kv.d.ts +1 -1
- package/dist/modules/sqlite/kv.js +2 -10
- package/dist/modules/sqlite/open.d.ts +3 -0
- package/dist/modules/sqlite/open.js +13 -0
- package/dist/modules/ssr/Component.d.ts +5 -1
- package/dist/modules/ssr/Component.js +3 -1
- package/dist/modules/ssr/applySSRResult.d.ts +8 -1
- package/dist/modules/ssr/applySSRResult.js +23 -3
- package/dist/modules/ssr/handler.js +30 -5
- package/dist/modules/ssr/prepareRender.js +27 -5
- package/dist/modules/ssr/preview.d.ts +2 -0
- package/dist/modules/ssr/preview.js +6 -3
- package/dist/modules/ssr/registerExternalPlugins.d.ts +2 -6
- package/dist/modules/ssr/registerExternalPlugins.js +2 -2
- package/dist/modules/ssr/resolvePageSeo.d.ts +11 -0
- package/dist/modules/ssr/resolvePageSeo.js +13 -2
- package/dist/modules/ssr/streamBody.js +2 -2
- package/dist/modules/ssr/views/template.ejs +21 -17
- package/dist/mysql.d.ts +1 -1
- package/dist/mysql.js +2 -2
- package/dist/plugins/manager.d.ts +5 -0
- package/dist/plugins/manager.js +9 -0
- package/dist/sqlite.d.ts +8 -1
- package/dist/sqlite.js +3 -1
- package/package.json +5 -5
- package/skills/plitzi-authoring/CHEATSHEET.md +6 -6
- package/skills/plitzi-authoring/SKILL.md +4 -2
- package/skills/plitzi-authoring/recipes/accordion.ts +2 -1
- package/skills/plitzi-authoring/recipes/carousel.ts +24 -3
- package/skills/plitzi-authoring/recipes/detail-page.ts +0 -1
- package/skills/plitzi-authoring/recipes/embed-and-svg.ts +3 -1
- package/skills/plitzi-authoring/recipes/filter-a-list.ts +0 -1
- package/skills/plitzi-authoring/recipes/show-data.ts +0 -1
- package/skills/plitzi-authoring/recipes/typed-data.ts +0 -1
- package/skills/plitzi-authoring/reference/accessibility.md +7 -2
- package/skills/plitzi-authoring/reference/auth.md +15 -4
- package/skills/plitzi-authoring/reference/authoring-errors.md +51 -10
- package/skills/plitzi-authoring/reference/colours-and-motion.md +7 -1
- package/skills/plitzi-authoring/reference/components.md +4 -1
- package/skills/plitzi-authoring/reference/data-and-visibility.md +31 -22
- package/skills/plitzi-authoring/reference/efficiency.md +2 -1
- package/skills/plitzi-authoring/reference/elements-and-styles.md +16 -15
- package/skills/plitzi-authoring/reference/flows.md +20 -8
- package/skills/plitzi-authoring/reference/kept-state.md +8 -0
- package/skills/plitzi-authoring/reference/layouts.md +18 -2
- package/skills/plitzi-authoring/reference/lists.md +20 -4
- package/skills/plitzi-authoring/reference/plugin-reach.md +12 -0
- package/skills/plitzi-authoring/reference/plugins.md +13 -2
- package/skills/plitzi-authoring/reference/realtime.md +8 -5
- package/skills/plitzi-authoring/reference/structure.md +17 -1
- package/skills/plitzi-authoring/reference/templates.md +11 -3
- package/skills/plitzi-authoring/reference/testing.md +82 -5
- package/skills/plitzi-authoring/reference/typed-sources.md +6 -0
- package/skills/plitzi-authoring/reference/validation.md +1 -1
- package/dist/core/auth/api.js +0 -1323
- package/dist/modules/functions/sandbox/guest.js +0 -662
|
@@ -1,43 +1,61 @@
|
|
|
1
1
|
import { consoleLogger } from "../../helpers/serverLog.js";
|
|
2
2
|
import { isFleetWorker } from "../../core/server/fleet/role.js";
|
|
3
|
-
import {
|
|
3
|
+
import { fleetJobQueue, fleetKv } from "../../core/server/fleet/stores.js";
|
|
4
|
+
import { oauthCallbackUrlOn } from "../../modules/functions/oauth.js";
|
|
4
5
|
import { loadFunctions } from "../../modules/functions/load.js";
|
|
5
6
|
import { createServer as createServer$1 } from "../../core/createServer.js";
|
|
6
7
|
import { closeOnSignals } from "../../core/server/closeOnSignals.js";
|
|
7
|
-
import {
|
|
8
|
+
import { reservePort } from "../../core/freePort.js";
|
|
8
9
|
import { createCloudAdapters } from "../../adapters/cloudAdapters.js";
|
|
9
10
|
import { createJsonAdapters } from "../../adapters/jsonAdapters.js";
|
|
11
|
+
import { createFileJobQueue } from "../../modules/actions/jobs/fileQueue.js";
|
|
10
12
|
import { createFileKv } from "../../modules/actions/runtime/fileKv.js";
|
|
11
13
|
import { credentialsFromEnv } from "../../modules/actions/runtime/credentials.js";
|
|
12
14
|
import { reachOwnServer } from "../../modules/runtime/inside.js";
|
|
13
15
|
import { loadRuntime, loadRuntimeModule } from "../../modules/runtime/bundle.js";
|
|
14
16
|
import { serveRuntime } from "../../modules/runtime/stages.js";
|
|
17
|
+
import { runReportStage, runStatusStage, watchAgentRuns } from "./agentRuns.js";
|
|
18
|
+
import { watchLaterAsks } from "./laterAsks.js";
|
|
15
19
|
import { projectPlugins, watchProjectPlugins } from "./plugins.js";
|
|
16
20
|
import { createSpaceFailure } from "./spaceFailure.js";
|
|
17
21
|
import { watchSpace } from "./watchSpace.js";
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
22
|
+
import { isRecord } from "@plitzi/sdk-shared/helpers";
|
|
23
|
+
import { isIP } from "node:net";
|
|
20
24
|
import { X509Certificate } from "node:crypto";
|
|
21
25
|
import { hostname, networkInterfaces } from "node:os";
|
|
22
|
-
import { isIP } from "node:net";
|
|
23
26
|
import path from "node:path";
|
|
24
27
|
import { EMPTY_SCHEMA } from "@plitzi/sdk-shared/schema";
|
|
25
28
|
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
26
29
|
import { EMPTY_STYLE_SCHEMA } from "@plitzi/sdk-shared/style";
|
|
27
|
-
import { DATA_DIR, DEV_SERVER_FILE, FUNCTIONS_DIR, KV_FILE, PROJECT_TMP, PUBLIC_DIR, RUNTIME_BUNDLE, RUNTIME_ENTRY, assertProjectLayout, layoutFindingText, localNetworkName, networkAddresses, projectModule, projectRoot } from "@plitzi/sdk-shared/project";
|
|
30
|
+
import { DATA_DIR, DEV_SERVER_FILE, FUNCTIONS_DIR, JOBS_FILE, KV_FILE, PROJECT_STATE, PROJECT_TMP, PUBLIC_DIR, RUNTIME_BUNDLE, RUNTIME_ENTRY, SERVER_RECORD_ENV, STATE_DIR_ENV, assertProjectLayout, layoutFindingText, localNetworkName, networkAddresses, projectMark, projectModule, projectRoot } from "@plitzi/sdk-shared/project";
|
|
31
|
+
import { RUN_REPORTS_ENV, RUN_STATUS_ENV } from "@plitzi/sdk-shared/runs";
|
|
28
32
|
//#region src/hosts/project/serveProject.ts
|
|
29
33
|
/**
|
|
30
34
|
* The errors whose message is the whole report — every problem, where it is and what to write instead — and whose
|
|
31
35
|
* stack would only point inside the SDK: the project's root, its layout, a space module with no space, a space that does
|
|
32
|
-
* not author. Told by name, since each package that throws one carries its own copy of the class.
|
|
36
|
+
* not author, a state file another server of the folder holds. Told by name, since each package that throws one carries its own copy of the class.
|
|
33
37
|
*/
|
|
34
38
|
var REPORTS = /* @__PURE__ */ new Set([
|
|
35
39
|
"ProjectRootError",
|
|
36
40
|
"ProjectLayoutError",
|
|
37
41
|
"ProjectSpaceError",
|
|
38
|
-
"SpaceRefusedError"
|
|
42
|
+
"SpaceRefusedError",
|
|
43
|
+
"SpacePreviewError",
|
|
44
|
+
"FileInUseError"
|
|
39
45
|
]);
|
|
40
|
-
var
|
|
46
|
+
var isStartupReport = (error) => error instanceof Error && REPORTS.has(error.name);
|
|
47
|
+
/**
|
|
48
|
+
* A second server of the project, started while the first runs, said as what it is: the project already served, where,
|
|
49
|
+
* since when, and how to stop it — where it said a state file was in use by a process, with a stack (the maintainer: "debería
|
|
50
|
+
* ser más amigable"). Undefined for a holder that serves nothing, whose own report is said as it is.
|
|
51
|
+
*/
|
|
52
|
+
var alreadyServed = (error) => {
|
|
53
|
+
const holder = Reflect.get(error, "holder");
|
|
54
|
+
if (error.name !== "FileInUseError" || !isRecord(holder) || typeof holder.serves !== "string") return;
|
|
55
|
+
const port = new URL(holder.serves).port;
|
|
56
|
+
const since = typeof holder.since === "string" ? holder.since.slice(11, 16) : "";
|
|
57
|
+
return [`This project is already running at ${holder.serves}${typeof holder.pid === "number" ? ` (process ${String(holder.pid)}${since ? `, since ${since} UTC` : ""})` : ""}.`, `Open it there — or stop it before starting another: Ctrl+C in its terminal, or plitzi server stop${port ? ` --port ${port}` : ""}.`].join("\n");
|
|
58
|
+
};
|
|
41
59
|
var ENVIRONMENTS = [
|
|
42
60
|
"main",
|
|
43
61
|
"production",
|
|
@@ -73,14 +91,16 @@ var LOOPBACK = /* @__PURE__ */ new Set([
|
|
|
73
91
|
]);
|
|
74
92
|
var ANY_ADDRESS = /* @__PURE__ */ new Set(["0.0.0.0", "::"]);
|
|
75
93
|
/**
|
|
76
|
-
* Where OAuth providers send a visitor back (`ctx.oauth`) when the project does not say: the
|
|
77
|
-
*
|
|
78
|
-
*
|
|
79
|
-
* change and providers refuse (a private IP, a `.local` name), nor `localhost`, refused too (RFC 8252).
|
|
94
|
+
* Where OAuth providers send a visitor back (`ctx.oauth`) when the project does not say: `PUBLIC_URL`, the address
|
|
95
|
+
* people reach it at, when it is HTTPS. Else, while developing — a server opened on `localhost`, its loopback and the
|
|
96
|
+
* network — this machine's loopback, the one address every provider takes: never its address on the network, which the
|
|
97
|
+
* router may change and providers refuse (a private IP, a `.local` name), nor `localhost`, refused too (RFC 8252). In
|
|
98
|
+
* production none is fixed: behind its proxy, the address each visitor's request came on — the site's own domain.
|
|
80
99
|
*/
|
|
81
|
-
var oauthCallbackOrigin = (publicUrl, localUrl) => {
|
|
100
|
+
var oauthCallbackOrigin = (publicUrl, localUrl, developing) => {
|
|
82
101
|
const reached = publicUrl === void 0 ? void 0 : new URL(publicUrl);
|
|
83
|
-
|
|
102
|
+
if (reached?.protocol === "https:") return reached.origin;
|
|
103
|
+
return developing ? new URL(localUrl).origin : void 0;
|
|
84
104
|
};
|
|
85
105
|
/** An address as a URL writes it: an IPv6 one in brackets. */
|
|
86
106
|
var urlHost = (address) => address.includes(":") ? `[${address}]` : address;
|
|
@@ -153,7 +173,7 @@ var spaceToServe = async ({ space, cloud }, developing, root) => {
|
|
|
153
173
|
} catch (error) {
|
|
154
174
|
if (!developing) throw error;
|
|
155
175
|
return {
|
|
156
|
-
failure:
|
|
176
|
+
failure: isStartupReport(error) ? error.message : error instanceof Error ? error.stack ?? error.message : String(error),
|
|
157
177
|
name: path.basename(root)
|
|
158
178
|
};
|
|
159
179
|
}
|
|
@@ -173,7 +193,8 @@ var startProject = async (options) => {
|
|
|
173
193
|
});
|
|
174
194
|
if (developing) for (const warning of layout) console.warn(`[layout] ${layoutFindingText(warning)}`);
|
|
175
195
|
const host = process.env.HOST ?? "127.0.0.1";
|
|
176
|
-
const
|
|
196
|
+
const reserved = !process.env.PORT && developing ? await reservePort(8080, host) : void 0;
|
|
197
|
+
const port = process.env.PORT ? Number(process.env.PORT) : reserved?.port ?? 8080;
|
|
177
198
|
const tls = serverOptions.tls ?? tlsFromEnv(root);
|
|
178
199
|
const scheme = tls ? "https" : "http";
|
|
179
200
|
const localUrl = `${scheme}://${urlHost(localAddress(host))}:${String(port)}`;
|
|
@@ -217,21 +238,37 @@ var startProject = async (options) => {
|
|
|
217
238
|
}) : cloudAdapters(plugins.names);
|
|
218
239
|
const functionsDir = path.join(root, FUNCTIONS_DIR);
|
|
219
240
|
const functions = existsSync(functionsDir) ? await loadFunctions(functionsDir) : [];
|
|
220
|
-
const callbackOrigin = serverOptions.functions?.oauth?.callbackOrigin ?? oauthCallbackOrigin(process.env.PUBLIC_URL, localUrl);
|
|
241
|
+
const callbackOrigin = serverOptions.functions?.oauth?.callbackOrigin ?? oauthCallbackOrigin(process.env.PUBLIC_URL, localUrl, developing);
|
|
221
242
|
const runtimeBundle = path.join(root, RUNTIME_BUNDLE);
|
|
222
243
|
const spaceRuntime = await loadRuntimeModule(projectModule(root, RUNTIME_ENTRY, process.argv[1])) ?? (existsSync(runtimeBundle) ? await loadRuntime(readFileSync(runtimeBundle), path.join(root, PROJECT_TMP, "runtime")) : void 0);
|
|
223
244
|
const runtime = spaceRuntime && await serveRuntime(spaceRuntime, {
|
|
224
245
|
env: process.env,
|
|
225
246
|
publicUrl
|
|
226
247
|
});
|
|
248
|
+
const holder = `the server of "${name}", on port ${String(port)} (plitzi server stop --port ${String(port)} stops it)`;
|
|
227
249
|
let keptKv;
|
|
228
|
-
const
|
|
250
|
+
const stateDir = path.resolve(root, process.env[STATE_DIR_ENV] || PROJECT_STATE);
|
|
251
|
+
const kv = serverOptions.action?.kv ?? fleetKv(() => {
|
|
229
252
|
keptKv = createFileKv({
|
|
230
|
-
file: path.join(
|
|
231
|
-
owner:
|
|
253
|
+
file: path.join(stateDir, path.basename(KV_FILE)),
|
|
254
|
+
owner: holder,
|
|
255
|
+
serves: localUrl
|
|
232
256
|
});
|
|
233
257
|
return keptKv;
|
|
234
258
|
});
|
|
259
|
+
let keptJobs;
|
|
260
|
+
const jobsConfig = serverOptions.action?.jobs;
|
|
261
|
+
const jobs = jobsConfig === false ? false : {
|
|
262
|
+
...jobsConfig,
|
|
263
|
+
queue: jobsConfig?.queue ?? fleetJobQueue(() => {
|
|
264
|
+
keptJobs = createFileJobQueue({
|
|
265
|
+
file: path.join(stateDir, path.basename(JOBS_FILE)),
|
|
266
|
+
owner: holder,
|
|
267
|
+
serves: localUrl
|
|
268
|
+
});
|
|
269
|
+
return keptJobs;
|
|
270
|
+
})
|
|
271
|
+
};
|
|
235
272
|
const server = createServer$1({
|
|
236
273
|
logLevel: process.argv.includes("--verbose") ? "info" : "warn",
|
|
237
274
|
logger: consoleLogger,
|
|
@@ -240,7 +277,11 @@ var startProject = async (options) => {
|
|
|
240
277
|
port,
|
|
241
278
|
devMode: serverOptions.devMode ?? developing,
|
|
242
279
|
livePages: serverOptions.livePages ?? serverOptions.devMode ?? developing,
|
|
243
|
-
health: {
|
|
280
|
+
health: {
|
|
281
|
+
name,
|
|
282
|
+
instance: projectMark(root),
|
|
283
|
+
check: spaceFailure.health
|
|
284
|
+
},
|
|
244
285
|
adapters,
|
|
245
286
|
plugins: plugins.sources,
|
|
246
287
|
publicDir: path.join(root, PUBLIC_DIR),
|
|
@@ -248,22 +289,30 @@ var startProject = async (options) => {
|
|
|
248
289
|
functions: {
|
|
249
290
|
native: [...functions, ...runtime?.native ?? []],
|
|
250
291
|
plugins: plugins.functions,
|
|
251
|
-
oauth: { callbackOrigin }
|
|
292
|
+
oauth: callbackOrigin === void 0 ? {} : { callbackOrigin }
|
|
252
293
|
},
|
|
253
294
|
action: {
|
|
254
295
|
signingSecret: process.env.PLITZI_SIGNING_SECRET,
|
|
255
296
|
kv,
|
|
256
297
|
...serverOptions.action,
|
|
298
|
+
jobs,
|
|
257
299
|
...actions ? { lookups: actionLookups(actions, connectors, credentialsFromEnv()) } : {}
|
|
258
300
|
}
|
|
259
301
|
}, {
|
|
260
|
-
preAuth: [
|
|
302
|
+
preAuth: [
|
|
303
|
+
spaceFailure.stage,
|
|
304
|
+
...developing && process.env[RUN_STATUS_ENV] ? [runStatusStage(process.env[RUN_STATUS_ENV])] : [],
|
|
305
|
+
...developing && process.env[RUN_REPORTS_ENV] ? [runReportStage(process.env[RUN_REPORTS_ENV])] : []
|
|
306
|
+
],
|
|
261
307
|
data: runtime ? [runtime.stage] : []
|
|
262
308
|
});
|
|
263
309
|
await server.listen(port, host);
|
|
310
|
+
reserved?.release();
|
|
264
311
|
if (speaks) {
|
|
265
312
|
mkdirSync(path.join(root, PROJECT_TMP), { recursive: true });
|
|
266
|
-
|
|
313
|
+
const record = process.env[SERVER_RECORD_ENV] || DEV_SERVER_FILE;
|
|
314
|
+
mkdirSync(path.dirname(path.join(root, record)), { recursive: true });
|
|
315
|
+
writeFileSync(path.join(root, record), `${JSON.stringify({
|
|
267
316
|
name,
|
|
268
317
|
port,
|
|
269
318
|
url: localUrl,
|
|
@@ -274,21 +323,30 @@ var startProject = async (options) => {
|
|
|
274
323
|
if (network.length > 0) console.log(`also on ${network.map((address) => `${address}/`).join(", ")} — anyone on this network can open it (HOST=${host})`);
|
|
275
324
|
else if (developing && LOOPBACK.has(host)) console.log("only this machine opens it: HOST=0.0.0.0 in .env opens it to your network (a phone on the Wi-Fi)");
|
|
276
325
|
if ([...functions, ...runtime?.native ?? []].some((definition) => Object.keys(definition.oauth ?? {}).length > 0)) {
|
|
277
|
-
console.log(`OAuth providers send visitors back to ${
|
|
278
|
-
if (network.length > 0 &&
|
|
326
|
+
console.log(callbackOrigin === void 0 ? `OAuth providers send visitors back to the address they asked from — register ${oauthCallbackUrlOn("https://<your domain>")} for each domain the site answers on (PUBLIC_URL fixes one)` : `OAuth providers send visitors back to ${oauthCallbackUrlOn(callbackOrigin)} — the address to register with each`);
|
|
327
|
+
if (callbackOrigin !== void 0 && network.length > 0 && callbackOrigin === new URL(localUrl).origin) console.log(" a sign-in started on another device (a tablet) comes back to its own loopback: for one, give this server a name providers accept — functions.oauth.callbackOrigin in src/config/serverOptions.ts, or PUBLIC_URL");
|
|
279
328
|
}
|
|
280
329
|
if (reached.unnamed.length > 0) console.warn(`[tls] the certificate does not name ${reached.unnamed.join(", ")}: a device that opens it there is refused — \`plitzi cert\` makes one for this machine as it is now`);
|
|
281
330
|
}
|
|
282
|
-
const watching = developing ? [
|
|
283
|
-
held
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
331
|
+
const watching = developing ? [
|
|
332
|
+
...held ? [watchSpace(root, (authored) => {
|
|
333
|
+
held.documents = authored;
|
|
334
|
+
spaceFailure.clear();
|
|
335
|
+
server.updatePages(authored);
|
|
336
|
+
}, (why) => {
|
|
337
|
+
if (held.documents) spaceFailure.stale(why);
|
|
338
|
+
else spaceFailure.fail(why);
|
|
339
|
+
})] : [],
|
|
340
|
+
watchProjectPlugins(root, server, plugins),
|
|
341
|
+
...speaks ? [watchAgentRuns(root)] : [],
|
|
342
|
+
...speaks && jobs !== false ? [watchLaterAsks(root, () => jobs.queue, SPACE_ID)] : []
|
|
343
|
+
] : [];
|
|
287
344
|
const close = async () => {
|
|
288
345
|
watching.forEach((stop) => stop());
|
|
289
346
|
await server.close();
|
|
290
347
|
await runtime?.close();
|
|
291
348
|
await keptKv?.close();
|
|
349
|
+
await keptJobs?.close();
|
|
292
350
|
};
|
|
293
351
|
const stopListening = closeOnSignals({ close });
|
|
294
352
|
return {
|
|
@@ -320,7 +378,7 @@ var startProject = async (options) => {
|
|
|
320
378
|
* - a signal closes it, finishing what runs.
|
|
321
379
|
*
|
|
322
380
|
* While developing (`NODE_ENV` other than `production`), a save to the space is authored again by the project's
|
|
323
|
-
*
|
|
381
|
+
* `.plitzi/author.ts`, in a process of its own, which hands the documents back over IPC: the server swaps them in memory
|
|
324
382
|
* and every open page loads again. A plugin folder added is registered, one removed turned off, and a plugin's
|
|
325
383
|
* `functions/` loaded again; a folder it cannot build is said in the terminal, and the server goes on.
|
|
326
384
|
*/
|
|
@@ -328,11 +386,11 @@ var serveProject = async (options) => {
|
|
|
328
386
|
try {
|
|
329
387
|
return await startProject(options);
|
|
330
388
|
} catch (error) {
|
|
331
|
-
if (!
|
|
332
|
-
console.error(error.message);
|
|
389
|
+
if (!isStartupReport(error)) throw error;
|
|
390
|
+
console.error(alreadyServed(error) ?? error.message);
|
|
333
391
|
process.exitCode = 1;
|
|
334
392
|
process.exit(1);
|
|
335
393
|
}
|
|
336
394
|
};
|
|
337
395
|
//#endregion
|
|
338
|
-
export { serveProject };
|
|
396
|
+
export { alreadyServed, isStartupReport, serveProject };
|
|
@@ -3,6 +3,10 @@ export declare const createSpaceFailure: () => {
|
|
|
3
3
|
stage: Stage;
|
|
4
4
|
/** The space did not author: every page says why, until it does. */
|
|
5
5
|
fail: (message: string) => void;
|
|
6
|
+
/** A save did not author: the last space that did is still served, and this is why it is not the saved one. */
|
|
7
|
+
stale: (message: string) => void;
|
|
8
|
+
/** What `/health` adds while a save has not authored: why the page is the space as it last authored. */
|
|
9
|
+
health: () => Record<string, unknown>;
|
|
6
10
|
/** It authored: the pages are the space's again. */
|
|
7
11
|
clear: () => void;
|
|
8
12
|
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { LIVE_PAGES_PATH } from "../../core/http/stages/livePages.js";
|
|
2
2
|
import { escapeHtml } from "../../helpers/escapeHtml.js";
|
|
3
|
+
import { SPACE_FAILURE_META } from "@plitzi/sdk-shared/devTools";
|
|
3
4
|
//#region src/hosts/project/spaceFailure.ts
|
|
4
5
|
/**
|
|
5
6
|
* The page a project's server answers with while its space does not author — while developing only.
|
|
@@ -15,6 +16,7 @@ var pageOf = (message) => `<!doctype html>
|
|
|
15
16
|
<head>
|
|
16
17
|
<meta charset="utf-8">
|
|
17
18
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
19
|
+
<meta name="${SPACE_FAILURE_META}" content="1">
|
|
18
20
|
<title>The space does not author</title>
|
|
19
21
|
<style>
|
|
20
22
|
:root { color-scheme: light dark; }
|
|
@@ -52,6 +54,7 @@ var pageOf = (message) => `<!doctype html>
|
|
|
52
54
|
var asksForPage = (method, accept) => method === "GET" && [accept].flat().some((value) => value?.includes("text/html"));
|
|
53
55
|
var createSpaceFailure = () => {
|
|
54
56
|
let failure;
|
|
57
|
+
let stale;
|
|
55
58
|
const stage = (ctx) => {
|
|
56
59
|
if (failure === void 0 || !asksForPage(ctx.req.method, ctx.req.headers.accept)) return Promise.resolve(false);
|
|
57
60
|
ctx.res.setStatus(503);
|
|
@@ -66,9 +69,16 @@ var createSpaceFailure = () => {
|
|
|
66
69
|
fail: (message) => {
|
|
67
70
|
failure = message;
|
|
68
71
|
},
|
|
72
|
+
/** A save did not author: the last space that did is still served, and this is why it is not the saved one. */
|
|
73
|
+
stale: (message) => {
|
|
74
|
+
stale = message;
|
|
75
|
+
},
|
|
76
|
+
/** What `/health` adds while a save has not authored: why the page is the space as it last authored. */
|
|
77
|
+
health: () => stale === void 0 ? {} : { spaceStale: stale },
|
|
69
78
|
/** It authored: the pages are the space's again. */
|
|
70
79
|
clear: () => {
|
|
71
80
|
failure = void 0;
|
|
81
|
+
stale = void 0;
|
|
72
82
|
}
|
|
73
83
|
};
|
|
74
84
|
};
|
|
@@ -5,10 +5,10 @@ export type AuthoredDocuments = {
|
|
|
5
5
|
style: Style;
|
|
6
6
|
};
|
|
7
7
|
/**
|
|
8
|
-
* A save to the space, while developing: re-authored by the project's
|
|
8
|
+
* A save to the space, while developing: re-authored by the project's `.plitzi/author.ts` in a process of its own — the
|
|
9
9
|
* only way to read every file of it again, which an import never does twice — and handed over IPC (`--ipc`), so
|
|
10
|
-
* `onAuthored` swaps the documents the server serves. What it refuses is printed by the script, and
|
|
11
|
-
* the last space that authored. Saves in quick succession author once; one during a run,
|
|
12
|
-
* what stops watching.
|
|
10
|
+
* `onAuthored` swaps the documents the server serves. What it refuses is printed by the script, and handed to
|
|
11
|
+
* `onRefused`: the page keeps the last space that authored. Saves in quick succession author once; one during a run,
|
|
12
|
+
* once more after it. Answers what stops watching.
|
|
13
13
|
*/
|
|
14
|
-
export declare const watchSpace: (root: string, onAuthored: (documents: AuthoredDocuments) => void) => (() => void);
|
|
14
|
+
export declare const watchSpace: (root: string, onAuthored: (documents: AuthoredDocuments) => void, onRefused: (why: string) => void) => (() => void);
|
|
@@ -15,14 +15,16 @@ var isAuthoredDocuments = (message) => isRecord(message) && isRecord(message.sch
|
|
|
15
15
|
* its declaration — its component is swapped in the open pages by the server itself.
|
|
16
16
|
*/
|
|
17
17
|
var authored = (file) => file !== "main.ts" && !/^(config|actions|connectors|functions|runtime)([\\/]|$)/.test(file) && (!/^plugins([\\/]|$)/.test(file) || path.basename(file) === "declaration.ts");
|
|
18
|
+
/** The most of what a refusing script printed that is kept to say why: its report starts with what matters. */
|
|
19
|
+
var SAID_MOST = 4e3;
|
|
18
20
|
/**
|
|
19
|
-
* A save to the space, while developing: re-authored by the project's
|
|
21
|
+
* A save to the space, while developing: re-authored by the project's `.plitzi/author.ts` in a process of its own — the
|
|
20
22
|
* only way to read every file of it again, which an import never does twice — and handed over IPC (`--ipc`), so
|
|
21
|
-
* `onAuthored` swaps the documents the server serves. What it refuses is printed by the script, and
|
|
22
|
-
* the last space that authored. Saves in quick succession author once; one during a run,
|
|
23
|
-
* what stops watching.
|
|
23
|
+
* `onAuthored` swaps the documents the server serves. What it refuses is printed by the script, and handed to
|
|
24
|
+
* `onRefused`: the page keeps the last space that authored. Saves in quick succession author once; one during a run,
|
|
25
|
+
* once more after it. Answers what stops watching.
|
|
24
26
|
*/
|
|
25
|
-
var watchSpace = (root, onAuthored) => {
|
|
27
|
+
var watchSpace = (root, onAuthored, onRefused) => {
|
|
26
28
|
let timer;
|
|
27
29
|
let running;
|
|
28
30
|
let again = false;
|
|
@@ -34,27 +36,34 @@ var watchSpace = (root, onAuthored) => {
|
|
|
34
36
|
return;
|
|
35
37
|
}
|
|
36
38
|
let documents;
|
|
39
|
+
let said = "";
|
|
37
40
|
const child = spawn(process.execPath, [path.join(root, AUTHOR_FILE), "--ipc"], {
|
|
38
41
|
cwd: root,
|
|
39
42
|
stdio: [
|
|
40
43
|
"inherit",
|
|
41
44
|
"inherit",
|
|
42
|
-
"
|
|
45
|
+
"pipe",
|
|
43
46
|
"ipc"
|
|
44
47
|
]
|
|
45
48
|
});
|
|
46
49
|
running = child;
|
|
50
|
+
child.stderr?.on("data", (chunk) => {
|
|
51
|
+
process.stderr.write(chunk);
|
|
52
|
+
said = `${said}${chunk.toString("utf8")}`.slice(0, SAID_MOST);
|
|
53
|
+
});
|
|
47
54
|
child.on("message", (message) => {
|
|
48
55
|
if (isAuthoredDocuments(message)) documents = message;
|
|
49
56
|
});
|
|
50
57
|
child.on("error", (error) => {
|
|
51
58
|
console.error(`[author] ${AUTHOR_FILE} did not run: ${error.message}`);
|
|
59
|
+
onRefused(`${AUTHOR_FILE} did not run: ${error.message}`);
|
|
52
60
|
});
|
|
53
61
|
child.on("close", (code) => {
|
|
54
62
|
running = void 0;
|
|
55
63
|
if (stopped) return;
|
|
56
64
|
if (code === 0 && documents) onAuthored(documents);
|
|
57
65
|
else if (code === 0) console.error(`[author] ${AUTHOR_FILE} authored the space and handed nothing over: it is older than this server — npx plitzi upgrade files --write`);
|
|
66
|
+
else onRefused(said.trim() || `${AUTHOR_FILE} exited with ${String(code)} and said nothing`);
|
|
58
67
|
if (again) {
|
|
59
68
|
again = false;
|
|
60
69
|
author();
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { consoleLogger, isLogged, logLevelOf, renderLogEvent, serverLog } from "./helpers/serverLog.js";
|
|
2
|
+
import { PREVIEW_TOKEN_PARAM } from "./core/previewToken.js";
|
|
3
|
+
import { createMemoryDraftStore, takeDraftOverride } from "./modules/ssr/preview.js";
|
|
2
4
|
import { fetchConnectorRecords, rebaseMedia, writeConnectorRecord } from "./modules/connectors/engine.js";
|
|
3
5
|
import { createMemoryPubSub } from "./modules/realtime/memoryPubSub.js";
|
|
4
6
|
import { createConnectorResolver } from "./modules/connectors/resolver.js";
|
|
5
7
|
import { resolveRscData } from "./modules/rsc/resolveRscData.js";
|
|
6
8
|
import { loadFunctions, loadFunctionsSource, readFunctionsDir } from "./modules/functions/load.js";
|
|
7
|
-
import { PREVIEW_TOKEN_PARAM } from "./core/previewToken.js";
|
|
8
|
-
import { createMemoryDraftStore, takeDraftOverride } from "./modules/ssr/preview.js";
|
|
9
9
|
import { resolveServices } from "./core/services/resolve.js";
|
|
10
10
|
import { buildHealthPayload, registerHealthCheck } from "./core/health.js";
|
|
11
11
|
import { createServer } from "./core/createServer.js";
|
package/dist/kernel.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { consoleLogger, isLogged, logLevelOf, renderLogEvent, serverLog } from "./helpers/serverLog.js";
|
|
2
2
|
import { assertOutboundAllowed, isBlockedHost } from "./helpers/outboundGuard.js";
|
|
3
|
+
import { PREVIEW_TOKEN_PARAM } from "./core/previewToken.js";
|
|
3
4
|
import { clientIp, parseRequest, readRawBody, requestOrigin } from "./core/requestParser.js";
|
|
4
5
|
import { createHttpServer } from "./core/server/baseServer.js";
|
|
5
|
-
import { PREVIEW_TOKEN_PARAM } from "./core/previewToken.js";
|
|
6
6
|
import { makeHandler } from "./core/http/dispatcher.js";
|
|
7
7
|
import { buildHealthPayload, registerHealthCheck } from "./core/health.js";
|
|
8
8
|
import { healthStage } from "./core/http/stages/health.js";
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { serverLog } from "../../helpers/serverLog.js";
|
|
2
|
+
import { privateOriginsOf } from "../../helpers/outboundGuard.js";
|
|
2
3
|
import { writeConnectorRecord } from "../connectors/engine.js";
|
|
3
4
|
//#region src/modules/actions/connectorWrite.ts
|
|
4
5
|
var parseBody = (body) => {
|
|
@@ -66,7 +67,8 @@ var handleAction = async (req, res, config, lookups) => {
|
|
|
66
67
|
resource,
|
|
67
68
|
recordId: body.recordId,
|
|
68
69
|
values: body.values,
|
|
69
|
-
fetchImpl: lookups.fetchImpl
|
|
70
|
+
fetchImpl: lookups.fetchImpl,
|
|
71
|
+
outbound: { privateOrigins: privateOriginsOf(config.outbound?.privateOrigins) }
|
|
70
72
|
});
|
|
71
73
|
res.setStatus(200);
|
|
72
74
|
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
@@ -4,11 +4,11 @@ import "./jobs/scheduler.js";
|
|
|
4
4
|
import "./runtime/errors.js";
|
|
5
5
|
import "./jobs/worker.js";
|
|
6
6
|
import { fleetStore } from "../../core/server/fleet/link.js";
|
|
7
|
+
import { KV_METHODS, createMemoryKv } from "./runtime/memoryKv.js";
|
|
7
8
|
import { createActionJobs } from "./jobs/index.js";
|
|
8
9
|
import { createRunGuards } from "./runtime/guards.js";
|
|
9
10
|
import { createKvStore } from "./runtime/kvStore.js";
|
|
10
11
|
import { resolveLimits } from "./runtime/limits.js";
|
|
11
|
-
import { KV_METHODS, createMemoryKv } from "./runtime/memoryKv.js";
|
|
12
12
|
import { namespaceKv, spaceKvPatterns } from "./runtime/namespaceKv.js";
|
|
13
13
|
import "./runtime/precheck.js";
|
|
14
14
|
import { createActionRunner } from "./runtime/runAction.js";
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { JobQueue } from '@plitzi/sdk-shared';
|
|
2
|
+
export type FileJobQueueOptions = {
|
|
3
|
+
/** The JSON file the queue lives in — created, with its folder, on the first change. */
|
|
4
|
+
file: string;
|
|
5
|
+
/** Who holds it, said to a second process that tries: `the server of "acme", on port 8080`. */
|
|
6
|
+
owner?: string;
|
|
7
|
+
/** Where the process that holds it answers, for a second one to be pointed there: `http://localhost:8080`. */
|
|
8
|
+
serves?: string;
|
|
9
|
+
/** How many finished jobs to keep before the oldest are dropped. Default 500. */
|
|
10
|
+
retainFinished?: number;
|
|
11
|
+
/** What the queue calls now, in epoch ms. */
|
|
12
|
+
clock?: () => number;
|
|
13
|
+
};
|
|
14
|
+
export type FileJobQueue = JobQueue & {
|
|
15
|
+
/** Resolves once everything changed so far is on disk: for a shutdown, or a test that reads the file. */
|
|
16
|
+
flush: () => Promise<void>;
|
|
17
|
+
/** Writes what is pending and lets go of the file, for the next process to take. */
|
|
18
|
+
close: () => Promise<void>;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The job queue in one JSON file: what `ctx.later`, a schedule's fires and a function's jobs wait in, surviving a
|
|
22
|
+
* restart — for a deployment with no database. A job due while the server was down runs once it is back; one a worker
|
|
23
|
+
* held when it went down is taken again, its attempt written `lost`.
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* createServer({ action: { jobs: { queue: createFileJobQueue({ file: 'state/jobs.json' }) } } });
|
|
27
|
+
* ```
|
|
28
|
+
*
|
|
29
|
+
* The rules are the in-process queue's, to the letter (`queueRules`): the file is only where its state is kept, written
|
|
30
|
+
* whole after each change that changed something, as `createFileKv` writes its own. ONE process holds the file
|
|
31
|
+
* (`<file>.lock`); the workers of one server reach the primary's through the fleet (`fleetJobQueue`); replicas share
|
|
32
|
+
* `createSqliteJobQueue` (`@plitzi/sdk-server/sqlite`) or a database's queue.
|
|
33
|
+
*/
|
|
34
|
+
export declare const createFileJobQueue: ({ file, owner, serves, retainFinished, clock }: FileJobQueueOptions) => FileJobQueue;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { applyRule, changedBy, emptyState, queueOver, queueRules } from "./queueRules.js";
|
|
2
|
+
import { documentOf, stateOf } from "./queueDocument.js";
|
|
3
|
+
import { documentWriter, holdFile, letGo } from "../../../helpers/fileStore.js";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
//#region src/modules/actions/jobs/fileQueue.ts
|
|
6
|
+
var load = (file) => {
|
|
7
|
+
if (!fs.existsSync(file)) return emptyState();
|
|
8
|
+
const refuse = (why) => /* @__PURE__ */ new Error(`createFileJobQueue: ${file} is not a queue it wrote (${why}). Move it aside, or point \`file\` elsewhere.`);
|
|
9
|
+
let parsed;
|
|
10
|
+
try {
|
|
11
|
+
parsed = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
12
|
+
} catch (error) {
|
|
13
|
+
throw refuse(error instanceof Error ? error.message : String(error));
|
|
14
|
+
}
|
|
15
|
+
const state = stateOf(parsed);
|
|
16
|
+
if (typeof state === "string") throw refuse(state);
|
|
17
|
+
return state;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The job queue in one JSON file: what `ctx.later`, a schedule's fires and a function's jobs wait in, surviving a
|
|
21
|
+
* restart — for a deployment with no database. A job due while the server was down runs once it is back; one a worker
|
|
22
|
+
* held when it went down is taken again, its attempt written `lost`.
|
|
23
|
+
*
|
|
24
|
+
* ```ts
|
|
25
|
+
* createServer({ action: { jobs: { queue: createFileJobQueue({ file: 'state/jobs.json' }) } } });
|
|
26
|
+
* ```
|
|
27
|
+
*
|
|
28
|
+
* The rules are the in-process queue's, to the letter (`queueRules`): the file is only where its state is kept, written
|
|
29
|
+
* whole after each change that changed something, as `createFileKv` writes its own. ONE process holds the file
|
|
30
|
+
* (`<file>.lock`); the workers of one server reach the primary's through the fleet (`fleetJobQueue`); replicas share
|
|
31
|
+
* `createSqliteJobQueue` (`@plitzi/sdk-server/sqlite`) or a database's queue.
|
|
32
|
+
*/
|
|
33
|
+
var createFileJobQueue = ({ file, owner, serves, retainFinished = 500, clock = Date.now }) => {
|
|
34
|
+
const lock = holdFile(file, {
|
|
35
|
+
owner,
|
|
36
|
+
serves
|
|
37
|
+
}, "createFileJobQueue");
|
|
38
|
+
let state;
|
|
39
|
+
try {
|
|
40
|
+
state = load(file);
|
|
41
|
+
} catch (error) {
|
|
42
|
+
letGo(lock);
|
|
43
|
+
throw error;
|
|
44
|
+
}
|
|
45
|
+
const rules = queueRules(state, {
|
|
46
|
+
retainFinished,
|
|
47
|
+
clock
|
|
48
|
+
});
|
|
49
|
+
const { changed, flush } = documentWriter({
|
|
50
|
+
file,
|
|
51
|
+
document: () => `${JSON.stringify(documentOf(state), null, 2)}\n`,
|
|
52
|
+
store: "createFileJobQueue",
|
|
53
|
+
what: "job queue file"
|
|
54
|
+
});
|
|
55
|
+
return {
|
|
56
|
+
...queueOver((method, args) => {
|
|
57
|
+
const answer = applyRule(rules, method, args);
|
|
58
|
+
if (changedBy(method, answer)) changed();
|
|
59
|
+
return Promise.resolve(answer);
|
|
60
|
+
}),
|
|
61
|
+
flush,
|
|
62
|
+
close: async () => {
|
|
63
|
+
try {
|
|
64
|
+
await flush();
|
|
65
|
+
} finally {
|
|
66
|
+
letGo(lock);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
//#endregion
|
|
72
|
+
export { createFileJobQueue };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createMemoryJobQueue } from "./memoryQueue.js";
|
|
2
2
|
import { DEFAULT_MAX_ATTEMPTS, scheduleFor, scheduleJobId, schedulesFor } from "./schedules.js";
|
|
3
3
|
import { createScheduler } from "./scheduler.js";
|
|
4
4
|
import { createJobWorker } from "./worker.js";
|
|
5
|
-
import {
|
|
5
|
+
import { fleetJobQueue } from "../../../core/server/fleet/stores.js";
|
|
6
6
|
//#region src/modules/actions/jobs/index.ts
|
|
7
7
|
/**
|
|
8
8
|
* The scheduling half of actions: a producer, a consumer and the store they meet in.
|
|
@@ -18,7 +18,7 @@ import { fleetStore } from "../../../core/server/fleet/link.js";
|
|
|
18
18
|
* the primary's queue, and only one of them runs the scheduler and the jobs (`runsFleetJobs`).
|
|
19
19
|
*/
|
|
20
20
|
var createActionJobs = (config, module, lookups, functionJobs) => {
|
|
21
|
-
const queue = config.queue ??
|
|
21
|
+
const queue = config.queue ?? fleetJobQueue(() => createMemoryJobQueue());
|
|
22
22
|
const { produce = true, workers = 4 } = config;
|
|
23
23
|
const scheduler = createScheduler({
|
|
24
24
|
queue,
|