@basaltkit/deploy 0.1.4 → 0.2.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
@@ -87,9 +87,63 @@ every deploy checks it.
87
87
 
88
88
  `--skip=fetch,backup,tls`, `--config=<file>`, `--overrides=<file>`.
89
89
 
90
+ ## Docker Compose apps
91
+
92
+ ```ts
93
+ runtime: compose({
94
+ file: 'docker/compose.prod.yml',
95
+ images: [
96
+ { tag: 'myapp', dockerfile: 'docker/app/Dockerfile', env: 'MYAPP_IMAGE' },
97
+ { tag: 'myapp-worker', dockerfile: 'docker/worker/Dockerfile', env: 'MYAPP_WORKER_IMAGE' },
98
+ ],
99
+ upstream: { service: 'api', port: 3001 }, // published on 127.0.0.1 by the compose file
100
+ env: { MYAPP_API_HOST_PORT: '3001' }, // compose interpolation — never secrets
101
+ keepImages: 3,
102
+ }),
103
+ ```
104
+
105
+ - Each image is built once per commit as `<tag>:<7-char sha>` and skipped when it
106
+ exists; `compose up -d` gets the tags through the `env` variable of each image.
107
+ - Health: the upstream service healthy by its own healthcheck, **no service of
108
+ the project restarting**, then the loopback and public URLs.
109
+ - Rollback starts the previous commit's images again — no rebuild. After a
110
+ healthy release, `<sha>` tags of these images outside the last `keepImages`
111
+ releases are removed; nothing else is ever pruned.
112
+ - Image tags must be `<app>` or `<app>-…` (C4).
113
+
114
+ **The env file outside the checkout:** `env: { file: '/etc/myapp/api.env', mirror: ['/etc/myapp/worker.env'] }`.
115
+ Mirrors are rewritten as exact copies; one that differs is a C10 error. `install`
116
+ gives the files — and `/etc/myapp` itself, when its name contains the app's —
117
+ to the deploy user.
118
+
119
+ **Migrations by command**, with values that override the `.env` for them and for
120
+ the pre-migration dump (a container name the host cannot resolve):
121
+
122
+ ```ts
123
+ migrate: {
124
+ command: ['./node_modules/.bin/tsx', 'scripts/db.ts', 'deploy'],
125
+ env: (v) => ({ DATABASE_URL: v.get('DATABASE_URL')!.replace('@myapp-postgres:', '@127.0.0.1:') }),
126
+ },
127
+ ```
128
+
129
+ **Hooks** — what only your app does, as commands that also run by hand:
130
+
131
+ ```ts
132
+ hooks: {
133
+ infra: [['bash', 'scripts/deploy/infra.sh']], // after the .env and infra, before the build
134
+ verify: [['bash', 'scripts/deploy/verify.sh']], // after the health check; failing rolls back
135
+ },
136
+ ```
137
+
138
+ They run in the checkout as the deploy user with the `.env` values, the image
139
+ variables, `DEPLOY_SHA` and `DEPLOY_APP`. They run on every deploy: idempotent.
140
+
141
+ **Apache you write yourself:** `apache({ managed: false, vhosts: ['myapp.conf'] })`
142
+ checks C2 and C1 on each vhost on every deploy and never writes them.
143
+
90
144
  ## What runs by default
91
145
 
92
- - `prisma migrate deploy` — when `build.prisma` lists a config, or `migrate.central: true`.
146
+ - `prisma migrate deploy` — when `build.prisma` lists a config, or `migrate.central: true`; not with a `migrate.command` unless `central: true`.
93
147
  - `tenant:migrate` — only with `migrate.tenants`.
94
148
  - The dump before migrating — when something is migrated and there is a
95
149
  Postgres to dump (dedicated, or a `postgres://` URL in the `.env`);
package/dist/apache.js CHANGED
@@ -67,9 +67,55 @@ ${alias}
67
67
  }
68
68
  /** The ports a vhost proxies to on this machine. */
69
69
  export function proxiedPorts(vhost) {
70
- return [...vhost.matchAll(/^\s*ProxyPass\s+\S+\s+(?:https?|wss?):\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/gim)].map((m) => Number(m[1]));
70
+ // Path and URL may be quoted (`ProxyPass "/api/" "http://127.0.0.1:3001/"`):
71
+ // unquoted-only matching found no port in that form and C1 passed in silence.
72
+ return [...vhost.matchAll(/^\s*ProxyPass\s+(?:"[^"]*"|\S+)\s+"?(?:https?|wss?):\/\/(?:127\.0\.0\.1|localhost|\[::1\]):(\d+)/gim)].map((m) => Number(m[1]));
73
+ }
74
+ /**
75
+ * `managed: false` (RFC 0006 §13.4): the app's own vhosts, checked — each one
76
+ * linked into sites-enabled (C2) and every local ProxyPass on the upstream
77
+ * port (C1) — and never rendered, diffed or written.
78
+ */
79
+ async function unmanagedPreflight(ctx, port) {
80
+ const proxy = apacheOf(ctx);
81
+ const root = proxy.root ?? '/etc/apache2';
82
+ const findings = [];
83
+ for (const file of proxy.vhosts ?? []) {
84
+ const available = join(root, 'sites-available', file);
85
+ const enabled = join(root, 'sites-enabled', file);
86
+ const stat = await ctx.host.stat(enabled);
87
+ if (!stat) {
88
+ findings.push({ id: 'proxy', level: 'error', message: `sites-enabled/${file} does not exist`, fix: `sudo a2ensite ${file} && sudo apachectl configtest && sudo systemctl reload apache2` });
89
+ continue;
90
+ }
91
+ if (stat.kind === 'file') {
92
+ const copy = await ctx.host.readFile(enabled);
93
+ const original = await ctx.host.readFile(available);
94
+ findings.push({
95
+ id: 'C2',
96
+ level: 'error',
97
+ message: `sites-enabled/${file} is a regular file, not a link to sites-available — ${copy === original ? 'identical today, but edits to sites-available will not be served' : 'and it DIFFERS from sites-available: Apache serves the copy'}`,
98
+ fix: `after merging any difference into sites-available/${file}: sudo rm ${enabled} && sudo a2ensite ${file} && sudo apachectl configtest && sudo systemctl reload apache2`,
99
+ });
100
+ }
101
+ else if (stat.kind === 'symlink') {
102
+ const target = await ctx.host.readlink(enabled);
103
+ if (target !== `../sites-available/${file}` && target !== available) {
104
+ findings.push({ id: 'C2', level: 'error', message: `sites-enabled/${file} links to ${target}, not to sites-available/${file}` });
105
+ }
106
+ }
107
+ const served = await ctx.host.readFile(enabled);
108
+ for (const proxied of proxiedPorts(served ?? '')) {
109
+ if (proxied !== port) {
110
+ findings.push({ id: 'C1', level: 'error', message: `${file} proxies to 127.0.0.1:${proxied}, but the app is reached on ${port}`, fix: `edit the ProxyPass lines of sites-available/${file}, then sudo apachectl configtest && sudo systemctl reload apache2` });
111
+ }
112
+ }
113
+ }
114
+ return findings;
71
115
  }
72
116
  export async function apachePreflight(ctx, port) {
117
+ if (apacheOf(ctx).managed === false)
118
+ return unmanagedPreflight(ctx, port);
73
119
  const { host } = ctx;
74
120
  const paths = vhostPaths(ctx);
75
121
  const findings = [];
package/dist/cli.js CHANGED
@@ -77,7 +77,7 @@ export async function createContext(host, dir, config) {
77
77
  dir,
78
78
  host,
79
79
  pm: await detectPackageManager(host, dir),
80
- envPath: join(dir, config.env.file ?? '.env'),
80
+ envPath: resolve(dir, config.env.file ?? '.env'),
81
81
  stateDir: await resolveStateDir(host, config, dir),
82
82
  };
83
83
  }
