@webiny/api-composition-standalone 0.0.0-unstable.e1999482d0 → 6.6.0-alpha.14

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.
@@ -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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CAACmB,sBACDL,SAAS,IAAI,CAAC,GAAGd,IAAI,oBAAoB,CAAC,YAAY,CAAC;QAG3D,MAAMoB,gBAAgBhB,WAAWF,KAAKF,IAAI,aAAa;QACvD,IAAI,CAACoB,eACDN,SAAS,IAAI,CAAC,GAAGd,IAAI,aAAa,CAAC,YAAY,CAAC;QAIpD,MAAMY,WAAWX,KAAKC,KAAKF,IAAI,QAAQ;QACvC,IAAIY,YAAY,CAAC,gBAAgB,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"}
@@ -5,8 +5,6 @@ export interface IStandaloneConfig {
5
5
  /** `WEBINY_ADMIN_URL`. Optional: unknown when not set. */
6
6
  readonly adminUrl: PublicUrl;
7
7
  readonly fileStorage: {
8
- /** `WEBINY_LOCAL_STORAGE_PATH`, resolved to an absolute path. Required. */
9
- readonly storagePath: string;
10
8
  /** `WEBINY_UPLOAD_SECRET`. Required. */
11
9
  readonly uploadSecret: string;
12
10
  };
@@ -25,6 +23,12 @@ export interface IStandaloneConfig {
25
23
  * through this Redis or Valkey server; required when more than one API process runs.
26
24
  */
27
25
  readonly redisUrl: string | undefined;
26
+ /**
27
+ * `WEBINY_KEEP_ALIVE_TIMEOUT_MS`. Optional. How long an idle HTTP connection stays open; set it
28
+ * above the idle timeout of the proxy in front of the API. Unset keeps the server's default of
29
+ * 65 s, above an AWS Application Load Balancer's 60 s.
30
+ */
31
+ readonly keepAliveTimeoutMs: number | undefined;
28
32
  }
29
33
  /**
30
34
  * Deployment-specific settings of a standalone API, read from env once when the server starts.
@@ -1 +1 @@
1
- {"version":3,"file":"config/abstractions.js","sources":["../../src/config/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { PublicUrl } from \"@webiny/api-core/features/publicUrls/index.js\";\n\nexport interface IStandaloneConfig {\n /** `WEBINY_API_URL`. Required. */\n readonly apiUrl: PublicUrl;\n /** `WEBINY_ADMIN_URL`. Optional: unknown when not set. */\n readonly adminUrl: PublicUrl;\n readonly fileStorage: {\n /** `WEBINY_LOCAL_STORAGE_PATH`, resolved to an absolute path. Required. */\n readonly storagePath: string;\n /** `WEBINY_UPLOAD_SECRET`. Required. */\n readonly uploadSecret: string;\n };\n readonly encryption: {\n /** `WEBINY_ENCRYPTION_PASSPHRASE`. Required: standalone always encrypts. */\n readonly passphrase: string;\n /** `WEBINY_ENCRYPTION_SALT`. Optional. */\n readonly salt: string;\n };\n readonly hashing: {\n /** `WEBINY_HASHING_PEPPER`. Required: standalone always peppers its hashes. */\n readonly pepper: string;\n };\n /**\n * `WEBINY_REDIS_URL`. Optional. When set, websocket messages travel between API processes\n * through this Redis or Valkey server; required when more than one API process runs.\n */\n readonly redisUrl: string | undefined;\n}\n\n/**\n * Deployment-specific settings of a standalone API, read from env once when the server starts.\n * Nothing here is baked into the build, so one build runs in every environment.\n */\nexport const StandaloneConfig = createAbstraction<IStandaloneConfig>(\"Standalone/Config\");\n\nexport namespace StandaloneConfig {\n export type Interface = IStandaloneConfig;\n}\n"],"names":["StandaloneConfig","createAbstraction"],"mappings":";AAmCO,MAAMA,mBAAmBC,kBAAqC"}
1
+ {"version":3,"file":"config/abstractions.js","sources":["../../src/config/abstractions.ts"],"sourcesContent":["import { createAbstraction } from \"@webiny/feature/api\";\nimport type { PublicUrl } from \"@webiny/api-core/features/publicUrls/index.js\";\n\nexport interface IStandaloneConfig {\n /** `WEBINY_API_URL`. Required. */\n readonly apiUrl: PublicUrl;\n /** `WEBINY_ADMIN_URL`. Optional: unknown when not set. */\n readonly adminUrl: PublicUrl;\n readonly fileStorage: {\n /** `WEBINY_UPLOAD_SECRET`. Required. */\n readonly uploadSecret: string;\n };\n readonly encryption: {\n /** `WEBINY_ENCRYPTION_PASSPHRASE`. Required: standalone always encrypts. */\n readonly passphrase: string;\n /** `WEBINY_ENCRYPTION_SALT`. Optional. */\n readonly salt: string;\n };\n readonly hashing: {\n /** `WEBINY_HASHING_PEPPER`. Required: standalone always peppers its hashes. */\n readonly pepper: string;\n };\n /**\n * `WEBINY_REDIS_URL`. Optional. When set, websocket messages travel between API processes\n * through this Redis or Valkey server; required when more than one API process runs.\n */\n readonly redisUrl: string | undefined;\n /**\n * `WEBINY_KEEP_ALIVE_TIMEOUT_MS`. Optional. How long an idle HTTP connection stays open; set it\n * above the idle timeout of the proxy in front of the API. Unset keeps the server's default of\n * 65 s, above an AWS Application Load Balancer's 60 s.\n */\n readonly keepAliveTimeoutMs: number | undefined;\n}\n\n/**\n * Deployment-specific settings of a standalone API, read from env once when the server starts.\n * Nothing here is baked into the build, so one build runs in every environment.\n */\nexport const StandaloneConfig = createAbstraction<IStandaloneConfig>(\"Standalone/Config\");\n\nexport namespace StandaloneConfig {\n export type Interface = IStandaloneConfig;\n}\n"],"names":["StandaloneConfig","createAbstraction"],"mappings":";AAuCO,MAAMA,mBAAmBC,kBAAqC"}
@@ -0,0 +1,8 @@
1
+ import type { BuildParams } from "@webiny/api-core/features/buildParams/index.js";
2
+ /**
3
+ * Throws unless the build has a storage for uploaded files: a project extension that provides
4
+ * `ObjectStorage` says so with the `ObjectStorage` build param (`<Infra.FileStorage.Disk />` sets
5
+ * `"disk"`, `<Infra.FileStorage.S3 />` sets `"s3"`). Checked when the API starts, before any request
6
+ * registers the extension.
7
+ */
8
+ export declare function assertFileStorage(buildParams: BuildParams.Interface): void;
@@ -0,0 +1,8 @@
1
+ import { OBJECT_STORAGE_BUILD_PARAM } from "@webiny/api-object-storage";
2
+ function assertFileStorage(buildParams) {
3
+ const storage = buildParams.get(OBJECT_STORAGE_BUILD_PARAM);
4
+ if (!storage) throw new Error("No file storage is in the build. Add <Infra.FileStorage.Disk /> or <Infra.FileStorage.S3 />.");
5
+ }
6
+ export { assertFileStorage };
7
+
8
+ //# sourceMappingURL=assertFileStorage.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config/assertFileStorage.js","sources":["../../src/config/assertFileStorage.ts"],"sourcesContent":["import type { BuildParams } from \"@webiny/api-core/features/buildParams/index.js\";\nimport { OBJECT_STORAGE_BUILD_PARAM } from \"@webiny/api-object-storage\";\n\n/**\n * Throws unless the build has a storage for uploaded files: a project extension that provides\n * `ObjectStorage` says so with the `ObjectStorage` build param (`<Infra.FileStorage.Disk />` sets\n * `\"disk\"`, `<Infra.FileStorage.S3 />` sets `\"s3\"`). Checked when the API starts, before any request\n * registers the extension.\n */\nexport function assertFileStorage(buildParams: BuildParams.Interface): void {\n const storage = buildParams.get<string>(OBJECT_STORAGE_BUILD_PARAM);\n if (!storage) {\n throw new Error(\n \"No file storage is in the build. Add <Infra.FileStorage.Disk /> or \" +\n \"<Infra.FileStorage.S3 />.\"\n );\n }\n}\n"],"names":["assertFileStorage","buildParams","storage","OBJECT_STORAGE_BUILD_PARAM","Error"],"mappings":";AASO,SAASA,kBAAkBC,WAAkC;IAChE,MAAMC,UAAUD,YAAY,GAAG,CAASE;IACxC,IAAI,CAACD,SACD,MAAM,IAAIE,MACN;AAIZ"}
@@ -1,10 +1,10 @@
1
1
  import { GraphQLSchemaCacheFeature } from "@webiny/api-graphql";
2
2
  import { EncryptionKeyCacheFeature } from "@webiny/api-core/features/encryption/index.js";
3
3
  import { JwksStoreFeature } from "@webiny/api-core/idp/index.js";
4
- import { NodeHttpFeature, createServerHandler } from "@webiny/api-kernel-core/nodeHttp/index.js";
4
+ import { NodeHttpFeature, NodeHttpInputHandler, createServerHandler } from "@webiny/api-kernel-core/nodeHttp/index.js";
5
+ import { ApiRequestRegistration, createLogger, registerApiRequestStack, registerApiRequestStackInOneContainer, registerHttpTransport, registerRootAllowedRequestHeaders, registerRootBuildParams } from "@webiny/api-composition-core";
5
6
  import { ProcessOwner, RandomProcessOwner } from "@webiny/api-kernel-core";
6
- import { ApiRequestRegistration, createLogger, readBuildParams, registerApiRequestStack } from "@webiny/api-composition-core";
7
- import { NodeHttpAssumePermissionsDecorator, NodeHttpIdentityLoaderDecorator, NodeHttpTenantLoaderDecorator } from "@webiny/api-composition-core/nodeHttp/index.js";
7
+ import { TenantScopesRootFeature } from "@webiny/api-core/features/tenancy/TenantScopes/index.js";
8
8
  import { InProcessMessageBus, WebsocketsConnectionManager, WebsocketsMessageBus, WebsocketsServerAdapter, WebsocketsServerRootFeature, WebsocketsStandaloneFeature, attachWebsocketsServer, createBusMessageHandler } from "@webiny/api-websockets-standalone";
9
9
  import { WebsocketsRedisFeature } from "@webiny/api-websockets-standalone-redis";
10
10
  import { BackgroundTasksStandaloneFeature, startTaskRecovery, stopBackgroundTasks } from "@webiny/background-tasks-standalone";
@@ -13,55 +13,53 @@ import { registerSchedulerServer, startSchedulerServer } from "./scheduler/sched
13
13
  import { startBulkActionsServer } from "./bulkActions/bulkActionsServer.js";
14
14
  import { createWebsocketsAuthenticator } from "./websockets/createWebsocketsAuthenticator.js";
15
15
  import { EmptyTrashBinsFeature } from "@webiny/api-headless-cms-bulk-actions-standalone";
16
- import { mkdirSync } from "node:fs";
17
16
  import { ConfigPublicUrlsFeature } from "./publicUrls/feature.js";
18
17
  import { StandaloneConfig } from "./config/abstractions.js";
19
- import { readStandaloneConfig } from "./config/readStandaloneConfig.js";
18
+ import { EnvStandaloneConfig } from "./config/EnvStandaloneConfig.js";
20
19
  import { assertNoBakedSecrets } from "./config/bakedSecrets.js";
20
+ import { assertFileStorage } from "./config/assertFileStorage.js";
21
21
  import { StandaloneCryptoConfigFeature } from "./crypto/feature.js";
22
22
  import { Logger } from "@webiny/api-core/features/logger/index.js";
23
+ import { guardDeclaredTenantStorages } from "./tenantStorages/guardDeclaredTenantStorages.js";
23
24
  const SHUTDOWN_WAIT_MS = 6000;
24
25
  function createWebinyApiHandler(config) {
25
26
  let stopTaskRecovery;
26
27
  let stopScheduler;
27
28
  let stopWebsockets;
28
29
  let closeMessageBus;
29
- const standaloneConfig = readStandaloneConfig(process.env);
30
+ const standaloneConfig = EnvStandaloneConfig.fromEnv(process.env);
30
31
  const logger = createLogger();
31
- const registerRequest = async (container)=>{
32
- await registerApiRequestStack(container, {
33
- extensions: config.extensions,
34
- transports: {
35
- hostingConfig: (requestContainer)=>{
36
- ConfigPublicUrlsFeature.register(requestContainer);
37
- StandaloneCryptoConfigFeature.register(requestContainer);
38
- },
39
- realtime: (requestContainer)=>{
40
- WebsocketsStandaloneFeature.register(requestContainer);
41
- },
42
- fileManager: (requestContainer)=>{
43
- FileManagerStandaloneFeature.register(requestContainer, standaloneConfig.fileStorage);
44
- }
32
+ const stackConfig = {
33
+ extensions: config.extensions,
34
+ transports: {
35
+ hostingConfig: (scopeContainer)=>{
36
+ ConfigPublicUrlsFeature.register(scopeContainer);
37
+ StandaloneCryptoConfigFeature.register(scopeContainer);
38
+ },
39
+ realtime: (scopeContainer)=>{
40
+ WebsocketsStandaloneFeature.register(scopeContainer);
41
+ },
42
+ fileManager: (scopeContainer)=>{
43
+ const { uploadSecret } = standaloneConfig.fileStorage;
44
+ FileManagerStandaloneFeature.register(scopeContainer, {
45
+ uploadSecret
46
+ });
45
47
  }
46
- });
48
+ }
47
49
  };
48
50
  return createServerHandler({
51
+ keepAliveTimeoutMs: standaloneConfig.keepAliveTimeoutMs,
49
52
  root: async (rootContainer)=>{
50
- const extensions = config.extensions();
51
- const buildParams = await readBuildParams(extensions);
53
+ const buildParams = await registerRootBuildParams(rootContainer, config.extensions());
52
54
  assertNoBakedSecrets(buildParams);
55
+ assertFileStorage(buildParams);
53
56
  rootContainer.registerInstance(StandaloneConfig, standaloneConfig);
54
57
  rootContainer.registerInstance(Logger, logger);
55
58
  rootContainer.register(RandomProcessOwner).inSingletonScope();
56
- mkdirSync(standaloneConfig.fileStorage.storagePath, {
57
- recursive: true
58
- });
59
- NodeHttpFeature.register(rootContainer);
60
- rootContainer.registerDecorator(NodeHttpIdentityLoaderDecorator);
61
- rootContainer.registerDecorator(NodeHttpTenantLoaderDecorator);
62
- rootContainer.registerDecorator(NodeHttpAssumePermissionsDecorator);
59
+ registerHttpTransport(rootContainer, NodeHttpFeature, NodeHttpInputHandler);
60
+ TenantScopesRootFeature.register(rootContainer);
63
61
  rootContainer.registerInstance(ApiRequestRegistration, {
64
- register: registerRequest
62
+ register: (container, options)=>registerApiRequestStackInOneContainer(container, stackConfig, options)
65
63
  });
66
64
  await config.registerRootStorage(rootContainer, {
67
65
  buildParams
@@ -78,9 +76,14 @@ function createWebinyApiHandler(config) {
78
76
  BackgroundTasksStandaloneFeature.register(rootContainer);
79
77
  registerSchedulerServer(rootContainer);
80
78
  EmptyTrashBinsFeature.register(rootContainer);
79
+ await registerRootAllowedRequestHeaders(rootContainer);
80
+ await guardDeclaredTenantStorages({
81
+ root: rootContainer,
82
+ registerRequest: (container)=>registerApiRequestStack(container, stackConfig)
83
+ });
81
84
  },
82
85
  child: async (container)=>{
83
- await registerRequest(container);
86
+ await registerApiRequestStack(container, stackConfig);
84
87
  },
85
88
  onServer: async (server, rootContainer)=>{
86
89
  const connectionManager = rootContainer.resolve(WebsocketsConnectionManager);
@@ -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 { createServerHandler, NodeHttpFeature } from \"@webiny/api-kernel-core/nodeHttp/index.js\";\nimport { RandomProcessOwner } from \"@webiny/api-kernel-core\";\nimport { registerExtensions } from \"@webiny/handler\";\nimport { ApiRequestRegistration, registerApiRequestStack } from \"@webiny/api-composition-core\";\nimport { NodeHttpIdentityLoaderDecorator } from \"@webiny/api-composition-core/nodeHttp/index.js\";\nimport { NodeHttpTenantLoaderDecorator } from \"@webiny/api-composition-core/nodeHttp/index.js\";\nimport { NodeHttpAssumePermissionsDecorator } from \"@webiny/api-composition-core/nodeHttp/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 { mkdirSync } from \"node:fs\";\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 { StandaloneCryptoConfigFeature } from \"~/crypto/feature.js\";\nimport { createLogger, readBuildParams } from \"@webiny/api-composition-core\";\nimport { Logger } from \"@webiny/api-core/features/logger/index.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 * What every request's container gets (`child`). Also in the root as `ApiRequestRegistration`,\n * for work outside a request that needs a container a request would have: the SQL schema setup\n * builds one on its own connection.\n */\n const registerRequest = async (container: Container): Promise<void> => {\n // The transport-agnostic per-request stack. The realtime hook installs the server\n // WebSockets transport (overriding the domain's NullWebsocketsTransport); it resolves the\n // shared connection manager + adapter from the root. Scheduler is NOT a per-request\n // transport here — it's a root singleton wired in `root` + `onServer` (see below).\n await registerApiRequestStack(container, {\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: requestContainer => {\n ConfigPublicUrlsFeature.register(requestContainer);\n StandaloneCryptoConfigFeature.register(requestContainer);\n },\n // Server WebSockets transport; resolves the shared connection manager + adapter\n // from the root (registered as singletons in `root`).\n realtime: requestContainer => {\n WebsocketsStandaloneFeature.register(requestContainer);\n },\n // File-manager storage transport: local disk. Where AWS uses S3 (+ a separate asset-\n // delivery Lambda), the single-process server stores files on disk and serves them\n // in-process — FileManagerStandaloneFeature registers local asset delivery (overriding\n // the domain's null impls), the upload/multipart HTTP routes, and disk file ops.\n fileManager: requestContainer => {\n FileManagerStandaloneFeature.register(\n requestContainer,\n standaloneConfig.fileStorage\n );\n }\n }\n });\n };\n\n return createServerHandler({\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 const extensions = config.extensions();\n const buildParams = await readBuildParams(extensions);\n assertNoBakedSecrets(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 mkdirSync(standaloneConfig.fileStorage.storagePath, { recursive: true });\n\n // ── Transport (Node HTTP) ──────────────────────────────────\n // NodeHttpFeature registers the event type + HttpFeature (router) + the routing terminal.\n NodeHttpFeature.register(rootContainer);\n\n // ── Tenant + auth (extract → shared load) ──────────────────\n // registerDecorator applies LATER registrations as the OUTER wrapper (whose execute()\n // runs first). TENANT must be established before IDENTITY: API-key authentication resolves\n // the key by tenant partition (ApiKeysRepository reads TenantContext.getTenant()), so\n // identity depends on the tenant; the reverse is not true (RequestTenantLoader has no\n // identity dependency). Register identity first (inner) and tenant last (outer) → tenant\n // runs, then identity, then the router.\n rootContainer.registerDecorator(NodeHttpIdentityLoaderDecorator);\n rootContainer.registerDecorator(NodeHttpTenantLoaderDecorator);\n\n // Preview-as. Mirrors the AWS handler.\n rootContainer.registerDecorator(NodeHttpAssumePermissionsDecorator);\n\n rootContainer.registerInstance(ApiRequestRegistration, { register: registerRequest });\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\n child: async container => {\n await registerRequest(container);\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","registerRequest","container","registerApiRequestStack","requestContainer","ConfigPublicUrlsFeature","StandaloneCryptoConfigFeature","WebsocketsStandaloneFeature","FileManagerStandaloneFeature","createServerHandler","rootContainer","extensions","buildParams","readBuildParams","assertNoBakedSecrets","StandaloneConfig","Logger","RandomProcessOwner","mkdirSync","NodeHttpFeature","NodeHttpIdentityLoaderDecorator","NodeHttpTenantLoaderDecorator","NodeHttpAssumePermissionsDecorator","ApiRequestRegistration","WebsocketsServerRootFeature","WebsocketsRedisFeature","InProcessMessageBus","GraphQLSchemaCacheFeature","EncryptionKeyCacheFeature","JwksStoreFeature","BackgroundTasksStandaloneFeature","registerSchedulerServer","EmptyTrashBinsFeature","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":";;;;;;;;;;;;;;;;;;;;;;AAiFA,MAAMA,mBAAmB;AAElB,SAASC,uBAAuBC,MAAoC;IACvE,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IACJ,IAAIC;IAMJ,MAAMC,mBAAmBC,qBAAqBC,QAAQ,GAAG;IAGzD,MAAMC,SAASC;IAOf,MAAMC,kBAAkB,OAAOC;QAK3B,MAAMC,wBAAwBD,WAAW;YACrC,YAAYX,OAAO,UAAU;YAU7B,YAAY;gBAKR,eAAea,CAAAA;oBACXC,wBAAwB,QAAQ,CAACD;oBACjCE,8BAA8B,QAAQ,CAACF;gBAC3C;gBAGA,UAAUA,CAAAA;oBACNG,4BAA4B,QAAQ,CAACH;gBACzC;gBAKA,aAAaA,CAAAA;oBACTI,6BAA6B,QAAQ,CACjCJ,kBACAR,iBAAiB,WAAW;gBAEpC;YACJ;QACJ;IACJ;IAEA,OAAOa,oBAAoB;QACvB,MAAM,OAAMC;YAKR,MAAMC,aAAapB,OAAO,UAAU;YACpC,MAAMqB,cAAc,MAAMC,gBAAgBF;YAC1CG,qBAAqBF;YAErBF,cAAc,gBAAgB,CAACK,kBAAkBnB;YACjDc,cAAc,gBAAgB,CAACM,QAAQjB;YAGvCW,cAAc,QAAQ,CAACO,oBAAoB,gBAAgB;YAC3DC,UAAUtB,iBAAiB,WAAW,CAAC,WAAW,EAAE;gBAAE,WAAW;YAAK;YAItEuB,gBAAgB,QAAQ,CAACT;YASzBA,cAAc,iBAAiB,CAACU;YAChCV,cAAc,iBAAiB,CAACW;YAGhCX,cAAc,iBAAiB,CAACY;YAEhCZ,cAAc,gBAAgB,CAACa,wBAAwB;gBAAE,UAAUtB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ACA,MAAM2D,QAAQC,oBAAoB1C,eAAerB;YACjD,MAAMgE,mBAAmB5D,gBAAgBJ;YACzC,MAAMiD,aAAa5C;YACnB,MAAM4D,WAAWC,QAAQ,UAAU,CAAC;gBAACJ;gBAAOE;gBAAkBH;aAAiB;YAC/E,MAAMT,aAAaa,SAAS,IAAI,CAAC,IAAM3D;YAGvC,MAAM6D,UAAU,MAAMD,QAAQ,UAAU,CAAC;gBACrCJ;gBACAE;gBACAf;gBACAG;aACH;YACD,MAAMgB,SAASD,QAAQ,IAAI,CAAC,CAACE,SAClBA,AAAkB,eAAlBA,OAAO,MAAM;YAExB,IAAID,QACA,MAAMA,OAAO,MAAM;QAE3B;IACJ;AACJ"}
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,MAAM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BAACJ;gBAAOE;gBAAkBH;aAAiB;YAC/E,MAAMT,aAAaa,SAAS,IAAI,CAAC,IAAM/D;YAGvC,MAAMiE,UAAU,MAAMD,QAAQ,UAAU,CAAC;gBACrCJ;gBACAE;gBACAf;gBACAG;aACH;YACD,MAAMgB,SAASD,QAAQ,IAAI,CAAC,CAACE,SAClBA,AAAkB,eAAlBA,OAAO,MAAM;YAExB,IAAID,QACA,MAAMA,OAAO,MAAM;QAE3B;IACJ;AACJ"}
package/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { createWebinyApiHandler } from "./createWebinyApiHandler.js";
2
2
  export type { CreateWebinyApiHandlerConfig } from "./createWebinyApiHandler.js";
3
+ export { TenantStorageRemovedError, DECLARED_TENANT_STORAGES_KEY } from "./tenantStorages/guardDeclaredTenantStorages.js";
package/index.js CHANGED
@@ -1 +1,2 @@
1
1
  export { createWebinyApiHandler } from "./createWebinyApiHandler.js";
2
+ export { DECLARED_TENANT_STORAGES_KEY, TenantStorageRemovedError } from "./tenantStorages/guardDeclaredTenantStorages.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webiny/api-composition-standalone",
3
- "version": "0.0.0-unstable.e1999482d0",
3
+ "version": "6.6.0-alpha.14",
4
4
  "type": "module",
5
5
  "main": "index.js",
6
6
  "exports": {
@@ -18,25 +18,26 @@
18
18
  ],
19
19
  "license": "MIT",
20
20
  "dependencies": {
21
- "@webiny/api-composition-core": "0.0.0-unstable.e1999482d0",
22
- "@webiny/api-core": "0.0.0-unstable.e1999482d0",
23
- "@webiny/api-file-manager-standalone": "0.0.0-unstable.e1999482d0",
24
- "@webiny/api-graphql": "0.0.0-unstable.e1999482d0",
25
- "@webiny/api-headless-cms-bulk-actions-standalone": "0.0.0-unstable.e1999482d0",
26
- "@webiny/api-kernel-core": "0.0.0-unstable.e1999482d0",
27
- "@webiny/api-scheduler": "0.0.0-unstable.e1999482d0",
28
- "@webiny/api-scheduler-standalone": "0.0.0-unstable.e1999482d0",
29
- "@webiny/api-websockets-standalone": "0.0.0-unstable.e1999482d0",
30
- "@webiny/api-websockets-standalone-redis": "0.0.0-unstable.e1999482d0",
31
- "@webiny/background-tasks-standalone": "0.0.0-unstable.e1999482d0",
32
- "@webiny/feature": "0.0.0-unstable.e1999482d0",
33
- "@webiny/handler": "0.0.0-unstable.e1999482d0"
21
+ "@webiny/api-composition-core": "6.6.0-alpha.14",
22
+ "@webiny/api-core": "6.6.0-alpha.14",
23
+ "@webiny/api-file-manager-standalone": "6.6.0-alpha.14",
24
+ "@webiny/api-graphql": "6.6.0-alpha.14",
25
+ "@webiny/api-headless-cms-bulk-actions-standalone": "6.6.0-alpha.14",
26
+ "@webiny/api-kernel-core": "6.6.0-alpha.14",
27
+ "@webiny/api-object-storage": "6.6.0-alpha.14",
28
+ "@webiny/api-scheduler": "6.6.0-alpha.14",
29
+ "@webiny/api-scheduler-standalone": "6.6.0-alpha.14",
30
+ "@webiny/api-websockets-standalone": "6.6.0-alpha.14",
31
+ "@webiny/api-websockets-standalone-redis": "6.6.0-alpha.14",
32
+ "@webiny/background-tasks-standalone": "6.6.0-alpha.14",
33
+ "@webiny/feature": "6.6.0-alpha.14",
34
+ "@webiny/handler": "6.6.0-alpha.14"
34
35
  },
35
36
  "peerDependencies": {
36
37
  "@webiny/di": "^2.0.0"
37
38
  },
38
39
  "devDependencies": {
39
- "@webiny/build-tools": "0.0.0-unstable.e1999482d0",
40
+ "@webiny/build-tools": "6.6.0-alpha.14",
40
41
  "@webiny/di": "2.0.0",
41
42
  "rimraf": "6.1.4",
42
43
  "typescript": "7.0.2",
@@ -1,8 +1,6 @@
1
1
  import { ListTenantsUseCase } from "@webiny/api-core/features/tenancy/ListTenants/index.js";
2
- import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/index.js";
3
- import { IdentityContext } from "@webiny/api-core/exports/api/security.js";
2
+ import { TenantScopes } from "@webiny/api-core/features/tenancy/TenantScopes/index.js";
4
3
  import { Logger } from "@webiny/api-core/features/logger/abstractions.js";
5
- import { ListScheduledActionsUseCase } from "@webiny/api-scheduler/features/ListScheduledActions/index.js";
6
4
  import { ScheduledActionRecoverInputHandler } from "./ScheduledActionRecoverInputHandler.js";
7
5
  import { SchedulerSingleton } from "./abstractions/SchedulerSingleton.js";
8
6
  /**
@@ -15,12 +13,10 @@ import { SchedulerSingleton } from "./abstractions/SchedulerSingleton.js";
15
13
  */
16
14
  declare class RecoverScheduledActionsHandlerImpl implements ScheduledActionRecoverInputHandler.Interface {
17
15
  private readonly listTenants;
18
- private readonly tenantContext;
19
- private readonly identityContext;
20
- private readonly listScheduledActions;
16
+ private readonly tenantScopes;
21
17
  private readonly scheduler;
22
18
  private readonly logger;
23
- constructor(listTenants: ListTenantsUseCase.Interface, tenantContext: TenantContext.Interface, identityContext: IdentityContext.Interface, listScheduledActions: ListScheduledActionsUseCase.Interface, scheduler: SchedulerSingleton.Interface, logger: Logger.Interface);
19
+ constructor(listTenants: ListTenantsUseCase.Interface, tenantScopes: TenantScopes.Interface, scheduler: SchedulerSingleton.Interface, logger: Logger.Interface);
24
20
  execute(): Promise<ScheduledActionRecoverInputHandler.Result>;
25
21
  private recoverTenant;
26
22
  private recoverAllPending;
@@ -1,5 +1,5 @@
1
1
  import { ListTenantsUseCase } from "@webiny/api-core/features/tenancy/ListTenants/index.js";
2
- import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/index.js";
2
+ import { TenantScopes } from "@webiny/api-core/features/tenancy/TenantScopes/index.js";
3
3
  import { IdentityContext } from "@webiny/api-core/exports/api/security.js";
4
4
  import { Logger } from "@webiny/api-core/features/logger/abstractions.js";
5
5
  import { ListScheduledActionsUseCase } from "@webiny/api-scheduler/features/ListScheduledActions/index.js";
@@ -10,11 +10,9 @@ function canRecover(tenant) {
10
10
  return tenant.isInstalled && "disabled" !== tenant.status;
11
11
  }
12
12
  class RecoverScheduledActionsHandlerImpl {
13
- constructor(listTenants, tenantContext, identityContext, listScheduledActions, scheduler, logger){
13
+ constructor(listTenants, tenantScopes, scheduler, logger){
14
14
  this.listTenants = listTenants;
15
- this.tenantContext = tenantContext;
16
- this.identityContext = identityContext;
17
- this.listScheduledActions = listScheduledActions;
15
+ this.tenantScopes = tenantScopes;
18
16
  this.scheduler = scheduler;
19
17
  this.logger = logger;
20
18
  }
@@ -38,13 +36,13 @@ class RecoverScheduledActionsHandlerImpl {
38
36
  };
39
37
  }
40
38
  recoverTenant(tenant) {
41
- return this.tenantContext.withTenant(tenant, ()=>this.identityContext.withoutAuthorization(()=>this.recoverAllPending(tenant.id)));
39
+ return this.tenantScopes.withTenant(tenant, (scope)=>scope.resolve(IdentityContext).withoutAuthorization(()=>this.recoverAllPending(tenant.id, scope.resolve(ListScheduledActionsUseCase))));
42
40
  }
43
- async recoverAllPending(tenant) {
41
+ async recoverAllPending(tenant, listScheduledActions) {
44
42
  let recovered = 0;
45
43
  let after;
46
44
  do {
47
- const listResult = await this.listScheduledActions.execute({
45
+ const listResult = await listScheduledActions.execute({
48
46
  where: {},
49
47
  limit: PAGE_SIZE,
50
48
  after
@@ -69,9 +67,7 @@ const RecoverScheduledActionsHandler = ScheduledActionRecoverInputHandler.create
69
67
  implementation: RecoverScheduledActionsHandlerImpl,
70
68
  dependencies: [
71
69
  ListTenantsUseCase,
72
- TenantContext,
73
- IdentityContext,
74
- ListScheduledActionsUseCase,
70
+ TenantScopes,
75
71
  SchedulerSingleton,
76
72
  Logger
77
73
  ]
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler/RecoverScheduledActionsHandler.js","sources":["../../src/scheduler/RecoverScheduledActionsHandler.ts"],"sourcesContent":["import { ListTenantsUseCase } from \"@webiny/api-core/features/tenancy/ListTenants/index.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport type { Tenant } from \"@webiny/api-core/types/tenancy.js\";\nimport { IdentityContext } from \"@webiny/api-core/exports/api/security.js\";\nimport { Logger } from \"@webiny/api-core/features/logger/abstractions.js\";\nimport { ListScheduledActionsUseCase } from \"@webiny/api-scheduler/features/ListScheduledActions/index.js\";\nimport { ScheduledActionRecoverInputHandler } from \"./ScheduledActionRecoverInputHandler.js\";\nimport type { IPendingAction } from \"@webiny/api-scheduler-standalone\";\nimport { SchedulerSingleton } from \"./abstractions/SchedulerSingleton.js\";\n\n// Pending actions read per page.\nconst PAGE_SIZE = 1000;\n\n/*\n * A tenant that isn't installed has no scheduler model to read, and a disabled one must not run its\n * schedules. Both are left alone; a disabled tenant's schedules come back on the next restart after\n * it is re-enabled.\n */\nfunction canRecover(tenant: Tenant): boolean {\n return tenant.isInstalled && tenant.status !== \"disabled\";\n}\n\n/**\n * Re-arms every tenant's pending scheduled actions in the scheduler singleton. It keeps its timers in\n * memory, so a restart loses them all. Overdue actions run at once (see\n * `TimerSchedulerService.recover`).\n *\n * Each tenant is recovered on its own: one that fails is logged and reported in the result, and the\n * rest are still recovered. A fresh install has no tenants yet and recovers nothing.\n */\nclass RecoverScheduledActionsHandlerImpl implements ScheduledActionRecoverInputHandler.Interface {\n public constructor(\n private readonly listTenants: ListTenantsUseCase.Interface,\n private readonly tenantContext: TenantContext.Interface,\n private readonly identityContext: IdentityContext.Interface,\n private readonly listScheduledActions: ListScheduledActionsUseCase.Interface,\n private readonly scheduler: SchedulerSingleton.Interface,\n private readonly logger: Logger.Interface\n ) {}\n\n public async execute(): Promise<ScheduledActionRecoverInputHandler.Result> {\n // A failed lookup is not a fresh install: it throws, so the boot step reports it.\n const tenantsResult = await this.listTenants.execute();\n if (tenantsResult.isFail()) {\n throw tenantsResult.error;\n }\n\n let recovered = 0;\n const failedTenants: string[] = [];\n\n for (const tenant of tenantsResult.value) {\n if (!canRecover(tenant)) {\n continue;\n }\n try {\n recovered += await this.recoverTenant(tenant);\n } catch (error) {\n failedTenants.push(tenant.id);\n this.logger.error(\n { error, tenant: tenant.id },\n \"Could not recover the tenant's scheduled actions.\"\n );\n }\n }\n\n return { recovered, failedTenants };\n }\n\n private recoverTenant(tenant: Tenant): Promise<number> {\n return this.tenantContext.withTenant(tenant, () => {\n /*\n * Nobody is signed in at boot. Listing without authorization is what the run side does\n * too (ExecuteScheduledActionUseCase); otherwise the anonymous identity fails the\n * permission check.\n */\n return this.identityContext.withoutAuthorization(() => {\n return this.recoverAllPending(tenant.id);\n });\n });\n }\n\n /*\n * Re-arms page by page, so a lookup that fails on a later page still leaves the earlier pages\n * armed. The failure is rethrown and logged by the boot step.\n */\n private async recoverAllPending(tenant: string): Promise<number> {\n let recovered = 0;\n let after: string | undefined;\n\n do {\n const listResult = await this.listScheduledActions.execute({\n where: {},\n limit: PAGE_SIZE,\n after\n });\n if (listResult.isFail()) {\n throw listResult.error;\n }\n\n const page: IPendingAction[] = [];\n for (const action of listResult.value.items) {\n page.push({\n id: action.id,\n namespace: action.namespace,\n tenant,\n scheduledFor: action.scheduledFor\n });\n }\n\n await this.scheduler.recover(page);\n recovered += page.length;\n\n const { meta } = listResult.value;\n after = meta.hasMoreItems && meta.cursor ? meta.cursor : undefined;\n } while (after);\n\n return recovered;\n }\n}\n\nexport const RecoverScheduledActionsHandler =\n ScheduledActionRecoverInputHandler.createImplementation({\n implementation: RecoverScheduledActionsHandlerImpl,\n dependencies: [\n ListTenantsUseCase,\n TenantContext,\n IdentityContext,\n ListScheduledActionsUseCase,\n SchedulerSingleton,\n Logger\n ]\n });\n"],"names":["PAGE_SIZE","canRecover","tenant","RecoverScheduledActionsHandlerImpl","listTenants","tenantContext","identityContext","listScheduledActions","scheduler","logger","tenantsResult","recovered","failedTenants","error","after","listResult","page","action","meta","undefined","RecoverScheduledActionsHandler","ScheduledActionRecoverInputHandler","ListTenantsUseCase","TenantContext","IdentityContext","ListScheduledActionsUseCase","SchedulerSingleton","Logger"],"mappings":";;;;;;;AAWA,MAAMA,YAAY;AAOlB,SAASC,WAAWC,MAAc;IAC9B,OAAOA,OAAO,WAAW,IAAIA,AAAkB,eAAlBA,OAAO,MAAM;AAC9C;AAUA,MAAMC;IACF,YACqBC,WA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IC,OAAO,EAAE;gBACb,WAAWA,OAAO,SAAS;gBAC3Bf;gBACA,cAAce,OAAO,YAAY;YACrC;YAGJ,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAACD;YAC7BL,aAAaK,KAAK,MAAM;YAExB,MAAM,EAAEE,IAAI,EAAE,GAAGH,WAAW,KAAK;YACjCD,QAAQI,KAAK,YAAY,IAAIA,KAAK,MAAM,GAAGA,KAAK,MAAM,GAAGC;QAC7D,QAASL,MAAO;QAEhB,OAAOH;IACX;AACJ;AAEO,MAAMS,iCACTC,mCAAmC,oBAAoB,CAAC;IACpD,gBAAgBlB;IAChB,cAAc;QACVmB;QACAC;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
1
+ {"version":3,"file":"scheduler/RecoverScheduledActionsHandler.js","sources":["../../src/scheduler/RecoverScheduledActionsHandler.ts"],"sourcesContent":["import { ListTenantsUseCase } from \"@webiny/api-core/features/tenancy/ListTenants/index.js\";\nimport { TenantScopes } from \"@webiny/api-core/features/tenancy/TenantScopes/index.js\";\nimport type { Tenant } from \"@webiny/api-core/types/tenancy.js\";\nimport { IdentityContext } from \"@webiny/api-core/exports/api/security.js\";\nimport { Logger } from \"@webiny/api-core/features/logger/abstractions.js\";\nimport { ListScheduledActionsUseCase } from \"@webiny/api-scheduler/features/ListScheduledActions/index.js\";\nimport { ScheduledActionRecoverInputHandler } from \"./ScheduledActionRecoverInputHandler.js\";\nimport type { IPendingAction } from \"@webiny/api-scheduler-standalone\";\nimport { SchedulerSingleton } from \"./abstractions/SchedulerSingleton.js\";\n\n// Pending actions read per page.\nconst PAGE_SIZE = 1000;\n\n/*\n * A tenant that isn't installed has no scheduler model to read, and a disabled one must not run its\n * schedules. Both are left alone; a disabled tenant's schedules come back on the next restart after\n * it is re-enabled.\n */\nfunction canRecover(tenant: Tenant): boolean {\n return tenant.isInstalled && tenant.status !== \"disabled\";\n}\n\n/**\n * Re-arms every tenant's pending scheduled actions in the scheduler singleton. It keeps its timers in\n * memory, so a restart loses them all. Overdue actions run at once (see\n * `TimerSchedulerService.recover`).\n *\n * Each tenant is recovered on its own: one that fails is logged and reported in the result, and the\n * rest are still recovered. A fresh install has no tenants yet and recovers nothing.\n */\nclass RecoverScheduledActionsHandlerImpl implements ScheduledActionRecoverInputHandler.Interface {\n public constructor(\n private readonly listTenants: ListTenantsUseCase.Interface,\n private readonly tenantScopes: TenantScopes.Interface,\n private readonly scheduler: SchedulerSingleton.Interface,\n private readonly logger: Logger.Interface\n ) {}\n\n public async execute(): Promise<ScheduledActionRecoverInputHandler.Result> {\n // A failed lookup is not a fresh install: it throws, so the boot step reports it.\n const tenantsResult = await this.listTenants.execute();\n if (tenantsResult.isFail()) {\n throw tenantsResult.error;\n }\n\n let recovered = 0;\n const failedTenants: string[] = [];\n\n for (const tenant of tenantsResult.value) {\n if (!canRecover(tenant)) {\n continue;\n }\n try {\n recovered += await this.recoverTenant(tenant);\n } catch (error) {\n failedTenants.push(tenant.id);\n this.logger.error(\n { error, tenant: tenant.id },\n \"Could not recover the tenant's scheduled actions.\"\n );\n }\n }\n\n return { recovered, failedTenants };\n }\n\n private recoverTenant(tenant: Tenant): Promise<number> {\n return this.tenantScopes.withTenant(tenant, scope => {\n /*\n * Nobody is signed in at boot. Listing without authorization is what the run side does\n * too (ExecuteScheduledActionUseCase); otherwise the anonymous identity fails the\n * permission check.\n */\n return scope.resolve(IdentityContext).withoutAuthorization(() => {\n return this.recoverAllPending(\n tenant.id,\n scope.resolve(ListScheduledActionsUseCase)\n );\n });\n });\n }\n\n /*\n * Re-arms page by page, so a lookup that fails on a later page still leaves the earlier pages\n * armed. The failure is rethrown and logged by the boot step.\n */\n private async recoverAllPending(\n tenant: string,\n listScheduledActions: ListScheduledActionsUseCase.Interface\n ): Promise<number> {\n let recovered = 0;\n let after: string | undefined;\n\n do {\n const listResult = await listScheduledActions.execute({\n where: {},\n limit: PAGE_SIZE,\n after\n });\n if (listResult.isFail()) {\n throw listResult.error;\n }\n\n const page: IPendingAction[] = [];\n for (const action of listResult.value.items) {\n page.push({\n id: action.id,\n namespace: action.namespace,\n tenant,\n scheduledFor: action.scheduledFor\n });\n }\n\n await this.scheduler.recover(page);\n recovered += page.length;\n\n const { meta } = listResult.value;\n after = meta.hasMoreItems && meta.cursor ? meta.cursor : undefined;\n } while (after);\n\n return recovered;\n }\n}\n\nexport const RecoverScheduledActionsHandler =\n ScheduledActionRecoverInputHandler.createImplementation({\n implementation: RecoverScheduledActionsHandlerImpl,\n dependencies: [ListTenantsUseCase, TenantScopes, SchedulerSingleton, Logger]\n });\n"],"names":["PAGE_SIZE","canRecover","tenant","RecoverScheduledActionsHandlerImpl","listTenants","tenantScopes","scheduler","logger","tenantsResult","recovered","failedTenants","error","scope","IdentityContext","ListScheduledActionsUseCase","listScheduledActions","after","listResult","page","action","meta","undefined","RecoverScheduledActionsHandler","ScheduledActionRecoverInputHandler","ListTenantsUseCase","TenantScopes","SchedulerSingleton","Logger"],"mappings":";;;;;;;AAWA,MAAMA,YAAY;AAOlB,SAASC,WAAWC,MAAc;IAC9B,OAAOA,OAAO,WAAW,IAAIA,AAAkB,eAAlBA,OAAO,MAAM;AAC9C;AAUA,MAAMC;IACF,YACqBC,WAAyC,EACzCC,YAAoC,EACpCC,SAAuC,EACvCC,MAAwB,CAC3C;aAJmBH,WAAW,GAAXA;aACAC,YAAY,GAAZA;aACAC,SAAS,GAATA;aACAC,MAAM,GAANA;IAClB;IAEH,MAAa,UAA8D;QAEvE,MAAMC,gBAAgB,MAAM,IAAI,CAAC,WAAW,CAAC,OAAO;QACpD,IAAIA,cAAc,MAAM,IACpB,MAAMA,cAAc,KAAK;QAG7B,IAAIC,YAAY;QAChB,MAAMC,gBAA0B,EAAE;QAElC,KAAK,MAAMR,UAAUM,cAAc,KAAK,CACpC,IAAKP,WAAWC,SAGhB,IAAI;YACAO,aAAa,MAAM,IAAI,CAAC,aAAa,CAACP;QAC1C,EAAE,OAAOS,OAAO;YACZD,cAAc,IAAI,CAACR,OAAO,EAAE;YAC5B,IAAI,CAAC,MAAM,CAAC,KAAK,CACb;gBAAES;gBAAO,QAAQT,OAAO,EAAE;YAAC,GAC3B;QAER;QAGJ,OAAO;YAAEO;YAAWC;QAAc;IACtC;IAEQ,cAAcR,MAAc,EAAmB;QACnD,OAAO,IAAI,CAAC,YAAY,CAAC,UAAU,CAACA,QAAQU,CAAAA,QAMjCA,MAAM,OAAO,CAACC,iBAAiB,oBAAoB,CAAC,IAChD,IAAI,CAAC,iBAAiB,CACzBX,OAAO,EAAE,EACTU,MAAM,OAAO,CAACE;IAI9B;IAMA,MAAc,kBACVZ,MAAc,EACda,oBAA2D,EAC5C;QACf,IAAIN,YAAY;QAChB,IAAIO;QAEJ,GAAG;YACC,MAAMC,aAAa,MAAMF,qBAAqB,OAAO,CAAC;gBAClD,OAAO,CAAC;gBACR,OAAOf;gBACPgB;YACJ;YACA,IAAIC,WAAW,MAAM,IACjB,MAAMA,WAAW,KAAK;YAG1B,MAAMC,OAAyB,EAAE;YACjC,KAAK,MAAMC,UAAUF,WAAW,KAAK,CAAC,KAAK,CACvCC,KAAK,IAAI,CAAC;gBACN,IAAIC,OAAO,EAAE;gBACb,WAAWA,OAAO,SAAS;gBAC3BjB;gBACA,cAAciB,OAAO,YAAY;YACrC;YAGJ,MAAM,IAAI,CAAC,SAAS,CAAC,OAAO,CAACD;YAC7BT,aAAaS,KAAK,MAAM;YAExB,MAAM,EAAEE,IAAI,EAAE,GAAGH,WAAW,KAAK;YACjCD,QAAQI,KAAK,YAAY,IAAIA,KAAK,MAAM,GAAGA,KAAK,MAAM,GAAGC;QAC7D,QAASL,MAAO;QAEhB,OAAOP;IACX;AACJ;AAEO,MAAMa,iCACTC,mCAAmC,oBAAoB,CAAC;IACpD,gBAAgBpB;IAChB,cAAc;QAACqB;QAAoBC;QAAcC;QAAoBC;KAAO;AAChF"}
@@ -3,11 +3,9 @@ import type { IScheduledActionEvent } from "@webiny/api-kernel-core";
3
3
  import type { IScheduledActionResult } from "@webiny/api-kernel-core";
4
4
  import type { InputContext } from "@webiny/api-kernel-core";
5
5
  import type { NextFunction } from "@webiny/api-kernel-core";
6
- import { GetTenantByIdUseCase } from "@webiny/api-core/exports/api/tenancy.js";
6
+ import { GetTenantByIdUseCase, TenantScopes } from "@webiny/api-core/exports/api/tenancy.js";
7
7
  import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/index.js";
8
- import { IdentityContext } from "@webiny/api-core/exports/api/security.js";
9
8
  import { GlobalKeyValueStore } from "@webiny/api-core/features/keyValueStore/index.js";
10
- import { GetScheduledActionUseCase } from "@webiny/api-scheduler/features/GetScheduledAction/index.js";
11
9
  /**
12
10
  * Runs a fired scheduled action at most once across all processes. Every standalone process holds its
13
11
  * own timers for the same actions, so the same action fires in each of them; on AWS, EventBridge
@@ -21,11 +19,10 @@ import { GetScheduledActionUseCase } from "@webiny/api-scheduler/features/GetSch
21
19
  declare class RunScheduledActionOnceDecoratorImpl implements ScheduledActionInputHandler.Interface {
22
20
  private readonly getTenantById;
23
21
  private readonly tenantContext;
24
- private readonly identityContext;
25
- private readonly getScheduledAction;
22
+ private readonly tenantScopes;
26
23
  private readonly store;
27
24
  private readonly decoratee;
28
- constructor(getTenantById: GetTenantByIdUseCase.Interface, tenantContext: TenantContext.Interface, identityContext: IdentityContext.Interface, getScheduledAction: GetScheduledActionUseCase.Interface, store: GlobalKeyValueStore.Interface, decoratee: ScheduledActionInputHandler.Interface);
25
+ constructor(getTenantById: GetTenantByIdUseCase.Interface, tenantContext: TenantContext.Interface, tenantScopes: TenantScopes.Interface, store: GlobalKeyValueStore.Interface, decoratee: ScheduledActionInputHandler.Interface);
29
26
  execute(inputCtx: InputContext<IScheduledActionEvent>, next: NextFunction): Promise<IScheduledActionResult>;
30
27
  private findDueTime;
31
28
  private takeClaim;
@@ -1,6 +1,6 @@
1
1
  import { hostname } from "node:os";
2
2
  import { SCHEDULED_ACTION_EVENT_IDENTIFIER, ScheduledActionInputHandler } from "@webiny/api-kernel-core";
3
- import { GetTenantByIdUseCase } from "@webiny/api-core/exports/api/tenancy.js";
3
+ import { GetTenantByIdUseCase, TenantScopes } from "@webiny/api-core/exports/api/tenancy.js";
4
4
  import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/index.js";
5
5
  import { IdentityContext } from "@webiny/api-core/exports/api/security.js";
6
6
  import { GlobalKeyValueStore, KeyValueConditionFailedError } from "@webiny/api-core/features/keyValueStore/index.js";
@@ -18,11 +18,10 @@ const expiresIn = (ms)=>{
18
18
  return new Date(expiresAtMs);
19
19
  };
20
20
  class RunScheduledActionOnceDecoratorImpl {
21
- constructor(getTenantById, tenantContext, identityContext, getScheduledAction, store, decoratee){
21
+ constructor(getTenantById, tenantContext, tenantScopes, store, decoratee){
22
22
  this.getTenantById = getTenantById;
23
23
  this.tenantContext = tenantContext;
24
- this.identityContext = identityContext;
25
- this.getScheduledAction = getScheduledAction;
24
+ this.tenantScopes = tenantScopes;
26
25
  this.store = store;
27
26
  this.decoratee = decoratee;
28
27
  }
@@ -45,8 +44,8 @@ class RunScheduledActionOnceDecoratorImpl {
45
44
  async findDueTime(tenantId, input) {
46
45
  const tenantResult = await this.getTenantById.execute(tenantId);
47
46
  if (tenantResult.isFail()) throw tenantResult.error;
48
- return this.tenantContext.withTenant(tenantResult.value, ()=>this.identityContext.withoutAuthorization(async ()=>{
49
- const result = await this.getScheduledAction.execute({
47
+ return this.tenantScopes.withTenant(tenantResult.value, (scope)=>scope.resolve(IdentityContext).withoutAuthorization(async ()=>{
48
+ const result = await scope.resolve(GetScheduledActionUseCase).execute({
50
49
  id: input.id,
51
50
  namespace: input.namespace
52
51
  });
@@ -81,8 +80,7 @@ const RunScheduledActionOnceDecorator = ScheduledActionInputHandler.createDecora
81
80
  dependencies: [
82
81
  GetTenantByIdUseCase,
83
82
  TenantContext,
84
- IdentityContext,
85
- GetScheduledActionUseCase,
83
+ TenantScopes,
86
84
  GlobalKeyValueStore
87
85
  ]
88
86
  });
@@ -1 +1 @@
1
- {"version":3,"file":"scheduler/RunScheduledActionOnceDecorator.js","sources":["../../src/scheduler/RunScheduledActionOnceDecorator.ts"],"sourcesContent":["import { hostname } from \"node:os\";\nimport { ScheduledActionInputHandler } from \"@webiny/api-kernel-core\";\nimport { SCHEDULED_ACTION_EVENT_IDENTIFIER } from \"@webiny/api-kernel-core\";\nimport type { IScheduledActionEvent } from \"@webiny/api-kernel-core\";\nimport type { IScheduledActionEventPayload } from \"@webiny/api-kernel-core\";\nimport type { IScheduledActionResult } from \"@webiny/api-kernel-core\";\nimport type { InputContext } from \"@webiny/api-kernel-core\";\nimport type { NextFunction } from \"@webiny/api-kernel-core\";\nimport { GetTenantByIdUseCase } from \"@webiny/api-core/exports/api/tenancy.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport { IdentityContext } from \"@webiny/api-core/exports/api/security.js\";\nimport { GlobalKeyValueStore } from \"@webiny/api-core/features/keyValueStore/index.js\";\nimport { KeyValueConditionFailedError } from \"@webiny/api-core/features/keyValueStore/index.js\";\nimport { GetScheduledActionUseCase } from \"@webiny/api-scheduler/features/GetScheduledAction/index.js\";\n\nconst CLAIM_SCOPE = \"scheduler/claims\";\n\n/*\n * How long one run of an action holds its claim. Long enough for any action to finish; a run that\n * succeeds deletes the action, so the claim only matters while it runs.\n */\nconst RUN_CLAIM_MS = 10 * 60_000;\n\n// After a failed run, other processes leave the action alone this long before trying it again.\nconst RETRY_AFTER_FAILURE_MS = 24 * 60 * 60_000;\n\n/*\n * Timers fire slightly early or late; an action due within this much is run. One due later than that\n * belongs to a timer another process moved, and this firing is stale.\n */\nconst EARLY_TOLERANCE_MS = 1000;\n\nconst SUCCESS: IScheduledActionResult = { success: true };\n\n// Names this process in the claims it writes, for whoever reads them in the database.\nconst PROCESS_NAME = `${hostname()}:${process.pid}`;\n\nconst expiresIn = (ms: number): Date => {\n const expiresAtMs = Date.now() + ms;\n return new Date(expiresAtMs);\n};\n\n/**\n * Runs a fired scheduled action at most once across all processes. Every standalone process holds its\n * own timers for the same actions, so the same action fires in each of them; on AWS, EventBridge\n * fires it once and this decorator is not registered.\n *\n * Before the action runs, it is read again. Gone means it was cancelled or already ran. Due later\n * means another process moved it and this timer is stale. Otherwise the process takes a claim on the\n * action at its due time, and only the process that gets it runs the action. Rescheduling changes\n * the due time, so a moved action gets a fresh claim.\n */\nclass RunScheduledActionOnceDecoratorImpl implements ScheduledActionInputHandler.Interface {\n public constructor(\n private readonly getTenantById: GetTenantByIdUseCase.Interface,\n private readonly tenantContext: TenantContext.Interface,\n private readonly identityContext: IdentityContext.Interface,\n private readonly getScheduledAction: GetScheduledActionUseCase.Interface,\n private readonly store: GlobalKeyValueStore.Interface,\n private readonly decoratee: ScheduledActionInputHandler.Interface\n ) {}\n\n public async execute(\n inputCtx: InputContext<IScheduledActionEvent>,\n next: NextFunction\n ): Promise<IScheduledActionResult> {\n const input = inputCtx.input[SCHEDULED_ACTION_EVENT_IDENTIFIER];\n const tenantId = input.tenant || this.tenantContext.getTenant().id;\n\n const dueAt = await this.findDueTime(tenantId, input);\n if (!dueAt) {\n return SUCCESS;\n }\n if (dueAt.getTime() > Date.now() + EARLY_TOLERANCE_MS) {\n return SUCCESS;\n }\n\n const key = `${tenantId}/${input.id}/${dueAt.toISOString()}`;\n const claimed = await this.takeClaim(key);\n if (!claimed) {\n return SUCCESS;\n }\n\n try {\n return await this.decoratee.execute(inputCtx, next);\n } catch (error) {\n await this.holdAfterFailure(key);\n throw error;\n }\n }\n\n // The action's due time, or `null` when it no longer exists.\n private async findDueTime(\n tenantId: string,\n input: IScheduledActionEventPayload\n ): Promise<Date | null> {\n const tenantResult = await this.getTenantById.execute(tenantId);\n if (tenantResult.isFail()) {\n throw tenantResult.error;\n }\n\n return this.tenantContext.withTenant(tenantResult.value, () => {\n // GetScheduledAction checks permissions, and nobody is signed in when a timer fires.\n return this.identityContext.withoutAuthorization(async () => {\n const result = await this.getScheduledAction.execute({\n id: input.id,\n namespace: input.namespace\n });\n if (result.isOk()) {\n return result.value.scheduledFor;\n }\n if (result.error.code === \"Scheduler/ScheduledAction/NotFound\") {\n return null;\n }\n throw result.error;\n });\n });\n }\n\n private async takeClaim(key: string): Promise<boolean> {\n const expiresAt = expiresIn(RUN_CLAIM_MS);\n const result = await this.store.set(key, PROCESS_NAME, {\n scope: CLAIM_SCOPE,\n expiresAt,\n condition: { exists: false }\n });\n if (result.isOk()) {\n return true;\n }\n if (result.error instanceof KeyValueConditionFailedError) {\n return false;\n }\n throw result.error;\n }\n\n /*\n * The action stays stored after a failed run, with the error on it, and every process's\n * recovery fires overdue actions each minute. Holding the claim keeps that to one retry a day.\n */\n private async holdAfterFailure(key: string): Promise<void> {\n const expiresAt = expiresIn(RETRY_AFTER_FAILURE_MS);\n await this.store.set(key, PROCESS_NAME, { scope: CLAIM_SCOPE, expiresAt });\n }\n}\n\nexport const RunScheduledActionOnceDecorator = ScheduledActionInputHandler.createDecorator({\n decorator: RunScheduledActionOnceDecoratorImpl,\n dependencies: [\n GetTenantByIdUseCase,\n TenantContext,\n IdentityContext,\n GetScheduledActionUseCase,\n GlobalKeyValueStore\n ]\n});\n"],"names":["CLAIM_SCOPE","RUN_CLAIM_MS","RETRY_AFTER_FAILURE_MS","EARLY_TOLERANCE_MS","SUCCESS","PROCESS_NAME","hostname","process","expiresIn","ms","expiresAtMs","Date","RunScheduledActionOnceDecoratorImpl","getTenantById","tenantContext","identityContext","getScheduledAction","store","decoratee","inputCtx","next","input","SCHEDULED_ACTION_EVENT_IDENTIFIER","tenantId","dueAt","key","claimed","error","tenantResult","result","expiresAt","KeyValueConditionFailedError","RunScheduledActionOnceDecorator","ScheduledActionInputHandler","GetTenantByIdUseCase","TenantContext","IdentityContext","GetScheduledActionUseCase","GlobalKeyValueStore"],"mappings":";;;;;;;AAeA,MAAMA,cAAc;AAMpB,MAAMC,eAAe;AAGrB,MAAMC,yBAAyB;AAM/B,MAAMC,qBAAqB;AAE3B,MAAMC,UAAkC;IAAE,SAAS;AAAK;AAGx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OAAO,IAAI,CAAC,aAAa,CAAC,UAAU,CAACA,aAAa,KAAK,EAAE,IAE9C,IAAI,CAAC,eAAe,CAAC,oBAAoB,CAAC;gBAC7C,MAAMC,SAAS,MAAM,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC;oBACjD,IAAIR,MAAM,EAAE;oBACZ,WAAWA,MAAM,SAAS;gBAC9B;gBACA,IAAIQ,OAAO,IAAI,IACX,OAAOA,OAAO,KAAK,CAAC,YAAY;gBAEpC,IAAIA,AAAsB,yCAAtBA,OAAO,KAAK,CAAC,IAAI,EACjB,OAAO;gBAEX,MAAMA,OAAO,KAAK;YACtB;IAER;IAEA,MAAc,UAAUJ,GAAW,EAAoB;QACnD,MAAMK,YAAYtB,UAAUP;QAC5B,MAAM4B,SAAS,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAACJ,KAAKpB,cAAc;YACnD,OAAOL;YACP8B;YACA,WAAW;gBAAE,QAAQ;YAAM;QAC/B;QACA,IAAID,OAAO,IAAI,IACX,OAAO;QAEX,IAAIA,OAAO,KAAK,YAAYE,8BACxB,OAAO;QAEX,MAAMF,OAAO,KAAK;IACtB;IAMA,MAAc,iBAAiBJ,GAAW,EAAiB;QACvD,MAAMK,YAAYtB,UAAUN;QAC5B,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAACuB,KAAKpB,cAAc;YAAE,OAAOL;YAAa8B;QAAU;IAC5E;AACJ;AAEO,MAAME,kCAAkCC,4BAA4B,eAAe,CAAC;IACvF,WAAWrB;IACX,cAAc;QACVsB;QACAC;QACAC;QACAC;QACAC;KACH;AACL"}
1
+ {"version":3,"file":"scheduler/RunScheduledActionOnceDecorator.js","sources":["../../src/scheduler/RunScheduledActionOnceDecorator.ts"],"sourcesContent":["import { hostname } from \"node:os\";\nimport { ScheduledActionInputHandler } from \"@webiny/api-kernel-core\";\nimport { SCHEDULED_ACTION_EVENT_IDENTIFIER } from \"@webiny/api-kernel-core\";\nimport type { IScheduledActionEvent } from \"@webiny/api-kernel-core\";\nimport type { IScheduledActionEventPayload } from \"@webiny/api-kernel-core\";\nimport type { IScheduledActionResult } from \"@webiny/api-kernel-core\";\nimport type { InputContext } from \"@webiny/api-kernel-core\";\nimport type { NextFunction } from \"@webiny/api-kernel-core\";\nimport { GetTenantByIdUseCase, TenantScopes } from \"@webiny/api-core/exports/api/tenancy.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport { IdentityContext } from \"@webiny/api-core/exports/api/security.js\";\nimport { GlobalKeyValueStore } from \"@webiny/api-core/features/keyValueStore/index.js\";\nimport { KeyValueConditionFailedError } from \"@webiny/api-core/features/keyValueStore/index.js\";\nimport { GetScheduledActionUseCase } from \"@webiny/api-scheduler/features/GetScheduledAction/index.js\";\n\nconst CLAIM_SCOPE = \"scheduler/claims\";\n\n/*\n * How long one run of an action holds its claim. Long enough for any action to finish; a run that\n * succeeds deletes the action, so the claim only matters while it runs.\n */\nconst RUN_CLAIM_MS = 10 * 60_000;\n\n// After a failed run, other processes leave the action alone this long before trying it again.\nconst RETRY_AFTER_FAILURE_MS = 24 * 60 * 60_000;\n\n/*\n * Timers fire slightly early or late; an action due within this much is run. One due later than that\n * belongs to a timer another process moved, and this firing is stale.\n */\nconst EARLY_TOLERANCE_MS = 1000;\n\nconst SUCCESS: IScheduledActionResult = { success: true };\n\n// Names this process in the claims it writes, for whoever reads them in the database.\nconst PROCESS_NAME = `${hostname()}:${process.pid}`;\n\nconst expiresIn = (ms: number): Date => {\n const expiresAtMs = Date.now() + ms;\n return new Date(expiresAtMs);\n};\n\n/**\n * Runs a fired scheduled action at most once across all processes. Every standalone process holds its\n * own timers for the same actions, so the same action fires in each of them; on AWS, EventBridge\n * fires it once and this decorator is not registered.\n *\n * Before the action runs, it is read again. Gone means it was cancelled or already ran. Due later\n * means another process moved it and this timer is stale. Otherwise the process takes a claim on the\n * action at its due time, and only the process that gets it runs the action. Rescheduling changes\n * the due time, so a moved action gets a fresh claim.\n */\nclass RunScheduledActionOnceDecoratorImpl implements ScheduledActionInputHandler.Interface {\n public constructor(\n private readonly getTenantById: GetTenantByIdUseCase.Interface,\n private readonly tenantContext: TenantContext.Interface,\n private readonly tenantScopes: TenantScopes.Interface,\n private readonly store: GlobalKeyValueStore.Interface,\n private readonly decoratee: ScheduledActionInputHandler.Interface\n ) {}\n\n public async execute(\n inputCtx: InputContext<IScheduledActionEvent>,\n next: NextFunction\n ): Promise<IScheduledActionResult> {\n const input = inputCtx.input[SCHEDULED_ACTION_EVENT_IDENTIFIER];\n const tenantId = input.tenant || this.tenantContext.getTenant().id;\n\n const dueAt = await this.findDueTime(tenantId, input);\n if (!dueAt) {\n return SUCCESS;\n }\n if (dueAt.getTime() > Date.now() + EARLY_TOLERANCE_MS) {\n return SUCCESS;\n }\n\n const key = `${tenantId}/${input.id}/${dueAt.toISOString()}`;\n const claimed = await this.takeClaim(key);\n if (!claimed) {\n return SUCCESS;\n }\n\n try {\n return await this.decoratee.execute(inputCtx, next);\n } catch (error) {\n await this.holdAfterFailure(key);\n throw error;\n }\n }\n\n // The action's due time, or `null` when it no longer exists.\n private async findDueTime(\n tenantId: string,\n input: IScheduledActionEventPayload\n ): Promise<Date | null> {\n const tenantResult = await this.getTenantById.execute(tenantId);\n if (tenantResult.isFail()) {\n throw tenantResult.error;\n }\n\n return this.tenantScopes.withTenant(tenantResult.value, scope => {\n // GetScheduledAction checks permissions, and nobody is signed in when a timer fires.\n return scope.resolve(IdentityContext).withoutAuthorization(async () => {\n const result = await scope.resolve(GetScheduledActionUseCase).execute({\n id: input.id,\n namespace: input.namespace\n });\n if (result.isOk()) {\n return result.value.scheduledFor;\n }\n if (result.error.code === \"Scheduler/ScheduledAction/NotFound\") {\n return null;\n }\n throw result.error;\n });\n });\n }\n\n private async takeClaim(key: string): Promise<boolean> {\n const expiresAt = expiresIn(RUN_CLAIM_MS);\n const result = await this.store.set(key, PROCESS_NAME, {\n scope: CLAIM_SCOPE,\n expiresAt,\n condition: { exists: false }\n });\n if (result.isOk()) {\n return true;\n }\n if (result.error instanceof KeyValueConditionFailedError) {\n return false;\n }\n throw result.error;\n }\n\n /*\n * The action stays stored after a failed run, with the error on it, and every process's\n * recovery fires overdue actions each minute. Holding the claim keeps that to one retry a day.\n */\n private async holdAfterFailure(key: string): Promise<void> {\n const expiresAt = expiresIn(RETRY_AFTER_FAILURE_MS);\n await this.store.set(key, PROCESS_NAME, { scope: CLAIM_SCOPE, expiresAt });\n }\n}\n\nexport const RunScheduledActionOnceDecorator = ScheduledActionInputHandler.createDecorator({\n decorator: RunScheduledActionOnceDecoratorImpl,\n dependencies: [GetTenantByIdUseCase, TenantContext, TenantScopes, GlobalKeyValueStore]\n});\n"],"names":["CLAIM_SCOPE","RUN_CLAIM_MS","RETRY_AFTER_FAILURE_MS","EARLY_TOLERANCE_MS","SUCCESS","PROCESS_NAME","hostname","process","expiresIn","ms","expiresAtMs","Date","RunScheduledActionOnceDecoratorImpl","getTenantById","tenantContext","tenantScopes","store","decoratee","inputCtx","next","input","SCHEDULED_ACTION_EVENT_IDENTIFIER","tenantId","dueAt","key","claimed","error","tenantResult","scope","IdentityContext","result","GetScheduledActionUseCase","expiresAt","KeyValueConditionFailedError","RunScheduledActionOnceDecorator","ScheduledActionInputHandler","GetTenantByIdUseCase","TenantContext","TenantScopes","GlobalKeyValueStore"],"mappings":";;;;;;;AAeA,MAAMA,cAAc;AAMpB,MAAMC,eAAe;AAGrB,MAAMC,yBAAyB;AAM/B,MAAMC,qBAAqB;AAE3B,MAAMC,UAAkC;IAAE,SAAS;AAAK;AAGxD,MAAMC,eAAe,GAAGC,WAAW,CAAC,EAAEC,QAAQ,GAAG,EAAE;AAEnD,MAAMC,YAAY,CAACC;IACf,MAAMC,cAAcC,KAAK,GAAG,KAAKF;IACjC,OAAO,IAAIE,KAAKD;AACpB;AAYA,MAAME;IACF,YACqBC,aAA6C,EAC7CC,aAAsC,EACtCC,YAAoC,EACpCC,KAAoC,EACpCC,SAAgD,CACnE;a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CAAC,YAAY;gBAEpC,IAAIA,AAAsB,yCAAtBA,OAAO,KAAK,CAAC,IAAI,EACjB,OAAO;gBAEX,MAAMA,OAAO,KAAK;YACtB;IAER;IAEA,MAAc,UAAUN,GAAW,EAAoB;QACnD,MAAMQ,YAAYxB,UAAUP;QAC5B,MAAM6B,SAAS,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAACN,KAAKnB,cAAc;YACnD,OAAOL;YACPgC;YACA,WAAW;gBAAE,QAAQ;YAAM;QAC/B;QACA,IAAIF,OAAO,IAAI,IACX,OAAO;QAEX,IAAIA,OAAO,KAAK,YAAYG,8BACxB,OAAO;QAEX,MAAMH,OAAO,KAAK;IACtB;IAMA,MAAc,iBAAiBN,GAAW,EAAiB;QACvD,MAAMQ,YAAYxB,UAAUN;QAC5B,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAACsB,KAAKnB,cAAc;YAAE,OAAOL;YAAagC;QAAU;IAC5E;AACJ;AAEO,MAAME,kCAAkCC,4BAA4B,eAAe,CAAC;IACvF,WAAWvB;IACX,cAAc;QAACwB;QAAsBC;QAAeC;QAAcC;KAAoB;AAC1F"}
@@ -0,0 +1,36 @@
1
+ import type { Container } from "@webiny/di";
2
+ /** Where the declared storages are recorded: root's global key-value store. */
3
+ export declare const DECLARED_TENANT_STORAGES_KEY = "TenantStorages/Declared";
4
+ /** An extra storage, as the server records it at start. */
5
+ export interface DeclaredTenantStorage {
6
+ id: string;
7
+ retired: boolean;
8
+ }
9
+ /**
10
+ * A storage that was declared, and not retired, when the server last started, and is declared no
11
+ * more. Tenants may still run on it, and they would stop working: retire it first, so it's no longer
12
+ * offered for new tenants, move its tenants off, then remove it.
13
+ */
14
+ export declare class TenantStorageRemovedError extends Error {
15
+ readonly storages: string[];
16
+ constructor(storages: string[]);
17
+ }
18
+ /** The recorded storages that weren't retired and are declared no more. */
19
+ export declare const findRemovedTenantStorages: (recorded: DeclaredTenantStorage[], declared: DeclaredTenantStorage[]) => string[];
20
+ export interface GuardDeclaredTenantStoragesParams {
21
+ /** The root container, with every root registration done. */
22
+ root: Container;
23
+ /** Registers a request's services in a fresh child of the root. */
24
+ registerRequest: (container: Container) => Promise<void>;
25
+ }
26
+ /**
27
+ * The standalone server's guard against removing a storage tenants may still run on. A deploy on
28
+ * AWS compares the config with the stack's outputs before Pulumi runs; a standalone server has no
29
+ * outputs, so it records the extra storages it was started with (`id`, `retired`) in root's global
30
+ * key-value store, and at the next start refuses to start when one that wasn't retired is gone.
31
+ * One read at every start, and a write when the storages changed.
32
+ *
33
+ * It runs once every root registration is done, in a request container built for it, in root's
34
+ * scope: the record is root's data, on the default storage.
35
+ */
36
+ export declare function guardDeclaredTenantStorages(params: GuardDeclaredTenantStoragesParams): Promise<void>;
@@ -0,0 +1,60 @@
1
+ import { RequestContainer } from "@webiny/api-kernel-core";
2
+ import { GlobalKeyValueStore, KeyNotFoundError } from "@webiny/api-core/features/keyValueStore/index.js";
3
+ import { TenantScopes } from "@webiny/api-core/features/tenancy/TenantScopes/index.js";
4
+ import { TenantStorages } from "@webiny/api-core/features/tenancy/TenantStorages/index.js";
5
+ const DECLARED_TENANT_STORAGES_KEY = "TenantStorages/Declared";
6
+ class TenantStorageRemovedError extends Error {
7
+ constructor(storages){
8
+ const names = storages.map((id)=>`\`${id}\``).join(", ");
9
+ const one = 1 === storages.length;
10
+ super([
11
+ `${one ? "Storage" : "Storages"} ${names} ${one ? "was" : "were"} removed but not retired.`,
12
+ `Tenants may still run on ${one ? "it" : "them"}. Declare ${one ? "it" : "them"} again with \`retired\` set,`,
13
+ `start the server once, and remove ${one ? "it" : "them"} only once no tenant runs there.`
14
+ ].join(" "));
15
+ this.name = "TenantStorageRemovedError";
16
+ this.storages = storages;
17
+ }
18
+ }
19
+ const findRemovedTenantStorages = (recorded, declared)=>{
20
+ const declaredIds = new Set(declared.map((storage)=>storage.id));
21
+ return recorded.filter((storage)=>!storage.retired && !declaredIds.has(storage.id)).map((storage)=>storage.id);
22
+ };
23
+ const sameStorages = (a, b)=>{
24
+ const key = (storages)=>JSON.stringify([
25
+ ...storages
26
+ ].sort((x, y)=>x.id.localeCompare(y.id)).map((s)=>[
27
+ s.id,
28
+ s.retired
29
+ ]));
30
+ return key(a) === key(b);
31
+ };
32
+ async function guardDeclaredTenantStorages(params) {
33
+ const { root } = params;
34
+ const [storages] = root.resolveAll(TenantStorages);
35
+ const declared = (storages?.list() ?? []).filter((storage)=>!storage.isDefault).map((storage)=>({
36
+ id: storage.id,
37
+ retired: storage.retired
38
+ }));
39
+ const request = root.createChildContainer();
40
+ request.registerInstance(RequestContainer, request);
41
+ await params.registerRequest(request);
42
+ await request.resolve(TenantScopes).withRootTenant(async (scope)=>{
43
+ const store = scope.resolve(GlobalKeyValueStore);
44
+ const result = await store.get(DECLARED_TENANT_STORAGES_KEY);
45
+ let recorded = [];
46
+ if (result.isOk()) recorded = result.value?.storages ?? [];
47
+ else if (!(result.error instanceof KeyNotFoundError)) throw result.error;
48
+ const removed = findRemovedTenantStorages(recorded, declared);
49
+ if (removed.length > 0) throw new TenantStorageRemovedError(removed);
50
+ if (sameStorages(recorded, declared)) return;
51
+ const record = {
52
+ storages: declared
53
+ };
54
+ const written = await store.set(DECLARED_TENANT_STORAGES_KEY, record);
55
+ if (written.isFail()) throw written.error;
56
+ });
57
+ }
58
+ export { DECLARED_TENANT_STORAGES_KEY, TenantStorageRemovedError, findRemovedTenantStorages, guardDeclaredTenantStorages };
59
+
60
+ //# sourceMappingURL=guardDeclaredTenantStorages.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tenantStorages/guardDeclaredTenantStorages.js","sources":["../../src/tenantStorages/guardDeclaredTenantStorages.ts"],"sourcesContent":["import type { Container } from \"@webiny/di\";\nimport { RequestContainer } from \"@webiny/api-kernel-core\";\nimport {\n GlobalKeyValueStore,\n KeyNotFoundError\n} from \"@webiny/api-core/features/keyValueStore/index.js\";\nimport { TenantScopes } from \"@webiny/api-core/features/tenancy/TenantScopes/index.js\";\nimport { TenantStorages } from \"@webiny/api-core/features/tenancy/TenantStorages/index.js\";\n\n/** Where the declared storages are recorded: root's global key-value store. */\nexport const DECLARED_TENANT_STORAGES_KEY = \"TenantStorages/Declared\";\n\n/** An extra storage, as the server records it at start. */\nexport interface DeclaredTenantStorage {\n id: string;\n retired: boolean;\n}\n\ninterface DeclaredTenantStoragesRecord {\n storages: DeclaredTenantStorage[];\n}\n\n/**\n * A storage that was declared, and not retired, when the server last started, and is declared no\n * more. Tenants may still run on it, and they would stop working: retire it first, so it's no longer\n * offered for new tenants, move its tenants off, then remove it.\n */\nexport class TenantStorageRemovedError extends Error {\n public readonly storages: string[];\n\n constructor(storages: string[]) {\n const names = storages.map(id => `\\`${id}\\``).join(\", \");\n const one = storages.length === 1;\n super(\n [\n `${one ? \"Storage\" : \"Storages\"} ${names} ${one ? \"was\" : \"were\"} removed but not retired.`,\n `Tenants may still run on ${one ? \"it\" : \"them\"}. Declare ${one ? \"it\" : \"them\"} again with \\`retired\\` set,`,\n `start the server once, and remove ${one ? \"it\" : \"them\"} only once no tenant runs there.`\n ].join(\" \")\n );\n this.name = \"TenantStorageRemovedError\";\n this.storages = storages;\n }\n}\n\n/** The recorded storages that weren't retired and are declared no more. */\nexport const findRemovedTenantStorages = (\n recorded: DeclaredTenantStorage[],\n declared: DeclaredTenantStorage[]\n): string[] => {\n const declaredIds = new Set(declared.map(storage => storage.id));\n return recorded\n .filter(storage => !storage.retired && !declaredIds.has(storage.id))\n .map(storage => storage.id);\n};\n\nconst sameStorages = (a: DeclaredTenantStorage[], b: DeclaredTenantStorage[]): boolean => {\n const key = (storages: DeclaredTenantStorage[]) => {\n return JSON.stringify(\n [...storages].sort((x, y) => x.id.localeCompare(y.id)).map(s => [s.id, s.retired])\n );\n };\n return key(a) === key(b);\n};\n\nexport interface GuardDeclaredTenantStoragesParams {\n /** The root container, with every root registration done. */\n root: Container;\n /** Registers a request's services in a fresh child of the root. */\n registerRequest: (container: Container) => Promise<void>;\n}\n\n/**\n * The standalone server's guard against removing a storage tenants may still run on. A deploy on\n * AWS compares the config with the stack's outputs before Pulumi runs; a standalone server has no\n * outputs, so it records the extra storages it was started with (`id`, `retired`) in root's global\n * key-value store, and at the next start refuses to start when one that wasn't retired is gone.\n * One read at every start, and a write when the storages changed.\n *\n * It runs once every root registration is done, in a request container built for it, in root's\n * scope: the record is root's data, on the default storage.\n */\nexport async function guardDeclaredTenantStorages(\n params: GuardDeclaredTenantStoragesParams\n): Promise<void> {\n const { root } = params;\n const [storages] = root.resolveAll(TenantStorages);\n const declared: DeclaredTenantStorage[] = (storages?.list() ?? [])\n .filter(storage => !storage.isDefault)\n .map(storage => ({ id: storage.id, retired: storage.retired }));\n\n const request = root.createChildContainer();\n request.registerInstance(RequestContainer, request);\n await params.registerRequest(request);\n\n await request.resolve(TenantScopes).withRootTenant(async scope => {\n const store = scope.resolve(GlobalKeyValueStore);\n const result = await store.get<DeclaredTenantStoragesRecord>(DECLARED_TENANT_STORAGES_KEY);\n let recorded: DeclaredTenantStorage[] = [];\n if (result.isOk()) {\n recorded = result.value?.storages ?? [];\n } else if (!(result.error instanceof KeyNotFoundError)) {\n throw result.error;\n }\n\n const removed = findRemovedTenantStorages(recorded, declared);\n if (removed.length > 0) {\n throw new TenantStorageRemovedError(removed);\n }\n if (sameStorages(recorded, declared)) {\n return;\n }\n const record: DeclaredTenantStoragesRecord = { storages: declared };\n const written = await store.set(DECLARED_TENANT_STORAGES_KEY, record);\n if (written.isFail()) {\n throw written.error;\n }\n });\n}\n"],"names":["DECLARED_TENANT_STORAGES_KEY","TenantStorageRemovedError","Error","storages","names","id","one","findRemovedTenantStorages","recorded","declared","declaredIds","Set","storage","sameStorages","a","b","key","JSON","x","y","s","guardDeclaredTenantStorages","params","root","TenantStorages","request","RequestContainer","TenantScopes","scope","store","GlobalKeyValueStore","result","KeyNotFoundError","removed","record","written"],"mappings":";;;;AAUO,MAAMA,+BAA+B;AAiBrC,MAAMC,kCAAkCC;IAG3C,YAAYC,QAAkB,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Mf,WAAqCN,AAAAA,CAAAA,UAAU,UAAU,EAAC,EAC3D,MAAM,CAACS,CAAAA,UAAW,CAACA,QAAQ,SAAS,EACpC,GAAG,CAACA,CAAAA,UAAY;YAAE,IAAIA,QAAQ,EAAE;YAAE,SAASA,QAAQ,OAAO;QAAC;IAEhE,MAAMa,UAAUF,KAAK,oBAAoB;IACzCE,QAAQ,gBAAgB,CAACC,kBAAkBD;IAC3C,MAAMH,OAAO,eAAe,CAACG;IAE7B,MAAMA,QAAQ,OAAO,CAACE,cAAc,cAAc,CAAC,OAAMC;QACrD,MAAMC,QAAQD,MAAM,OAAO,CAACE;QAC5B,MAAMC,SAAS,MAAMF,MAAM,GAAG,CAA+B7B;QAC7D,IAAIQ,WAAoC,EAAE;QAC1C,IAAIuB,OAAO,IAAI,IACXvB,WAAWuB,OAAO,KAAK,EAAE,YAAY,EAAE;aACpC,IAAI,CAAEA,CAAAA,OAAO,KAAK,YAAYC,gBAAe,GAChD,MAAMD,OAAO,KAAK;QAGtB,MAAME,UAAU1B,0BAA0BC,UAAUC;QACpD,IAAIwB,QAAQ,MAAM,GAAG,GACjB,MAAM,IAAIhC,0BAA0BgC;QAExC,IAAIpB,aAAaL,UAAUC,WACvB;QAEJ,MAAMyB,SAAuC;YAAE,UAAUzB;QAAS;QAClE,MAAM0B,UAAU,MAAMN,MAAM,GAAG,CAAC7B,8BAA8BkC;QAC9D,IAAIC,QAAQ,MAAM,IACd,MAAMA,QAAQ,KAAK;IAE3B;AACJ"}
@@ -2,7 +2,7 @@ import { RequestContainer } from "@webiny/api-kernel-core";
2
2
  import { registerApiRequestStack } from "@webiny/api-composition-core";
3
3
  import { AuthenticationError } from "@webiny/api-core/features/security/authentication/AuthenticationContext/index.js";
4
4
  import { RawAuthToken, RawTenantId, RequestIdentityLoader, RequestTenantLoader, TenantNotFoundError } from "@webiny/api-core/features/requestContext/index.js";
5
- import { TenantContext } from "@webiny/api-core/features/tenancy/TenantContext/index.js";
5
+ import { TenantScopes } from "@webiny/api-core/features/tenancy/TenantScopes/index.js";
6
6
  import { IdentityContext } from "@webiny/api-core/features/security/IdentityContext/index.js";
7
7
  import { CanAccessCurrentTenantUseCase } from "@webiny/api-core/features/security/CanAccessCurrentTenant/index.js";
8
8
  import { Logger } from "@webiny/api-core/features/logger/index.js";
@@ -27,19 +27,21 @@ function createWebsocketsAuthenticator(rootContainer, extensions) {
27
27
  });
28
28
  child.resolve(RawTenantId).set(tenantId);
29
29
  child.resolve(RawAuthToken).set(token);
30
- const tenantLoaded = await child.resolve(RequestTenantLoader).establish().then(()=>true).catch(refuseUnknownTenant);
31
- if (!tenantLoaded || !child.resolve(TenantContext).getTenant()) return null;
32
- const refuse = refuseOnAuthenticationError(child.resolve(Logger));
33
- const authenticated = await child.resolve(RequestIdentityLoader).establish().then(()=>true).catch(refuse);
34
- if (!authenticated) return null;
35
- const canAccessTenant = await child.resolve(CanAccessCurrentTenantUseCase).execute();
36
- if (!canAccessTenant) return null;
37
- const identity = child.resolve(IdentityContext).getIdentity();
38
- return {
39
- id: identity.id,
40
- displayName: identity.displayName,
41
- type: identity.type
42
- };
30
+ const tenant = await child.resolve(RequestTenantLoader).establish().catch(refuseUnknownTenant);
31
+ if (!tenant) return null;
32
+ return child.resolve(TenantScopes).withTenant(tenant, async (scope)=>{
33
+ const refuse = refuseOnAuthenticationError(scope.resolve(Logger));
34
+ const authenticated = await scope.resolve(RequestIdentityLoader).establish().then(()=>true).catch(refuse);
35
+ if (!authenticated) return null;
36
+ const canAccessTenant = await scope.resolve(CanAccessCurrentTenantUseCase).execute();
37
+ if (!canAccessTenant) return null;
38
+ const identity = scope.resolve(IdentityContext).getIdentity();
39
+ return {
40
+ id: identity.id,
41
+ displayName: identity.displayName,
42
+ type: identity.type
43
+ };
44
+ });
43
45
  };
44
46
  }
45
47
  export { createWebsocketsAuthenticator };
@@ -1 +1 @@
1
- {"version":3,"file":"websockets/createWebsocketsAuthenticator.js","sources":["../../src/websockets/createWebsocketsAuthenticator.ts"],"sourcesContent":["import type { Container } from \"@webiny/di\";\nimport { RequestContainer } from \"@webiny/api-kernel-core\";\nimport {\n registerApiRequestStack,\n type RegisterApiRequestStackConfig\n} from \"@webiny/api-composition-core\";\nimport { AuthenticationError } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/index.js\";\nimport { RawTenantId } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { RawAuthToken } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { RequestTenantLoader } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { TenantNotFoundError } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { RequestIdentityLoader } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { TenantContext } from \"@webiny/api-core/features/tenancy/TenantContext/index.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { CanAccessCurrentTenantUseCase } from \"@webiny/api-core/features/security/CanAccessCurrentTenant/index.js\";\nimport { Logger } from \"@webiny/api-core/features/logger/index.js\";\nimport type { WebsocketsConnectionAuthenticator } from \"@webiny/api-websockets-standalone\";\n\n/*\n * An `AuthenticationError` refuses the handshake rather than failing it. That includes more than bad\n * tokens: `AuthenticationError.from` wraps every error an authenticator throws, a failed key lookup\n * as well, so the reason is logged here, where it would otherwise be lost.\n */\nconst refuseOnAuthenticationError = (logger: Logger.Interface) => {\n return (error: unknown): false => {\n if (!(error instanceof AuthenticationError)) {\n throw error;\n }\n logger.warn({ code: error.code, error: error.message }, \"[websockets] handshake refused\");\n return false;\n };\n};\n\n/**\n * Builds the `authenticate` callback the server WebSocket upgrade acceptor uses to turn a\n * connection's `?token` JWT into an identity in the connection's `?tenant`.\n *\n * Each new WebSocket connection (the HTTP upgrade handshake) is authenticated from its `?token` JWT\n * so the connection is registered under the real identity — targeted server→client sends need this,\n * since SendToIdentity matches connections by identity id. The catch is that AuthenticationContext\n * lives in the per-request stack (registered by ApiCoreFeature, not registerRootStorage), so we can't\n * resolve it from the root container. Instead we spin up a short-lived request-scoped child container,\n * the same way createHandler does for each HTTP request, and resolve it there. We only need the core\n * stack, not the transports. Like an HTTP transport, it only extracts the raw tenant id and token and\n * leaves the rest to the shared request loaders, tenant first, because an API key is looked up in the\n * current tenant. The identity must then be able to access that tenant: the client names the tenant,\n * so a valid token alone would let a user of one tenant receive another tenant's messages.\n * Connections are rare (one per admin session), so a fresh child per connection is cheap enough.\n *\n * This is also why the WebSocket server takes `authenticate` as a plain callback instead of resolving\n * auth itself: AuthenticationContext isn't reachable from the root container (it's per-request), so\n * only the handler — which can build a request-scoped child — can supply it. So authenticate has to be\n * a callback the handler builds, regardless of DI.\n */\nconst refuseUnknownTenant = (error: unknown): false => {\n if (error instanceof TenantNotFoundError) {\n return false;\n }\n throw error;\n};\n\nexport function createWebsocketsAuthenticator(\n rootContainer: Container,\n extensions: RegisterApiRequestStackConfig[\"extensions\"]\n): WebsocketsConnectionAuthenticator {\n return async (token, tenantId) => {\n const child = rootContainer.createChildContainer();\n child.registerInstance(RequestContainer, child);\n await registerApiRequestStack(child, { extensions });\n\n child.resolve(RawTenantId).set(tenantId);\n child.resolve(RawAuthToken).set(token);\n\n const tenantLoaded = await child\n .resolve(RequestTenantLoader)\n .establish()\n .then(() => true)\n .catch(refuseUnknownTenant);\n // An unknown tenant refuses the handshake rather than failing it.\n if (!tenantLoaded || !child.resolve(TenantContext).getTenant()) {\n return null;\n }\n\n const refuse = refuseOnAuthenticationError(child.resolve(Logger));\n const authenticated = await child\n .resolve(RequestIdentityLoader)\n .establish()\n .then(() => true)\n .catch(refuse);\n if (!authenticated) {\n return null;\n }\n\n // False for the anonymous identity, which is what a token no authenticator recognises gives.\n const canAccessTenant = await child.resolve(CanAccessCurrentTenantUseCase).execute();\n if (!canAccessTenant) {\n return null;\n }\n\n const identity = child.resolve(IdentityContext).getIdentity();\n return {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n };\n };\n}\n"],"names":["refuseOnAuthenticationError","logger","error","AuthenticationError","refuseUnknownTenant","TenantNotFoundError","createWebsocketsAuthenticator","rootContainer","extensions","token","tenantId","child","RequestContainer","registerApiRequestStack","RawTenantId","RawAuthToken","tenantLoaded","RequestTenantLoader","TenantContext","refuse","Logger","authenticated","RequestIdentityLoader","canAccessTenant","CanAccessCurrentTenantUseCase","identity","IdentityContext"],"mappings":";;;;;;;;AAuBA,MAAMA,8BAA8B,CAACC,SAC1B,CAACC;QACJ,IAAI,CAAEA,CAAAA,iBAAiBC,mBAAkB,GACrC,MAAMD;QAEVD,OAAO,IAAI,CAAC;YAAE,MAAMC,MAAM,IAAI;YAAE,OAAOA,MAAM,OAAO;QAAC,GAAG;QACxD,OAAO;IACX;AAwBJ,MAAME,sBAAsB,CAACF;IACzB,IAAIA,iBAAiBG,qBACjB,OAAO;IAEX,MAAMH;AACV;AAEO,SAASI,8BACZC,aAAwB,EACxBC,UAAuD;IAEvD,OAAO,OAAOC,OAAOC;QACjB,MAAMC,QAAQJ,cAAc,oBAAoB;QAChDI,MAAM,gBAAgB,CAACC,kBAAkBD;QACzC,MAAME,wBAAwBF,OAAO;YAAEH;QAAW;QAElDG,MAAM,OAAO,CAACG,aAAa,GAAG,CAACJ;QAC/BC,MAAM,OAAO,CAACI,cAAc,GAAG,CAACN;QAEhC,MAAMO,eAAe,MAAML,MACtB,OAAO,CAACM,qBACR,SAAS,GACT,IAAI,CAAC,IAAM,MACX,KAAK,CAACb;QAEX,IAAI,CAACY,gBAAgB,CAACL,MAAM,OAAO,CAACO,eAAe,SAAS,IACxD,OAAO;QAGX,MAAMC,SAASnB,4BAA4BW,MAAM,OAAO,CAACS;QACzD,MAAMC,gBAAgB,MAAMV,MACvB,OAAO,CAACW,uBACR,SAAS,GACT,IAAI,CAAC,IAAM,MACX,KAAK,CAACH;QACX,IAAI,CAACE,eACD,OAAO;QAIX,MAAME,kBAAkB,MAAMZ,MAAM,OAAO,CAACa,+BAA+B,OAAO;QAClF,IAAI,CAACD,iBACD,OAAO;QAGX,MAAME,WAAWd,MAAM,OAAO,CAACe,iBAAiB,WAAW;QAC3D,OAAO;YACH,IAAID,SAAS,EAAE;YACf,aAAaA,SAAS,WAAW;YACjC,MAAMA,SAAS,IAAI;QACvB;IACJ;AACJ"}
1
+ {"version":3,"file":"websockets/createWebsocketsAuthenticator.js","sources":["../../src/websockets/createWebsocketsAuthenticator.ts"],"sourcesContent":["import type { Container } from \"@webiny/di\";\nimport { RequestContainer } from \"@webiny/api-kernel-core\";\nimport {\n registerApiRequestStack,\n type RegisterApiRequestStackConfig\n} from \"@webiny/api-composition-core\";\nimport { AuthenticationError } from \"@webiny/api-core/features/security/authentication/AuthenticationContext/index.js\";\nimport { RawTenantId } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { RawAuthToken } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { RequestTenantLoader } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { TenantNotFoundError } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { RequestIdentityLoader } from \"@webiny/api-core/features/requestContext/index.js\";\nimport { TenantScopes } from \"@webiny/api-core/features/tenancy/TenantScopes/index.js\";\nimport { IdentityContext } from \"@webiny/api-core/features/security/IdentityContext/index.js\";\nimport { CanAccessCurrentTenantUseCase } from \"@webiny/api-core/features/security/CanAccessCurrentTenant/index.js\";\nimport { Logger } from \"@webiny/api-core/features/logger/index.js\";\nimport type { WebsocketsConnectionAuthenticator } from \"@webiny/api-websockets-standalone\";\n\n/*\n * An `AuthenticationError` refuses the handshake rather than failing it. That includes more than bad\n * tokens: `AuthenticationError.from` wraps every error an authenticator throws, a failed key lookup\n * as well, so the reason is logged here, where it would otherwise be lost.\n */\nconst refuseOnAuthenticationError = (logger: Logger.Interface) => {\n return (error: unknown): false => {\n if (!(error instanceof AuthenticationError)) {\n throw error;\n }\n logger.warn({ code: error.code, error: error.message }, \"[websockets] handshake refused\");\n return false;\n };\n};\n\n/**\n * Builds the `authenticate` callback the server WebSocket upgrade acceptor uses to turn a\n * connection's `?token` JWT into an identity in the connection's `?tenant`, in that tenant's scope.\n *\n * Each new WebSocket connection (the HTTP upgrade handshake) is authenticated from its `?token` JWT\n * so the connection is registered under the real identity — targeted server→client sends need this,\n * since SendToIdentity matches connections by identity id. The catch is that AuthenticationContext\n * lives in the per-request stack (registered by ApiCoreFeature, not registerRootStorage), so we can't\n * resolve it from the root container. Instead we spin up a short-lived request-scoped child container,\n * the same way createHandler does for each HTTP request, and resolve it there. We only need the core\n * stack, not the transports. Like an HTTP transport, it only extracts the raw tenant id and token and\n * leaves the rest to the shared request loaders, tenant first, because an API key is looked up in the\n * current tenant. The identity must then be able to access that tenant: the client names the tenant,\n * so a valid token alone would let a user of one tenant receive another tenant's messages.\n * Connections are rare (one per admin session), so a fresh child per connection is cheap enough.\n *\n * This is also why the WebSocket server takes `authenticate` as a plain callback instead of resolving\n * auth itself: AuthenticationContext isn't reachable from the root container (it's per-request), so\n * only the handler — which can build a request-scoped child — can supply it. So authenticate has to be\n * a callback the handler builds, regardless of DI.\n */\nconst refuseUnknownTenant = (error: unknown): false => {\n if (error instanceof TenantNotFoundError) {\n return false;\n }\n throw error;\n};\n\nexport function createWebsocketsAuthenticator(\n rootContainer: Container,\n extensions: RegisterApiRequestStackConfig[\"extensions\"]\n): WebsocketsConnectionAuthenticator {\n return async (token, tenantId) => {\n const child = rootContainer.createChildContainer();\n child.registerInstance(RequestContainer, child);\n await registerApiRequestStack(child, { extensions });\n\n child.resolve(RawTenantId).set(tenantId);\n child.resolve(RawAuthToken).set(token);\n\n const tenant = await child\n .resolve(RequestTenantLoader)\n .establish()\n .catch(refuseUnknownTenant);\n // An unknown tenant refuses the handshake rather than failing it.\n if (!tenant) {\n return null;\n }\n\n // Identity is the tenant's: an API key is looked up in it, and access is checked against it.\n return child.resolve(TenantScopes).withTenant(tenant, async scope => {\n const refuse = refuseOnAuthenticationError(scope.resolve(Logger));\n const authenticated = await scope\n .resolve(RequestIdentityLoader)\n .establish()\n .then(() => true)\n .catch(refuse);\n if (!authenticated) {\n return null;\n }\n\n // False for the anonymous identity, which is what a token no authenticator recognises gives.\n const canAccessTenant = await scope.resolve(CanAccessCurrentTenantUseCase).execute();\n if (!canAccessTenant) {\n return null;\n }\n\n const identity = scope.resolve(IdentityContext).getIdentity();\n return {\n id: identity.id,\n displayName: identity.displayName,\n type: identity.type\n };\n });\n };\n}\n"],"names":["refuseOnAuthenticationError","logger","error","AuthenticationError","refuseUnknownTenant","TenantNotFoundError","createWebsocketsAuthenticator","rootContainer","extensions","token","tenantId","child","RequestContainer","registerApiRequestStack","RawTenantId","RawAuthToken","tenant","RequestTenantLoader","TenantScopes","scope","refuse","Logger","authenticated","RequestIdentityLoader","canAccessTenant","CanAccessCurrentTenantUseCase","identity","IdentityContext"],"mappings":";;;;;;;;AAuBA,MAAMA,8BAA8B,CAACC,SAC1B,CAACC;QACJ,IAAI,CAAEA,CAAAA,iBAAiBC,mBAAkB,GACrC,MAAMD;QAEVD,OAAO,IAAI,CAAC;YAAE,MAAMC,MAAM,IAAI;YAAE,OAAOA,MAAM,OAAO;QAAC,GAAG;QACxD,OAAO;IACX;AAwBJ,MAAME,sBAAsB,CAACF;IACzB,IAAIA,iBAAiBG,qBACjB,OAAO;IAEX,MAAMH;AACV;AAEO,SAASI,8BACZC,aAAwB,EACxBC,UAAuD;IAEvD,OAAO,OAAOC,OAAOC;QACjB,MAAMC,QAAQJ,cAAc,oBAAoB;QAChDI,MAAM,gBAAgB,CAACC,kBAAkBD;QACzC,MAAME,wBAAwBF,OAAO;YAAEH;QAAW;QAElDG,MAAM,OAAO,CAACG,aAAa,GAAG,CAACJ;QAC/BC,MAAM,OAAO,CAACI,cAAc,GAAG,CAACN;QAEhC,MAAMO,SAAS,MAAML,MAChB,OAAO,CAACM,qBACR,SAAS,GACT,KAAK,CAACb;QAEX,IAAI,CAACY,QACD,OAAO;QAIX,OAAOL,MAAM,OAAO,CAACO,cAAc,UAAU,CAACF,QAAQ,OAAMG;YACxD,MAAMC,SAASpB,4BAA4BmB,MAAM,OAAO,CAACE;YACzD,MAAMC,gBAAgB,MAAMH,MACvB,OAAO,CAACI,uBACR,SAAS,GACT,IAAI,CAAC,IAAM,MACX,KAAK,CAACH;YACX,IAAI,CAACE,eACD,OAAO;YAIX,MAAME,kBAAkB,MAAML,MAAM,OAAO,CAACM,+BAA+B,OAAO;YAClF,IAAI,CAACD,iBACD,OAAO;YAGX,MAAME,WAAWP,MAAM,OAAO,CAACQ,iBAAiB,WAAW;YAC3D,OAAO;gBACH,IAAID,SAAS,EAAE;gBACf,aAAaA,SAAS,WAAW;gBACjC,MAAMA,SAAS,IAAI;YACvB;QACJ;IACJ;AACJ"}
@@ -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 node_path from "node:path";
2
- import { PublicUrl } from "@webiny/api-core/features/publicUrls/index.js";
3
- function read(env, name) {
4
- return env[name]?.trim() ?? "";
5
- }
6
- function readSecret(env, name) {
7
- const value = env[name] ?? "";
8
- return value.trim() ? value : "";
9
- }
10
- function readStandaloneConfig(env) {
11
- const problems = [];
12
- const apiUrlValue = read(env, "WEBINY_API_URL");
13
- const apiUrl = PublicUrl.from(apiUrlValue);
14
- if (apiUrlValue) {
15
- if (!apiUrl.isKnown()) problems.push(`WEBINY_API_URL is not an absolute http(s) URL: "${apiUrlValue}".`);
16
- } else problems.push("WEBINY_API_URL is not set.");
17
- const adminUrlValue = read(env, "WEBINY_ADMIN_URL");
18
- const adminUrl = PublicUrl.from(adminUrlValue);
19
- if (adminUrlValue && !adminUrl.isKnown()) problems.push(`WEBINY_ADMIN_URL is not an absolute http(s) URL: "${adminUrlValue}".`);
20
- const storagePath = read(env, "WEBINY_LOCAL_STORAGE_PATH");
21
- if (!storagePath) problems.push("WEBINY_LOCAL_STORAGE_PATH is not set.");
22
- const uploadSecret = readSecret(env, "WEBINY_UPLOAD_SECRET");
23
- if (!uploadSecret) problems.push("WEBINY_UPLOAD_SECRET is not set.");
24
- const encryptionPassphrase = readSecret(env, "WEBINY_ENCRYPTION_PASSPHRASE");
25
- if (!encryptionPassphrase) problems.push("WEBINY_ENCRYPTION_PASSPHRASE is not set.");
26
- const hashingPepper = readSecret(env, "WEBINY_HASHING_PEPPER");
27
- if (!hashingPepper) problems.push("WEBINY_HASHING_PEPPER is not set.");
28
- const redisUrl = read(env, "WEBINY_REDIS_URL");
29
- if (redisUrl && !/^rediss?:\/\//.test(redisUrl)) problems.push("WEBINY_REDIS_URL must start with redis:// or rediss://.");
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
- storagePath: node_path.resolve(storagePath),
42
- uploadSecret
43
- },
44
- encryption: {
45
- passphrase: encryptionPassphrase,
46
- salt: readSecret(env, "WEBINY_ENCRYPTION_SALT")
47
- },
48
- hashing: {
49
- pepper: hashingPepper
50
- },
51
- redisUrl: redisUrl || void 0
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 nodePath from \"node:path\";\nimport { 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 storagePath = read(env, \"WEBINY_LOCAL_STORAGE_PATH\");\n if (!storagePath) {\n problems.push(\"WEBINY_LOCAL_STORAGE_PATH is not set.\");\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 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 storagePath: nodePath.resolve(storagePath),\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 };\n}\n"],"names":["read","env","name","readSecret","value","readStandaloneConfig","problems","apiUrlValue","apiUrl","PublicUrl","adminUrlValue","adminUrl","storagePath","uploadSecret","encryptionPassphrase","hashingPepper","redisUrl","message","Error","nodePath","undefined"],"mappings":";;AAMA,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;I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