@basaltkit/deploy 0.1.0 → 0.1.2
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 +16 -2
- package/dist/apache.js +5 -5
- package/dist/checks.d.ts +14 -0
- package/dist/checks.js +50 -0
- package/dist/cli.js +2 -1
- package/dist/context.d.ts +5 -0
- package/dist/context.js +5 -0
- package/dist/host.d.ts +2 -0
- package/dist/host.js +1 -0
- package/dist/pipeline.d.ts +14 -0
- package/dist/pipeline.js +104 -20
- package/dist/pm2.d.ts +2 -2
- package/dist/pm2.js +5 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -53,13 +53,18 @@ What is true of one server only (a port taken there, another branch) goes in
|
|
|
53
53
|
pnpm install
|
|
54
54
|
pnpm exec basalt-deploy env # writes the .env (asks once), starts the containers, validates
|
|
55
55
|
|
|
56
|
-
# once, as an administrator:
|
|
57
|
-
sudo
|
|
56
|
+
# once, as an administrator (node on the file: root often has no pnpm on its PATH):
|
|
57
|
+
sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user=<app user> # Apache vhost, /var/lib/basalt/<app>
|
|
58
58
|
|
|
59
59
|
# then, every deploy, as the app user:
|
|
60
60
|
pnpm exec basalt-deploy run
|
|
61
61
|
```
|
|
62
62
|
|
|
63
|
+
`run` pulls the code itself. Store the git credentials once
|
|
64
|
+
(`git config credential.helper store && git fetch`, or a read-only deploy key):
|
|
65
|
+
preflight probes the remote with prompts disabled, warns at a terminal and
|
|
66
|
+
stops before anything changes when nobody can type them (cron, CI).
|
|
67
|
+
|
|
63
68
|
The TLS certificate is yours to issue (`certbot --dns-cloudflare -d <domain> -d '*.<domain>'`);
|
|
64
69
|
every deploy checks it.
|
|
65
70
|
|
|
@@ -76,6 +81,14 @@ every deploy checks it.
|
|
|
76
81
|
|
|
77
82
|
`--skip=fetch,backup,tls`, `--config=<file>`, `--overrides=<file>`.
|
|
78
83
|
|
|
84
|
+
## What runs by default
|
|
85
|
+
|
|
86
|
+
- `prisma migrate deploy` — when `build.prisma` lists a config, or `migrate.central: true`.
|
|
87
|
+
- `tenant:migrate` — only with `migrate.tenants`.
|
|
88
|
+
- The dump before migrating — when something is migrated and there is a
|
|
89
|
+
Postgres to dump (dedicated, or a `postgres://` URL in the `.env`);
|
|
90
|
+
`backup.beforeMigrate` forces it either way. `plan` says why when it is skipped.
|
|
91
|
+
|
|
79
92
|
## What it refuses to do
|
|
80
93
|
|
|
81
94
|
Each of these is a check that runs on every deploy, written after a production
|
|
@@ -91,6 +104,7 @@ incident (RFC 0006 §5):
|
|
|
91
104
|
- **C8** stay silent about a certificate that does not cover the apex or a tenant host;
|
|
92
105
|
- **C9** run with a package manager major other than the one `packageManager` declares;
|
|
93
106
|
- **C10** keep a forbidden key, or a fixed key with another value.
|
|
107
|
+
- **C11** build a commit whose `packageManager` (pnpm ≥ 12) the lockfile does not record — checked in preflight and again on the commit the fetch brings, before any install.
|
|
94
108
|
|
|
95
109
|
Secrets never reach a command line, the compose file, or the terminal: the
|
|
96
110
|
summary names keys, passwords travel in child-process environments only.
|
package/dist/apache.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
import { vhostName } from './config.js';
|
|
3
|
-
import { DeployError } from './context.js';
|
|
3
|
+
import { DeployError, INSTALL_COMMAND } from './context.js';
|
|
4
4
|
import { lineDiff } from './diff.js';
|
|
5
5
|
/**
|
|
6
6
|
* The Apache target (RFC 0006 §11.3): the vhost is written ONLY by `install`,
|
|
@@ -76,7 +76,7 @@ export async function apachePreflight(ctx, port) {
|
|
|
76
76
|
const enabled = await host.stat(paths.enabled);
|
|
77
77
|
const available = await host.readFile(paths.available);
|
|
78
78
|
if (!enabled && available === undefined) {
|
|
79
|
-
return [{ id: 'proxy', level: 'error', message: `no Apache vhost ${paths.file} yet`, fix:
|
|
79
|
+
return [{ id: 'proxy', level: 'error', message: `no Apache vhost ${paths.file} yet`, fix: `${INSTALL_COMMAND} (once per server)` }];
|
|
80
80
|
}
|
|
81
81
|
if (!enabled) {
|
|
82
82
|
findings.push({ id: 'proxy', level: 'error', message: `${paths.file} is in sites-available but not enabled`, fix: `sudo a2ensite ${paths.file} && sudo systemctl reload apache2` });
|
|
@@ -91,7 +91,7 @@ export async function apachePreflight(ctx, port) {
|
|
|
91
91
|
id: 'C2',
|
|
92
92
|
level: 'error',
|
|
93
93
|
message: `sites-enabled/${paths.file} is a regular file, not a link to sites-available — ${same ? 'identical today, but edits to sites-available will not be served' : 'and it DIFFERS from sites-available: Apache serves the copy'}`,
|
|
94
|
-
fix:
|
|
94
|
+
fix: `${INSTALL_COMMAND} (replaces it with a link, after showing the diff)`,
|
|
95
95
|
});
|
|
96
96
|
}
|
|
97
97
|
else if (enabled.kind === 'symlink') {
|
|
@@ -110,7 +110,7 @@ export async function apachePreflight(ctx, port) {
|
|
|
110
110
|
id: 'C1',
|
|
111
111
|
level: 'error',
|
|
112
112
|
message: `the vhost proxies to 127.0.0.1:${proxied}, but the app listens on ${port}`,
|
|
113
|
-
fix:
|
|
113
|
+
fix: `${INSTALL_COMMAND} (shows the diff and rewrites it)`,
|
|
114
114
|
});
|
|
115
115
|
}
|
|
116
116
|
}
|
|
@@ -120,7 +120,7 @@ export async function apachePreflight(ctx, port) {
|
|
|
120
120
|
id: 'vhost',
|
|
121
121
|
level: 'warning',
|
|
122
122
|
message: `the installed vhost differs from what install would write (not changed — audit only):\n${diff.map((l) => ` ${l}`).join('\n')}`,
|
|
123
|
-
fix:
|
|
123
|
+
fix: `to apply: ${INSTALL_COMMAND}`,
|
|
124
124
|
});
|
|
125
125
|
}
|
|
126
126
|
}
|
package/dist/checks.d.ts
CHANGED
|
@@ -11,3 +11,17 @@ export declare function covers(name: string, host: string): boolean;
|
|
|
11
11
|
export declare function tlsFindings(ctx: DeployContext): Promise<Finding[]>;
|
|
12
12
|
/** C9 — the toolchain the pipeline will call, before it calls it. */
|
|
13
13
|
export declare function toolingFindings(ctx: DeployContext): Promise<Finding[]>;
|
|
14
|
+
/** The pnpm version the lockfile records for `packageManager` (`packageManagerDependencies`), if any. */
|
|
15
|
+
export declare function lockedPnpm(lockfile: string): string | undefined;
|
|
16
|
+
/**
|
|
17
|
+
* C11 — a `packageManager` the lockfile does not record. pnpm 12 writes the
|
|
18
|
+
* pnpm it runs as into the lockfile (`packageManagerDependencies`) and its
|
|
19
|
+
* frozen install refuses a lockfile without it, or with another version:
|
|
20
|
+
* ERR_PNPM_FROZEN_LOCKFILE_WITH_OUTDATED_LOCKFILE, half-way through a deploy.
|
|
21
|
+
* It happened twice on the first day: `packageManager: pnpm@12.3.4` was
|
|
22
|
+
* committed with a lockfile written by pnpm 11.
|
|
23
|
+
*
|
|
24
|
+
* Checked when it can bite: pnpm declared at 12 or later, or a lockfile that
|
|
25
|
+
* already records a version (which must then be the declared one).
|
|
26
|
+
*/
|
|
27
|
+
export declare function lockfileFindings(ctx: DeployContext): Promise<Finding[]>;
|
package/dist/checks.js
CHANGED
|
@@ -97,3 +97,53 @@ export async function toolingFindings(ctx) {
|
|
|
97
97
|
}
|
|
98
98
|
return findings;
|
|
99
99
|
}
|
|
100
|
+
/** The pnpm version the lockfile records for `packageManager` (`packageManagerDependencies`), if any. */
|
|
101
|
+
export function lockedPnpm(lockfile) {
|
|
102
|
+
const at = lockfile.indexOf('packageManagerDependencies:');
|
|
103
|
+
if (at === -1)
|
|
104
|
+
return undefined;
|
|
105
|
+
const match = /\n\s+pnpm:\s*\n\s+specifier:\s*['"]?([^\s'"]+)/.exec(lockfile.slice(at, at + 2000));
|
|
106
|
+
return match?.[1];
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* C11 — a `packageManager` the lockfile does not record. pnpm 12 writes the
|
|
110
|
+
* pnpm it runs as into the lockfile (`packageManagerDependencies`) and its
|
|
111
|
+
* frozen install refuses a lockfile without it, or with another version:
|
|
112
|
+
* ERR_PNPM_FROZEN_LOCKFILE_WITH_OUTDATED_LOCKFILE, half-way through a deploy.
|
|
113
|
+
* It happened twice on the first day: `packageManager: pnpm@12.3.4` was
|
|
114
|
+
* committed with a lockfile written by pnpm 11.
|
|
115
|
+
*
|
|
116
|
+
* Checked when it can bite: pnpm declared at 12 or later, or a lockfile that
|
|
117
|
+
* already records a version (which must then be the declared one).
|
|
118
|
+
*/
|
|
119
|
+
export async function lockfileFindings(ctx) {
|
|
120
|
+
if (ctx.pm !== 'pnpm')
|
|
121
|
+
return [];
|
|
122
|
+
let declared;
|
|
123
|
+
try {
|
|
124
|
+
const pkg = JSON.parse((await ctx.host.readFile(join(ctx.dir, 'package.json'))) ?? '{}');
|
|
125
|
+
const match = /^pnpm@(\d+[^+\s]*)/.exec(pkg.packageManager ?? '');
|
|
126
|
+
declared = match?.[1];
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
if (!declared)
|
|
132
|
+
return [];
|
|
133
|
+
const lockfile = await ctx.host.readFile(join(ctx.dir, 'pnpm-lock.yaml'));
|
|
134
|
+
if (lockfile === undefined)
|
|
135
|
+
return [];
|
|
136
|
+
const locked = lockedPnpm(lockfile);
|
|
137
|
+
if (locked === undefined && Number(declared.split('.')[0]) < 12)
|
|
138
|
+
return [];
|
|
139
|
+
if (locked === declared)
|
|
140
|
+
return [];
|
|
141
|
+
return [{
|
|
142
|
+
id: 'C11',
|
|
143
|
+
level: 'error',
|
|
144
|
+
message: locked === undefined
|
|
145
|
+
? `package.json declares pnpm@${declared}, but pnpm-lock.yaml does not record it (packageManagerDependencies): pnpm's frozen install will refuse the lockfile`
|
|
146
|
+
: `package.json declares pnpm@${declared}, but pnpm-lock.yaml records pnpm ${locked}: pnpm's frozen install will refuse the lockfile`,
|
|
147
|
+
fix: `run pnpm install --lockfile-only with pnpm ${declared} and commit pnpm-lock.yaml`,
|
|
148
|
+
}];
|
|
149
|
+
}
|
package/dist/cli.js
CHANGED
|
@@ -12,7 +12,8 @@ export const USAGE = `basalt-deploy — deploy this Basalt app on this server (R
|
|
|
12
12
|
basalt-deploy env the .env and the dedicated infra only (first setup)
|
|
13
13
|
basalt-deploy rollback [--to=<sha>] back to the last healthy release (code only)
|
|
14
14
|
basalt-deploy status the last releases and the process
|
|
15
|
-
sudo
|
|
15
|
+
sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user=<name>
|
|
16
|
+
once per server, as root: vhost, state directory
|
|
16
17
|
|
|
17
18
|
Options:
|
|
18
19
|
--config=<file> default deploy.config.ts
|
package/dist/context.d.ts
CHANGED
|
@@ -19,6 +19,11 @@ export interface Finding {
|
|
|
19
19
|
/** One line the operator can act on. */
|
|
20
20
|
fix?: string;
|
|
21
21
|
}
|
|
22
|
+
/**
|
|
23
|
+
* How an administrator runs `install`. `node` on the file, not `pnpm exec`:
|
|
24
|
+
* root often has no pnpm on its PATH (a per-user install, corepack).
|
|
25
|
+
*/
|
|
26
|
+
export declare const INSTALL_COMMAND = "sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user=\"$USER\"";
|
|
22
27
|
export declare const errors: (findings: Finding[]) => Finding[];
|
|
23
28
|
export declare function report(host: Host, findings: Finding[]): void;
|
|
24
29
|
export declare function detectPackageManager(host: Host, dir: string): Promise<DeployContext['pm']>;
|
package/dist/context.js
CHANGED
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
|
+
/**
|
|
3
|
+
* How an administrator runs `install`. `node` on the file, not `pnpm exec`:
|
|
4
|
+
* root often has no pnpm on its PATH (a per-user install, corepack).
|
|
5
|
+
*/
|
|
6
|
+
export const INSTALL_COMMAND = 'sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user="$USER"';
|
|
2
7
|
export const errors = (findings) => findings.filter((f) => f.level === 'error');
|
|
3
8
|
export function report(host, findings) {
|
|
4
9
|
for (const finding of findings) {
|
package/dist/host.d.ts
CHANGED
|
@@ -43,6 +43,8 @@ export interface Host {
|
|
|
43
43
|
}>;
|
|
44
44
|
/** The environment the deploy itself was started with (answers for non-interactive runs). */
|
|
45
45
|
env: Readonly<Record<string, string | undefined>>;
|
|
46
|
+
/** Whether a person can answer a prompt (a terminal, not CI). */
|
|
47
|
+
interactive(): boolean;
|
|
46
48
|
uid(): number;
|
|
47
49
|
out: Output;
|
|
48
50
|
}
|
package/dist/host.js
CHANGED
|
@@ -23,6 +23,7 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
23
23
|
out: output,
|
|
24
24
|
env: process.env,
|
|
25
25
|
uid: () => (typeof process.getuid === 'function' ? process.getuid() : -1),
|
|
26
|
+
interactive: () => Boolean(process.stdin.isTTY) && !process.env['CI'],
|
|
26
27
|
now: () => new Date(),
|
|
27
28
|
randomHex: (bytes) => randomBytes(bytes).toString('hex'),
|
|
28
29
|
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
package/dist/pipeline.d.ts
CHANGED
|
@@ -18,6 +18,20 @@ export interface Preflight {
|
|
|
18
18
|
values: Map<string, string>;
|
|
19
19
|
}
|
|
20
20
|
export declare function preflight(ctx: DeployContext, options?: RunOptions): Promise<Preflight>;
|
|
21
|
+
/** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
|
|
22
|
+
export declare function migratesCentral(config: DeployContext['config']): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Whether the pre-migration dump runs, and why not when it does not. Unsaid,
|
|
25
|
+
* it runs when there is something to migrate AND a Postgres to dump: the
|
|
26
|
+
* dedicated one, or a `postgres…` URL in the `.env`. Explicitly on, a missing
|
|
27
|
+
* database is the backup step's error to report.
|
|
28
|
+
*/
|
|
29
|
+
export declare function backupDecision(config: DeployContext['config'], values: Map<string, string>, skip?: Iterable<string>): {
|
|
30
|
+
run: true;
|
|
31
|
+
} | {
|
|
32
|
+
run: false;
|
|
33
|
+
why: string;
|
|
34
|
+
};
|
|
21
35
|
export declare function plan(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
22
36
|
/** `basalt-deploy env` — the .env and the infra only (first setup, before `install`). */
|
|
23
37
|
export declare function envCommand(ctx: DeployContext): Promise<number>;
|
package/dist/pipeline.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { join } from 'node:path';
|
|
2
2
|
import { apacheInstall, apachePreflight, vhostPaths } from './apache.js';
|
|
3
3
|
import { backupDatabase, restoreCommand } from './backup.js';
|
|
4
|
-
import { tlsFindings, toolingFindings } from './checks.js';
|
|
4
|
+
import { lockfileFindings, tlsFindings, toolingFindings } from './checks.js';
|
|
5
5
|
import { processName } from './config.js';
|
|
6
|
-
import { DeployError, errors, report } from './context.js';
|
|
6
|
+
import { DeployError, errors, INSTALL_COMMAND, report } from './context.js';
|
|
7
7
|
import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
|
|
8
8
|
import { answerQuestions, describeEnv, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
|
|
9
9
|
import { envValues } from './dotenv.js';
|
|
@@ -11,8 +11,13 @@ import { applyInfra, describeInfra, planInfra } from './infra.js';
|
|
|
11
11
|
import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
|
|
12
12
|
import { lastGood, migrationNames, readReleases, recordRelease } from './state.js';
|
|
13
13
|
export const SKIPPABLE = ['fetch', 'backup', 'tls'];
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Never a credential prompt: one in the middle of a deploy hangs cron and CI,
|
|
16
|
+
* and interrupts a person half-way. With nobody to answer, git fails instead.
|
|
17
|
+
*/
|
|
18
|
+
const NO_PROMPT = { GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_SSH_COMMAND: 'ssh -o BatchMode=yes' };
|
|
19
|
+
async function git(ctx, args, options = {}) {
|
|
20
|
+
const result = await ctx.host.exec('git', args, { cwd: ctx.dir, ...(options.noPrompt ? { env: NO_PROMPT } : {}) });
|
|
16
21
|
if (result.code !== 0)
|
|
17
22
|
throw new DeployError(`git ${args[0]} failed: ${result.stderr.trim()}`);
|
|
18
23
|
return result.stdout.trim();
|
|
@@ -27,6 +32,7 @@ export async function preflight(ctx, options = {}) {
|
|
|
27
32
|
const findings = [...syntaxFindings(document, ctx.config.env.file ?? '.env')];
|
|
28
33
|
const port = await resolvePort(ctx, values);
|
|
29
34
|
findings.push(...await toolingFindings(ctx));
|
|
35
|
+
findings.push(...await lockfileFindings(ctx));
|
|
30
36
|
findings.push(...await pm2Preflight(ctx, port));
|
|
31
37
|
if (ctx.config.proxy?.kind === 'apache')
|
|
32
38
|
findings.push(...await apachePreflight(ctx, port));
|
|
@@ -44,15 +50,63 @@ export async function preflight(ctx, options = {}) {
|
|
|
44
50
|
const wanted = ctx.config.branch ?? 'main';
|
|
45
51
|
if (branch !== wanted)
|
|
46
52
|
findings.push({ id: 'git', level: 'error', message: `the checkout is on "${branch}", the deploy tracks "${wanted}"`, fix: `git checkout ${wanted}` });
|
|
53
|
+
if (!options.skip?.includes('fetch'))
|
|
54
|
+
findings.push(...await remoteFindings(ctx));
|
|
47
55
|
}
|
|
48
56
|
return { findings, port, values };
|
|
49
57
|
}
|
|
58
|
+
const CREDENTIALS = /terminal prompts disabled|could not read (Username|Password)|Authentication failed|Permission denied \(publickey|Host key verification failed|Invalid username or (password|token)/i;
|
|
59
|
+
/** Can the fetch reach the branch without asking anyone for anything? */
|
|
60
|
+
async function remoteFindings(ctx) {
|
|
61
|
+
const remote = ctx.config.remote ?? 'origin';
|
|
62
|
+
const branch = ctx.config.branch ?? 'main';
|
|
63
|
+
const probe = await ctx.host.exec('git', ['ls-remote', '--exit-code', remote, `refs/heads/${branch}`], { cwd: ctx.dir, env: NO_PROMPT });
|
|
64
|
+
if (probe.code === 0)
|
|
65
|
+
return [];
|
|
66
|
+
if (probe.code === 2)
|
|
67
|
+
return [{ id: 'git', level: 'error', message: `the branch "${branch}" does not exist on ${remote}` }];
|
|
68
|
+
const reason = probe.stderr.trim().split('\n').find((l) => l.trim()) ?? `exit ${probe.code}`;
|
|
69
|
+
if (CREDENTIALS.test(probe.stderr)) {
|
|
70
|
+
const fix = 'store them once: git config credential.helper store && git fetch (or a read-only deploy key and an ssh remote)';
|
|
71
|
+
return ctx.host.interactive()
|
|
72
|
+
? [{ id: 'git', level: 'warning', message: `${remote} needs credentials: the fetch will ask for them`, fix }]
|
|
73
|
+
: [{ id: 'git', level: 'error', message: `${remote} needs credentials and nobody can type them here (no terminal)`, fix }];
|
|
74
|
+
}
|
|
75
|
+
return [{ id: 'git', level: 'warning', message: `could not reach ${remote}: ${reason}`, fix: '--skip=fetch deploys the code already in the checkout' }];
|
|
76
|
+
}
|
|
50
77
|
function stopOnErrors(ctx, findings, what) {
|
|
51
78
|
report(ctx.host, findings);
|
|
52
79
|
const blocking = errors(findings);
|
|
53
80
|
if (blocking.length > 0)
|
|
54
81
|
throw new DeployError(`${what}: ${blocking.length} problem(s) above — nothing was changed`, blocking);
|
|
55
82
|
}
|
|
83
|
+
// ── what runs by default ───────────────────────────────────────────────────
|
|
84
|
+
/** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
|
|
85
|
+
export function migratesCentral(config) {
|
|
86
|
+
return config.migrate?.central ?? (config.build?.prisma?.length ?? 0) > 0;
|
|
87
|
+
}
|
|
88
|
+
const migratesAnything = (config) => migratesCentral(config) || Boolean(config.migrate?.tenants);
|
|
89
|
+
/**
|
|
90
|
+
* Whether the pre-migration dump runs, and why not when it does not. Unsaid,
|
|
91
|
+
* it runs when there is something to migrate AND a Postgres to dump: the
|
|
92
|
+
* dedicated one, or a `postgres…` URL in the `.env`. Explicitly on, a missing
|
|
93
|
+
* database is the backup step's error to report.
|
|
94
|
+
*/
|
|
95
|
+
export function backupDecision(config, values, skip = []) {
|
|
96
|
+
if ([...skip].includes('backup'))
|
|
97
|
+
return { run: false, why: '--skip=backup' };
|
|
98
|
+
const wanted = config.backup?.beforeMigrate;
|
|
99
|
+
if (wanted === false)
|
|
100
|
+
return { run: false, why: 'backup.beforeMigrate is false' };
|
|
101
|
+
if (wanted === true)
|
|
102
|
+
return { run: true };
|
|
103
|
+
if (!migratesAnything(config))
|
|
104
|
+
return { run: false, why: 'nothing to migrate' };
|
|
105
|
+
if (config.infra?.kind === 'docker' && config.infra.postgres)
|
|
106
|
+
return { run: true };
|
|
107
|
+
const url = values.get(config.backup?.urlKey ?? 'DATABASE_URL') ?? '';
|
|
108
|
+
return /^postgres(ql)?:\/\//.test(url) ? { run: true } : { run: false, why: 'no Postgres database in the .env' };
|
|
109
|
+
}
|
|
56
110
|
// ── the building blocks ────────────────────────────────────────────────────
|
|
57
111
|
async function prepareEnv(ctx, port) {
|
|
58
112
|
const document = await readEnv(ctx);
|
|
@@ -88,7 +142,7 @@ async function validate(ctx, values) {
|
|
|
88
142
|
async function migrate(ctx, values) {
|
|
89
143
|
const { host, pm } = ctx;
|
|
90
144
|
const env = { cwd: ctx.dir, stream: true, env: Object.fromEntries(values) };
|
|
91
|
-
if (ctx.config
|
|
145
|
+
if (migratesCentral(ctx.config)) {
|
|
92
146
|
host.out.info(`${pm} exec prisma migrate deploy`);
|
|
93
147
|
const central = await host.exec(pm, ['exec', 'prisma', 'migrate', 'deploy'], env);
|
|
94
148
|
if (central.code !== 0)
|
|
@@ -102,6 +156,8 @@ async function migrate(ctx, values) {
|
|
|
102
156
|
if (result.code !== 0)
|
|
103
157
|
throw new DeployError('the tenant migrations failed');
|
|
104
158
|
}
|
|
159
|
+
if (!migratesAnything(ctx.config))
|
|
160
|
+
host.out.info('nothing to migrate (no build.prisma, no migrate.tenants)');
|
|
105
161
|
}
|
|
106
162
|
async function healthy(ctx, port) {
|
|
107
163
|
const { host, config } = ctx;
|
|
@@ -136,6 +192,26 @@ async function restoreCode(ctx, sha, values) {
|
|
|
136
192
|
await git(ctx, ['reset', '--hard', sha]);
|
|
137
193
|
await build(ctx, values);
|
|
138
194
|
}
|
|
195
|
+
/** The env step's summary: what changed, or that nothing did. */
|
|
196
|
+
function reportEnv(ctx, plan) {
|
|
197
|
+
const lines = describeEnv(plan);
|
|
198
|
+
if (lines.length === 0)
|
|
199
|
+
ctx.host.out.ok(`${ctx.config.env.file ?? '.env'} unchanged`);
|
|
200
|
+
for (const line of lines)
|
|
201
|
+
ctx.host.out.info(line);
|
|
202
|
+
}
|
|
203
|
+
async function infraStep(ctx, infra) {
|
|
204
|
+
stopOnErrors(ctx, await applyInfra(ctx, infra), 'infra');
|
|
205
|
+
if (infra.services.length === 0)
|
|
206
|
+
ctx.host.out.ok('nothing to start (external infra)');
|
|
207
|
+
else
|
|
208
|
+
ctx.host.out.ok(`${infra.services.map((s) => s.container).join(', ')} healthy; credentials accepted${ctx.config.infra?.kind === 'docker' && ctx.config.infra.minio?.buckets.length ? '; buckets in place' : ''}`);
|
|
209
|
+
}
|
|
210
|
+
async function validateStep(ctx, values) {
|
|
211
|
+
stopOnErrors(ctx, await validate(ctx, values), 'validate');
|
|
212
|
+
const schema = ctx.config.env.schema;
|
|
213
|
+
ctx.host.out.ok(schema ? `${ctx.config.env.file ?? '.env'} is valid for ${schema}` : `${ctx.config.env.file ?? '.env'}: syntax and policy only (no env.schema configured)`);
|
|
214
|
+
}
|
|
139
215
|
// ── commands ───────────────────────────────────────────────────────────────
|
|
140
216
|
export async function plan(ctx, options = {}) {
|
|
141
217
|
const checked = await step(ctx, 'preflight', () => preflight(ctx, options));
|
|
@@ -150,8 +226,10 @@ export async function plan(ctx, options = {}) {
|
|
|
150
226
|
...describeInfra(infra).map((l) => `infra: ${l}`),
|
|
151
227
|
`build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.web ? `, ${config.build.web} build` : ''}`,
|
|
152
228
|
`validate: ${config.env.schema ?? '(no schema configured)'} against the new .env`,
|
|
153
|
-
|
|
154
|
-
|
|
229
|
+
((decision) => decision.run
|
|
230
|
+
? `backup: pg_dump → ${config.backup?.dir ?? 'backups/predeploy'} (keep ${config.backup?.keep ?? 10})`
|
|
231
|
+
: `backup: skipped (${decision.why})`)(backupDecision(config, checked.values, options.skip ?? [])),
|
|
232
|
+
`migrate: ${[migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
|
|
155
233
|
`release: pm2 ${processName(config)} on 127.0.0.1:${checked.port}`,
|
|
156
234
|
`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'}` : ''}`,
|
|
157
235
|
];
|
|
@@ -169,11 +247,10 @@ export async function envCommand(ctx) {
|
|
|
169
247
|
const missing = await answerQuestions(ctx, env);
|
|
170
248
|
if (missing.length > 0)
|
|
171
249
|
throw new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`);
|
|
172
|
-
|
|
173
|
-
ctx.host.out.info(line);
|
|
250
|
+
reportEnv(ctx, env);
|
|
174
251
|
await writeEnv(ctx, env);
|
|
175
|
-
await step(ctx, 'infra',
|
|
176
|
-
await step(ctx, 'validate',
|
|
252
|
+
await step(ctx, 'infra', () => infraStep(ctx, infra));
|
|
253
|
+
await step(ctx, 'validate', () => validateStep(ctx, env.values));
|
|
177
254
|
ctx.host.out.ok(`.env ready (PORT=${port})`);
|
|
178
255
|
return 0;
|
|
179
256
|
}
|
|
@@ -186,7 +263,7 @@ export async function run(ctx, options = {}) {
|
|
|
186
263
|
const previous = await git(ctx, ['rev-parse', 'HEAD']);
|
|
187
264
|
if (!skip.has('fetch')) {
|
|
188
265
|
await step(ctx, 'fetch', async () => {
|
|
189
|
-
await git(ctx, ['fetch', '--quiet', config.remote ?? 'origin', config.branch ?? 'main']);
|
|
266
|
+
await git(ctx, ['fetch', '--quiet', config.remote ?? 'origin', config.branch ?? 'main'], { noPrompt: !host.interactive() });
|
|
190
267
|
await git(ctx, ['merge', '--ff-only', `${config.remote ?? 'origin'}/${config.branch ?? 'main'}`]);
|
|
191
268
|
});
|
|
192
269
|
}
|
|
@@ -198,23 +275,30 @@ export async function run(ctx, options = {}) {
|
|
|
198
275
|
let values = checked.values;
|
|
199
276
|
let infra = { services: [], env: [], findings: [], secrets: {} };
|
|
200
277
|
try {
|
|
278
|
+
// Again on the code the fetch brought: preflight saw the commit before it.
|
|
279
|
+
if (sha !== previous)
|
|
280
|
+
stopOnErrors(ctx, await lockfileFindings(ctx), `the incoming commit ${sha.slice(0, 7)}`);
|
|
201
281
|
const prepared = await step(ctx, 'env', () => prepareEnv(ctx, port));
|
|
202
282
|
infra = prepared.infra;
|
|
203
283
|
stopOnErrors(ctx, infra.findings, 'infra');
|
|
204
284
|
const missing = await answerQuestions(ctx, prepared.env);
|
|
205
285
|
if (missing.length > 0)
|
|
206
286
|
throw new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`);
|
|
207
|
-
|
|
208
|
-
host.out.info(line);
|
|
287
|
+
reportEnv(ctx, prepared.env);
|
|
209
288
|
await writeEnv(ctx, prepared.env);
|
|
210
289
|
values = prepared.env.values;
|
|
211
|
-
await step(ctx, 'infra',
|
|
290
|
+
await step(ctx, 'infra', () => infraStep(ctx, infra));
|
|
212
291
|
await step(ctx, 'build', () => build(ctx, values));
|
|
213
|
-
await step(ctx, 'validate',
|
|
214
|
-
|
|
292
|
+
await step(ctx, 'validate', () => validateStep(ctx, values));
|
|
293
|
+
const backup = backupDecision(config, values, skip);
|
|
294
|
+
if (backup.run) {
|
|
215
295
|
release.backup = await step(ctx, 'backup', () => backupDatabase(ctx, values, infra, sha));
|
|
216
296
|
host.out.ok(release.backup);
|
|
217
297
|
}
|
|
298
|
+
else {
|
|
299
|
+
host.out.step('backup');
|
|
300
|
+
host.out.info(`skipped: ${backup.why}`);
|
|
301
|
+
}
|
|
218
302
|
await step(ctx, 'migrate', () => migrate(ctx, values));
|
|
219
303
|
}
|
|
220
304
|
catch (error) {
|
|
@@ -243,7 +327,7 @@ export async function run(ctx, options = {}) {
|
|
|
243
327
|
return 1;
|
|
244
328
|
};
|
|
245
329
|
try {
|
|
246
|
-
await step(ctx, 'release', () => pm2Release(ctx, values));
|
|
330
|
+
host.out.ok(await step(ctx, 'release', () => pm2Release(ctx, values)));
|
|
247
331
|
}
|
|
248
332
|
catch (error) {
|
|
249
333
|
return recover(error.message);
|
|
@@ -265,7 +349,7 @@ export async function run(ctx, options = {}) {
|
|
|
265
349
|
async function rollbackTo(ctx, sha, values, port) {
|
|
266
350
|
await restoreCode(ctx, sha, values);
|
|
267
351
|
ctx.host.out.step(`release ${sha.slice(0, 7)}`);
|
|
268
|
-
await pm2Release(ctx, values);
|
|
352
|
+
ctx.host.out.ok(await pm2Release(ctx, values));
|
|
269
353
|
if (await healthy(ctx, port))
|
|
270
354
|
ctx.host.out.ok(`back on ${sha.slice(0, 7)}`);
|
|
271
355
|
else
|
|
@@ -314,7 +398,7 @@ export async function status(ctx) {
|
|
|
314
398
|
export async function install(ctx, user) {
|
|
315
399
|
const { host, config } = ctx;
|
|
316
400
|
if (host.uid() !== 0)
|
|
317
|
-
throw new DeployError(
|
|
401
|
+
throw new DeployError(`install needs root: ${INSTALL_COMMAND}`);
|
|
318
402
|
if (!user || user === 'root')
|
|
319
403
|
throw new DeployError('install needs the unprivileged user the deploys run as: --user=<name> (never root)');
|
|
320
404
|
const port = Number(envValues(await readEnv(ctx)).get('PORT'));
|
package/dist/pm2.d.ts
CHANGED
|
@@ -19,5 +19,5 @@ export declare function pm2Preflight(ctx: DeployContext, port: number): Promise<
|
|
|
19
19
|
* `.env`, as it does in development; only what PM2 itself must know is passed.
|
|
20
20
|
*/
|
|
21
21
|
export declare function processEnv(host: DeployContext['host'], env: Map<string, string>): Record<string, string>;
|
|
22
|
-
/** Starts, restarts or re-creates the process. */
|
|
23
|
-
export declare function pm2Release(ctx: DeployContext, env: Map<string, string>): Promise<
|
|
22
|
+
/** Starts, restarts or re-creates the process; says which. */
|
|
23
|
+
export declare function pm2Release(ctx: DeployContext, env: Map<string, string>): Promise<string>;
|
package/dist/pm2.js
CHANGED
|
@@ -81,7 +81,7 @@ export function processEnv(host, env) {
|
|
|
81
81
|
out['PM2_HOME'] = pm2Home;
|
|
82
82
|
return out;
|
|
83
83
|
}
|
|
84
|
-
/** Starts, restarts or re-creates the process. */
|
|
84
|
+
/** Starts, restarts or re-creates the process; says which. */
|
|
85
85
|
export async function pm2Release(ctx, env) {
|
|
86
86
|
const { host } = ctx;
|
|
87
87
|
const name = processName(ctx.config);
|
|
@@ -91,13 +91,17 @@ export async function pm2Release(ctx, env) {
|
|
|
91
91
|
host.out.info(`pm2 delete ${name} (it ran from ${ours.cwd})`);
|
|
92
92
|
await must(ctx, ['delete', name], options);
|
|
93
93
|
}
|
|
94
|
+
let done;
|
|
94
95
|
if (ours && ours.cwd === ctx.dir) {
|
|
95
96
|
await must(ctx, ['restart', name, '--update-env'], options);
|
|
97
|
+
done = `${name} restarted`;
|
|
96
98
|
}
|
|
97
99
|
else {
|
|
98
100
|
await must(ctx, ['start', ctx.pm, '--name', name, '--cwd', ctx.dir, '--', 'run', ctx.config.runtime.script], options);
|
|
101
|
+
done = ours ? `${name} re-created in ${ctx.dir}` : `${name} started`;
|
|
99
102
|
}
|
|
100
103
|
await must(ctx, ['save'], options);
|
|
104
|
+
return `${done} (${ctx.pm} run ${ctx.config.runtime.script}, port ${env.get('PORT') ?? '?'})`;
|
|
101
105
|
}
|
|
102
106
|
async function must(ctx, args, options) {
|
|
103
107
|
const result = await ctx.host.exec('pm2', args, options);
|