@@ -0,0 +1,40 @@
1
+ import type { ComposeRuntime } from './config.js';
2
+ import { type DeployContext, type Finding } from './context.js';
3
+ /**
4
+ * The Docker Compose runtime (RFC 0006 §13.2): images built once per commit
5
+ * and tagged `<tag>:<sha>`, `compose up -d` with those tags, a rollback that
6
+ * reuses the images of an earlier release instead of rebuilding them.
7
+ *
8
+ * Only the configured image tags (C4: `<app>` or `<app>-…`) and the project
9
+ * named after the app are ever touched.
10
+ */
11
+ export declare const composeOf: (ctx: DeployContext) => ComposeRuntime;
12
+ /** Compose's own environment: each image variable → `<tag>:<sha>`, plus `runtime.env`. */
13
+ export declare function composeEnv(ctx: DeployContext, sha: string): Record<string, string>;
14
+ interface ServiceState {
15
+ service: string;
16
+ state: string;
17
+ health: string;
18
+ publishers: number[];
19
+ }
20
+ /** `docker compose ps` of the project, one entry per container. */
21
+ export declare function composeServices(ctx: DeployContext, sha: string): Promise<ServiceState[] | undefined>;
22
+ export declare function composePreflight(ctx: DeployContext, sha: string): Promise<Finding[]>;
23
+ /** `docker build` of every image not built yet for this commit. */
24
+ export declare function composeBuild(ctx: DeployContext, sha: string): Promise<void>;
25
+ export declare function composeRelease(ctx: DeployContext, sha: string): Promise<string>;
26
+ /**
27
+ * The upstream service healthy by its own healthcheck (or running, when it
28
+ * declares none), and no service of the project restarting — the ingest
29
+ * worker once crash-looped through a whole deploy unnoticed.
30
+ */
31
+ export declare function composeHealthy(ctx: DeployContext, sha: string): Promise<{
32
+ ok: true;
33
+ } | {
34
+ ok: false;
35
+ why: string;
36
+ }>;
37
+ /** Removes `<tag>:<sha>` of the configured images for commits outside `keep`. Nothing else. */
38
+ export declare function pruneImages(ctx: DeployContext, keep: string[]): Promise<string[]>;
39
+ export declare function composeStatus(ctx: DeployContext, sha: string): Promise<string[]>;
40
+ export {};
@@ -0,0 +1,152 @@
1
+ import { join } from 'node:path';
2
+ import { DeployError } from './context.js';
3
+ import { listeners } from './ports.js';
4
+ /**
5
+ * The Docker Compose runtime (RFC 0006 §13.2): images built once per commit
6
+ * and tagged `<tag>:<sha>`, `compose up -d` with those tags, a rollback that
7
+ * reuses the images of an earlier release instead of rebuilding them.
8
+ *
9
+ * Only the configured image tags (C4: `<app>` or `<app>-…`) and the project
10
+ * named after the app are ever touched.
11
+ */
12
+ export const composeOf = (ctx) => {
13
+ if (ctx.config.runtime.kind !== 'compose')
14
+ throw new Error('not a compose runtime');
15
+ return ctx.config.runtime;
16
+ };
17
+ /** 7 characters, as `git rev-parse --short` and the scripts before this one: their images stay usable for a rollback. */
18
+ const short = (sha) => sha.slice(0, 7);
19
+ /** Compose's own environment: each image variable → `<tag>:<sha>`, plus `runtime.env`. */
20
+ export function composeEnv(ctx, sha) {
21
+ const rt = composeOf(ctx);
22
+ const env = { ...rt.env };
23
+ for (const image of rt.images)
24
+ env[image.env] = `${image.tag}:${short(sha)}`;
25
+ return env;
26
+ }
27
+ const composeArgs = (ctx, ...args) => ['compose', '-p', ctx.config.app, '-f', join(ctx.dir, composeOf(ctx).file), ...args];
28
+ /** `docker compose ps` of the project, one entry per container. */
29
+ export async function composeServices(ctx, sha) {
30
+ const result = await ctx.host.exec('docker', composeArgs(ctx, 'ps', '--all', '--format', 'json'), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
31
+ if (result.code !== 0)
32
+ return undefined;
33
+ // Compose prints one JSON object per line (v2.21+) or a single array (older).
34
+ const text = result.stdout.trim();
35
+ if (!text)
36
+ return [];
37
+ const rows = text.startsWith('[')
38
+ ? JSON.parse(text)
39
+ : text.split('\n').filter(Boolean).map((line) => JSON.parse(line));
40
+ return rows.map((row) => ({
41
+ service: String(row['Service'] ?? ''),
42
+ state: String(row['State'] ?? ''),
43
+ health: String(row['Health'] ?? ''),
44
+ publishers: (Array.isArray(row['Publishers']) ? row['Publishers'] : [])
45
+ .map((p) => Number(p.PublishedPort ?? 0)).filter((port) => port > 0),
46
+ }));
47
+ }
48
+ export async function composePreflight(ctx, sha) {
49
+ const rt = composeOf(ctx);
50
+ const findings = [];
51
+ if (!(await ctx.host.exists(join(ctx.dir, rt.file)))) {
52
+ return [{ id: 'compose', level: 'error', message: `the compose file ${rt.file} does not exist` }];
53
+ }
54
+ const config = await ctx.host.exec('docker', composeArgs(ctx, 'config', '--quiet'), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
55
+ if (config.code !== 0) {
56
+ findings.push({ id: 'compose', level: 'error', message: `docker compose rejects ${rt.file}: ${config.stderr.trim().split('\n')[0] ?? ''}` });
57
+ }
58
+ // C1 under compose: the published port belongs to docker-proxy (root), so a
59
+ // listener with no visible pid is not foreign by itself — it is ours when
60
+ // the upstream service of THIS project publishes it.
61
+ const port = rt.upstream.port;
62
+ if ((await listeners(ctx.host)).some((l) => l.port === port)) {
63
+ const services = await composeServices(ctx, sha);
64
+ const ours = services?.some((s) => s.service === rt.upstream.service && s.publishers.includes(port));
65
+ if (!ours) {
66
+ findings.push({
67
+ id: 'C1',
68
+ level: 'error',
69
+ message: `port ${port} (runtime.upstream.port) is taken by something that is not the "${rt.upstream.service}" service of the ${ctx.config.app} project`,
70
+ fix: 'pick another: "port": <n> in /etc/basalt/<app>.json, and publish the same in the compose file',
71
+ });
72
+ }
73
+ }
74
+ return findings;
75
+ }
76
+ /** `docker build` of every image not built yet for this commit. */
77
+ export async function composeBuild(ctx, sha) {
78
+ const rt = composeOf(ctx);
79
+ for (const image of rt.images) {
80
+ const ref = `${image.tag}:${short(sha)}`;
81
+ if ((await ctx.host.exec('docker', ['image', 'inspect', ref])).code === 0) {
82
+ ctx.host.out.info(`${ref} already built`);
83
+ continue;
84
+ }
85
+ ctx.host.out.info(`docker build -f ${image.dockerfile} -t ${ref} ${image.context ?? '.'}`);
86
+ const built = await ctx.host.exec('docker', ['build', '-f', join(ctx.dir, image.dockerfile), '-t', ref, join(ctx.dir, image.context ?? '.')], { cwd: ctx.dir, stream: true });
87
+ if (built.code !== 0)
88
+ throw new DeployError(`docker build of ${ref} failed (exit ${built.code})`);
89
+ }
90
+ }
91
+ export async function composeRelease(ctx, sha) {
92
+ const rt = composeOf(ctx);
93
+ for (const image of rt.images) {
94
+ const ref = `${image.tag}:${short(sha)}`;
95
+ if ((await ctx.host.exec('docker', ['image', 'inspect', ref])).code !== 0)
96
+ throw new DeployError(`the image ${ref} does not exist — nothing to start`);
97
+ }
98
+ const up = await ctx.host.exec('docker', composeArgs(ctx, 'up', '-d'), { cwd: ctx.dir, env: composeEnv(ctx, sha), stream: true });
99
+ if (up.code !== 0)
100
+ throw new DeployError(`docker compose up failed (exit ${up.code})`);
101
+ return `${ctx.config.app} project up on ${short(sha)} (${rt.images.map((i) => i.tag).join(', ')})`;
102
+ }
103
+ /**
104
+ * The upstream service healthy by its own healthcheck (or running, when it
105
+ * declares none), and no service of the project restarting — the ingest
106
+ * worker once crash-looped through a whole deploy unnoticed.
107
+ */
108
+ export async function composeHealthy(ctx, sha) {
109
+ const rt = composeOf(ctx);
110
+ const deadline = ctx.host.now().getTime() + (ctx.config.health?.timeoutSeconds ?? 240) * 1000;
111
+ let last = 'no container';
112
+ do {
113
+ const services = await composeServices(ctx, sha) ?? [];
114
+ const upstream = services.filter((s) => s.service === rt.upstream.service);
115
+ const restarting = [...new Set(services.filter((s) => s.state === 'restarting').map((s) => s.service))];
116
+ if (restarting.length > 0)
117
+ return { ok: false, why: `restarting: ${restarting.join(', ')}` };
118
+ const ready = upstream.length > 0 && upstream.every((s) => s.state === 'running' && (s.health === '' || s.health === 'healthy'));
119
+ if (ready)
120
+ return { ok: true };
121
+ last = upstream.length === 0 ? 'no container' : upstream.map((s) => s.health || s.state).join(', ');
122
+ await ctx.host.sleep(5000);
123
+ } while (ctx.host.now().getTime() < deadline);
124
+ return { ok: false, why: `${rt.upstream.service}: ${last} after ${ctx.config.health?.timeoutSeconds ?? 240}s` };
125
+ }
126
+ /** Removes `<tag>:<sha>` of the configured images for commits outside `keep`. Nothing else. */
127
+ export async function pruneImages(ctx, keep) {
128
+ const rt = composeOf(ctx);
129
+ const keepTags = new Set(keep.map(short));
130
+ const removed = [];
131
+ for (const image of rt.images) {
132
+ const listed = await ctx.host.exec('docker', ['image', 'ls', image.tag, '--format', '{{.Tag}}']);
133
+ if (listed.code !== 0)
134
+ continue;
135
+ for (const tag of listed.stdout.split('\n').map((t) => t.trim()).filter(Boolean)) {
136
+ if (!/^[0-9a-f]{7,40}$/.test(tag) || keepTags.has(tag))
137
+ continue;
138
+ const rm = await ctx.host.exec('docker', ['image', 'rm', `${image.tag}:${tag}`]);
139
+ if (rm.code === 0)
140
+ removed.push(`${image.tag}:${tag}`);
141
+ }
142
+ }
143
+ return removed;
144
+ }
145
+ export async function composeStatus(ctx, sha) {
146
+ const services = await composeServices(ctx, sha);
147
+ if (services === undefined)
148
+ return [`compose project ${ctx.config.app}: docker compose is not available`];
149
+ if (services.length === 0)
150
+ return [`compose project ${ctx.config.app}: no containers`];
151
+ return services.map((s) => `${s.service}: ${s.state}${s.health ? ` (${s.health})` : ''}`);
152
+ }
package/dist/config.d.ts CHANGED
@@ -29,10 +29,27 @@ export interface DeployConfig {
29
29
  * for the pre-migration dump instead (RFC 0006 §8).
30
30
  */
31
31
  destructive?: string[];
32
+ /**
33
+ * Commands only this app needs, run at fixed points (RFC 0006 §13.3): in the
34
+ * checkout, as the deploy user, with the `.env` values plus `DEPLOY_SHA` and
35
+ * `DEPLOY_APP` in their environment. Idempotent — they run on every deploy.
36
+ */
37
+ hooks?: HooksConfig;
38
+ }
39
+ export interface HooksConfig {
40
+ /** After the `.env` and the infra, before the build. Failing stops the deploy (code put back). */
41
+ infra?: string[][];
42
+ /** After the health check. Failing is a failed release (rolled back). */
43
+ verify?: string[][];
32
44
  }
33
45
  export interface EnvConfig {
34
- /** Relative to the app directory. Written 0600, backed up before every change. */
46
+ /**
47
+ * Relative to the app directory, or absolute (e.g. `/etc/mukanda/api.env`).
48
+ * Written 0600, backed up before every change, in its own directory.
49
+ */
35
50
  file?: string;
51
+ /** Exact copies of the file (0600), rewritten with it; one that differs is a C10 error. */
52
+ mirror?: string[];
36
53
  /** The module whose import runs the app's `defineEnv(...)`, e.g. `src/env.ts`. */
37
54
  schema?: string;
38
55
  /** Always these values — a different one in the file is corrected. */
@@ -114,6 +131,17 @@ export interface MigrateConfig {
114
131
  central?: boolean;
115
132
  /** `<pm> basalt tenant:migrate` (or the given package.json script arguments). */
116
133
  tenants?: boolean | string[];
134
+ /**
135
+ * The app's own migration command, run in the checkout instead of
136
+ * `central`/`tenants` (e.g. `['./node_modules/.bin/tsx', 'scripts/db.ts', 'deploy']`).
137
+ */
138
+ command?: string[];
139
+ /**
140
+ * Values that override the `.env` for the migration and the pre-migration
141
+ * dump — e.g. URLs that name a container (`@mukanda-postgres:`) rewritten to
142
+ * reach it from the host (`@127.0.0.1:`).
143
+ */
144
+ env?: (values: ReadonlyMap<string, string>) => Record<string, string>;
117
145
  }
118
146
  export interface BackupConfig {
119
147
  beforeMigrate?: boolean;
@@ -123,7 +151,32 @@ export interface BackupConfig {
123
151
  /** With external infra: the `.env` key holding the database URL. Default `DATABASE_URL`. */
124
152
  urlKey?: string;
125
153
  }
126
- export type RuntimeConfig = Pm2Runtime;
154
+ export type RuntimeConfig = Pm2Runtime | ComposeRuntime;
155
+ /** A Docker Compose project, its images built per commit (RFC 0006 §13.2). */
156
+ export interface ComposeRuntime {
157
+ kind: 'compose';
158
+ /** The compose file, relative to the checkout. */
159
+ file: string;
160
+ /** Built as `<tag>:<sha>`; each tag must start with the app name (C4). */
161
+ images: ComposeImage[];
162
+ /** What the proxy reaches on 127.0.0.1: the service and its published port. */
163
+ upstream: {
164
+ service: string;
165
+ port: number;
166
+ };
167
+ /** Compose interpolation values (never secrets: they are not in a 0600 file). */
168
+ env: Record<string, string>;
169
+ /** Releases whose images are kept for a rollback without a rebuild. */
170
+ keepImages: number;
171
+ }
172
+ export interface ComposeImage {
173
+ tag: string;
174
+ dockerfile: string;
175
+ /** Build context, relative to the checkout. Default `.`. */
176
+ context?: string;
177
+ /** The compose variable that receives `<tag>:<sha>`. */
178
+ env: string;
179
+ }
127
180
  export interface Pm2Runtime {
128
181
  kind: 'pm2';
129
182
  /** Default `<app>-api`. Must start with `<app>-` (RFC 0006 §5, C4). */
@@ -137,6 +190,15 @@ export interface Pm2Runtime {
137
190
  export type ProxyConfig = ApacheProxy | NoProxy;
138
191
  export interface ApacheProxy {
139
192
  kind: 'apache';
193
+ /**
194
+ * `false`: the app writes its own vhosts (more than one site, special
195
+ * rules). They are checked on every deploy — C2 (linked, not copied) and C1
196
+ * (every ProxyPass to 127.0.0.1 targets the upstream port) — and never
197
+ * rendered, diffed or written; `install` leaves Apache alone (§13.4).
198
+ */
199
+ managed?: boolean;
200
+ /** With `managed: false`: the vhost file names to check. */
201
+ vhosts?: string[];
140
202
  /** File name under `sites-available/`. Default `<app>.conf`. */
141
203
  vhost?: string;
142
204
  /** Directory served as the site's root, relative to the app directory. */
@@ -181,7 +243,19 @@ export declare const apache: (options?: {
181
243
  apiPrefix?: string;
182
244
  certName?: string;
183
245
  root?: string;
246
+ managed?: boolean;
247
+ vhosts?: string[];
184
248
  }) => ApacheProxy;
249
+ export declare const compose: (options: {
250
+ file: string;
251
+ images: ComposeImage[];
252
+ upstream: {
253
+ service: string;
254
+ port: number;
255
+ };
256
+ env?: Record<string, string>;
257
+ keepImages?: number;
258
+ }) => ComposeRuntime;
185
259
  export declare const none: () => NoProxy;
186
260
  export declare const external: () => ExternalInfra;
187
261
  export declare const MINIO_IMAGE = "minio/minio:RELEASE.2025-03-12T18-04-18Z";
@@ -202,6 +276,7 @@ export declare class DeployConfigError extends Error {
202
276
  readonly problems: string[];
203
277
  constructor(problems: string[]);
204
278
  }
279
+ /** The PM2 process name (`<app>-api` by default). Compose names its own containers. */
205
280
  export declare const processName: (config: DeployConfig) => string;
206
281
  export declare const vhostName: (config: DeployConfig) => string | undefined;
207
282
  export declare function validateConfig(config: DeployConfig): DeployConfig;
package/dist/config.js CHANGED
@@ -28,12 +28,22 @@ export const pm2 = (options = {}) => ({
28
28
  });
29
29
  export const apache = (options = {}) => ({
30
30
  kind: 'apache',
31
+ ...(options.managed === undefined ? {} : { managed: options.managed }),
32
+ ...(options.vhosts === undefined ? {} : { vhosts: options.vhosts }),
31
33
  ...(options.vhost === undefined ? {} : { vhost: options.vhost }),
32
34
  webRoot: options.webRoot ?? 'web/dist',
33
35
  apiPrefix: options.apiPrefix ?? '/api',
34
36
  ...(options.certName === undefined ? {} : { certName: options.certName }),
35
37
  ...(options.root === undefined ? {} : { root: options.root }),
36
38
  });
39
+ export const compose = (options) => ({
40
+ kind: 'compose',
41
+ file: options.file,
42
+ images: options.images,
43
+ upstream: options.upstream,
44
+ env: options.env ?? {},
45
+ keepImages: options.keepImages ?? 3,
46
+ });
37
47
  export const none = () => ({ kind: 'none' });
38
48
  export const external = () => ({ kind: 'external' });
39
49
  export const MINIO_IMAGE = 'minio/minio:RELEASE.2025-03-12T18-04-18Z';
@@ -74,7 +84,8 @@ export class DeployConfigError extends Error {
74
84
  this.name = 'DeployConfigError';
75
85
  }
76
86
  }
77
- export const processName = (config) => config.runtime.name ?? `${config.app}-api`;
87
+ /** The PM2 process name (`<app>-api` by default). Compose names its own containers. */
88
+ export const processName = (config) => config.runtime.kind === 'pm2' ? (config.runtime.name ?? `${config.app}-api`) : config.app;
78
89
  export const vhostName = (config) => config.proxy?.kind === 'apache' ? (config.proxy.vhost ?? `${config.app}.conf`) : undefined;
79
90
  export function validateConfig(config) {
80
91
  const problems = [];
@@ -84,11 +95,52 @@ export function validateConfig(config) {
84
95
  problems.push(`domain "${config.domain}" is not a lowercase host name`);
85
96
  // C4: the deploy only ever names what carries the app's label. `pm2 restart
86
97
  // all` once was one keystroke away from a production app that is not ours.
87
- const name = processName(config);
88
- if (!name.startsWith(`${config.app}-`))
89
- problems.push(`runtime.name "${name}" must start with "${config.app}-" — the deploy only touches what the app owns`);
90
- if (!/^[a-z0-9-]+$/.test(name))
91
- problems.push(`runtime.name "${name}" may only use a-z, 0-9 and -`);
98
+ if (config.runtime.kind === 'pm2') {
99
+ const name = processName(config);
100
+ if (!name.startsWith(`${config.app}-`))
101
+ problems.push(`runtime.name "${name}" must start with "${config.app}-" — the deploy only touches what the app owns`);
102
+ if (!/^[a-z0-9-]+$/.test(name))
103
+ problems.push(`runtime.name "${name}" may only use a-z, 0-9 and -`);
104
+ }
105
+ else {
106
+ const rt = config.runtime;
107
+ if (rt.images.length === 0)
108
+ problems.push('runtime.images: at least one image');
109
+ for (const image of rt.images) {
110
+ // C4: an image tag outside the app's name could prune another app's images.
111
+ if (image.tag !== config.app && !image.tag.startsWith(`${config.app}-`))
112
+ problems.push(`runtime image "${image.tag}" must be "${config.app}" or start with "${config.app}-" — the deploy only touches what the app owns`);
113
+ if (!/^[a-z0-9][a-z0-9._-]*$/.test(image.tag))
114
+ problems.push(`runtime image "${image.tag}" is not a plain image name (no registry, no tag)`);
115
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(image.env))
116
+ problems.push(`runtime image env "${image.env}" is not a variable name`);
117
+ }
118
+ if (new Set(rt.images.map((i) => i.tag)).size !== rt.images.length)
119
+ problems.push('runtime.images: each tag once');
120
+ if (!/^[a-z0-9][a-z0-9_-]*$/.test(rt.upstream.service))
121
+ problems.push(`runtime.upstream.service "${rt.upstream.service}" is not a compose service name`);
122
+ if (!Number.isInteger(rt.upstream.port) || rt.upstream.port < 1 || rt.upstream.port > 65535)
123
+ problems.push('runtime.upstream.port must be a port number');
124
+ if (!Number.isInteger(rt.keepImages) || rt.keepImages < 1)
125
+ problems.push('runtime.keepImages must be a whole number ≥ 1');
126
+ for (const key of Object.keys(rt.env))
127
+ if (!/^[A-Z_][A-Z0-9_]*$/.test(key))
128
+ problems.push(`runtime.env key "${key}" is not a variable name`);
129
+ }
130
+ if (config.proxy?.kind === 'apache' && config.proxy.managed === false) {
131
+ const vhosts = config.proxy.vhosts ?? [];
132
+ if (vhosts.length === 0)
133
+ problems.push('proxy.vhosts: name the vhost files to check when managed is false');
134
+ for (const v of vhosts)
135
+ if (!/^[a-z0-9.-]+\.conf$/.test(v))
136
+ problems.push(`proxy.vhosts "${v}" must be a plain *.conf file name`);
137
+ }
138
+ for (const hook of [...(config.hooks?.infra ?? []), ...(config.hooks?.verify ?? [])]) {
139
+ if (!Array.isArray(hook) || hook.length === 0 || hook.some((part) => typeof part !== 'string'))
140
+ problems.push('hooks: each hook is a non-empty array of strings (a command and its arguments)');
141
+ }
142
+ if (config.migrate?.command && config.migrate.command.length === 0)
143
+ problems.push('migrate.command must not be empty');
92
144
  const vhost = vhostName(config);
93
145
  if (vhost !== undefined && !/^[a-z0-9.-]+\.conf$/.test(vhost))
94
146
  problems.push(`proxy.vhost "${vhost}" must be a plain *.conf file name`);
@@ -124,8 +176,11 @@ export function applyOverrides(config, overrides) {
124
176
  next.domain = overrides.domain;
125
177
  if (overrides.branch !== undefined)
126
178
  next.branch = overrides.branch;
127
- if (overrides.port !== undefined)
128
- next.runtime = { ...config.runtime, port: overrides.port };
179
+ if (overrides.port !== undefined) {
180
+ next.runtime = config.runtime.kind === 'pm2'
181
+ ? { ...config.runtime, port: overrides.port }
182
+ : { ...config.runtime, upstream: { ...config.runtime.upstream, port: overrides.port } };
183
+ }
129
184
  if (overrides.infra && config.infra?.kind === 'docker') {
130
185
  const infra = { ...config.infra };
131
186
  const o = overrides.infra;
@@ -14,7 +14,10 @@ export interface EnvPlan {
14
14
  questions: string[];
15
15
  findings: Finding[];
16
16
  }
17
+ /** The `.env`: relative to the checkout, or absolute (`/etc/<app>/api.env`). */
17
18
  export declare const envFile: (ctx: DeployContext) => string;
19
+ /** Its exact copies (`env.mirror`), resolved the same way. */
20
+ export declare const envMirrors: (ctx: DeployContext) => string[];
18
21
  export declare function readEnv(ctx: DeployContext): Promise<EnvDocument>;
19
22
  export declare function syntaxFindings(document: EnvDocument, file: string): Finding[];
20
23
  export declare function planEnv(ctx: DeployContext, document: EnvDocument, port: number, infra: EnvChange[]): EnvPlan;
@@ -27,3 +30,7 @@ export declare function answerQuestions(ctx: DeployContext, plan: EnvPlan): Prom
27
30
  export declare function describeEnv(plan: EnvPlan): string[];
28
31
  /** Backs the file up (0600, last 5 kept) and writes it atomically, 0600. */
29
32
  export declare function writeEnv(ctx: DeployContext, plan: EnvPlan): Promise<void>;
33
+ /** Rewrites every mirror as an exact copy of the file (0600). */
34
+ export declare function writeMirrors(ctx: DeployContext, text: string): Promise<void>;
35
+ /** C10 — a mirror that is not an exact copy: two env files that disagree are two configurations. */
36
+ export declare function mirrorFindings(ctx: DeployContext): Promise<Finding[]>;
package/dist/env-step.js CHANGED
@@ -1,6 +1,9 @@
1
- import { join } from 'node:path';
1
+ import { basename, dirname, join, resolve } from 'node:path';
2
2
  import { applyEnvChanges, envValues, formatValue, parseEnv, UnwritableValueError } from './dotenv.js';
3
- export const envFile = (ctx) => join(ctx.dir, ctx.config.env.file ?? '.env');
3
+ /** The `.env`: relative to the checkout, or absolute (`/etc/<app>/api.env`). */
4
+ export const envFile = (ctx) => resolve(ctx.dir, ctx.config.env.file ?? '.env');
5
+ /** Its exact copies (`env.mirror`), resolved the same way. */
6
+ export const envMirrors = (ctx) => (ctx.config.env.mirror ?? []).map((m) => resolve(ctx.dir, m));
4
7
  export async function readEnv(ctx) {
5
8
  return parseEnv((await ctx.host.readFile(envFile(ctx))) ?? '');
6
9
  }
@@ -26,7 +29,10 @@ export function planEnv(ctx, document, port, infra) {
26
29
  changes.push({ kind: 'set', key, value, reason });
27
30
  pending.set(key, value);
28
31
  };
29
- set('PORT', String(port), 'the port the process listens on');
32
+ // PM2 runs the app on the host: PORT is where it listens. Under compose the
33
+ // port inside the container is the compose file's business, not the .env's.
34
+ if (config.runtime.kind === 'pm2')
35
+ set('PORT', String(port), 'the port the process listens on');
30
36
  for (const [key, value] of Object.entries(config.env.fixed ?? {}))
31
37
  set(key, value, 'fixed in deploy.config.ts');
32
38
  for (const [key, spec] of Object.entries(config.env.generate ?? {})) {
@@ -113,14 +119,43 @@ export async function writeEnv(ctx, plan) {
113
119
  if (await host.exists(file)) {
114
120
  const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
115
121
  await host.copyFile(file, `${file}.bak-${stamp}`, 0o600);
116
- const base = file.slice(file.lastIndexOf('/') + 1);
117
- const dir = file.slice(0, file.lastIndexOf('/'));
122
+ const base = basename(file);
123
+ const dir = dirname(file);
118
124
  const backups = (await host.list(dir)).filter((name) => name.startsWith(`${base}.bak-`)).sort();
119
125
  for (const old of backups.slice(0, -5))
120
126
  await host.remove(join(dir, old));
121
127
  }
122
128
  await host.writeFile(file, text, 0o600);
129
+ await writeMirrors(ctx, text);
123
130
  plan.document = parseEnv(text);
124
131
  plan.values = envValues(plan.document);
125
132
  plan.changes = [];
126
133
  }
134
+ /** Rewrites every mirror as an exact copy of the file (0600). */
135
+ export async function writeMirrors(ctx, text) {
136
+ for (const mirror of envMirrors(ctx)) {
137
+ if ((await ctx.host.readFile(mirror)) === text)
138
+ continue;
139
+ await ctx.host.writeFile(mirror, text, 0o600);
140
+ }
141
+ }
142
+ /** C10 — a mirror that is not an exact copy: two env files that disagree are two configurations. */
143
+ export async function mirrorFindings(ctx) {
144
+ const mirrors = envMirrors(ctx);
145
+ if (mirrors.length === 0)
146
+ return [];
147
+ const text = await ctx.host.readFile(envFile(ctx));
148
+ const findings = [];
149
+ for (const mirror of mirrors) {
150
+ const copy = await ctx.host.readFile(mirror);
151
+ if (text === undefined || copy === text)
152
+ continue;
153
+ findings.push({
154
+ id: 'C10',
155
+ level: 'error',
156
+ message: copy === undefined ? `${mirror} (env.mirror) does not exist` : `${mirror} (env.mirror) differs from ${envFile(ctx)}`,
157
+ fix: `cp -p ${envFile(ctx)} ${mirror} — after checking which one is right; the deploy rewrites the mirror from the file`,
158
+ });
159
+ }
160
+ return findings;
161
+ }
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- export { defineDeploy, secret, ask, pm2, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, type DeployConfig, type EnvConfig, type DeriveContext, type SecretSpec, type Question, type InfraConfig, type DockerInfra, type DockerInfraOptions, type ExternalInfra, type PostgresService, type RedisService, type MinioService, type BuildConfig, type MigrateConfig, type BackupConfig, type RuntimeConfig, type Pm2Runtime, type ProxyConfig, type ApacheProxy, type NoProxy, type HealthConfig, type ServerOverrides, } from './config.js';
1
+ export { defineDeploy, secret, ask, pm2, compose, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, type DeployConfig, type EnvConfig, type DeriveContext, type SecretSpec, type Question, type InfraConfig, type DockerInfra, type DockerInfraOptions, type ExternalInfra, type PostgresService, type RedisService, type MinioService, type BuildConfig, type MigrateConfig, type BackupConfig, type RuntimeConfig, type Pm2Runtime, type ComposeRuntime, type ComposeImage, type HooksConfig, type ProxyConfig, type ApacheProxy, type NoProxy, type HealthConfig, type ServerOverrides, } from './config.js';
2
2
  export { main, loadConfig, createContext, USAGE } from './cli.js';
3
3
  export { nodeHost, consoleOutput, type Host, type ExecOptions, type ExecResult, type Output, type TlsCertificate } from './host.js';
4
- export { DeployError, type DeployContext, type Finding } from './context.js';
4
+ export { DeployError, INSTALL_COMMAND, RUN_COMMAND, type DeployContext, type Finding } from './context.js';
5
5
  export { parseEnv, applyEnvChanges, formatValue, envValues, UnwritableValueError, type EnvDocument, type EnvChange } from './dotenv.js';
6
6
  export { renderVhost, proxiedPorts } from './apache.js';
7
7
  export { renderCompose } from './infra.js';
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- export { defineDeploy, secret, ask, pm2, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, } from './config.js';
1
+ export { defineDeploy, secret, ask, pm2, compose, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, } from './config.js';
2
2
  export { main, loadConfig, createContext, USAGE } from './cli.js';
3
3
  export { nodeHost, consoleOutput } from './host.js';
4
- export { DeployError } from './context.js';
4
+ export { DeployError, INSTALL_COMMAND, RUN_COMMAND } from './context.js';
5
5
  export { parseEnv, applyEnvChanges, formatValue, envValues, UnwritableValueError } from './dotenv.js';
6
6
  export { renderVhost, proxiedPorts } from './apache.js';
7
7
  export { renderCompose } from './infra.js';
@@ -20,6 +20,8 @@ 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
25
  /**
24
26
  * Whether the pre-migration dump runs, and why not when it does not. Unsaid,
25
27
  * it runs when there is something to migrate AND a Postgres to dump: the
@@ -39,11 +41,4 @@ export declare function run(ctx: DeployContext, options?: RunOptions): Promise<n
39
41
  /** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
40
42
  export declare function rollback(ctx: DeployContext, to?: string): Promise<number>;
41
43
  export declare function status(ctx: DeployContext): Promise<number>;
42
- /**
43
- * `sudo basalt-deploy install` — once per server, by an administrator (RFC
44
- * 0006 §11.4). Everything that needs root and nothing else: the vhost, the
45
- * state directory owned by the app user. The app user is never added to the
46
- * `docker` group (root-equivalent); with dedicated infra it needs rootless
47
- * Docker, and this says so.
48
- */
49
44
  export declare function install(ctx: DeployContext, user: string | undefined): Promise<number>;
package/dist/pipeline.js CHANGED
@@ -1,11 +1,12 @@
1
- import { join } from 'node:path';
1
+ import { basename, dirname, join } from 'node:path';
2
2
  import { apacheInstall, apachePreflight, vhostPaths } from './apache.js';
3
3
  import { backupDatabase, restoreCommand } from './backup.js';
4
4
  import { lockfileFindings, tlsFindings, toolingFindings } from './checks.js';
5
+ import { composeBuild, composeEnv, composeHealthy, composeOf, composePreflight, composeRelease, composeStatus, pruneImages } from './compose.js';
5
6
  import { processName } from './config.js';
6
7
  import { DeployError, errors, INSTALL_COMMAND, report, RUN_COMMAND } from './context.js';
7
8
  import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
8
- import { answerQuestions, describeEnv, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
9
+ import { answerQuestions, describeEnv, envFile, envMirrors, mirrorFindings, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
9
10
  import { envValues } from './dotenv.js';
10
11
  import { applyInfra, describeInfra, planInfra } from './infra.js';
11
12
  import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
@@ -26,6 +27,42 @@ async function step(ctx, title, run) {
26
27
  ctx.host.out.step(title);
27
28
  return run();
28
29
  }
30
+ // ── the runtime: PM2 on the host, or a compose project ────────────────────
31
+ const isCompose = (ctx) => ctx.config.runtime.kind === 'compose';
32
+ async function runtimePreflight(ctx, port, sha) {
33
+ return isCompose(ctx) ? composePreflight(ctx, sha) : pm2Preflight(ctx, port);
34
+ }
35
+ async function release(ctx, values, sha) {
36
+ return isCompose(ctx) ? composeRelease(ctx, sha) : pm2Release(ctx, values);
37
+ }
38
+ function describeRelease(ctx, port) {
39
+ if (!isCompose(ctx))
40
+ return `pm2 ${processName(ctx.config)} on 127.0.0.1:${port}`;
41
+ const rt = composeOf(ctx);
42
+ return `docker compose -p ${ctx.config.app} up -d (${rt.images.map((i) => `${i.tag}:<sha>`).join(', ')}); ${rt.upstream.service} on 127.0.0.1:${port}`;
43
+ }
44
+ const logsHint = (ctx) => isCompose(ctx)
45
+ ? `docker compose -p ${ctx.config.app} logs ${composeOf(ctx).upstream.service} --tail=50`
46
+ : `pm2 logs ${processName(ctx.config)}`;
47
+ // ── hooks (RFC 0006 §13.3) ─────────────────────────────────────────────────
48
+ async function runHooks(ctx, which, values, sha) {
49
+ const hooks = ctx.config.hooks?.[which] ?? [];
50
+ if (hooks.length === 0)
51
+ return;
52
+ const env = {
53
+ ...Object.fromEntries(values),
54
+ ...(isCompose(ctx) ? composeEnv(ctx, sha) : {}),
55
+ DEPLOY_SHA: sha,
56
+ DEPLOY_APP: ctx.config.app,
57
+ };
58
+ for (const [command, ...args] of hooks) {
59
+ ctx.host.out.info(`${which} hook: ${[command, ...args].join(' ')}`);
60
+ const result = await ctx.host.exec(command, args, { cwd: ctx.dir, env, stream: true });
61
+ if (result.code !== 0)
62
+ throw new DeployError(`${which} hook \`${[command, ...args].join(' ')}\` failed (exit ${result.code})`);
63
+ }
64
+ ctx.host.out.ok(`${hooks.length} ${which} hook(s) passed`);
65
+ }
29
66
  export async function preflight(ctx, options = {}) {
30
67
  // First, before any command runs: the tree as the operator left it. A
31
68
  // later probe that writes to the checkout would otherwise be blamed on them.
@@ -36,7 +73,9 @@ export async function preflight(ctx, options = {}) {
36
73
  const port = await resolvePort(ctx, values);
37
74
  findings.push(...await toolingFindings(ctx));
38
75
  findings.push(...await lockfileFindings(ctx));
39
- findings.push(...await pm2Preflight(ctx, port));
76
+ const head = (await ctx.host.exec('git', ['rev-parse', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
77
+ findings.push(...await runtimePreflight(ctx, port, head));
78
+ findings.push(...await mirrorFindings(ctx));
40
79
  if (ctx.config.proxy?.kind === 'apache')
41
80
  findings.push(...await apachePreflight(ctx, port));
42
81
  if (!options.skip?.includes('tls'))
@@ -97,9 +136,17 @@ function stopOnErrors(ctx, findings, what) {
97
136
  // ── what runs by default ───────────────────────────────────────────────────
98
137
  /** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
99
138
  export function migratesCentral(config) {
139
+ // An app migrating by its own command does not also get `prisma migrate deploy` unasked.
140
+ if (config.migrate?.command)
141
+ return config.migrate.central === true;
100
142
  return config.migrate?.central ?? (config.build?.prisma?.length ?? 0) > 0;
101
143
  }
102
- const migratesAnything = (config) => migratesCentral(config) || Boolean(config.migrate?.tenants);
144
+ const migratesAnything = (config) => Boolean(config.migrate?.command) || migratesCentral(config) || Boolean(config.migrate?.tenants);
145
+ /** The `.env` as the migration and the dump see it: `migrate.env` on top (host URLs for container names). */
146
+ export function migrationValues(config, values) {
147
+ const extra = config.migrate?.env?.(values) ?? {};
148
+ return new Map([...values, ...Object.entries(extra)]);
149
+ }
103
150
  /**
104
151
  * Whether the pre-migration dump runs, and why not when it does not. Unsaid,
105
152
  * it runs when there is something to migrate AND a Postgres to dump: the
@@ -118,7 +165,7 @@ export function backupDecision(config, values, skip = []) {
118
165
  return { run: false, why: 'nothing to migrate' };
119
166
  if (config.infra?.kind === 'docker' && config.infra.postgres)
120
167
  return { run: true };
121
- const url = values.get(config.backup?.urlKey ?? 'DATABASE_URL') ?? '';
168
+ const url = migrationValues(config, values).get(config.backup?.urlKey ?? 'DATABASE_URL') ?? '';
122
169
  return /^postgres(ql)?:\/\//.test(url) ? { run: true } : { run: false, why: 'no Postgres database in the .env' };
123
170
  }
124
171
  // ── the building blocks ────────────────────────────────────────────────────
@@ -128,7 +175,7 @@ async function prepareEnv(ctx, port) {
128
175
  const env = planEnv(ctx, document, port, infra.env);
129
176
  return { env, infra };
130
177
  }
131
- async function build(ctx, values) {
178
+ async function build(ctx, values, sha) {
132
179
  const { host, pm } = ctx;
133
180
  const run = async (args, options = {}) => {
134
181
  host.out.info(`${pm} ${args.join(' ')}`);
@@ -148,6 +195,8 @@ async function build(ctx, values) {
148
195
  await run(['exec', 'prisma', 'generate', '--config', config], { env: values });
149
196
  if (ctx.config.build?.web)
150
197
  await run(['--dir', ctx.config.build.web, 'run', 'build'], { env: values });
198
+ if (isCompose(ctx))
199
+ await composeBuild(ctx, sha);
151
200
  }
152
201
  /**
153
202
  * The deploy leaves the checkout as committed. pnpm ≥ 12 may rewrite the
@@ -177,9 +226,17 @@ async function validate(ctx, values) {
177
226
  const schema = await checkSchema(ctx, values);
178
227
  return [...schema.findings, ...coercionFindings(values, schema.trueKeys), ...policyFindings(ctx, values)];
179
228
  }
180
- async function migrate(ctx, values) {
229
+ async function migrate(ctx, raw) {
181
230
  const { host, pm } = ctx;
231
+ const values = migrationValues(ctx.config, raw);
182
232
  const env = { cwd: ctx.dir, stream: true, env: Object.fromEntries(values) };
233
+ const command = ctx.config.migrate?.command;
234
+ if (command) {
235
+ host.out.info(command.join(' '));
236
+ const result = await host.exec(command[0], command.slice(1), env);
237
+ if (result.code !== 0)
238
+ throw new DeployError(`${command.join(' ')} failed (exit ${result.code})`);
239
+ }
183
240
  if (migratesCentral(ctx.config)) {
184
241
  host.out.info(`${pm} exec prisma migrate deploy`);
185
242
  const central = await host.exec(pm, ['exec', 'prisma', 'migrate', 'deploy'], env);
@@ -195,7 +252,19 @@ async function migrate(ctx, values) {
195
252
  throw new DeployError('the tenant migrations failed');
196
253
  }
197
254
  if (!migratesAnything(ctx.config))
198
- host.out.info('nothing to migrate (no build.prisma, no migrate.tenants)');
255
+ host.out.info('nothing to migrate (no build.prisma, no migrate.tenants, no migrate.command)');
256
+ }
257
+ /** Compose: the upstream service healthy and nothing restarting; then, any runtime, the loopback URL. */
258
+ async function healthCheck(ctx, port, sha) {
259
+ if (isCompose(ctx)) {
260
+ const services = await composeHealthy(ctx, sha);
261
+ if (!services.ok)
262
+ return services;
263
+ ctx.host.out.ok(`${composeOf(ctx).upstream.service} healthy; no service restarting`);
264
+ }
265
+ if (await healthy(ctx, port))
266
+ return { ok: true };
267
+ return { ok: false, why: `the app does not answer on http://127.0.0.1:${port}${ctx.config.health?.path ?? '/health'}` };
199
268
  }
200
269
  async function healthy(ctx, port) {
201
270
  const { host, config } = ctx;
@@ -228,7 +297,7 @@ async function publicHealthy(ctx) {
228
297
  async function restoreCode(ctx, sha, values) {
229
298
  ctx.host.out.step(`restoring the code to ${sha.slice(0, 7)}`);
230
299
  await git(ctx, ['reset', '--hard', sha]);
231
- await build(ctx, values);
300
+ await build(ctx, values, sha);
232
301
  await settleLockfile(ctx);
233
302
  }
234
303
  /** The env step's summary: what changed, or that nothing did. */
@@ -263,15 +332,18 @@ export async function plan(ctx, options = {}) {
263
332
  options.skip?.includes('fetch') ? 'fetch: skipped' : `fetch: git fetch ${config.remote ?? 'origin'} ${config.branch ?? 'main'} && git merge --ff-only`,
264
333
  ...describeEnv(env).map((l) => `env: ${l}`),
265
334
  ...describeInfra(infra).map((l) => `infra: ${l}`),
266
- `build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.web ? `, ${config.build.web} build` : ''}`,
335
+ `build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.web ? `, ${config.build.web} build` : ''}${isCompose(ctx) ? `, docker build ${composeOf(ctx).images.map((i) => i.tag).join(', ')} (skipped when the commit's tag exists)` : ''}`,
336
+ ...(config.hooks?.infra ?? []).map((h) => `infra hook: ${h.join(' ')}`),
267
337
  `validate: ${config.env.schema ?? '(no schema configured)'} against the new .env`,
268
338
  ((decision) => decision.run
269
339
  ? `backup: pg_dump → ${config.backup?.dir ?? 'backups/predeploy'} (keep ${config.backup?.keep ?? 10})`
270
340
  : `backup: skipped (${decision.why})`)(backupDecision(config, checked.values, options.skip ?? [])),
271
- `migrate: ${[migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
272
- `release: pm2 ${processName(config)} on 127.0.0.1:${checked.port}`,
341
+ `migrate: ${[config.migrate?.command?.join(' ') ?? '', migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
342
+ `release: ${describeRelease(ctx, checked.port)}`,
273
343
  `health: http://127.0.0.1:${checked.port}${config.health?.path ?? '/health'} (Host: ${config.domain})${config.proxy?.kind === 'apache' && config.health?.public !== false ? `, then https://${config.domain}${config.proxy.apiPrefix}${config.health?.path ?? '/health'}` : ''}`,
274
344
  ];
345
+ for (const hook of config.hooks?.verify ?? [])
346
+ lines.push(`verify hook: ${hook.join(' ')}`);
275
347
  for (const line of lines)
276
348
  host.out.info(line);
277
349
  return errors([...checked.findings, ...infra.findings]).length > 0 ? 1 : 0;
@@ -290,7 +362,7 @@ export async function envCommand(ctx) {
290
362
  await writeEnv(ctx, env);
291
363
  await step(ctx, 'infra', () => infraStep(ctx, infra));
292
364
  await step(ctx, 'validate', () => validateStep(ctx, env.values));
293
- ctx.host.out.ok(`.env ready (PORT=${port})`);
365
+ ctx.host.out.ok(isCompose(ctx) ? `${envFile(ctx)} ready` : `.env ready (PORT=${port})`);
294
366
  return 0;
295
367
  }
296
368
  export async function run(ctx, options = {}) {
@@ -309,7 +381,7 @@ export async function run(ctx, options = {}) {
309
381
  const sha = await git(ctx, ['rev-parse', 'HEAD']);
310
382
  host.out.info(sha === previous ? `already at ${sha.slice(0, 7)}` : `${previous.slice(0, 7)} → ${sha.slice(0, 7)}`);
311
383
  const applied = sha === previous ? [] : migrationNames((await git(ctx, ['diff', '--name-only', previous, sha])).split('\n'));
312
- const release = { sha, previous, at: host.now().toISOString(), user: host.env['USER'] ?? String(host.uid()), status: 'failed', migrations: applied };
384
+ const record = { sha, previous, at: host.now().toISOString(), user: host.env['USER'] ?? String(host.uid()), status: 'failed', migrations: applied };
313
385
  // From here a failure puts the code on disk back before it is reported.
314
386
  const lockfileSaid = { warned: false };
315
387
  let values = checked.values;
@@ -327,13 +399,13 @@ export async function run(ctx, options = {}) {
327
399
  reportEnv(ctx, prepared.env);
328
400
  await writeEnv(ctx, prepared.env);
329
401
  values = prepared.env.values;
330
- await step(ctx, 'infra', () => infraStep(ctx, infra));
331
- await step(ctx, 'build', async () => { await build(ctx, values); await settleLockfile(ctx, lockfileSaid); });
402
+ await step(ctx, 'infra', async () => { await infraStep(ctx, infra); await runHooks(ctx, 'infra', values, sha); });
403
+ await step(ctx, 'build', async () => { await build(ctx, values, sha); await settleLockfile(ctx, lockfileSaid); });
332
404
  await step(ctx, 'validate', () => validateStep(ctx, values));
333
405
  const backup = backupDecision(config, values, skip);
334
406
  if (backup.run) {
335
- release.backup = await step(ctx, 'backup', () => backupDatabase(ctx, values, infra, sha));
336
- host.out.ok(release.backup);
407
+ record.backup = await step(ctx, 'backup', () => backupDatabase(ctx, migrationValues(config, values), infra, sha));
408
+ host.out.ok(record.backup);
337
409
  }
338
410
  else {
339
411
  host.out.step('backup');
@@ -344,8 +416,8 @@ export async function run(ctx, options = {}) {
344
416
  catch (error) {
345
417
  if (sha !== previous)
346
418
  await restoreCode(ctx, previous, values).catch((e) => host.out.error(`could not restore the code: ${e.message}`));
347
- release.note = error.message;
348
- await recordRelease(ctx, release).catch(() => undefined);
419
+ record.note = error.message;
420
+ await recordRelease(ctx, record).catch(() => undefined);
349
421
  throw error;
350
422
  }
351
423
  const destructive = applied.filter((name) => config.destructive?.includes(name));
@@ -354,33 +426,43 @@ export async function run(ctx, options = {}) {
354
426
  if (destructive.length > 0 || sha === previous) {
355
427
  if (destructive.length > 0)
356
428
  host.out.error(`not rolled back automatically: ${destructive.join(', ')} ${destructive.length === 1 ? 'is' : 'are'} marked destructive`);
357
- if (release.backup)
358
- host.out.info(`database before this release: ${restoreCommand(ctx, infra, release.backup)}`);
359
- release.note = why;
360
- await recordRelease(ctx, release);
429
+ if (record.backup)
430
+ host.out.info(`database before this release: ${restoreCommand(ctx, infra, record.backup)}`);
431
+ record.note = why;
432
+ await recordRelease(ctx, record);
361
433
  return 1;
362
434
  }
363
435
  await rollbackTo(ctx, previous, values, port);
364
- release.status = 'rolled-back';
365
- release.note = why;
366
- await recordRelease(ctx, release);
436
+ record.status = 'rolled-back';
437
+ record.note = why;
438
+ await recordRelease(ctx, record);
367
439
  return 1;
368
440
  };
369
441
  try {
370
- host.out.ok(await step(ctx, 'release', () => pm2Release(ctx, values)));
442
+ host.out.ok(await step(ctx, 'release', () => release(ctx, values, sha)));
371
443
  }
372
444
  catch (error) {
373
445
  return recover(error.message);
374
446
  }
375
- const ok = await step(ctx, 'health', () => healthy(ctx, port));
376
- if (!ok)
377
- return recover(`the app does not answer on http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
447
+ const health = await step(ctx, 'health', () => healthCheck(ctx, port, sha));
448
+ if (!health.ok)
449
+ return recover(health.why);
378
450
  host.out.ok(`http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
451
+ if (config.hooks?.verify?.length) {
452
+ try {
453
+ await step(ctx, 'verify', () => runHooks(ctx, 'verify', values, sha));
454
+ }
455
+ catch (error) {
456
+ return recover(error.message);
457
+ }
458
+ }
379
459
  const publicProblem = await publicHealthy(ctx);
380
- release.status = publicProblem ? 'public-unreachable' : 'ok';
460
+ record.status = publicProblem ? 'public-unreachable' : 'ok';
381
461
  // `pnpm run start`, launched by PM2 in the checkout, may rewrite it too.
382
462
  await settleLockfile(ctx, lockfileSaid);
383
- await step(ctx, 'record', () => recordRelease(ctx, release));
463
+ await step(ctx, 'record', () => recordRelease(ctx, record));
464
+ if (isCompose(ctx) && !publicProblem)
465
+ await retainImages(ctx);
384
466
  if (publicProblem) {
385
467
  report(host, [publicProblem]);
386
468
  return 1;
@@ -388,14 +470,26 @@ export async function run(ctx, options = {}) {
388
470
  host.out.ok(`${config.app} ${sha.slice(0, 7)} is live at https://${config.domain}`);
389
471
  return 0;
390
472
  }
473
+ /** Compose: keep the images of the last `keepImages` healthy releases; remove older ones of these tags only. */
474
+ async function retainImages(ctx) {
475
+ const keep = composeOf(ctx).keepImages;
476
+ const releases = await readReleases(ctx);
477
+ const shas = [...new Set([...releases].reverse().filter((r) => r.status === 'ok').map((r) => r.sha))].slice(0, keep);
478
+ const removed = await pruneImages(ctx, shas);
479
+ if (removed.length > 0)
480
+ ctx.host.out.info(`removed ${removed.length} image(s) of releases older than the last ${keep}: ${removed.join(', ')}`);
481
+ }
391
482
  async function rollbackTo(ctx, sha, values, port) {
483
+ // Compose: the images of `sha` exist (kept by retention), so the rebuild
484
+ // inside restoreCode skips them — a rollback is not a new build.
392
485
  await restoreCode(ctx, sha, values);
393
486
  ctx.host.out.step(`release ${sha.slice(0, 7)}`);
394
- ctx.host.out.ok(await pm2Release(ctx, values));
395
- if (await healthy(ctx, port))
487
+ ctx.host.out.ok(await release(ctx, values, sha));
488
+ const health = await healthCheck(ctx, port, sha);
489
+ if (health.ok)
396
490
  ctx.host.out.ok(`back on ${sha.slice(0, 7)}`);
397
491
  else
398
- ctx.host.out.error(`${sha.slice(0, 7)} does not answer either — pm2 logs ${processName(ctx.config)}`);
492
+ ctx.host.out.error(`${sha.slice(0, 7)} does not answer either (${health.why}) — ${logsHint(ctx)}`);
399
493
  }
400
494
  /** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
401
495
  export async function rollback(ctx, to) {
@@ -426,6 +520,12 @@ export async function status(ctx) {
426
520
  host.out.step(`${ctx.config.app} — last ${releases.length} release(s)`);
427
521
  for (const r of releases)
428
522
  host.out.info(`${r.at} ${r.sha.slice(0, 7)} ${r.status.padEnd(18)} ${r.user}${r.migrations.length ? ` +${r.migrations.length} migration(s)` : ''}${r.note ? ` — ${r.note}` : ''}`);
523
+ if (isCompose(ctx)) {
524
+ const head = (await ctx.host.exec('git', ['rev-parse', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
525
+ for (const line of await composeStatus(ctx, head))
526
+ host.out.info(line);
527
+ return 0;
528
+ }
429
529
  const process = (await pm2List(ctx))?.find((p) => p.name === processName(ctx.config));
430
530
  host.out.info(process ? `pm2 ${process.name}: ${process.status} (pid ${process.pid}, ${process.cwd})` : `pm2 ${processName(ctx.config)}: not running`);
431
531
  return 0;
@@ -437,13 +537,50 @@ export async function status(ctx) {
437
537
  * `docker` group (root-equivalent); with dedicated infra it needs rootless
438
538
  * Docker, and this says so.
439
539
  */
540
+ /**
541
+ * An env file outside the checkout (`/etc/<app>/api.env`) was root's while
542
+ * deploys ran under sudo. Deploys run as the app user (§11.4, §13.5), so it
543
+ * takes over the files — and their directory, where the atomic write and the
544
+ * backups are created, but only a directory that is plainly the app's own
545
+ * (its name contains the app's). Never /etc, never a shared directory.
546
+ */
547
+ async function envOwnership(ctx, user) {
548
+ const files = [envFile(ctx), ...envMirrors(ctx)].filter((f) => !f.startsWith(`${ctx.dir}/`));
549
+ if (files.length === 0)
550
+ return;
551
+ await step(ctx, 'env files outside the checkout', async () => {
552
+ const { host } = ctx;
553
+ for (const file of files) {
554
+ if (!(await host.exists(file))) {
555
+ host.out.warn(`${file} does not exist yet — the first deploy creates it`);
556
+ continue;
557
+ }
558
+ const chown = await host.exec('chown', [`${user}:`, file]);
559
+ if (chown.code !== 0)
560
+ throw new DeployError(`chown ${user} ${file}: ${chown.stderr.trim()}`);
561
+ await host.exec('chmod', ['600', file]);
562
+ }
563
+ for (const dir of [...new Set(files.map((f) => dirname(f)))]) {
564
+ if (basename(dir).includes(ctx.config.app) && dir !== '/' && dir !== '/etc') {
565
+ const chown = await host.exec('chown', [`${user}:`, dir]);
566
+ if (chown.code !== 0)
567
+ throw new DeployError(`chown ${user} ${dir}: ${chown.stderr.trim()}`);
568
+ await host.exec('chmod', ['700', dir]);
569
+ host.out.ok(`${dir} and its env files (${files.filter((f) => dirname(f) === dir).map((f) => basename(f)).join(', ')}) now owned by ${user}, 0700/0600`);
570
+ }
571
+ else {
572
+ host.out.warn(`${dir} is not ${ctx.config.app}'s own directory: the files are ${user}'s, but backups and atomic writes need ${user} to write in ${dir}`);
573
+ }
574
+ }
575
+ });
576
+ }
440
577
  export async function install(ctx, user) {
441
578
  const { host, config } = ctx;
442
579
  if (host.uid() !== 0)
443
580
  throw new DeployError(`install needs root: ${INSTALL_COMMAND}`);
444
581
  if (!user || user === 'root')
445
582
  throw new DeployError('install needs the unprivileged user the deploys run as: --user=<name> (never root)');
446
- const port = Number(envValues(await readEnv(ctx)).get('PORT'));
583
+ const port = isCompose(ctx) ? composeOf(ctx).upstream.port : Number(envValues(await readEnv(ctx)).get('PORT'));
447
584
  if (!Number.isInteger(port) || port <= 0)
448
585
  throw new DeployError(`no PORT in the .env yet: run \`${RUN_COMMAND.replace(/ run$/, ' env')}\` as the app user first`);
449
586
  const stateDir = `/var/lib/basalt/${config.app}`;
@@ -478,7 +615,8 @@ export async function install(ctx, user) {
478
615
  host.out.ok(`${overrides} created (server-local overrides, no secrets)`);
479
616
  }
480
617
  });
481
- if (config.proxy?.kind === 'apache') {
618
+ await envOwnership(ctx, user);
619
+ if (config.proxy?.kind === 'apache' && config.proxy.managed !== false) {
482
620
  await step(ctx, `Apache vhost ${vhostPaths(ctx).file}`, () => apacheInstall(ctx, port, join(stateDir, 'install-backups')));
483
621
  }
484
622
  if (config.infra?.kind === 'docker') {
package/dist/pm2.d.ts CHANGED
@@ -9,6 +9,7 @@ export interface Pm2Process {
9
9
  status: string;
10
10
  }
11
11
  export declare function pm2List(ctx: DeployContext): Promise<Pm2Process[] | undefined>;
12
+ /** The port the app listens on: the compose upstream's, or PM2's (`auto` picks a free one). */
12
13
  export declare function resolvePort(ctx: DeployContext, values: Map<string, string>): Promise<number>;
13
14
  export declare function pm2Preflight(ctx: DeployContext, port: number): Promise<Finding[]>;
14
15
  /**
package/dist/pm2.js CHANGED
@@ -18,8 +18,16 @@ export async function pm2List(ctx) {
18
18
  }
19
19
  }
20
20
  const PORT_FROM = 3000;
21
+ const pm2Of = (ctx) => {
22
+ if (ctx.config.runtime.kind !== 'pm2')
23
+ throw new Error('not a pm2 runtime');
24
+ return ctx.config.runtime;
25
+ };
26
+ /** The port the app listens on: the compose upstream's, or PM2's (`auto` picks a free one). */
21
27
  export async function resolvePort(ctx, values) {
22
- const runtime = ctx.config.runtime;
28
+ if (ctx.config.runtime.kind === 'compose')
29
+ return ctx.config.runtime.upstream.port;
30
+ const runtime = pm2Of(ctx);
23
31
  if (typeof runtime.port === 'number')
24
32
  return runtime.port;
25
33
  const current = Number(values.get('PORT'));
@@ -97,11 +105,11 @@ export async function pm2Release(ctx, env) {
97
105
  done = `${name} restarted`;
98
106
  }
99
107
  else {
100
- await must(ctx, ['start', ctx.pm, '--name', name, '--cwd', ctx.dir, '--', 'run', ctx.config.runtime.script], options);
108
+ await must(ctx, ['start', ctx.pm, '--name', name, '--cwd', ctx.dir, '--', 'run', pm2Of(ctx).script], options);
101
109
  done = ours ? `${name} re-created in ${ctx.dir}` : `${name} started`;
102
110
  }
103
111
  await must(ctx, ['save'], options);
104
- return `${done} (${ctx.pm} run ${ctx.config.runtime.script}, port ${env.get('PORT') ?? '?'})`;
112
+ return `${done} (${ctx.pm} run ${pm2Of(ctx).script}, port ${env.get('PORT') ?? '?'})`;
105
113
  }
106
114
  async function must(ctx, args, options) {
107
115
  const result = await ctx.host.exec('pm2', args, options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },