@basaltkit/deploy 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -196,6 +196,28 @@ migrate: {
196
196
  },
197
197
  ```
198
198
 
199
+ **Dedicated infra for a compose app** — the containers created by the deploy
200
+ too, in their own compose project, reached by name from the app's containers:
201
+
202
+ ```ts
203
+ infra: dockerInfra('myapp', {
204
+ project: 'myapp-infra', // never the runtime's project: each would remove the other's containers
205
+ access: 'containers', // URLs name the containers (myapp-pg:5432); migrations get 127.0.0.1:<port>
206
+ postgres: { user: 'myapp_owner', urlKey: 'OWNER_DATABASE_URL', appRole: { name: 'myapp_app', urlKey: 'DATABASE_URL' } },
207
+ redis: { urlKey: 'REDIS_URL' },
208
+ minio: { buckets: [{ name: 'myapp-documents', versioned: true }] },
209
+ }),
210
+ runtime: compose({
211
+ // …
212
+ attach: { 'myapp-pg': ['data'], 'myapp-redis': ['data'], 'myapp-minio': ['data'] },
213
+ passEnv: ['REDIS_URL'], // a service without env_file gets it through ${REDIS_URL}: from memory only
214
+ }),
215
+ ```
216
+
217
+ Ports are still published on 127.0.0.1 for the host; the app role's URL
218
+ follows the database when it moves (a recreated container) and keeps its
219
+ password.
220
+
199
221
  **Services you keep but do not create** (RFC 0007 §4) — containers that outlive
200
222
  any release, adopted by name:
201
223
 
package/dist/cli.js CHANGED
@@ -6,6 +6,7 @@ import { check } from './check.js';
6
6
  import { init } from './init.js';
7
7
  import { applyOverrides, DeployConfigError, parseOverrides, validateConfig } from './config.js';
8
8
  import { DeployError, detectPackageManager, resolveStateDir } from './context.js';
9
+ import { envValues, parseEnv } from './dotenv.js';
9
10
  import { nodeHost } from './host.js';
10
11
  import { envCommand, install, plan, rollback, run, SKIPPABLE, status } from './pipeline.js';
11
12
  export const USAGE = `basalt-deploy — deploy this Basalt app on this server (RFC 0006)
@@ -81,13 +82,17 @@ export async function loadConfig(dir, file) {
81
82
  return config;
82
83
  }
83
84
  export async function createContext(host, dir, config) {
85
+ const envPath = resolve(dir, config.env.file ?? '.env');
86
+ const text = await host.readFile(envPath);
84
87
  return {
85
88
  config,
86
89
  dir,
87
90
  host,
88
91
  pm: await detectPackageManager(host, dir),
89
- envPath: resolve(dir, config.env.file ?? '.env'),
92
+ envPath,
90
93
  stateDir: await resolveStateDir(host, config, dir),
94
+ // What compose interpolation reads for passEnv in plan, status, rollback.
95
+ ...(text === undefined ? {} : { values: envValues(parseEnv(text)) }),
91
96
  };
92
97
  }
93
98
  export async function main(argv, host = nodeHost(), cwd = process.cwd()) {
package/dist/compose.js CHANGED
@@ -22,6 +22,13 @@ export function composeEnv(ctx, sha) {
22
22
  const env = { ...rt.env };
23
23
  for (const image of rt.images)
24
24
  env[image.env] = `${image.tag}:${short(sha)}`;
25
+ // From the .env, in compose's environment only (RFC 0007 §4): a password
26
+ // never goes into deploy.config.ts, a command line or a file.
27
+ for (const key of rt.passEnv ?? []) {
28
+ const value = ctx.values?.get(key);
29
+ if (value !== undefined)
30
+ env[key] = value;
31
+ }
25
32
  return env;
26
33
  }
27
34
  const composeArgs = (ctx, ...args) => ['compose', '-p', ctx.config.app, '-f', join(ctx.dir, composeOf(ctx).file), ...args];
package/dist/config.d.ts CHANGED
@@ -221,6 +221,22 @@ export interface DockerInfra<E extends object = EnvShape> {
221
221
  postgres?: PostgresService<E>;
222
222
  redis?: RedisService<E>;
223
223
  minio?: MinioService;
224
+ /**
225
+ * The compose project the containers belong to. Default: the app — what an
226
+ * older compose file of the app's infra already used. An app whose own
227
+ * runtime is a compose project named after it needs another one.
228
+ * @example 'myapp-infra'
229
+ */
230
+ project?: string;
231
+ /**
232
+ * Who reaches the services through the URLs written to the `.env`:
233
+ * `host` — a process on the host (PM2): `127.0.0.1:<published port>`;
234
+ * `containers` — the app's containers: `<container>:<internal port>`, on
235
+ * the networks `runtime.attach` connects them to. Migrations and the dump,
236
+ * which run on the host, get the `127.0.0.1` form either way.
237
+ * @default 'host'
238
+ */
239
+ access?: 'host' | 'containers';
224
240
  }
225
241
  export interface PostgresService<E extends object = EnvShape> {
226
242
  image: string;
@@ -339,6 +355,13 @@ export interface ComposeRuntime {
339
355
  env: Record<string, string>;
340
356
  /** Releases whose images are kept for a rollback without a rebuild. */
341
357
  keepImages: number;
358
+ /**
359
+ * `.env` keys handed to compose for interpolation (`${KEY}` in the file) —
360
+ * a service without `env_file` that still needs one value, a password among
361
+ * them. In compose's environment only: never on a command line, never in a file.
362
+ * @example ['MYAPP_REDIS_URL']
363
+ */
364
+ passEnv?: string[];
342
365
  /**
343
366
  * Containers this project does not own, connected to its networks before
344
367
  * `up` — creating the project first on a fresh server, so the first release
@@ -514,6 +537,7 @@ export declare const compose: (options: {
514
537
  keepImages?: number;
515
538
  attach?: Record<string, string[]>;
516
539
  jobs?: ComposeJob[];
540
+ passEnv?: string[];
517
541
  }) => ComposeRuntime;
518
542
  export declare const none: () => NoProxy;
519
543
  export declare const external: <E extends object = EnvShape>(services?: NoInfer<Omit<ExternalInfra<E>, 'kind'>>) => ExternalInfra<E>;
@@ -521,6 +545,8 @@ export declare const external: <E extends object = EnvShape>(services?: NoInfer<
521
545
  export declare const bucketName: (bucket: Bucket) => string;
522
546
  export declare const MINIO_IMAGE = "minio/minio:RELEASE.2025-03-12T18-04-18Z";
523
547
  export interface DockerInfraOptions<E extends object = EnvShape> {
548
+ project?: string;
549
+ access?: 'host' | 'containers';
524
550
  postgres?: Partial<PostgresService<E>> | false;
525
551
  redis?: Partial<RedisService<E>> | false;
526
552
  minio?: Partial<MinioService> | false;
package/dist/config.js CHANGED
@@ -67,6 +67,7 @@ export const compose = (options) => ({
67
67
  keepImages: options.keepImages ?? 3,
68
68
  ...(options.attach ? { attach: options.attach } : {}),
69
69
  ...(options.jobs ? { jobs: options.jobs } : {}),
70
+ ...(options.passEnv ? { passEnv: options.passEnv } : {}),
70
71
  });
71
72
  export const none = () => ({ kind: 'none' });
72
73
  export const external = (services = {}) => ({ kind: 'external', ...services });
@@ -80,7 +81,7 @@ export const MINIO_IMAGE = 'minio/minio:RELEASE.2025-03-12T18-04-18Z';
80
81
  * duplicated.
81
82
  */
82
83
  export function dockerInfra(app, options = {}) {
83
- const infra = { kind: 'docker' };
84
+ const infra = { kind: 'docker', ...(options.project ? { project: options.project } : {}), ...(options.access ? { access: options.access } : {}) };
84
85
  if (options.postgres !== false) {
85
86
  infra.postgres = {
86
87
  image: 'postgres:16', port: 'auto', user: app, database: app, urlKey: 'DATABASE_URL', urlParams: {},
@@ -209,6 +210,12 @@ export function validateConfig(typed) {
209
210
  if (container !== undefined && !/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(container))
210
211
  problems.push(`container "${container}" is not a container name`);
211
212
  }
213
+ if (config.infra?.kind === 'docker' && config.infra.project !== undefined && !/^[a-z0-9][a-z0-9_-]*$/.test(config.infra.project)) {
214
+ problems.push(`infra.project "${config.infra.project}" is not a compose project name`);
215
+ }
216
+ if (config.infra?.kind === 'docker' && (config.infra.project ?? config.app) === config.app && config.runtime.kind === 'compose') {
217
+ problems.push(`infra.project "${config.app}" is the runtime's compose project too: the two would remove each other's containers as orphans — use "${config.app}-infra"`);
218
+ }
212
219
  const role = services?.postgres?.appRole ?? (config.infra?.kind === 'docker' ? config.infra.postgres?.appRole : undefined);
213
220
  if (role && !/^[a-z_][a-z0-9_]{0,62}$/.test(role.name))
214
221
  problems.push(`appRole "${role.name}" must be a lowercase Postgres identifier`);
package/dist/context.d.ts CHANGED
@@ -10,6 +10,13 @@ export interface DeployContext {
10
10
  envPath: string;
11
11
  /** Releases, generated infra files. `/var/lib/basalt/<app>` once `install` ran, else `<dir>/.basalt`. */
12
12
  stateDir: string;
13
+ /**
14
+ * The `.env` as last read or written — what `compose({ passEnv })` hands to
15
+ * compose in its environment (never on a command line, never in a file).
16
+ */
17
+ values?: Map<string, string>;
18
+ /** Container addresses → their 127.0.0.1 form, for what runs on the host (`dockerInfra({ access: 'containers' })`). */
19
+ hostUrls?: Array<[string, string]>;
13
20
  }
14
21
  export interface Finding {
15
22
  /** The RFC 0006 §5 check id (`C1`…`C10`) or a step name. */
package/dist/infra.d.ts CHANGED
@@ -35,7 +35,15 @@ export interface InfraPlan {
35
35
  secrets: Record<string, string>;
36
36
  /** The dedicated Postgres's owner URL, as the `.env` will hold it (the app role's is derived from it). */
37
37
  ownerUrl?: string;
38
+ /**
39
+ * With `access: 'containers'`: each container address in the `.env` and the
40
+ * 127.0.0.1 one that reaches it from the host — for the migrations, which
41
+ * run on the host. `['@myapp-pg:5432', '@127.0.0.1:5433']`.
42
+ */
43
+ hostUrls?: Array<[string, string]>;
38
44
  }
45
+ /** The compose project of the dedicated infra. */
46
+ export declare const infraProject: (app: string, infra: DockerInfra) => string;
39
47
  export declare function planInfra(ctx: DeployContext, values: Map<string, string>): Promise<InfraPlan>;
40
48
  /** The compose file, with no secret in it: compose interpolates them from its environment. */
41
49
  export declare function renderCompose(app: string, infra: DockerInfra, plan: InfraPlan): string;
package/dist/infra.js CHANGED
@@ -25,17 +25,19 @@ async function inspect(ctx, container) {
25
25
  async function volumeExists(ctx, volume) {
26
26
  return (await ctx.host.exec('docker', ['volume', 'inspect', volume])).code === 0;
27
27
  }
28
- function urlParts(value) {
28
+ function urlParts(value, container) {
29
29
  if (!value)
30
30
  return undefined;
31
31
  try {
32
32
  const url = new URL(value);
33
- if (url.hostname !== 'localhost' && url.hostname !== '127.0.0.1')
33
+ const onHost = url.hostname === 'localhost' || url.hostname === '127.0.0.1';
34
+ if (!onHost && url.hostname !== container)
34
35
  return undefined;
35
36
  return {
36
37
  user: decodeURIComponent(url.username),
37
38
  password: decodeURIComponent(url.password),
38
- port: Number(url.port),
39
+ // A container's port is its internal one: no use for picking the published port.
40
+ port: onHost ? Number(url.port) : undefined,
39
41
  database: url.pathname.replace(/^\//, ''),
40
42
  };
41
43
  }
@@ -43,15 +45,17 @@ function urlParts(value) {
43
45
  return undefined;
44
46
  }
45
47
  }
46
- const names = (app, service, container) => {
48
+ const names = (app, project, service, container) => {
47
49
  const suffix = service === 'postgres' ? 'pg' : service;
48
- // Compose prefixes volumes with the project name — the app — so this is
49
- // what an older compose file with the same project name already created.
50
- return { container: container ?? `${app}-${suffix}`, volumeKey: `${app}-${suffix}-data`, volume: `${app}_${app}-${suffix}-data` };
50
+ // Compose prefixes volumes with the project name — by default the app — so
51
+ // this is what an older compose file with the same project name created.
52
+ return { container: container ?? `${app}-${suffix}`, volumeKey: `${app}-${suffix}-data`, volume: `${project}_${app}-${suffix}-data` };
51
53
  };
54
+ /** The compose project of the dedicated infra. */
55
+ export const infraProject = (app, infra) => infra.project ?? app;
52
56
  export async function planInfra(ctx, values) {
53
57
  const infra = ctx.config.infra;
54
- const plan = { services: [], env: [], findings: [], secrets: {} };
58
+ const plan = { services: [], env: [], findings: [], secrets: {}, hostUrls: [] };
55
59
  if (infra?.kind === 'external') {
56
60
  plan.findings.push(...await externalFindings(ctx));
57
61
  const pg = infra.postgres;
@@ -62,6 +66,15 @@ export async function planInfra(ctx, values) {
62
66
  if (infra?.kind !== 'docker')
63
67
  return plan;
64
68
  const { app } = ctx.config;
69
+ const project = infraProject(app, infra);
70
+ const inContainers = infra.access === 'containers';
71
+ /** The address the `.env` holds: the container's, or the host's. */
72
+ const address = (container, internal, published) => {
73
+ if (!inContainers)
74
+ return `127.0.0.1:${published}`;
75
+ plan.hostUrls?.push([`${container}:${internal}`, `127.0.0.1:${published}`]);
76
+ return `${container}:${internal}`;
77
+ };
65
78
  const picked = [];
66
79
  const pick = async (wanted, existing, from) => {
67
80
  const port = typeof wanted === 'number' ? wanted : existing ?? await freePort(ctx.host, from, [], picked);
@@ -80,9 +93,9 @@ export async function planInfra(ctx, values) {
80
93
  });
81
94
  if (infra.postgres) {
82
95
  const pg = infra.postgres;
83
- const { container, volume } = names(app, 'postgres', pg.container);
96
+ const { container, volume } = names(app, project, 'postgres', pg.container);
84
97
  const running = await inspect(ctx, container);
85
- const fromEnv = urlParts(values.get(pg.urlKey));
98
+ const fromEnv = urlParts(values.get(pg.urlKey), inContainers ? container : undefined);
86
99
  let password = running?.env.get('POSTGRES_PASSWORD');
87
100
  let source = 'container';
88
101
  if (password === undefined && fromEnv?.password) {
@@ -99,7 +112,7 @@ export async function planInfra(ctx, values) {
99
112
  const database = running?.env.get('POSTGRES_DB') ?? fromEnv?.database ?? pg.database;
100
113
  const port = await pick(pg.port, running?.ports.get('5432/tcp') ?? fromEnv?.port, 5433);
101
114
  const params = new URLSearchParams(pg.urlParams).toString();
102
- plan.ownerUrl = `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@127.0.0.1:${port}/${database}${params ? `?${params}` : ''}`;
115
+ plan.ownerUrl = `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@${address(container, 5432, port)}/${database}${params ? `?${params}` : ''}`;
103
116
  setEnv(pg.urlKey, plan.ownerUrl, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new database' : 'port or parameters');
104
117
  plan.env.push(...appRoleEnv(ctx, values, plan.ownerUrl));
105
118
  plan.secrets['BASALT_PG_PASSWORD'] = password;
@@ -107,9 +120,9 @@ export async function planInfra(ctx, values) {
107
120
  }
108
121
  if (infra.redis) {
109
122
  const redis = infra.redis;
110
- const { container, volume } = names(app, 'redis', redis.container);
123
+ const { container, volume } = names(app, project, 'redis', redis.container);
111
124
  const running = await inspect(ctx, container);
112
- const fromEnv = urlParts(values.get(redis.urlKey));
125
+ const fromEnv = urlParts(values.get(redis.urlKey), inContainers ? container : undefined);
113
126
  let password = running?.env.get('REDIS_PASSWORD');
114
127
  let source = 'container';
115
128
  if (password === undefined && fromEnv?.password) {
@@ -122,13 +135,13 @@ export async function planInfra(ctx, values) {
122
135
  source = 'generated';
123
136
  }
124
137
  const port = await pick(redis.port, running?.ports.get('6379/tcp') ?? fromEnv?.port, 6380);
125
- setEnv(redis.urlKey, `redis://:${encodeURIComponent(password)}@127.0.0.1:${port}`, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new redis' : 'port');
138
+ setEnv(redis.urlKey, `redis://:${encodeURIComponent(password)}@${address(container, 6379, port)}`, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new redis' : 'port');
126
139
  plan.secrets['BASALT_REDIS_PASSWORD'] = password;
127
140
  plan.services.push({ service: 'redis', container, volume, action: running ? 'adopt' : 'create', port, source });
128
141
  }
129
142
  if (infra.minio) {
130
143
  const minio = infra.minio;
131
- const { container, volume } = names(app, 'minio', minio.container);
144
+ const { container, volume } = names(app, project, 'minio', minio.container);
132
145
  const running = await inspect(ctx, container);
133
146
  let user = running?.env.get('MINIO_ROOT_USER');
134
147
  let password = running?.env.get('MINIO_ROOT_PASSWORD');
@@ -148,7 +161,7 @@ export async function planInfra(ctx, values) {
148
161
  let endpointPort;
149
162
  try {
150
163
  const endpoint = values.get(minio.keys.endpoint);
151
- endpointPort = endpoint ? Number(new URL(endpoint).port) || undefined : undefined;
164
+ endpointPort = endpoint && !inContainers ? Number(new URL(endpoint).port) || undefined : undefined;
152
165
  }
153
166
  catch {
154
167
  endpointPort = undefined;
@@ -156,7 +169,7 @@ export async function planInfra(ctx, values) {
156
169
  const port = await pick(minio.port, running?.ports.get('9000/tcp') ?? endpointPort, 9100);
157
170
  const consolePort = await pick(minio.consolePort, running?.ports.get('9001/tcp'), port + 1);
158
171
  const reason = source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new minio' : 'port';
159
- setEnv(minio.keys.endpoint, `http://127.0.0.1:${port}`, reason);
172
+ setEnv(minio.keys.endpoint, `http://${address(container, 9000, port)}`, reason);
160
173
  setEnv(minio.keys.accessKey, user, reason);
161
174
  setEnv(minio.keys.secretKey, password, reason);
162
175
  plan.secrets['BASALT_MINIO_USER'] = user;
@@ -180,13 +193,13 @@ export function renderCompose(app, infra, plan) {
180
193
  `# Generated by basalt-deploy for "${app}". Do not edit — change deploy.config.ts.`,
181
194
  '# Every port is bound to 127.0.0.1: Docker writes its own iptables rules and',
182
195
  '# ignores ufw, so a port published without an address is open to the internet.',
183
- `name: ${app}`,
196
+ `name: ${infraProject(app, infra)}`,
184
197
  '',
185
198
  'services:',
186
199
  ];
187
200
  const volumes = [];
188
201
  for (const service of plan.services) {
189
- const key = service.volume.slice(app.length + 1);
202
+ const key = service.volume.slice(infraProject(app, infra).length + 1);
190
203
  volumes.push(key);
191
204
  if (service.service === 'postgres' && infra.postgres) {
192
205
  lines.push(' postgres:', ` image: ${infra.postgres.image}`, ` container_name: ${service.container}`, ' restart: unless-stopped', ` labels: { basalt.app: ${app} }`, ` ports: ['127.0.0.1:${service.port}:5432']`, ' environment:', ` POSTGRES_USER: ${service.user}`, ' POSTGRES_PASSWORD: ${BASALT_PG_PASSWORD:?missing}', ` POSTGRES_DB: ${service.database}`, ` volumes: ['${key}:/var/lib/postgresql/data']`, ' healthcheck:', ` test: ['CMD-SHELL', 'pg_isready -U ${service.user} -d ${service.database}']`, ' interval: 10s', ' timeout: 5s', ' retries: 10');
@@ -211,9 +224,10 @@ export async function applyInfra(ctx, plan) {
211
224
  const { app } = ctx.config;
212
225
  await host.mkdir(ctx.stateDir, 0o700);
213
226
  await host.writeFile(composeFile(ctx), renderCompose(app, infra, plan), 0o600);
214
- const up = await host.exec('docker', ['compose', '-p', app, '-f', composeFile(ctx), 'up', '-d', '--wait', '--wait-timeout', '180'], { env: plan.secrets });
227
+ const project = infraProject(app, infra);
228
+ const up = await host.exec('docker', ['compose', '-p', project, '-f', composeFile(ctx), 'up', '-d', '--wait', '--wait-timeout', '180'], { env: plan.secrets });
215
229
  if (up.code !== 0) {
216
- return [{ id: 'infra', level: 'error', message: `docker compose up failed:\n${up.stderr.trim()}`, fix: `docker compose -p ${app} ps; docker logs ${app}-pg` }];
230
+ return [{ id: 'infra', level: 'error', message: `docker compose up failed:\n${up.stderr.trim()}`, fix: `docker compose -p ${project} ps; docker logs ${plan.services[0]?.container ?? app}` }];
217
231
  }
218
232
  const findings = [];
219
233
  for (const service of plan.services) {
@@ -20,8 +20,12 @@ export interface Preflight {
20
20
  export declare function preflight(ctx: DeployContext, options?: RunOptions): Promise<Preflight>;
21
21
  /** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
22
22
  export declare function migratesCentral(config: DeployContext['config']): boolean;
23
- /** The `.env` as the migration and the dump see it: `migrate.env` on top (host URLs for container names). */
24
- export declare function migrationValues(config: DeployContext['config'], values: Map<string, string>): Map<string, string>;
23
+ /**
24
+ * The `.env` as the migration and the dump see it — they run on the host:
25
+ * container addresses (`@myapp-pg:5432`) become the published 127.0.0.1 ones,
26
+ * then `migrate.env` on top.
27
+ */
28
+ export declare function migrationValues(config: DeployContext['config'], values: Map<string, string>, hostUrls?: Array<[string, string]>): Map<string, string>;
25
29
  /**
26
30
  * Whether the pre-migration dump runs, and why not when it does not. Unsaid,
27
31
  * it runs when there is something to migrate AND a Postgres to dump: the
package/dist/pipeline.js CHANGED
@@ -163,10 +163,20 @@ export function migratesCentral(config) {
163
163
  return config.migrate?.central ?? (config.build?.prisma?.length ?? 0) > 0;
164
164
  }
165
165
  const migratesAnything = (config) => Boolean(config.migrate?.command) || migratesCentral(config) || Boolean(config.migrate?.tenants);
166
- /** The `.env` as the migration and the dump see it: `migrate.env` on top (host URLs for container names). */
167
- export function migrationValues(config, values) {
168
- const extra = config.migrate?.env?.(values) ?? {};
169
- return new Map([...values, ...definedEntries(extra)]);
166
+ /**
167
+ * The `.env` as the migration and the dump see it — they run on the host:
168
+ * container addresses (`@myapp-pg:5432`) become the published 127.0.0.1 ones,
169
+ * then `migrate.env` on top.
170
+ */
171
+ export function migrationValues(config, values, hostUrls = []) {
172
+ const onHost = new Map([...values].map(([key, value]) => {
173
+ let rewritten = value;
174
+ for (const [from, to] of hostUrls)
175
+ rewritten = rewritten.replace(`@${from}`, `@${to}`).replace(`//${from}`, `//${to}`);
176
+ return [key, rewritten];
177
+ }));
178
+ const extra = config.migrate?.env?.(onHost) ?? {};
179
+ return new Map([...onHost, ...definedEntries(extra)]);
170
180
  }
171
181
  /**
172
182
  * Whether the pre-migration dump runs, and why not when it does not. Unsaid,
@@ -196,6 +206,8 @@ async function prepareEnv(ctx, port) {
196
206
  const document = await readEnv(ctx);
197
207
  const infra = await planInfra(ctx, envValues(document));
198
208
  const env = planEnv(ctx, document, port, infra.env);
209
+ ctx.hostUrls = infra.hostUrls ?? [];
210
+ ctx.values = env.values;
199
211
  return { env, infra };
200
212
  }
201
213
  async function build(ctx, values, sha) {
@@ -253,7 +265,7 @@ async function validate(ctx, values) {
253
265
  }
254
266
  async function migrate(ctx, raw) {
255
267
  const { host, pm } = ctx;
256
- const values = migrationValues(ctx.config, raw);
268
+ const values = migrationValues(ctx.config, raw, ctx.hostUrls);
257
269
  const env = { cwd: ctx.dir, stream: true, env: Object.fromEntries(values) };
258
270
  const command = ctx.config.migrate?.command;
259
271
  if (command) {
@@ -478,7 +490,7 @@ export async function run(ctx, options = {}) {
478
490
  await step(ctx, 'validate', () => validateStep(ctx, values));
479
491
  const backup = backupDecision(config, values, skip);
480
492
  if (backup.run) {
481
- record.backup = await step(ctx, 'backup', () => backupDatabase(ctx, migrationValues(config, values), infra, sha));
493
+ record.backup = await step(ctx, 'backup', () => backupDatabase(ctx, migrationValues(config, values, infra.hostUrls), infra, sha));
482
494
  host.out.ok(record.backup);
483
495
  }
484
496
  else {
@@ -38,8 +38,10 @@ export declare function appRoleOf(config: DeployConfig): AppRole | undefined;
38
38
  export declare function externalFindings(ctx: DeployContext): Promise<Finding[]>;
39
39
  export declare function externalPostgres(ctx: DeployContext, values: Map<string, string>): PostgresHandle | undefined;
40
40
  /**
41
- * The app role's URL, when the `.env` has none yet: the owner's, with the
42
- * role's name and a new password. Kept from then on — the role follows it.
41
+ * The app role's URL: the owner's, with the role's name and a new password,
42
+ * when the `.env` has none yet; then kept — the role follows its password.
43
+ * When the database moves (another host, port or name: a recreated
44
+ * container), the URL follows it and keeps the password.
43
45
  */
44
46
  export declare function appRoleEnv(ctx: DeployContext, values: Map<string, string>, ownerUrl: string | undefined): EnvChange[];
45
47
  /**
package/dist/services.js CHANGED
@@ -51,17 +51,31 @@ export function externalPostgres(ctx, values) {
51
51
  };
52
52
  }
53
53
  /**
54
- * The app role's URL, when the `.env` has none yet: the owner's, with the
55
- * role's name and a new password. Kept from then on — the role follows it.
54
+ * The app role's URL: the owner's, with the role's name and a new password,
55
+ * when the `.env` has none yet; then kept — the role follows its password.
56
+ * When the database moves (another host, port or name: a recreated
57
+ * container), the URL follows it and keeps the password.
56
58
  */
57
59
  export function appRoleEnv(ctx, values, ownerUrl) {
58
60
  const role = appRoleOf(ctx.config);
59
- if (!role || values.get(role.urlKey) || !ownerUrl)
61
+ if (!role || !ownerUrl)
60
62
  return [];
61
- const url = new URL(ownerUrl);
63
+ const owner = new URL(ownerUrl);
64
+ const current = values.get(role.urlKey);
65
+ if (!current) {
66
+ const url = new URL(ownerUrl);
67
+ url.username = role.name;
68
+ url.password = ctx.host.randomHex(24);
69
+ return [{ kind: 'set', key: role.urlKey, value: url.toString(), reason: `password of the ${role.name} role (new)` }];
70
+ }
71
+ const url = new URL(current);
72
+ if (url.host === owner.host && url.pathname === owner.pathname && url.search === owner.search && url.username === role.name)
73
+ return [];
74
+ url.host = owner.host;
75
+ url.pathname = owner.pathname;
76
+ url.search = owner.search;
62
77
  url.username = role.name;
63
- url.password = ctx.host.randomHex(24);
64
- return [{ kind: 'set', key: role.urlKey, value: url.toString(), reason: `password of the ${role.name} role (new)` }];
78
+ return [{ kind: 'set', key: role.urlKey, value: url.toString(), reason: `the ${role.name} role follows the database (${owner.host}${owner.pathname})` }];
65
79
  }
66
80
  const ident = (name) => `"${name.replace(/"/g, '""')}"`;
67
81
  const literal = (value) => `'${value.replace(/'/g, "''")}'`;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },