Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): keep the database a switch back to built-in finds

Yudhi Armyndharis99e56e25f98e
diff --git a/dashboard/src/pages/Infrastructure.test.ts b/dashboard/src/pages/Infrastructure.test.ts
index c57c77f0a..5a38a2d90 100644
--- a/dashboard/src/pages/Infrastructure.test.ts
+++ b/dashboard/src/pages/Infrastructure.test.ts
@@ -1279,42 +1279,54 @@ test('an unrelated save beside a pinned bundled endpoint warns of no storage swi
assert.equal(within(dialog).queryByText(STORAGE_WARNING, { exact: false }) === null, true, 'storage warning');
});
-// A pinned external host outranks the toggle, so turning Use Built-in on moves nothing.
-test('turning Use Built-in on under a pinned external host warns of no switch', async () => {
- const { screen, fireEvent, within } = rtl;
- resetFetchCalls();
- overrides = {
- status: {
- ...INFRA_STATUS,
- database: { connected: true, type: 'postgres', host: 'db.external.example', builtIn: false },
- storage: { type: 's3', bucket: 'openwa', endpoint: 'https://s3.example', builtIn: false, s3Available: true },
- envPinned: ['DATABASE_HOST', 'S3_ENDPOINT'],
- },
- saved: {
- ...SAVED_CONFIG,
- database: { ...SAVED_CONFIG.database, host: 'db.external.example', builtIn: false, builtInSet: false },
- storage: {
- ...SAVED_CONFIG.storage,
- type: 's3',
- builtIn: false,
- builtInSet: false,
- s3Bucket: 'openwa',
- s3Endpoint: 'https://s3.example',
+// A pinned external host outranks the toggle, so turning Use Built-in on moves nothing but the database name the
+// built-in save writes, openwa: with that name already in use nothing moves, with one of its own the database does.
+for (const { name, moves } of [
+ { name: 'openwa', moves: false },
+ { name: 'openwa_prod', moves: true },
+]) {
+ test(`turning Use Built-in on under a pinned external host over database ${name} ${moves ? 'warns of the database' : 'warns of no switch'}`, async () => {
+ const { screen, fireEvent, within } = rtl;
+ resetFetchCalls();
+ overrides = {
+ status: {
+ ...INFRA_STATUS,
+ database: { connected: true, type: 'postgres', host: 'db.external.example', builtIn: false },
+ storage: { type: 's3', bucket: 'openwa', endpoint: 'https://s3.example', builtIn: false, s3Available: true },
+ envPinned: ['DATABASE_HOST', 'S3_ENDPOINT'],
},
- },
- };
- const { container } = renderInfrastructure();
+ saved: {
+ ...SAVED_CONFIG,
+ database: {
+ ...SAVED_CONFIG.database,
+ host: 'db.external.example',
+ database: name,
+ builtIn: false,
+ builtInSet: false,
+ },
+ storage: {
+ ...SAVED_CONFIG.storage,
+ type: 's3',
+ builtIn: false,
+ builtInSet: false,
+ s3Bucket: 'openwa',
+ s3Endpoint: 'https://s3.example',
+ },
+ },
+ };
+ const { container } = renderInfrastructure();
- await screen.findByText('Database Configuration');
- await awaitSeeded(container);
- fireEvent.click(toggleInput(container, 'Use Built-in PostgreSQL Container'));
- fireEvent.click(toggleInput(container, 'Use Built-in MinIO Container'));
- fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));
+ await screen.findByText('Database Configuration');
+ await awaitSeeded(container);
+ fireEvent.click(toggleInput(container, 'Use Built-in PostgreSQL Container'));
+ fireEvent.click(toggleInput(container, 'Use Built-in MinIO Container'));
+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));
- const dialog = await screen.findByRole('dialog');
- assert.equal(within(dialog).queryByText(DB_SWITCH_WARNING, { exact: false }) === null, true, 'database warning');
- assert.equal(within(dialog).queryByText(STORAGE_WARNING, { exact: false }) === null, true, 'storage warning');
-});
+ const dialog = await screen.findByRole('dialog');
+ assert.equal(within(dialog).queryByText(DB_SWITCH_WARNING, { exact: false }) !== null, moves, 'database warning');
+ assert.equal(within(dialog).queryByText(STORAGE_WARNING, { exact: false }) === null, true, 'storage warning');
+ });
+}
// The host is compared as the save writes it, trimmed and with the default for an empty field.
test('a host typed with spaces around it is no switch', async () => {
@@ -2813,6 +2825,95 @@ test('typed external fields beside a host pinned elsewhere are sent with the fla
rtl.within(dialog).getByText(DB_SWITCH_WARNING, { exact: false });
});
+// A database and bucket of their own on the bundled containers (flags false, hosts on the container names), switched
+// away and saved with Restart Later, then switched back to Use Built-in in the same visit. The gateway keeps what the
+// bundled containers serve the running process, so the second save moves nothing, unless the first one renamed the
+// database on the bundled host itself, which the next boot then dials.
+const RUNNING_OWN_BUNDLED: InfraStatus = {
+ ...INFRA_STATUS,
+ database: { connected: true, type: 'postgres', host: 'openwa-postgres', builtIn: true, running: false },
+ storage: { type: 's3', bucket: 'media', endpoint: 'http://openwa-minio:9000', builtIn: true, s3Available: true },
+};
+const SAVED_OWN_BUNDLED: SavedConfig = {
+ ...SAVED_CONFIG,
+ database: {
+ ...SAVED_CONFIG.database,
+ host: 'openwa-postgres',
+ port: '5432',
+ username: 'app',
+ database: 'appdb',
+ schema: 'tenant',
+ builtIn: true,
+ builtInSet: false,
+ },
+ storage: {
+ ...SAVED_CONFIG.storage,
+ type: 's3',
+ builtIn: true,
+ builtInSet: false,
+ s3Bucket: 'media',
+ s3Region: 'eu-west-1',
+ s3Endpoint: 'http://openwa-minio:9000',
+ },
+};
+for (const { label, toggle, field, value, after, warning, warnsBack } of [
+ {
+ label: 'the database switched to another server',
+ toggle: 'Use Built-in PostgreSQL Container',
+ field: 'Host',
+ value: 'db.ext.example',
+ after: { database: { ...SAVED_OWN_BUNDLED.database, host: 'db.ext.example', builtIn: false, builtInSet: true } },
+ warning: DB_SWITCH_WARNING,
+ warnsBack: false,
+ },
+ {
+ label: 'the database renamed on the bundled host',
+ toggle: 'Use Built-in PostgreSQL Container',
+ field: 'Database Name',
+ value: 'appdb2',
+ after: { database: { ...SAVED_OWN_BUNDLED.database, database: 'appdb2' } },
+ warning: DB_SWITCH_WARNING,
+ warnsBack: true,
+ },
+ {
+ label: 'the storage switched to another endpoint',
+ toggle: 'Use Built-in MinIO Container',
+ field: 'Custom Endpoint (optional)',
+ value: 'https://s3.new.example',
+ after: {
+ storage: { ...SAVED_OWN_BUNDLED.storage, s3Endpoint: 'https://s3.new.example', builtIn: false, builtInSet: true },
+ },
+ warning: STORAGE_WARNING,
+ warnsBack: false,
+ },
+]) {
+ test(`back to Use Built-in after ${label} and Restart Later ${warnsBack ? 'warns' : 'warns of no move'}`, async () => {
+ const { screen, fireEvent, within } = rtl;
+ resetFetchCalls();
+ overrides = {
+ status: RUNNING_OWN_BUNDLED,
+ saved: SAVED_OWN_BUNDLED,
+ savedAfterSave: { ...SAVED_OWN_BUNDLED, ...after },
+ };
+ const { container } = renderInfrastructure();
+
+ await screen.findByText('Database Configuration');
+ await awaitSeeded(container);
+ fireEvent.click(toggleInput(container, toggle));
+ fireEvent.change(fieldInput(container, field), { target: { value } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));
+ const first = await screen.findByRole('dialog');
+ within(first).getByText(warning, { exact: false });
+ fireEvent.click(within(first).getByRole('button', { name: 'Restart Later' }));
+ await rtl.waitFor(() => assert.equal(screen.queryByRole('dialog'), null));
+
+ fireEvent.click(toggleInput(container, toggle));
+ fireEvent.click(screen.getByRole('button', { name: 'Save Configuration' }));
+ const second = await screen.findByRole('dialog');
+ assert.equal(within(second).queryByText(warning, { exact: false }) !== null, warnsBack);
+ });
+}
+
// ── Restart-flow timer cleanup on unmount ────────────────────────────────────
test('unmounting mid-restart cancels the health poll and countdown timers', { timeout: 10_000 }, async () => {
diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsx
index b8565f7be..29ea2656c 100644
--- a/dashboard/src/pages/Infrastructure.tsx
+++ b/dashboard/src/pages/Infrastructure.tsx
@@ -122,27 +122,45 @@ export function Infrastructure() {
const dbType = pinned('DATABASE_TYPE')?.database.type ?? db.type;
const dbHost =
(pinned('DATABASE_HOST')?.database.host ?? (db.builtIn ? 'postgres' : db.host.trim())) || 'localhost';
- const dbExternalRetarget =
- !db.builtIn &&
+ // The database name the save writes: the form's for an external server; for a built-in one the name the server
+ // keeps, the saved config's where its host already reaches the bundled container, else the one the bundled
+ // container serves now (the page loaded it), else openwa.
+ const dbName = db.builtIn
+ ? (namesBundledContainer('postgres', savedConfig?.database.host) && savedConfig?.database.type === 'postgres'
+ ? savedConfig.database.database
+ : infraStatus?.database.type === 'postgres' && namesBundledContainer('postgres', infraStatus.database.host)
+ ? loaded?.database.database
+ : '') || 'openwa'
+ : db.database;
+ const dbRetarget =
!!loaded &&
- ((!pinned('DATABASE_PORT') && db.port !== (loaded.database.port || '5432')) ||
- (!pinned('DATABASE_NAME') && db.database !== (loaded.database.database || 'openwa')));
+ ((!db.builtIn && !pinned('DATABASE_PORT') && db.port !== (loaded.database.port || '5432')) ||
+ (!pinned('DATABASE_NAME') && dbName !== (loaded.database.database || 'openwa')));
const dbSwitch =
!!infraStatus &&
(dbType !== infraStatus.database.type ||
- (dbType === 'postgres' && (!sameHost('postgres', dbHost, infraStatus.database.host) || dbExternalRetarget)));
+ (dbType === 'postgres' && (!sameHost('postgres', dbHost, infraStatus.database.host) || dbRetarget)));
const storage = configForm.storageConfig;
const storageType = pinned('STORAGE_TYPE')?.storage.type ?? storage.type;
// The storage section takes the bundled bucket for a flag sent as true only: beside a pinned endpoint an untouched
// toggle is left out of the save, and the stored bucket stays. It stays under the flag too when the saved config
- // (the file this save replaced) already reaches the bundled MinIO, which then serves that bucket.
+ // (the file this save replaced) already reaches the bundled MinIO, which then serves that bucket, and else the
+ // bucket the bundled MinIO serves now does.
const storageBuiltIn = sent.storage?.builtIn === true;
const keepsBucket = namesBundledContainer('minio', savedConfig?.storage.s3Endpoint);
+ const servesBucket =
+ infraStatus?.storage.type === 's3' && namesBundledContainer('minio', infraStatus.storage.endpoint);
const endpoint =
pinned('S3_ENDPOINT')?.storage.s3Endpoint ?? (storageBuiltIn ? 'http://minio:9000' : storage.s3Endpoint);
const bucket =
(pinned('S3_BUCKET')?.storage.s3Bucket ??
- (storageBuiltIn ? (keepsBucket ? savedConfig?.storage.s3Bucket : 'openwa') : storage.s3Bucket)) ||
+ (storageBuiltIn
+ ? keepsBucket
+ ? savedConfig?.storage.s3Bucket
+ : servesBucket
+ ? infraStatus?.storage.bucket
+ : 'openwa'
+ : storage.s3Bucket)) ||
'openwa';
const storageSwitch =
!!infraStatus &&
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index d500575ba..902b2d10c 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -5712,7 +5712,7 @@ Merge-save infrastructure config to `data/.env.generated` (a `0600` secret file)
| `engine.sessionDataPath` | string | No | — | Default `./data/sessions` |
| `engine.browserArgs` | string | No | — | Saved as `PUPPETEER_ARGS`. Empty saves the default `--no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu`; a non-empty value replaces that list in full |
-Built-in flags: a section sent without `builtIn` stays in the stored mode. A stored `POSTGRES_BUILTIN`, `REDIS_BUILTIN` or `MINIO_BUILTIN` of `true` writes the bundled connection values again, and the fields sent apply only to an external service; send `builtIn: false` with them to switch it, as the dashboard does once a card beside a host the environment pins elsewhere is edited. A built-in Redis asks for the `redis` profile only while something the next boot runs uses Redis (`REDIS_ENABLED`, `QUEUE_ENABLED` or `CACHE_ENABLED`, pinned, sent or stored); a save where nothing uses it, in the file either, writes `REDIS_BUILTIN=false` whatever `builtIn` says and drops a `REDIS_HOST` that names the bundled container. A built-in save keeps the stored database password and S3 keys (`S3_ACCESS_KEY_ID`/`S3_SECRET_ACCESS_KEY`, else the legacy `S3_ACCESS_KEY`/`S3_SECRET_KEY`) when the flag was already `true` or the next boot's host already reaches the bundled container, and writes `openwa` or `minioadmin` otherwise. It keeps the stored user, database name and schema (`DATABASE_USERNAME`, `DATABASE_NAME`, `POSTGRES_SCHEMA`), or the stored `S3_BUCKET` and `S3_REGION`, when the next boot already runs PostgreSQL or S3 storage on a host that reaches the bundled container (a file that names that container beside a database or bucket of its own), and writes `openwa`, `openwa` and `public`, or `openwa` and `us-east-1`, otherwise. The bundled container counts in any spelling: its alias (`postgres`, `redis`, `minio`) or its container name (`openwa-postgres`, `openwa-redis`, `openwa-minio`), in any letter case, with or without a trailing dot, and for storage as the host of the endpoint URL. A built-in database writes `DATABASE_SSL=false` and drops `DATABASE_SSL_REJECT_UNAUTHORIZED`, since the bundled container has no TLS, except beside a `DATABASE_HOST` the environment pins elsewhere: the next boot dials that server, and `sslEnabled` is written as sent. A boot with `POSTGRES_BUILTIN=true`, `DATABASE_SSL=true` and a `DATABASE_HOST` that reaches the bundled container is refused with a message naming `DATABASE_SSL`.
+Built-in flags: a section sent without `builtIn` stays in the stored mode. A stored `POSTGRES_BUILTIN`, `REDIS_BUILTIN` or `MINIO_BUILTIN` of `true` writes the bundled connection values again, and the fields sent apply only to an external service; send `builtIn: false` with them to switch it, as the dashboard does once a card beside a host the environment pins elsewhere is edited. A built-in Redis asks for the `redis` profile only while something the next boot runs uses Redis (`REDIS_ENABLED`, `QUEUE_ENABLED` or `CACHE_ENABLED`, pinned, sent or stored); a save where nothing uses it, in the file either, writes `REDIS_BUILTIN=false` whatever `builtIn` says and drops a `REDIS_HOST` that names the bundled container. A built-in save keeps the stored database password and S3 keys (`S3_ACCESS_KEY_ID`/`S3_SECRET_ACCESS_KEY`, else the legacy `S3_ACCESS_KEY`/`S3_SECRET_KEY`) when the flag was already `true` or the next boot's host already reaches the bundled container, else the ones the running process dials the bundled container with (a switch away saved without a restart, then back), and writes `openwa` or `minioadmin` otherwise. It keeps the stored user, database name and schema (`DATABASE_USERNAME`, `DATABASE_NAME`, `POSTGRES_SCHEMA`), or the stored `S3_BUCKET` and `S3_REGION`, when the next boot already runs PostgreSQL or S3 storage on a host that reaches the bundled container (a file that names that container beside a database or bucket of its own), else the ones the bundled container serves the running process, and writes `openwa`, `openwa` and `public`, or `openwa` and `us-east-1`, otherwise. The bundled container counts in any spelling: its alias (`postgres`, `redis`, `minio`) or its container name (`openwa-postgres`, `openwa-redis`, `openwa-minio`), in any letter case, with or without a trailing dot, and for storage as the host of the endpoint URL. A built-in database writes `DATABASE_SSL=false` and drops `DATABASE_SSL_REJECT_UNAUTHORIZED`, since the bundled container has no TLS, except beside a `DATABASE_HOST` the environment pins elsewhere: the next boot dials that server, and `sslEnabled` is written as sent. A boot with `POSTGRES_BUILTIN=true`, `DATABASE_SSL=true` and a `DATABASE_HOST` that reaches the bundled container is refused with a message naming `DATABASE_SSL`.
```json
{
diff --git a/src/modules/infra/config-sections.ts b/src/modules/infra/config-sections.ts
index e8f997ced..df96c1447 100644
--- a/src/modules/infra/config-sections.ts
+++ b/src/modules/infra/config-sections.ts
@@ -86,11 +86,16 @@ export function applyDatabaseSection(
updates.DATABASE_PORT = '5432';
// A database the next boot already dials on the bundled container (by a host that names it in any spelling)
// keeps the user, database and schema it uses there: such a file reads as built-in, and a save that changes
- // nothing else must not move the instance to another database. From anywhere else they belong to another server.
+ // nothing else must not move the instance to another database. So does the one the bundled container serves the
+ // running process, whose environment the boot loaded and a save leaves as it is: switched away and back before a
+ // restart, the file holds the other server's values. From anywhere else they belong to another server.
const servesStored =
nextBootValue('DATABASE_TYPE', existing) === 'postgres' &&
namesBundledContainer('postgres', nextBootValue('DATABASE_HOST', existing));
- updates.DATABASE_USERNAME = (servesStored && existing.DATABASE_USERNAME) || 'openwa';
+ const servesRunning =
+ process.env.DATABASE_TYPE === 'postgres' && namesBundledContainer('postgres', process.env.DATABASE_HOST);
+ const kept: Partial<Record<string, string>> = servesStored ? existing : servesRunning ? process.env : {};
+ updates.DATABASE_USERNAME = kept.DATABASE_USERNAME || 'openwa';
// The bundled credential is only the DEFAULT. Secrets are never echoed back to the form,
// so an absent password field means "unchanged", not "reset to 'openwa'" — and the
// dashboard ALWAYS sends builtIn, so keying the reset on "explicit builtIn:true" reset a
@@ -99,18 +104,21 @@ export function applyDatabaseSection(
// it does when the previous mode was already built-in, or when the next boot already dials the
// bundled host with it (the environment's host, else the file's, a file that names it without the
// flag included, in any spelling that reaches the container). Coming from external, the stored value is the
- // external DB's credential and must not be carried into the container.
+ // external DB's credential and must not be carried into the container; the one the running process dials the
+ // bundled container with is that container's own.
const storedPassword =
existing.POSTGRES_BUILTIN === 'true' ||
namesBundledContainer('postgres', nextBootValue('DATABASE_HOST', existing))
? existing.DATABASE_PASSWORD
- : undefined;
+ : servesRunning
+ ? process.env.DATABASE_PASSWORD
+ : undefined;
updates.DATABASE_PASSWORD = database.password || storedPassword || 'openwa';
- updates.DATABASE_NAME = (servesStored && existing.DATABASE_NAME) || 'openwa';
+ updates.DATABASE_NAME = kept.DATABASE_NAME || 'openwa';
// Built-in Postgres is initialized with the default 'public' schema (see
// scripts/postgres-init-schema.sh). Pin it so a later switch from a custom-schema
// external DB to built-in doesn't carry a stale POSTGRES_SCHEMA forward.
- updates.POSTGRES_SCHEMA = (servesStored && existing.POSTGRES_SCHEMA) || 'public';
+ updates.POSTGRES_SCHEMA = kept.POSTGRES_SCHEMA || 'public';
profiles.push('postgres');
} else {
// External PostgreSQL. Flipping built-in -> external must not carry the bundled
@@ -250,19 +258,24 @@ export function applyStorageSection(
if (storage.builtIn ?? existing.MINIO_BUILTIN === 'true') {
// Built-in MinIO - use container name as endpoint. The bundled keys are only the DEFAULT, as for the database
// password: keys the next boot already dials the bundled endpoint with (the flag already set, or the bundled
- // endpoint pinned or stored, in any spelling) are the ones that container was created with, and are kept.
+ // endpoint pinned or stored, in any spelling) are the ones that container was created with, and are kept; else
+ // the ones the running process dials it with, as for the database.
const keepKeys =
existing.MINIO_BUILTIN === 'true' || namesBundledContainer('minio', nextBootValue('S3_ENDPOINT', existing));
+ const servesRunning =
+ process.env.STORAGE_TYPE === 's3' && namesBundledContainer('minio', process.env.S3_ENDPOINT);
+ const keys: Partial<Record<string, string>> = keepKeys ? existing : servesRunning ? process.env : {};
updates.S3_ENDPOINT = 'http://minio:9000';
- updates.S3_ACCESS_KEY_ID = (keepKeys && (existing.S3_ACCESS_KEY_ID || existing.S3_ACCESS_KEY)) || 'minioadmin';
- updates.S3_SECRET_ACCESS_KEY =
- (keepKeys && (existing.S3_SECRET_ACCESS_KEY || existing.S3_SECRET_KEY)) || 'minioadmin';
- // As for the database: a bucket the next boot already reaches on the bundled MinIO is kept with its region.
+ updates.S3_ACCESS_KEY_ID = keys.S3_ACCESS_KEY_ID || keys.S3_ACCESS_KEY || 'minioadmin';
+ updates.S3_SECRET_ACCESS_KEY = keys.S3_SECRET_ACCESS_KEY || keys.S3_SECRET_KEY || 'minioadmin';
+ // As for the database: a bucket the next boot already reaches on the bundled MinIO, else the one it serves the
+ // running process, is kept with its region.
const servesStored =
nextBootValue('STORAGE_TYPE', existing) === 's3' &&
namesBundledContainer('minio', nextBootValue('S3_ENDPOINT', existing));
- updates.S3_BUCKET = (servesStored && existing.S3_BUCKET) || 'openwa';
- updates.S3_REGION = (servesStored && existing.S3_REGION) || 'us-east-1';
+ const kept: Partial<Record<string, string>> = servesStored ? existing : servesRunning ? process.env : {};
+ updates.S3_BUCKET = kept.S3_BUCKET || 'openwa';
+ updates.S3_REGION = kept.S3_REGION || 'us-east-1';
profiles.push('minio');
} else {
// External S3/MinIO. Flipping built-in -> external must not carry the bundled
diff --git a/src/modules/infra/infra-config.controller.spec.ts b/src/modules/infra/infra-config.controller.spec.ts
index 2c3ea538d..0bcc284c3 100644
--- a/src/modules/infra/infra-config.controller.spec.ts
+++ b/src/modules/infra/infra-config.controller.spec.ts
@@ -1722,6 +1722,135 @@ describe('InfraConfigController.saveConfig built-in/external mode flips and the
expect(env).toContain('S3_BUCKET=openwa');
expect(env).toContain('S3_REGION=us-east-1');
});
+
+ // A database and bucket of their own on the bundled containers, switched away to other servers and saved without a
+ // restart, then switched back: the file names the other servers now, but the running process still dials the
+ // bundled containers with the values its boot loaded into the environment, and those are what they serve.
+ describe('switched away and back before a restart', () => {
+ const RUNNING: Record<string, string> = {
+ DATABASE_TYPE: 'postgres',
+ DATABASE_HOST: 'openwa-postgres',
+ DATABASE_USERNAME: 'app',
+ DATABASE_PASSWORD: 'RunPw12345!',
+ DATABASE_NAME: 'appdb',
+ POSTGRES_SCHEMA: 'tenant',
+ STORAGE_TYPE: 's3',
+ S3_ENDPOINT: 'http://openwa-minio:9000',
+ S3_BUCKET: 'media',
+ S3_REGION: 'eu-west-1',
+ S3_ACCESS_KEY_ID: 'RunKey1234567',
+ S3_SECRET_ACCESS_KEY: 'RunSecret1234567890',
+ };
+ // What the switch away wrote: the other servers, with a password, bucket and keys of their own typed.
+ const SWITCHED =
+ 'DATABASE_TYPE=postgres\nPOSTGRES_BUILTIN=false\nDATABASE_HOST=db.ext.example\nDATABASE_USERNAME=app\n' +
+ 'DATABASE_PASSWORD=ExtPw12345!\nDATABASE_NAME=extdb\nPOSTGRES_SCHEMA=tenant\nSTORAGE_TYPE=s3\nMINIO_BUILTIN=false\n' +
+ 'S3_ENDPOINT=https://s3.ext.example\nS3_BUCKET=newbucket\nS3_REGION=us-west-2\nS3_ACCESS_KEY_ID=ExtKey1234567\n' +
+ 'S3_SECRET_ACCESS_KEY=ExtSecret1234567890\n';
+ const KEYS = [
+ 'DATABASE_HOST',
+ 'DATABASE_USERNAME',
+ 'DATABASE_PASSWORD',
+ 'DATABASE_NAME',
+ 'POSTGRES_SCHEMA',
+ 'S3_ENDPOINT',
+ 'S3_BUCKET',
+ 'S3_REGION',
+ 'S3_ACCESS_KEY_ID',
+ 'S3_SECRET_ACCESS_KEY',
+ ];
+ const switchBack = (running: Record<string, string>) => {
+ Object.assign(process.env, running);
+ const env = jest
+ .requireActual<typeof import('dotenv')>('dotenv')
+ .parse(
+ written(
+ { database: { type: 'postgres', builtIn: true }, storage: { type: 's3', builtIn: true } },
+ SWITCHED,
+ ),
+ );
+ return Object.fromEntries(KEYS.map(key => [key, env[key]]));
+ };
+ // Nothing is pinned: the running process holds the values its boot loaded from the file.
+ afterEach(() => {
+ for (const key of Object.keys(RUNNING)) delete process.env[key];
+ });
+
+ it('keeps the user, database, schema, password, bucket, region and keys the running process uses there', () => {
+ expect(switchBack(RUNNING)).toEqual({
+ DATABASE_HOST: 'postgres',
+ DATABASE_USERNAME: 'app',
+ DATABASE_PASSWORD: 'RunPw12345!',
+ DATABASE_NAME: 'appdb',
+ POSTGRES_SCHEMA: 'tenant',
+ S3_ENDPOINT: 'http://minio:9000',
+ S3_BUCKET: 'media',
+ S3_REGION: 'eu-west-1',
+ S3_ACCESS_KEY_ID: 'RunKey1234567',
+ S3_SECRET_ACCESS_KEY: 'RunSecret1234567890',
+ });
+ });
+
+ it.each(HOST_SPELLINGS.database.reach.map((db, i) => [db, HOST_SPELLINGS.storage.reach[i]]))(
+ 'keeps them while the running process dials %j and %j',
+ (db, s3) => {
+ const env = switchBack({ ...RUNNING, DATABASE_HOST: db, S3_ENDPOINT: s3 });
+ expect([env.DATABASE_NAME, env.DATABASE_PASSWORD, env.S3_BUCKET, env.S3_ACCESS_KEY_ID]).toEqual([
+ 'appdb',
+ 'RunPw12345!',
+ 'media',
+ 'RunKey1234567',
+ ]);
+ },
+ );
+
+ it('writes the bundled ones while the running process dials other servers', () => {
+ expect(
+ switchBack({ ...RUNNING, DATABASE_HOST: 'db.old.example', S3_ENDPOINT: 'https://s3.old.example' }),
+ ).toEqual({
+ DATABASE_HOST: 'postgres',
+ DATABASE_USERNAME: 'openwa',
+ DATABASE_PASSWORD: 'openwa',
+ DATABASE_NAME: 'openwa',
+ POSTGRES_SCHEMA: 'public',
+ S3_ENDPOINT: 'http://minio:9000',
+ S3_BUCKET: 'openwa',
+ S3_REGION: 'us-east-1',
+ S3_ACCESS_KEY_ID: 'minioadmin',
+ S3_SECRET_ACCESS_KEY: 'minioadmin',
+ });
+ });
+
+ it('writes the bundled ones while the running process uses SQLite and local storage', () => {
+ const env = switchBack({ ...RUNNING, DATABASE_TYPE: 'sqlite', STORAGE_TYPE: 'local' });
+ expect([env.DATABASE_NAME, env.DATABASE_PASSWORD, env.S3_BUCKET, env.S3_ACCESS_KEY_ID]).toEqual([
+ 'openwa',
+ 'openwa',
+ 'openwa',
+ 'minioadmin',
+ ]);
+ });
+
+ // A file that already names the bundled containers is the choice the next boot makes: its values stay.
+ it('keeps the stored ones of a file that names the bundled containers over the running ones', () => {
+ Object.assign(process.env, RUNNING);
+ const env = jest
+ .requireActual<typeof import('dotenv')>('dotenv')
+ .parse(
+ written(
+ { database: { type: 'postgres', builtIn: true }, storage: { type: 's3', builtIn: true } },
+ SWITCHED.replace('db.ext.example', 'postgres').replace('https://s3.ext.example', 'http://minio:9000'),
+ ),
+ );
+ expect([env.DATABASE_NAME, env.DATABASE_PASSWORD, env.S3_BUCKET, env.S3_REGION, env.S3_ACCESS_KEY_ID]).toEqual([
+ 'extdb',
+ 'ExtPw12345!',
+ 'newbucket',
+ 'us-west-2',
+ 'ExtKey1234567',
+ ]);
+ });
+ });
});
// The guard must evaluate what the next boot would SEE: load-env.ts loads with dotenv