@webiny/api-composition-standalone 0.0.0-unstable.48a4e5b6c1 → 0.0.0-unstable.676006d08e
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/config/EnvStandaloneConfig.d.ts +23 -0
- package/config/EnvStandaloneConfig.js +70 -0
- package/config/EnvStandaloneConfig.js.map +1 -0
- package/createWebinyApiHandler.js +2 -2
- package/createWebinyApiHandler.js.map +1 -1
- package/package.json +16 -16
- package/config/readStandaloneConfig.d.ts +0 -12
- package/config/readStandaloneConfig.js +0 -56
- package/config/readStandaloneConfig.js.map +0 -1
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { PublicUrl } from "@webiny/api-core/features/publicUrls/index.js";
|
|
2
|
+
import type { StandaloneConfig } from "./abstractions.js";
|
|
3
|
+
type Env = Record<string, string | undefined>;
|
|
4
|
+
/**
|
|
5
|
+
* The standalone API's settings, read from env. `fromEnv` throws one error naming every missing or
|
|
6
|
+
* invalid variable, so a misconfigured container fails at boot instead of on the first upload or login.
|
|
7
|
+
*
|
|
8
|
+
* Nothing falls back to a default: `webiny watch` and `webiny serve` get their values from
|
|
9
|
+
* `<Infra.ApiUrl>`, `<Infra.AdminUrl>`, `<Infra.FileStorage.*>` and `<Infra.Crypto.*>` in
|
|
10
|
+
* webiny.config, and a deployed container must set them explicitly.
|
|
11
|
+
*/
|
|
12
|
+
export declare class EnvStandaloneConfig implements StandaloneConfig.Interface {
|
|
13
|
+
readonly apiUrl: PublicUrl;
|
|
14
|
+
readonly adminUrl: PublicUrl;
|
|
15
|
+
readonly fileStorage: StandaloneConfig.Interface["fileStorage"];
|
|
16
|
+
readonly encryption: StandaloneConfig.Interface["encryption"];
|
|
17
|
+
readonly hashing: StandaloneConfig.Interface["hashing"];
|
|
18
|
+
readonly redisUrl: string | undefined;
|
|
19
|
+
readonly keepAliveTimeoutMs: number | undefined;
|
|
20
|
+
private constructor();
|
|
21
|
+
static fromEnv(env: Env): EnvStandaloneConfig;
|
|
22
|
+
}
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { PublicUrl } from "@webiny/api-core/features/publicUrls/index.js";
|
|
2
|
+
const ENV = {
|
|
3
|
+
apiUrl: "WEBINY_API_URL",
|
|
4
|
+
adminUrl: "WEBINY_ADMIN_URL",
|
|
5
|
+
uploadSecret: "WEBINY_UPLOAD_SECRET",
|
|
6
|
+
encryptionPassphrase: "WEBINY_ENCRYPTION_PASSPHRASE",
|
|
7
|
+
encryptionSalt: "WEBINY_ENCRYPTION_SALT",
|
|
8
|
+
hashingPepper: "WEBINY_HASHING_PEPPER",
|
|
9
|
+
redisUrl: "WEBINY_REDIS_URL",
|
|
10
|
+
keepAliveTimeout: "WEBINY_KEEP_ALIVE_TIMEOUT_MS"
|
|
11
|
+
};
|
|
12
|
+
function read(env, name) {
|
|
13
|
+
return env[name]?.trim() ?? "";
|
|
14
|
+
}
|
|
15
|
+
function readSecret(env, name) {
|
|
16
|
+
const value = env[name] ?? "";
|
|
17
|
+
return value.trim() ? value : "";
|
|
18
|
+
}
|
|
19
|
+
class EnvStandaloneConfig {
|
|
20
|
+
constructor(apiUrl, adminUrl, fileStorage, encryption, hashing, redisUrl, keepAliveTimeoutMs){
|
|
21
|
+
this.apiUrl = apiUrl;
|
|
22
|
+
this.adminUrl = adminUrl;
|
|
23
|
+
this.fileStorage = fileStorage;
|
|
24
|
+
this.encryption = encryption;
|
|
25
|
+
this.hashing = hashing;
|
|
26
|
+
this.redisUrl = redisUrl;
|
|
27
|
+
this.keepAliveTimeoutMs = keepAliveTimeoutMs;
|
|
28
|
+
}
|
|
29
|
+
static fromEnv(env) {
|
|
30
|
+
const problems = [];
|
|
31
|
+
const apiUrlValue = read(env, ENV.apiUrl);
|
|
32
|
+
const apiUrl = PublicUrl.from(apiUrlValue);
|
|
33
|
+
if (apiUrlValue) {
|
|
34
|
+
if (!apiUrl.isKnown()) problems.push(`${ENV.apiUrl} is not an absolute http(s) URL: "${apiUrlValue}".`);
|
|
35
|
+
} else problems.push(`${ENV.apiUrl} is not set.`);
|
|
36
|
+
const adminUrlValue = read(env, ENV.adminUrl);
|
|
37
|
+
const adminUrl = PublicUrl.from(adminUrlValue);
|
|
38
|
+
if (adminUrlValue && !adminUrl.isKnown()) problems.push(`${ENV.adminUrl} is not an absolute http(s) URL: "${adminUrlValue}".`);
|
|
39
|
+
const uploadSecret = readSecret(env, ENV.uploadSecret);
|
|
40
|
+
if (!uploadSecret) problems.push(`${ENV.uploadSecret} is not set.`);
|
|
41
|
+
const encryptionPassphrase = readSecret(env, ENV.encryptionPassphrase);
|
|
42
|
+
if (!encryptionPassphrase) problems.push(`${ENV.encryptionPassphrase} is not set.`);
|
|
43
|
+
const hashingPepper = readSecret(env, ENV.hashingPepper);
|
|
44
|
+
if (!hashingPepper) problems.push(`${ENV.hashingPepper} is not set.`);
|
|
45
|
+
const redisUrl = read(env, ENV.redisUrl);
|
|
46
|
+
if (redisUrl && !/^rediss?:\/\//.test(redisUrl)) problems.push(`${ENV.redisUrl} must start with redis:// or rediss://.`);
|
|
47
|
+
const keepAliveTimeoutValue = read(env, ENV.keepAliveTimeout);
|
|
48
|
+
const keepAliveTimeoutMs = keepAliveTimeoutValue ? Number(keepAliveTimeoutValue) : void 0;
|
|
49
|
+
if (void 0 !== keepAliveTimeoutMs && (!Number.isInteger(keepAliveTimeoutMs) || keepAliveTimeoutMs <= 0)) problems.push(`${ENV.keepAliveTimeout} must be a positive whole number of milliseconds: "${keepAliveTimeoutValue}".`);
|
|
50
|
+
if (problems.length > 0) {
|
|
51
|
+
const message = [
|
|
52
|
+
"The standalone API is missing required configuration:",
|
|
53
|
+
...problems
|
|
54
|
+
].join("\n ");
|
|
55
|
+
throw new Error(message);
|
|
56
|
+
}
|
|
57
|
+
const encryptionSalt = readSecret(env, ENV.encryptionSalt);
|
|
58
|
+
return new EnvStandaloneConfig(apiUrl, adminUrl, {
|
|
59
|
+
uploadSecret
|
|
60
|
+
}, {
|
|
61
|
+
passphrase: encryptionPassphrase,
|
|
62
|
+
salt: encryptionSalt
|
|
63
|
+
}, {
|
|
64
|
+
pepper: hashingPepper
|
|
65
|
+
}, redisUrl || void 0, keepAliveTimeoutMs);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
export { EnvStandaloneConfig };
|
|
69
|
+
|
|
70
|
+
//# sourceMappingURL=EnvStandaloneConfig.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"config/EnvStandaloneConfig.js","sources":["../../src/config/EnvStandaloneConfig.ts"],"sourcesContent":["import { PublicUrl } from \"@webiny/api-core/features/publicUrls/index.js\";\nimport type { StandaloneConfig } from \"./abstractions.js\";\n\ntype Env = Record<string, string | undefined>;\n\n/**\n * The variables read into this config: the settings only a standalone API has. Variables a package\n * also reads on AWS (storage, database, request body limit, log level, ...) stay in that package.\n */\nconst ENV = {\n apiUrl: \"WEBINY_API_URL\",\n adminUrl: \"WEBINY_ADMIN_URL\",\n uploadSecret: \"WEBINY_UPLOAD_SECRET\",\n encryptionPassphrase: \"WEBINY_ENCRYPTION_PASSPHRASE\",\n encryptionSalt: \"WEBINY_ENCRYPTION_SALT\",\n hashingPepper: \"WEBINY_HASHING_PEPPER\",\n redisUrl: \"WEBINY_REDIS_URL\",\n keepAliveTimeout: \"WEBINY_KEEP_ALIVE_TIMEOUT_MS\"\n} as const;\n\nfunction read(env: Env, name: string): string {\n return env[name]?.trim() ?? \"\";\n}\n\n/**\n * Secrets are used exactly as given: trimming would change the derived key or signature, so a value\n * with surrounding whitespace would no longer match what was encrypted, hashed or signed with it.\n * A blank value counts as unset.\n */\nfunction readSecret(env: Env, name: string): string {\n const value = env[name] ?? \"\";\n return value.trim() ? value : \"\";\n}\n\n/**\n * The standalone API's settings, read from env. `fromEnv` throws one error naming every missing or\n * invalid variable, so a misconfigured container fails at boot instead of on the first upload or login.\n *\n * Nothing falls back to a default: `webiny watch` and `webiny serve` get their values from\n * `<Infra.ApiUrl>`, `<Infra.AdminUrl>`, `<Infra.FileStorage.*>` and `<Infra.Crypto.*>` in\n * webiny.config, and a deployed container must set them explicitly.\n */\nexport class EnvStandaloneConfig implements StandaloneConfig.Interface {\n private constructor(\n readonly apiUrl: PublicUrl,\n readonly adminUrl: PublicUrl,\n readonly fileStorage: StandaloneConfig.Interface[\"fileStorage\"],\n readonly encryption: StandaloneConfig.Interface[\"encryption\"],\n readonly hashing: StandaloneConfig.Interface[\"hashing\"],\n readonly redisUrl: string | undefined,\n readonly keepAliveTimeoutMs: number | undefined\n ) {}\n\n static fromEnv(env: Env): EnvStandaloneConfig {\n const problems: string[] = [];\n\n const apiUrlValue = read(env, ENV.apiUrl);\n const apiUrl = PublicUrl.from(apiUrlValue);\n if (!apiUrlValue) {\n problems.push(`${ENV.apiUrl} is not set.`);\n } else if (!apiUrl.isKnown()) {\n problems.push(`${ENV.apiUrl} is not an absolute http(s) URL: \"${apiUrlValue}\".`);\n }\n\n const adminUrlValue = read(env, ENV.adminUrl);\n const adminUrl = PublicUrl.from(adminUrlValue);\n if (adminUrlValue && !adminUrl.isKnown()) {\n problems.push(`${ENV.adminUrl} is not an absolute http(s) URL: \"${adminUrlValue}\".`);\n }\n\n const uploadSecret = readSecret(env, ENV.uploadSecret);\n if (!uploadSecret) {\n problems.push(`${ENV.uploadSecret} is not set.`);\n }\n\n /*\n * Always required: a standalone project always encrypts and always peppers its hashes. There is\n * no deploy step that could check this for production, so it is checked here for every start.\n */\n const encryptionPassphrase = readSecret(env, ENV.encryptionPassphrase);\n if (!encryptionPassphrase) {\n problems.push(`${ENV.encryptionPassphrase} is not set.`);\n }\n\n const hashingPepper = readSecret(env, ENV.hashingPepper);\n if (!hashingPepper) {\n problems.push(`${ENV.hashingPepper} is not set.`);\n }\n\n // The value may hold a password, so the error does not repeat it.\n const redisUrl = read(env, ENV.redisUrl);\n if (redisUrl && !/^rediss?:\\/\\//.test(redisUrl)) {\n problems.push(`${ENV.redisUrl} must start with redis:// or rediss://.`);\n }\n\n // Unset leaves the timeout to the server's default (65 s, in `createServerHandler`).\n const keepAliveTimeoutValue = read(env, ENV.keepAliveTimeout);\n const keepAliveTimeoutMs = keepAliveTimeoutValue\n ? Number(keepAliveTimeoutValue)\n : undefined;\n if (\n keepAliveTimeoutMs !== undefined &&\n (!Number.isInteger(keepAliveTimeoutMs) || keepAliveTimeoutMs <= 0)\n ) {\n problems.push(\n `${ENV.keepAliveTimeout} must be a positive whole number of milliseconds: \"${keepAliveTimeoutValue}\".`\n );\n }\n\n if (problems.length > 0) {\n const message = [\n \"The standalone API is missing required configuration:\",\n ...problems\n ].join(\"\\n \");\n throw new Error(message);\n }\n\n const encryptionSalt = readSecret(env, ENV.encryptionSalt);\n\n return new EnvStandaloneConfig(\n apiUrl,\n adminUrl,\n { uploadSecret },\n { passphrase: encryptionPassphrase, salt: encryptionSalt },\n { pepper: hashingPepper },\n redisUrl || undefined,\n keepAliveTimeoutMs\n );\n }\n}\n"],"names":["ENV","read","env","name","readSecret","value","EnvStandaloneConfig","apiUrl","adminUrl","fileStorage","encryption","hashing","redisUrl","keepAliveTimeoutMs","problems","apiUrlValue","PublicUrl","adminUrlValue","uploadSecret","encryptionPassphrase","hashingPepper","keepAliveTimeoutValue","Number","undefined","message","Error","encryptionSalt"],"mappings":";AASA,MAAMA,MAAM;IACR,QAAQ;IACR,UAAU;IACV,cAAc;IACd,sBAAsB;IACtB,gBAAgB;IAChB,eAAe;IACf,UAAU;IACV,kBAAkB;AACtB;AAEA,SAASC,KAAKC,GAAQ,EAAEC,IAAY;IAChC,OAAOD,GAAG,CAACC,KAAK,EAAE,UAAU;AAChC;AAOA,SAASC,WAAWF,GAAQ,EAAEC,IAAY;IACtC,MAAME,QAAQH,GAAG,CAACC,KAAK,IAAI;IAC3B,OAAOE,MAAM,IAAI,KAAKA,QAAQ;AAClC;AAUO,MAAMC;IACT,YACaC,MAAiB,EACjBC,QAAmB,EACnBC,WAAsD,EACtDC,UAAoD,EACpDC,OAA8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BAAgB,IAAI,CAACA,WAClCE,SAAS,IAAI,CAAC,GAAGd,IAAI,QAAQ,CAAC,uCAAuC,CAAC;QAI1E,MAAMqB,wBAAwBpB,KAAKC,KAAKF,IAAI,gBAAgB;QAC5D,MAAMa,qBAAqBQ,wBACrBC,OAAOD,yBACPE;QACN,IACIV,AAAuBU,WAAvBV,sBACC,EAACS,OAAO,SAAS,CAACT,uBAAuBA,sBAAsB,IAEhEC,SAAS,IAAI,CACT,GAAGd,IAAI,gBAAgB,CAAC,mDAAmD,EAAEqB,sBAAsB,EAAE,CAAC;QAI9G,IAAIP,SAAS,MAAM,GAAG,GAAG;YACrB,MAAMU,UAAU;gBACZ;mBACGV;aACN,CAAC,IAAI,CAAC;YACP,MAAM,IAAIW,MAAMD;QACpB;QAEA,MAAME,iBAAiBtB,WAAWF,KAAKF,IAAI,cAAc;QAEzD,OAAO,IAAIM,oBACPC,QACAC,UACA;YAAEU;QAAa,GACf;YAAE,YAAYC;YAAsB,MAAMO;QAAe,GACzD;YAAE,QAAQN;QAAc,GACxBR,YAAYW,QACZV;IAER;AACJ"}
|
|
@@ -15,7 +15,7 @@ import { createWebsocketsAuthenticator } from "./websockets/createWebsocketsAuth
|
|
|
15
15
|
import { EmptyTrashBinsFeature } from "@webiny/api-headless-cms-bulk-actions-standalone";
|
|
16
16
|
import { ConfigPublicUrlsFeature } from "./publicUrls/feature.js";
|
|
17
17
|
import { StandaloneConfig } from "./config/abstractions.js";
|
|
18
|
-
import {
|
|
18
|
+
import { EnvStandaloneConfig } from "./config/EnvStandaloneConfig.js";
|
|
19
19
|
import { assertNoBakedSecrets } from "./config/bakedSecrets.js";
|
|
20
20
|
import { assertFileStorage } from "./config/assertFileStorage.js";
|
|
21
21
|
import { StandaloneCryptoConfigFeature } from "./crypto/feature.js";
|
|
@@ -27,7 +27,7 @@ function createWebinyApiHandler(config) {
|
|
|
27
27
|
let stopScheduler;
|
|
28
28
|
let stopWebsockets;
|
|
29
29
|
let closeMessageBus;
|
|
30
|
-
const standaloneConfig =
|
|
30
|
+
const standaloneConfig = EnvStandaloneConfig.fromEnv(process.env);
|
|
31
31
|
const logger = createLogger();
|
|
32
32
|
const stackConfig = {
|
|
33
33
|
extensions: config.extensions,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createWebinyApiHandler.js","sources":["../src/createWebinyApiHandler.ts"],"sourcesContent":["/**\n * Webiny API handler for the standalone Node HTTP server transport — storage-agnostic BASE.\n *\n * The ROOT container wires the Node HTTP transport (NodeHttpFeature = event type + router + HttpFeature)\n * plus the auth/tenant loader decorators (extract token / x-tenant from the IncomingMessage → shared\n * RequestIdentityLoader / RequestTenantLoader). The per-request feature stack is the transport-agnostic\n * `registerApiRequestStack` from `@webiny/api-composition-core` — the SAME stack the AWS handler uses.\n * The realtime transport hook installs the server WebSockets transport (vs AWS's API Gateway Management\n * API) with a SINGLE-PROCESS, in-process implementation. Background tasks and the scheduler are\n * ROOT-container singletons (below) — mirroring how the AWS handler registers background tasks at root,\n * and the WebSockets connection manager — rather than per-request transports; the scheduler fires timers\n * in-process (vs AWS's EventBridge). The storage variant (and identity provider) is injected via\n * `registerRootStorage`.\n *\n * The identity provider (e.g. `@webiny/self-hosted-auth`'s JWT IdP) must be registered by the variant\n * in `registerRootStorage`, so the RequestIdentityLoader driven by the identity decorator can resolve it.\n */\nimport { GraphQLSchemaCacheFeature } from \"@webiny/api-graphql\";\nimport { EncryptionKeyCacheFeature } from \"@webiny/api-core/features/encryption/index.js\";\nimport { JwksStoreFeature } from \"@webiny/api-core/idp/index.js\";\nimport type { Container } from \"@webiny/di\";\nimport {\n createServerHandler,\n NodeHttpFeature,\n NodeHttpInputHandler\n} from \"@webiny/api-kernel-core/nodeHttp/index.js\";\nimport { registerHttpTransport } from \"@webiny/api-composition-core\";\nimport { RandomProcessOwner } from \"@webiny/api-kernel-core\";\nimport { registerExtensions } from \"@webiny/handler\";\nimport {\n ApiRequestRegistration,\n registerApiRequestStack,\n registerApiRequestStackInOneContainer,\n type RegisterApiRequestStackConfig\n} from \"@webiny/api-composition-core\";\nimport { TenantScopesRootFeature } from \"@webiny/api-core/features/tenancy/TenantScopes/index.js\";\nimport {\n WebsocketsServerRootFeature,\n WebsocketsStandaloneFeature,\n WebsocketsConnectionManager,\n attachWebsocketsServer\n} from \"@webiny/api-websockets-standalone\";\nimport { WebsocketsServerAdapter } from \"@webiny/api-websockets-standalone\";\nimport { WebsocketsMessageBus } from \"@webiny/api-websockets-standalone\";\nimport { InProcessMessageBus } from \"@webiny/api-websockets-standalone\";\nimport { createBusMessageHandler } from \"@webiny/api-websockets-standalone\";\nimport { WebsocketsRedisFeature } from \"@webiny/api-websockets-standalone-redis\";\nimport { ProcessOwner } from \"@webiny/api-kernel-core\";\nimport { BackgroundTasksStandaloneFeature } from \"@webiny/background-tasks-standalone\";\nimport { startTaskRecovery } from \"@webiny/background-tasks-standalone\";\nimport { stopBackgroundTasks } from \"@webiny/background-tasks-standalone\";\nimport { FileManagerStandaloneFeature } from \"@webiny/api-file-manager-standalone\";\nimport { registerSchedulerServer, startSchedulerServer } from \"~/scheduler/schedulerServer.js\";\nimport { startBulkActionsServer } from \"~/bulkActions/bulkActionsServer.js\";\nimport { createWebsocketsAuthenticator } from \"~/websockets/createWebsocketsAuthenticator.js\";\nimport { EmptyTrashBinsFeature } from \"@webiny/api-headless-cms-bulk-actions-standalone\";\nimport { ConfigPublicUrlsFeature } from \"~/publicUrls/feature.js\";\nimport { StandaloneConfig } from \"~/config/abstractions.js\";\nimport { readStandaloneConfig } from \"~/config/readStandaloneConfig.js\";\nimport type { BuildParams } from \"@webiny/api-core/features/buildParams/index.js\";\nimport { assertNoBakedSecrets } from \"~/config/bakedSecrets.js\";\nimport { assertFileStorage } from \"~/config/assertFileStorage.js\";\nimport { StandaloneCryptoConfigFeature } from \"~/crypto/feature.js\";\nimport {\n createLogger,\n registerRootAllowedRequestHeaders,\n registerRootBuildParams\n} from \"@webiny/api-composition-core\";\nimport { Logger } from \"@webiny/api-core/features/logger/index.js\";\nimport { guardDeclaredTenantStorages } from \"~/tenantStorages/guardDeclaredTenantStorages.js\";\n\nexport interface CreateWebinyApiHandlerConfig {\n /**\n * Project-defined extensions, applied at register() time.\n */\n extensions: () => Parameters<typeof registerExtensions>[1];\n /**\n * Register the storage for this deployment AND the identity provider in the root container.\n * Unlike the AWS base, the server base bakes in no DB or IdP assumption — the variant supplies\n * the complete storage + auth wiring. A storage that registers per request puts only its\n * connection and a `RequestStorage` in the root (see `registerApiRequestStack`). `buildParams`\n * are the build params the project was built with (requests register their own copy).\n */\n registerRootStorage: (\n container: Container,\n params: { buildParams: BuildParams.Interface }\n ) => void | Promise<void>;\n}\n\n/*\n * The part of the 8 seconds a shutdown gets that running tasks and scheduled actions may spend\n * finishing or handing back; both wait at the same time. The rest leaves room to exit before a\n * process manager loses patience.\n */\nconst SHUTDOWN_WAIT_MS = 6000;\n\nexport function createWebinyApiHandler(config: CreateWebinyApiHandlerConfig) {\n let stopTaskRecovery: (() => void) | undefined;\n let stopScheduler: ((timeoutMs: number) => Promise<void>) | undefined;\n let stopWebsockets: (() => Promise<void>) | undefined;\n let closeMessageBus: (() => Promise<void>) | undefined;\n\n /*\n * Deployment-specific settings (public URLs, file storage, secrets) come from env, read once here\n * so a missing value stops the server at boot. Nothing deployment-specific is baked into the build.\n */\n const standaloneConfig = readStandaloneConfig(process.env);\n\n // One per process, to stdout. The root singletons below log through it, and so does every request.\n const logger = createLogger();\n\n /*\n * The transport-agnostic request stack, with the server's adapters. Every request's container\n * gets its tenant-neutral part (`child`), and each tenant scope of the request the rest. In one\n * container, it is also in the root as `ApiRequestRegistration`, for work outside a request that\n * needs a container a request would have: the SQL schema setup builds one on its own connection.\n */\n const stackConfig: RegisterApiRequestStackConfig = {\n extensions: config.extensions,\n // Why hooks (and not just registering the transports ourselves): `.register()` calls\n // are otherwise order-independent — you can register Features in any order, because\n // they only REGISTER, they don't RESOLVE during registration (resolution happens\n // later, in Initializers / SchemaFactories). The one thing that makes order matter is\n // a DEFAULT registration: e.g. `WebsocketsFeature` registers `NullWebsocketsTransport`\n // so the abstraction is always resolvable. Overriding it (last-registration-wins) means\n // our transport MUST be registered AFTER that Feature. These hooks are the seams\n // `registerApiRequestStack` provides for exactly that — each runs right after its Null\n // default, so the override is guaranteed without the caller knowing the internal order.\n transports: {\n /*\n * Public URLs and crypto secrets: no deploy step to discover them from, so they\n * come from env (StandaloneConfig, registered on the root).\n */\n hostingConfig: scopeContainer => {\n ConfigPublicUrlsFeature.register(scopeContainer);\n StandaloneCryptoConfigFeature.register(scopeContainer);\n },\n // Server WebSockets transport; resolves the shared connection manager + adapter\n // from the root (registered as singletons in `root`). Scheduler is NOT a per-request\n // transport here — it's a root singleton wired in `root` + `onServer` (see below).\n realtime: scopeContainer => {\n WebsocketsStandaloneFeature.register(scopeContainer);\n },\n /*\n * File-manager storage transport. Where AWS uploads straight to S3 (+ a separate\n * asset-delivery Lambda), the server takes uploads and serves files in-process.\n * FileManagerStandaloneFeature registers asset delivery (overriding the domain's\n * null impls) and the upload/multipart HTTP routes; they store through\n * `ObjectStorage`, which a project extension registers (`<Infra.FileStorage.Disk />`\n * a folder on disk, `<Infra.FileStorage.S3 />` an S3-compatible bucket).\n * `assertFileStorage` has made sure the build has one.\n */\n fileManager: scopeContainer => {\n const { uploadSecret } = standaloneConfig.fileStorage;\n FileManagerStandaloneFeature.register(scopeContainer, { uploadSecret });\n }\n }\n };\n\n return createServerHandler({\n keepAliveTimeoutMs: standaloneConfig.keepAliveTimeoutMs,\n root: async rootContainer => {\n /*\n * Secrets come from env only. A build that bakes one (the shared <Infra.Crypto.*> from\n * @webiny/project) is refused here, before the server accepts a request.\n */\n // Build params come from the deploy, the same for every request and tenant: they live in\n // the root, and every request container and tenant scope reads them from here.\n const buildParams = await registerRootBuildParams(rootContainer, config.extensions());\n assertNoBakedSecrets(buildParams);\n assertFileStorage(buildParams);\n\n rootContainer.registerInstance(StandaloneConfig, standaloneConfig);\n rootContainer.registerInstance(Logger, logger);\n\n // Names this process in shared storage: task claims and websocket connections.\n rootContainer.register(RandomProcessOwner).inSingletonScope();\n\n // ── Transport (Node HTTP) ──────────────────────────────────\n // NodeHttpFeature registers the event type + HttpFeature (router) + the routing terminal.\n // registerHttpTransport also registers the tenant, identity and preview-as loading, and the\n // hand-off of each request into its tenant's scope once CORS and the tenant step are done.\n registerHttpTransport(rootContainer, NodeHttpFeature, NodeHttpInputHandler);\n\n // Every other event's handler chain runs in its tenant's scope: a background task or\n // scheduled action in the tenant of its payload, anything else as the root tenant.\n TenantScopesRootFeature.register(rootContainer);\n\n rootContainer.registerInstance(ApiRequestRegistration, {\n register: (container, options) => {\n return registerApiRequestStackInOneContainer(container, stackConfig, options);\n }\n });\n\n // ── Storage + identity provider (variant-supplied) ─────────\n await config.registerRootStorage(rootContainer, { buildParams });\n\n // ── WebSockets transport (root) ────────────────────────────\n // The live sockets, the connection manager and the adapter live in the root as\n // singletons, shared between the upgrade acceptor (attachWebsocketsServer, below) and the\n // per-request ServerWebsocketsTransport that sends to those live sockets. The connections'\n // rows (ConnectionRegistry) are a storage, so they live in request containers: the\n // manager changes them by dispatching an event, which runs in a fresh one.\n WebsocketsServerRootFeature.register(rootContainer);\n\n /*\n * How a send reaches a socket another API process holds. Without a Redis URL there is\n * one process, and every socket is in it.\n */\n if (standaloneConfig.redisUrl) {\n WebsocketsRedisFeature.register(rootContainer, {\n url: standaloneConfig.redisUrl,\n logger\n });\n } else {\n rootContainer.register(InProcessMessageBus).inSingletonScope();\n }\n\n // ── GraphQL schema cache (root) ────────────────────────────\n // Root, so a built schema outlives the request that built it.\n GraphQLSchemaCacheFeature.register(rootContainer);\n\n // ── Encryption key cache (root) ────────────────────────────\n // Root, so the scrypt-derived key is computed once per process instead of per request.\n EncryptionKeyCacheFeature.register(rootContainer);\n // Root, so identity providers' signing keys are fetched once per process, not per request.\n JwksStoreFeature.register(rootContainer);\n\n // ── Background tasks (root) ────────────────────────────────\n // Mirrors the AWS handler registering its background-task transport at root. Where AWS\n // has Step Functions invoke the Lambda once per iteration, a root task loop dispatches a\n // BackgroundTaskEvent per iteration through the InputDispatcher (registered by\n // createServerHandler), and each one runs in a fresh request container.\n BackgroundTasksStandaloneFeature.register(rootContainer);\n\n // ── Scheduler (root) ───────────────────────────────────────\n // The scheduler is a single long-lived instance for ALL tenants, started once at boot\n // (onServer, below) — the counterpart of the WebSockets connection manager, NOT a per-request\n // transport. Registered here as SchedulerService (per-request create/update/delete during\n // mutations manipulate this one live timer set) plus the run/recover event handlers. When a\n // timer fires (outside any request) it dispatches a ScheduledActionEvent, handled in a fresh\n // request container by the same handler AWS uses.\n registerSchedulerServer(rootContainer);\n\n // ── Bulk actions (root) ───────────────────────────────────\n // Registers the EmptyTrashBinsEvent handler that the periodic trigger\n // (startBulkActionsServer, onServer below) dispatches.\n EmptyTrashBinsFeature.register(rootContainer);\n\n // ── CORS allowed headers (root) ────────────────────────────\n // The request headers extensions allow in the CORS preflight: read once, at start, for\n // the CORS step, which runs at request level, before any tenant scope (where extensions\n // register). Last: it registers what a request has, the extensions included, in a\n // throwaway container.\n await registerRootAllowedRequestHeaders(rootContainer);\n\n // ── Declared storages (root) ───────────────────────────────\n // Refuses to start when an extra storage that wasn't retired was removed from the\n // config: tenants may still run on it. Needs a request's services, so it runs last.\n await guardDeclaredTenantStorages({\n root: rootContainer,\n registerRequest: container => registerApiRequestStack(container, stackConfig)\n });\n },\n\n child: async container => {\n await registerApiRequestStack(container, stackConfig);\n },\n\n onServer: async (server, rootContainer) => {\n // Attach the WebSockets upgrade handler to the running HTTP server, backed by the shared\n // (root) connection manager so request-time sends reach the live sockets.\n //\n // Authenticate each WebSocket connection from its `?token` JWT so it's registered under\n // the real identity (targeted server→client sends match by identity id). It's a callback\n // the handler supplies rather than something the WS server resolves itself — see\n // createWebsocketsAuthenticator for why (AuthenticationContext is per-request, unreachable\n // from the root container the WS server is attached to).\n const connectionManager = rootContainer.resolve(WebsocketsConnectionManager);\n const adapter = rootContainer.resolve(WebsocketsServerAdapter);\n const websockets = attachWebsocketsServer({\n server,\n connectionManager,\n adapter,\n authenticate: createWebsocketsAuthenticator(rootContainer, config.extensions)\n });\n await websockets.start();\n stopWebsockets = () => websockets.stop();\n\n // Receive sends and disconnects other API processes publish for this one's sockets.\n const messageBus = rootContainer.resolve(WebsocketsMessageBus);\n const processOwner = rootContainer.resolve(ProcessOwner);\n const handleBusMessage = createBusMessageHandler({\n connectionManager,\n adapter,\n logger\n });\n await messageBus.subscribe(processOwner.id, handleBusMessage);\n closeMessageBus = () => messageBus.close();\n logger.info(\n { messageBus: standaloneConfig.redisUrl ? \"redis\" : \"in-process\" },\n \"[websockets] using message bus\"\n );\n\n /*\n * Start the in-process scheduler timers, then re-arm persisted schedules in the\n * background, at boot and then every minute (see startSchedulerServer).\n */\n stopScheduler = await startSchedulerServer(rootContainer);\n\n // Start the periodic empty-trash-bin trigger.\n startBulkActionsServer(rootContainer);\n\n /*\n * Take over tasks a restart or another process left behind, at boot and then every\n * minute (see startTaskRecovery).\n */\n stopTaskRecovery = startTaskRecovery(rootContainer);\n },\n\n onShutdown: async (rootContainer, { requestsFinished }) => {\n /*\n * Stop starting new work first: task recovery, and the scheduler's timers and recovery.\n * Then wait for what is running: tasks hand themselves back, so another process picks\n * them up at its next sweep, and scheduled actions already running get to finish.\n * Websockets close at the same time, with 1012 so clients reconnect to a process that\n * is up, and their connections leave the registry; that takes about a second. The\n * message bus closes last, once tasks, scheduled actions and HTTP requests in flight\n * are done: what they still send to browsers on other processes goes through it.\n */\n stopTaskRecovery?.();\n const tasks = stopBackgroundTasks(rootContainer, SHUTDOWN_WAIT_MS);\n const scheduledActions = stopScheduler?.(SHUTDOWN_WAIT_MS);\n const websockets = stopWebsockets?.();\n const workDone = Promise.allSettled([tasks, scheduledActions, requestsFinished]);\n const messageBus = workDone.then(() => closeMessageBus?.());\n\n // One failing part must not cut the others short; the first failure is reported after.\n const results = await Promise.allSettled([\n tasks,\n scheduledActions,\n websockets,\n messageBus\n ]);\n const failed = results.find((result): result is PromiseRejectedResult => {\n return result.status === \"rejected\";\n });\n if (failed) {\n throw failed.reason;\n }\n }\n });\n}\n"],"names":["SHUTDOWN_WAIT_MS","createWebinyApiHandler","config","stopTaskRecovery","stopScheduler","stopWebsockets","closeMessageBus","standaloneConfig","readStandaloneConfig","process","logger","createLogger","stackConfig","scopeContainer","ConfigPublicUrlsFeature","StandaloneCryptoConfigFeature","WebsocketsStandaloneFeature","uploadSecret","FileManagerStandaloneFeature","createServerHandler","rootContainer","buildParams","registerRootBuildParams","assertNoBakedSecrets","assertFileStorage","StandaloneConfig","Logger","RandomProcessOwner","registerHttpTransport","NodeHttpFeature","NodeHttpInputHandler","TenantScopesRootFeature","ApiRequestRegistration","container","options","registerApiRequestStackInOneContainer","WebsocketsServerRootFeature","WebsocketsRedisFeature","InProcessMessageBus","GraphQLSchemaCacheFeature","EncryptionKeyCacheFeature","JwksStoreFeature","BackgroundTasksStandaloneFeature","registerSchedulerServer","EmptyTrashBinsFeature","registerRootAllowedRequestHeaders","guardDeclaredTenantStorages","registerApiRequestStack","server","connectionManager","WebsocketsConnectionManager","adapter","WebsocketsServerAdapter","websockets","attachWebsocketsServer","createWebsocketsAuthenticator","messageBus","WebsocketsMessageBus","processOwner","ProcessOwner","handleBusMessage","createBusMessageHandler","startSchedulerServer","startBulkActionsServer","startTaskRecovery","requestsFinished","tasks","stopBackgroundTasks","scheduledActions","workDone","Promise","results","failed","result"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8FA,MAAMA,mBAAmB;AAElB,SAASC,uBAAuBC,MAAoC;IACvE,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAMJ,MAAMC,mBAAmBC,qBAAqBC,QAAQ,GAAG;IAGzD,MAAMC,SAASC;IAQf,MAAMC,cAA6C;QAC/C,YAAYV,OAAO,UAAU;QAU7B,YAAY;YAKR,eAAeW,CAAAA;gBACXC,wBAAwB,QAAQ,CAACD;gBACjCE,8BAA8B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J"}
|
|
1
|
+
{"version":3,"file":"createWebinyApiHandler.js","sources":["../src/createWebinyApiHandler.ts"],"sourcesContent":["/**\n * Webiny API handler for the standalone Node HTTP server transport — storage-agnostic BASE.\n *\n * The ROOT container wires the Node HTTP transport (NodeHttpFeature = event type + router + HttpFeature)\n * plus the auth/tenant loader decorators (extract token / x-tenant from the IncomingMessage → shared\n * RequestIdentityLoader / RequestTenantLoader). The per-request feature stack is the transport-agnostic\n * `registerApiRequestStack` from `@webiny/api-composition-core` — the SAME stack the AWS handler uses.\n * The realtime transport hook installs the server WebSockets transport (vs AWS's API Gateway Management\n * API) with a SINGLE-PROCESS, in-process implementation. Background tasks and the scheduler are\n * ROOT-container singletons (below) — mirroring how the AWS handler registers background tasks at root,\n * and the WebSockets connection manager — rather than per-request transports; the scheduler fires timers\n * in-process (vs AWS's EventBridge). The storage variant (and identity provider) is injected via\n * `registerRootStorage`.\n *\n * The identity provider (e.g. `@webiny/self-hosted-auth`'s JWT IdP) must be registered by the variant\n * in `registerRootStorage`, so the RequestIdentityLoader driven by the identity decorator can resolve it.\n */\nimport { GraphQLSchemaCacheFeature } from \"@webiny/api-graphql\";\nimport { EncryptionKeyCacheFeature } from \"@webiny/api-core/features/encryption/index.js\";\nimport { JwksStoreFeature } from \"@webiny/api-core/idp/index.js\";\nimport type { Container } from \"@webiny/di\";\nimport {\n createServerHandler,\n NodeHttpFeature,\n NodeHttpInputHandler\n} from \"@webiny/api-kernel-core/nodeHttp/index.js\";\nimport { registerHttpTransport } from \"@webiny/api-composition-core\";\nimport { RandomProcessOwner } from \"@webiny/api-kernel-core\";\nimport { registerExtensions } from \"@webiny/handler\";\nimport {\n ApiRequestRegistration,\n registerApiRequestStack,\n registerApiRequestStackInOneContainer,\n type RegisterApiRequestStackConfig\n} from \"@webiny/api-composition-core\";\nimport { TenantScopesRootFeature } from \"@webiny/api-core/features/tenancy/TenantScopes/index.js\";\nimport {\n WebsocketsServerRootFeature,\n WebsocketsStandaloneFeature,\n WebsocketsConnectionManager,\n attachWebsocketsServer\n} from \"@webiny/api-websockets-standalone\";\nimport { WebsocketsServerAdapter } from \"@webiny/api-websockets-standalone\";\nimport { WebsocketsMessageBus } from \"@webiny/api-websockets-standalone\";\nimport { InProcessMessageBus } from \"@webiny/api-websockets-standalone\";\nimport { createBusMessageHandler } from \"@webiny/api-websockets-standalone\";\nimport { WebsocketsRedisFeature } from \"@webiny/api-websockets-standalone-redis\";\nimport { ProcessOwner } from \"@webiny/api-kernel-core\";\nimport { BackgroundTasksStandaloneFeature } from \"@webiny/background-tasks-standalone\";\nimport { startTaskRecovery } from \"@webiny/background-tasks-standalone\";\nimport { stopBackgroundTasks } from \"@webiny/background-tasks-standalone\";\nimport { FileManagerStandaloneFeature } from \"@webiny/api-file-manager-standalone\";\nimport { registerSchedulerServer, startSchedulerServer } from \"~/scheduler/schedulerServer.js\";\nimport { startBulkActionsServer } from \"~/bulkActions/bulkActionsServer.js\";\nimport { createWebsocketsAuthenticator } from \"~/websockets/createWebsocketsAuthenticator.js\";\nimport { EmptyTrashBinsFeature } from \"@webiny/api-headless-cms-bulk-actions-standalone\";\nimport { ConfigPublicUrlsFeature } from \"~/publicUrls/feature.js\";\nimport { StandaloneConfig } from \"~/config/abstractions.js\";\nimport { EnvStandaloneConfig } from \"~/config/EnvStandaloneConfig.js\";\nimport type { BuildParams } from \"@webiny/api-core/features/buildParams/index.js\";\nimport { assertNoBakedSecrets } from \"~/config/bakedSecrets.js\";\nimport { assertFileStorage } from \"~/config/assertFileStorage.js\";\nimport { StandaloneCryptoConfigFeature } from \"~/crypto/feature.js\";\nimport {\n createLogger,\n registerRootAllowedRequestHeaders,\n registerRootBuildParams\n} from \"@webiny/api-composition-core\";\nimport { Logger } from \"@webiny/api-core/features/logger/index.js\";\nimport { guardDeclaredTenantStorages } from \"~/tenantStorages/guardDeclaredTenantStorages.js\";\n\nexport interface CreateWebinyApiHandlerConfig {\n /**\n * Project-defined extensions, applied at register() time.\n */\n extensions: () => Parameters<typeof registerExtensions>[1];\n /**\n * Register the storage for this deployment AND the identity provider in the root container.\n * Unlike the AWS base, the server base bakes in no DB or IdP assumption — the variant supplies\n * the complete storage + auth wiring. A storage that registers per request puts only its\n * connection and a `RequestStorage` in the root (see `registerApiRequestStack`). `buildParams`\n * are the build params the project was built with (requests register their own copy).\n */\n registerRootStorage: (\n container: Container,\n params: { buildParams: BuildParams.Interface }\n ) => void | Promise<void>;\n}\n\n/*\n * The part of the 8 seconds a shutdown gets that running tasks and scheduled actions may spend\n * finishing or handing back; both wait at the same time. The rest leaves room to exit before a\n * process manager loses patience.\n */\nconst SHUTDOWN_WAIT_MS = 6000;\n\nexport function createWebinyApiHandler(config: CreateWebinyApiHandlerConfig) {\n let stopTaskRecovery: (() => void) | undefined;\n let stopScheduler: ((timeoutMs: number) => Promise<void>) | undefined;\n let stopWebsockets: (() => Promise<void>) | undefined;\n let closeMessageBus: (() => Promise<void>) | undefined;\n\n /*\n * Deployment-specific settings (public URLs, file storage, secrets) come from env, read once here\n * so a missing value stops the server at boot. Nothing deployment-specific is baked into the build.\n */\n const standaloneConfig = EnvStandaloneConfig.fromEnv(process.env);\n\n // One per process, to stdout. The root singletons below log through it, and so does every request.\n const logger = createLogger();\n\n /*\n * The transport-agnostic request stack, with the server's adapters. Every request's container\n * gets its tenant-neutral part (`child`), and each tenant scope of the request the rest. In one\n * container, it is also in the root as `ApiRequestRegistration`, for work outside a request that\n * needs a container a request would have: the SQL schema setup builds one on its own connection.\n */\n const stackConfig: RegisterApiRequestStackConfig = {\n extensions: config.extensions,\n // Why hooks (and not just registering the transports ourselves): `.register()` calls\n // are otherwise order-independent — you can register Features in any order, because\n // they only REGISTER, they don't RESOLVE during registration (resolution happens\n // later, in Initializers / SchemaFactories). The one thing that makes order matter is\n // a DEFAULT registration: e.g. `WebsocketsFeature` registers `NullWebsocketsTransport`\n // so the abstraction is always resolvable. Overriding it (last-registration-wins) means\n // our transport MUST be registered AFTER that Feature. These hooks are the seams\n // `registerApiRequestStack` provides for exactly that — each runs right after its Null\n // default, so the override is guaranteed without the caller knowing the internal order.\n transports: {\n /*\n * Public URLs and crypto secrets: no deploy step to discover them from, so they\n * come from env (StandaloneConfig, registered on the root).\n */\n hostingConfig: scopeContainer => {\n ConfigPublicUrlsFeature.register(scopeContainer);\n StandaloneCryptoConfigFeature.register(scopeContainer);\n },\n // Server WebSockets transport; resolves the shared connection manager + adapter\n // from the root (registered as singletons in `root`). Scheduler is NOT a per-request\n // transport here — it's a root singleton wired in `root` + `onServer` (see below).\n realtime: scopeContainer => {\n WebsocketsStandaloneFeature.register(scopeContainer);\n },\n /*\n * File-manager storage transport. Where AWS uploads straight to S3 (+ a separate\n * asset-delivery Lambda), the server takes uploads and serves files in-process.\n * FileManagerStandaloneFeature registers asset delivery (overriding the domain's\n * null impls) and the upload/multipart HTTP routes; they store through\n * `ObjectStorage`, which a project extension registers (`<Infra.FileStorage.Disk />`\n * a folder on disk, `<Infra.FileStorage.S3 />` an S3-compatible bucket).\n * `assertFileStorage` has made sure the build has one.\n */\n fileManager: scopeContainer => {\n const { uploadSecret } = standaloneConfig.fileStorage;\n FileManagerStandaloneFeature.register(scopeContainer, { uploadSecret });\n }\n }\n };\n\n return createServerHandler({\n keepAliveTimeoutMs: standaloneConfig.keepAliveTimeoutMs,\n root: async rootContainer => {\n /*\n * Secrets come from env only. A build that bakes one (the shared <Infra.Crypto.*> from\n * @webiny/project) is refused here, before the server accepts a request.\n */\n // Build params come from the deploy, the same for every request and tenant: they live in\n // the root, and every request container and tenant scope reads them from here.\n const buildParams = await registerRootBuildParams(rootContainer, config.extensions());\n assertNoBakedSecrets(buildParams);\n assertFileStorage(buildParams);\n\n rootContainer.registerInstance(StandaloneConfig, standaloneConfig);\n rootContainer.registerInstance(Logger, logger);\n\n // Names this process in shared storage: task claims and websocket connections.\n rootContainer.register(RandomProcessOwner).inSingletonScope();\n\n // ── Transport (Node HTTP) ──────────────────────────────────\n // NodeHttpFeature registers the event type + HttpFeature (router) + the routing terminal.\n // registerHttpTransport also registers the tenant, identity and preview-as loading, and the\n // hand-off of each request into its tenant's scope once CORS and the tenant step are done.\n registerHttpTransport(rootContainer, NodeHttpFeature, NodeHttpInputHandler);\n\n // Every other event's handler chain runs in its tenant's scope: a background task or\n // scheduled action in the tenant of its payload, anything else as the root tenant.\n TenantScopesRootFeature.register(rootContainer);\n\n rootContainer.registerInstance(ApiRequestRegistration, {\n register: (container, options) => {\n return registerApiRequestStackInOneContainer(container, stackConfig, options);\n }\n });\n\n // ── Storage + identity provider (variant-supplied) ─────────\n await config.registerRootStorage(rootContainer, { buildParams });\n\n // ── WebSockets transport (root) ────────────────────────────\n // The live sockets, the connection manager and the adapter live in the root as\n // singletons, shared between the upgrade acceptor (attachWebsocketsServer, below) and the\n // per-request ServerWebsocketsTransport that sends to those live sockets. The connections'\n // rows (ConnectionRegistry) are a storage, so they live in request containers: the\n // manager changes them by dispatching an event, which runs in a fresh one.\n WebsocketsServerRootFeature.register(rootContainer);\n\n /*\n * How a send reaches a socket another API process holds. Without a Redis URL there is\n * one process, and every socket is in it.\n */\n if (standaloneConfig.redisUrl) {\n WebsocketsRedisFeature.register(rootContainer, {\n url: standaloneConfig.redisUrl,\n logger\n });\n } else {\n rootContainer.register(InProcessMessageBus).inSingletonScope();\n }\n\n // ── GraphQL schema cache (root) ────────────────────────────\n // Root, so a built schema outlives the request that built it.\n GraphQLSchemaCacheFeature.register(rootContainer);\n\n // ── Encryption key cache (root) ────────────────────────────\n // Root, so the scrypt-derived key is computed once per process instead of per request.\n EncryptionKeyCacheFeature.register(rootContainer);\n // Root, so identity providers' signing keys are fetched once per process, not per request.\n JwksStoreFeature.register(rootContainer);\n\n // ── Background tasks (root) ────────────────────────────────\n // Mirrors the AWS handler registering its background-task transport at root. Where AWS\n // has Step Functions invoke the Lambda once per iteration, a root task loop dispatches a\n // BackgroundTaskEvent per iteration through the InputDispatcher (registered by\n // createServerHandler), and each one runs in a fresh request container.\n BackgroundTasksStandaloneFeature.register(rootContainer);\n\n // ── Scheduler (root) ───────────────────────────────────────\n // The scheduler is a single long-lived instance for ALL tenants, started once at boot\n // (onServer, below) — the counterpart of the WebSockets connection manager, NOT a per-request\n // transport. Registered here as SchedulerService (per-request create/update/delete during\n // mutations manipulate this one live timer set) plus the run/recover event handlers. When a\n // timer fires (outside any request) it dispatches a ScheduledActionEvent, handled in a fresh\n // request container by the same handler AWS uses.\n registerSchedulerServer(rootContainer);\n\n // ── Bulk actions (root) ───────────────────────────────────\n // Registers the EmptyTrashBinsEvent handler that the periodic trigger\n // (startBulkActionsServer, onServer below) dispatches.\n EmptyTrashBinsFeature.register(rootContainer);\n\n // ── CORS allowed headers (root) ────────────────────────────\n // The request headers extensions allow in the CORS preflight: read once, at start, for\n // the CORS step, which runs at request level, before any tenant scope (where extensions\n // register). Last: it registers what a request has, the extensions included, in a\n // throwaway container.\n await registerRootAllowedRequestHeaders(rootContainer);\n\n // ── Declared storages (root) ───────────────────────────────\n // Refuses to start when an extra storage that wasn't retired was removed from the\n // config: tenants may still run on it. Needs a request's services, so it runs last.\n await guardDeclaredTenantStorages({\n root: rootContainer,\n registerRequest: container => registerApiRequestStack(container, stackConfig)\n });\n },\n\n child: async container => {\n await registerApiRequestStack(container, stackConfig);\n },\n\n onServer: async (server, rootContainer) => {\n // Attach the WebSockets upgrade handler to the running HTTP server, backed by the shared\n // (root) connection manager so request-time sends reach the live sockets.\n //\n // Authenticate each WebSocket connection from its `?token` JWT so it's registered under\n // the real identity (targeted server→client sends match by identity id). It's a callback\n // the handler supplies rather than something the WS server resolves itself — see\n // createWebsocketsAuthenticator for why (AuthenticationContext is per-request, unreachable\n // from the root container the WS server is attached to).\n const connectionManager = rootContainer.resolve(WebsocketsConnectionManager);\n const adapter = rootContainer.resolve(WebsocketsServerAdapter);\n const websockets = attachWebsocketsServer({\n server,\n connectionManager,\n adapter,\n authenticate: createWebsocketsAuthenticator(rootContainer, config.extensions)\n });\n await websockets.start();\n stopWebsockets = () => websockets.stop();\n\n // Receive sends and disconnects other API processes publish for this one's sockets.\n const messageBus = rootContainer.resolve(WebsocketsMessageBus);\n const processOwner = rootContainer.resolve(ProcessOwner);\n const handleBusMessage = createBusMessageHandler({\n connectionManager,\n adapter,\n logger\n });\n await messageBus.subscribe(processOwner.id, handleBusMessage);\n closeMessageBus = () => messageBus.close();\n logger.info(\n { messageBus: standaloneConfig.redisUrl ? \"redis\" : \"in-process\" },\n \"[websockets] using message bus\"\n );\n\n /*\n * Start the in-process scheduler timers, then re-arm persisted schedules in the\n * background, at boot and then every minute (see startSchedulerServer).\n */\n stopScheduler = await startSchedulerServer(rootContainer);\n\n // Start the periodic empty-trash-bin trigger.\n startBulkActionsServer(rootContainer);\n\n /*\n * Take over tasks a restart or another process left behind, at boot and then every\n * minute (see startTaskRecovery).\n */\n stopTaskRecovery = startTaskRecovery(rootContainer);\n },\n\n onShutdown: async (rootContainer, { requestsFinished }) => {\n /*\n * Stop starting new work first: task recovery, and the scheduler's timers and recovery.\n * Then wait for what is running: tasks hand themselves back, so another process picks\n * them up at its next sweep, and scheduled actions already running get to finish.\n * Websockets close at the same time, with 1012 so clients reconnect to a process that\n * is up, and their connections leave the registry; that takes about a second. The\n * message bus closes last, once tasks, scheduled actions and HTTP requests in flight\n * are done: what they still send to browsers on other processes goes through it.\n */\n stopTaskRecovery?.();\n const tasks = stopBackgroundTasks(rootContainer, SHUTDOWN_WAIT_MS);\n const scheduledActions = stopScheduler?.(SHUTDOWN_WAIT_MS);\n const websockets = stopWebsockets?.();\n const workDone = Promise.allSettled([tasks, scheduledActions, requestsFinished]);\n const messageBus = workDone.then(() => closeMessageBus?.());\n\n // One failing part must not cut the others short; the first failure is reported after.\n const results = await Promise.allSettled([\n tasks,\n scheduledActions,\n websockets,\n messageBus\n ]);\n const failed = results.find((result): result is PromiseRejectedResult => {\n return result.status === \"rejected\";\n });\n if (failed) {\n throw failed.reason;\n }\n }\n });\n}\n"],"names":["SHUTDOWN_WAIT_MS","createWebinyApiHandler","config","stopTaskRecovery","stopScheduler","stopWebsockets","closeMessageBus","standaloneConfig","EnvStandaloneConfig","process","logger","createLogger","stackConfig","scopeContainer","ConfigPublicUrlsFeature","StandaloneCryptoConfigFeature","WebsocketsStandaloneFeature","uploadSecret","FileManagerStandaloneFeature","createServerHandler","rootContainer","buildParams","registerRootBuildParams","assertNoBakedSecrets","assertFileStorage","StandaloneConfig","Logger","RandomProcessOwner","registerHttpTransport","NodeHttpFeature","NodeHttpInputHandler","TenantScopesRootFeature","ApiRequestRegistration","container","options","registerApiRequestStackInOneContainer","WebsocketsServerRootFeature","WebsocketsRedisFeature","InProcessMessageBus","GraphQLSchemaCacheFeature","EncryptionKeyCacheFeature","JwksStoreFeature","BackgroundTasksStandaloneFeature","registerSchedulerServer","EmptyTrashBinsFeature","registerRootAllowedRequestHeaders","guardDeclaredTenantStorages","registerApiRequestStack","server","connectionManager","WebsocketsConnectionManager","adapter","WebsocketsServerAdapter","websockets","attachWebsocketsServer","createWebsocketsAuthenticator","messageBus","WebsocketsMessageBus","processOwner","ProcessOwner","handleBusMessage","createBusMessageHandler","startSchedulerServer","startBulkActionsServer","startTaskRecovery","requestsFinished","tasks","stopBackgroundTasks","scheduledActions","workDone","Promise","results","failed","result"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8FA,MAAMA,mBAAmB;AAElB,SAASC,uBAAuBC,MAAoC;IACvE,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAMJ,MAAMC,mBAAmBC,oBAAoB,OAAO,CAACC,QAAQ,GAAG;IAGhE,MAAMC,SAASC;IAQf,MAAMC,cAA6C;QAC/C,YAAYV,OAAO,UAAU;QAU7B,YAAY;YAKR,eAAeW,CAAAA;gBACXC,wBAAwB,QAAQ,CAACD;gBACjCE,8BAA8B,QAAQ,CAACF;YAC3C;YAIA,UAAUA,CAAAA;gBACNG,4BAA4B,QAAQ,CAACH;YACzC;YAUA,aAAaA,CAAAA;gBACT,MAAM,EAAEI,YAAY,EAAE,GA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3
|
+
"version": "0.0.0-unstable.676006d08e",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "index.js",
|
|
6
6
|
"exports": {
|
|
@@ -18,26 +18,26 @@
|
|
|
18
18
|
],
|
|
19
19
|
"license": "MIT",
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@webiny/api-composition-core": "0.0.0-unstable.
|
|
22
|
-
"@webiny/api-core": "0.0.0-unstable.
|
|
23
|
-
"@webiny/api-file-manager-standalone": "0.0.0-unstable.
|
|
24
|
-
"@webiny/api-graphql": "0.0.0-unstable.
|
|
25
|
-
"@webiny/api-headless-cms-bulk-actions-standalone": "0.0.0-unstable.
|
|
26
|
-
"@webiny/api-kernel-core": "0.0.0-unstable.
|
|
27
|
-
"@webiny/api-object-storage": "0.0.0-unstable.
|
|
28
|
-
"@webiny/api-scheduler": "0.0.0-unstable.
|
|
29
|
-
"@webiny/api-scheduler-standalone": "0.0.0-unstable.
|
|
30
|
-
"@webiny/api-websockets-standalone": "0.0.0-unstable.
|
|
31
|
-
"@webiny/api-websockets-standalone-redis": "0.0.0-unstable.
|
|
32
|
-
"@webiny/background-tasks-standalone": "0.0.0-unstable.
|
|
33
|
-
"@webiny/feature": "0.0.0-unstable.
|
|
34
|
-
"@webiny/handler": "0.0.0-unstable.
|
|
21
|
+
"@webiny/api-composition-core": "0.0.0-unstable.676006d08e",
|
|
22
|
+
"@webiny/api-core": "0.0.0-unstable.676006d08e",
|
|
23
|
+
"@webiny/api-file-manager-standalone": "0.0.0-unstable.676006d08e",
|
|
24
|
+
"@webiny/api-graphql": "0.0.0-unstable.676006d08e",
|
|
25
|
+
"@webiny/api-headless-cms-bulk-actions-standalone": "0.0.0-unstable.676006d08e",
|
|
26
|
+
"@webiny/api-kernel-core": "0.0.0-unstable.676006d08e",
|
|
27
|
+
"@webiny/api-object-storage": "0.0.0-unstable.676006d08e",
|
|
28
|
+
"@webiny/api-scheduler": "0.0.0-unstable.676006d08e",
|
|
29
|
+
"@webiny/api-scheduler-standalone": "0.0.0-unstable.676006d08e",
|
|
30
|
+
"@webiny/api-websockets-standalone": "0.0.0-unstable.676006d08e",
|
|
31
|
+
"@webiny/api-websockets-standalone-redis": "0.0.0-unstable.676006d08e",
|
|
32
|
+
"@webiny/background-tasks-standalone": "0.0.0-unstable.676006d08e",
|
|
33
|
+
"@webiny/feature": "0.0.0-unstable.676006d08e",
|
|
34
|
+
"@webiny/handler": "0.0.0-unstable.676006d08e"
|
|
35
35
|
},
|
|
36
36
|
"peerDependencies": {
|
|
37
37
|
"@webiny/di": "^2.0.0"
|
|
38
38
|
},
|
|
39
39
|
"devDependencies": {
|
|
40
|
-
"@webiny/build-tools": "0.0.0-unstable.
|
|
40
|
+
"@webiny/build-tools": "0.0.0-unstable.676006d08e",
|
|
41
41
|
"@webiny/di": "2.0.0",
|
|
42
42
|
"rimraf": "6.1.4",
|
|
43
43
|
"typescript": "7.0.2",
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import type { StandaloneConfig } from "./abstractions.js";
|
|
2
|
-
type Env = Record<string, string | undefined>;
|
|
3
|
-
/**
|
|
4
|
-
* Reads the standalone API's settings from env. Throws one error naming every missing or invalid
|
|
5
|
-
* variable, so a misconfigured container fails at boot instead of on the first upload or login.
|
|
6
|
-
*
|
|
7
|
-
* Nothing falls back to a default: `webiny watch` and `webiny serve` get their values from
|
|
8
|
-
* `<Infra.ApiUrl>`, `<Infra.AdminUrl>`, `<Infra.FileStorage.*>` and `<Infra.Crypto.*>` in
|
|
9
|
-
* webiny.config, and a deployed container must set them explicitly.
|
|
10
|
-
*/
|
|
11
|
-
export declare function readStandaloneConfig(env: Env): StandaloneConfig.Interface;
|
|
12
|
-
export {};
|
|
@@ -1,56 +0,0 @@
|
|
|
1
|
-
import { PublicUrl } from "@webiny/api-core/features/publicUrls/index.js";
|
|
2
|
-
function read(env, name) {
|
|
3
|
-
return env[name]?.trim() ?? "";
|
|
4
|
-
}
|
|
5
|
-
function readSecret(env, name) {
|
|
6
|
-
const value = env[name] ?? "";
|
|
7
|
-
return value.trim() ? value : "";
|
|
8
|
-
}
|
|
9
|
-
function readStandaloneConfig(env) {
|
|
10
|
-
const problems = [];
|
|
11
|
-
const apiUrlValue = read(env, "WEBINY_API_URL");
|
|
12
|
-
const apiUrl = PublicUrl.from(apiUrlValue);
|
|
13
|
-
if (apiUrlValue) {
|
|
14
|
-
if (!apiUrl.isKnown()) problems.push(`WEBINY_API_URL is not an absolute http(s) URL: "${apiUrlValue}".`);
|
|
15
|
-
} else problems.push("WEBINY_API_URL is not set.");
|
|
16
|
-
const adminUrlValue = read(env, "WEBINY_ADMIN_URL");
|
|
17
|
-
const adminUrl = PublicUrl.from(adminUrlValue);
|
|
18
|
-
if (adminUrlValue && !adminUrl.isKnown()) problems.push(`WEBINY_ADMIN_URL is not an absolute http(s) URL: "${adminUrlValue}".`);
|
|
19
|
-
const uploadSecret = readSecret(env, "WEBINY_UPLOAD_SECRET");
|
|
20
|
-
if (!uploadSecret) problems.push("WEBINY_UPLOAD_SECRET is not set.");
|
|
21
|
-
const encryptionPassphrase = readSecret(env, "WEBINY_ENCRYPTION_PASSPHRASE");
|
|
22
|
-
if (!encryptionPassphrase) problems.push("WEBINY_ENCRYPTION_PASSPHRASE is not set.");
|
|
23
|
-
const hashingPepper = readSecret(env, "WEBINY_HASHING_PEPPER");
|
|
24
|
-
if (!hashingPepper) problems.push("WEBINY_HASHING_PEPPER is not set.");
|
|
25
|
-
const redisUrl = read(env, "WEBINY_REDIS_URL");
|
|
26
|
-
if (redisUrl && !/^rediss?:\/\//.test(redisUrl)) problems.push("WEBINY_REDIS_URL must start with redis:// or rediss://.");
|
|
27
|
-
const keepAliveTimeoutValue = read(env, "WEBINY_KEEP_ALIVE_TIMEOUT_MS");
|
|
28
|
-
const keepAliveTimeoutMs = keepAliveTimeoutValue ? Number(keepAliveTimeoutValue) : void 0;
|
|
29
|
-
if (void 0 !== keepAliveTimeoutMs && (!Number.isInteger(keepAliveTimeoutMs) || keepAliveTimeoutMs <= 0)) problems.push(`WEBINY_KEEP_ALIVE_TIMEOUT_MS must be a positive whole number of milliseconds: "${keepAliveTimeoutValue}".`);
|
|
30
|
-
if (problems.length > 0) {
|
|
31
|
-
const message = [
|
|
32
|
-
"The standalone API is missing required configuration:",
|
|
33
|
-
...problems
|
|
34
|
-
].join("\n ");
|
|
35
|
-
throw new Error(message);
|
|
36
|
-
}
|
|
37
|
-
return {
|
|
38
|
-
apiUrl,
|
|
39
|
-
adminUrl,
|
|
40
|
-
fileStorage: {
|
|
41
|
-
uploadSecret
|
|
42
|
-
},
|
|
43
|
-
encryption: {
|
|
44
|
-
passphrase: encryptionPassphrase,
|
|
45
|
-
salt: readSecret(env, "WEBINY_ENCRYPTION_SALT")
|
|
46
|
-
},
|
|
47
|
-
hashing: {
|
|
48
|
-
pepper: hashingPepper
|
|
49
|
-
},
|
|
50
|
-
redisUrl: redisUrl || void 0,
|
|
51
|
-
keepAliveTimeoutMs
|
|
52
|
-
};
|
|
53
|
-
}
|
|
54
|
-
export { readStandaloneConfig };
|
|
55
|
-
|
|
56
|
-
//# sourceMappingURL=readStandaloneConfig.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"config/readStandaloneConfig.js","sources":["../../src/config/readStandaloneConfig.ts"],"sourcesContent":["import { PublicUrl } from \"@webiny/api-core/features/publicUrls/index.js\";\nimport type { StandaloneConfig } from \"./abstractions.js\";\n\ntype Env = Record<string, string | undefined>;\n\nfunction read(env: Env, name: string): string {\n return env[name]?.trim() ?? \"\";\n}\n\n/**\n * Secrets are used exactly as given: trimming would change the derived key or signature, so a value\n * with surrounding whitespace would no longer match what was encrypted, hashed or signed with it.\n * A blank value counts as unset.\n */\nfunction readSecret(env: Env, name: string): string {\n const value = env[name] ?? \"\";\n return value.trim() ? value : \"\";\n}\n\n/**\n * Reads the standalone API's settings from env. Throws one error naming every missing or invalid\n * variable, so a misconfigured container fails at boot instead of on the first upload or login.\n *\n * Nothing falls back to a default: `webiny watch` and `webiny serve` get their values from\n * `<Infra.ApiUrl>`, `<Infra.AdminUrl>`, `<Infra.FileStorage.*>` and `<Infra.Crypto.*>` in\n * webiny.config, and a deployed container must set them explicitly.\n */\nexport function readStandaloneConfig(env: Env): StandaloneConfig.Interface {\n const problems: string[] = [];\n\n const apiUrlValue = read(env, \"WEBINY_API_URL\");\n const apiUrl = PublicUrl.from(apiUrlValue);\n if (!apiUrlValue) {\n problems.push(\"WEBINY_API_URL is not set.\");\n } else if (!apiUrl.isKnown()) {\n problems.push(`WEBINY_API_URL is not an absolute http(s) URL: \"${apiUrlValue}\".`);\n }\n\n const adminUrlValue = read(env, \"WEBINY_ADMIN_URL\");\n const adminUrl = PublicUrl.from(adminUrlValue);\n if (adminUrlValue && !adminUrl.isKnown()) {\n problems.push(`WEBINY_ADMIN_URL is not an absolute http(s) URL: \"${adminUrlValue}\".`);\n }\n\n const uploadSecret = readSecret(env, \"WEBINY_UPLOAD_SECRET\");\n if (!uploadSecret) {\n problems.push(\"WEBINY_UPLOAD_SECRET is not set.\");\n }\n\n /*\n * Always required: a standalone project always encrypts and always peppers its hashes. There is\n * no deploy step that could check this for production, so it is checked here for every start.\n */\n const encryptionPassphrase = readSecret(env, \"WEBINY_ENCRYPTION_PASSPHRASE\");\n if (!encryptionPassphrase) {\n problems.push(\"WEBINY_ENCRYPTION_PASSPHRASE is not set.\");\n }\n\n const hashingPepper = readSecret(env, \"WEBINY_HASHING_PEPPER\");\n if (!hashingPepper) {\n problems.push(\"WEBINY_HASHING_PEPPER is not set.\");\n }\n\n const redisUrl = read(env, \"WEBINY_REDIS_URL\");\n if (redisUrl && !/^rediss?:\\/\\//.test(redisUrl)) {\n problems.push(\"WEBINY_REDIS_URL must start with redis:// or rediss://.\");\n }\n\n const keepAliveTimeoutValue = read(env, \"WEBINY_KEEP_ALIVE_TIMEOUT_MS\");\n const keepAliveTimeoutMs = keepAliveTimeoutValue ? Number(keepAliveTimeoutValue) : undefined;\n if (\n keepAliveTimeoutMs !== undefined &&\n (!Number.isInteger(keepAliveTimeoutMs) || keepAliveTimeoutMs <= 0)\n ) {\n problems.push(\n `WEBINY_KEEP_ALIVE_TIMEOUT_MS must be a positive whole number of milliseconds: \"${keepAliveTimeoutValue}\".`\n );\n }\n\n if (problems.length > 0) {\n const message = [\"The standalone API is missing required configuration:\", ...problems].join(\n \"\\n \"\n );\n throw new Error(message);\n }\n\n return {\n apiUrl,\n adminUrl,\n fileStorage: {\n uploadSecret\n },\n encryption: {\n passphrase: encryptionPassphrase,\n salt: readSecret(env, \"WEBINY_ENCRYPTION_SALT\")\n },\n hashing: {\n pepper: hashingPepper\n },\n redisUrl: redisUrl || undefined,\n keepAliveTimeoutMs\n };\n}\n"],"names":["read","env","name","readSecret","value","readStandaloneConfig","problems","apiUrlValue","apiUrl","PublicUrl","adminUrlValue","adminUrl","uploadSecret","encryptionPassphrase","hashingPepper","redisUrl","keepAliveTimeoutValue","keepAliveTimeoutMs","Number","undefined","message","Error"],"mappings":";AAKA,SAASA,KAAKC,GAAQ,EAAEC,IAAY;IAChC,OAAOD,GAAG,CAACC,KAAK,EAAE,UAAU;AAChC;AAOA,SAASC,WAAWF,GAAQ,EAAEC,IAAY;IACtC,MAAME,QAAQH,GAAG,CAACC,KAAK,IAAI;IAC3B,OAAOE,MAAM,IAAI,KAAKA,QAAQ;AAClC;AAUO,SAASC,qBAAqBJ,GAAQ;IACzC,MAAMK,WAAqB,EAAE;IAE7B,MAAMC,cAAcP,KAAKC,KAAK;IAC9B,MAAMO,SAASC,UAAU,IAAI,CAACF;IAC9B,IAAKA,aAEE;QAAA,IAAI,CAACC,OAAO,OAAO,IACtBF,SAAS,IAAI,CAAC,CAAC,gDAAgD,EAAEC,YAAY,EAAE,CAAC;IACpF,OAHID,SAAS,IAAI,CAAC;IAKlB,MAAMI,gBAAgBV,KAAKC,KAAK;IAChC,MAAMU,WAAWF,UAAU,IAAI,CAACC;IAChC,IAAIA,iBAAiB,CAACC,SAAS,OAAO,IAClCL,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