@basaltkit/deploy 0.7.0 → 0.8.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 +3 -1
- package/dist/cli.js +29 -3
- package/dist/commits.d.ts +39 -0
- package/dist/commits.js +188 -0
- package/dist/host.d.ts +6 -0
- package/dist/host.js +38 -3
- package/dist/pipeline.d.ts +16 -0
- package/dist/pipeline.js +69 -2
- package/dist/protocol.d.ts +63 -0
- package/dist/protocol.js +7 -0
- package/dist/state.d.ts +6 -0
- package/dist/state.js +8 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -204,11 +204,13 @@ As the app user, in the checkout (`node node_modules/@basaltkit/deploy/dist/bin.
|
|
|
204
204
|
|---|---|
|
|
205
205
|
| `init --domain=<host>` | writes `deploy.config.ts` from the project (`--server`: also from this server), then `check` |
|
|
206
206
|
| `check` | the config is valid and types check (your `tsc`). No server needed — for CI. |
|
|
207
|
-
| `plan` | every check, then what `run` would do.
|
|
207
|
+
| `plan` | every check, then what `run` would do, and the commits it would deploy. Asks nothing, and changes nothing `run` uses: the commits are fetched into a private ref it deletes again. |
|
|
208
208
|
| `run` | preflight → fetch → env → infra → build → validate → backup → migrate → release → health → record |
|
|
209
209
|
| `env` | the `.env` and the containers only |
|
|
210
210
|
| `rollback [--to=<sha>]` | the last healthy release. Code only — the database keeps its migrations. Holds the commit it left. |
|
|
211
211
|
| `status` | the last releases (who, from where), the process, the deploy lock, a hold |
|
|
212
|
+
| `commits --from=<sha> --to=<sha>` | the commits between two releases. Read-only: no lock, no fetch. |
|
|
213
|
+
| `commits --rollback [--to=<sha>]` | what `rollback` would take out of production, to the commit it would choose |
|
|
212
214
|
| `install-plan [--out=<file>\|-]` | what `install` needs, as JSON (default `<state dir>/install-plan.json`, 0600), and the root command to run |
|
|
213
215
|
| `attach <runId> --json [--from-seq=<n>] [--follow]` | the events of a run, from any point (machine mode, below) |
|
|
214
216
|
| `cancel <runId> [--first-only]` | SIGTERM to a detached run; a second `cancel` stops it at once (`--first-only` refuses instead) |
|
package/dist/cli.js
CHANGED
|
@@ -18,7 +18,7 @@ import { VERSION } from './version.js';
|
|
|
18
18
|
import { DeployLockedError } from './lock.js';
|
|
19
19
|
import { envValues, parseEnv } from './dotenv.js';
|
|
20
20
|
import { nodeHost } from './host.js';
|
|
21
|
-
import { envCommand, plan, refuseRoot, rollback, run, SKIPPABLE, status } from './pipeline.js';
|
|
21
|
+
import { commitsCommand, envCommand, plan, refuseRoot, rollback, run, SKIPPABLE, status } from './pipeline.js';
|
|
22
22
|
export const USAGE = `basalt-deploy — deploy this Basalt app on this server (RFC 0006)
|
|
23
23
|
|
|
24
24
|
As the app user, in the checkout (node node_modules/@basaltkit/deploy/dist/bin.js <command>):
|
|
@@ -31,6 +31,9 @@ As the app user, in the checkout (node node_modules/@basaltkit/deploy/dist/bin.j
|
|
|
31
31
|
env the .env and the dedicated infra only (first setup)
|
|
32
32
|
rollback [--to=<sha>] back to the last healthy release (code only); holds the commit it left
|
|
33
33
|
status the last releases, the process, the lock
|
|
34
|
+
commits --from=<sha> --to=<sha> | --rollback [--to=<sha>]
|
|
35
|
+
the commits between two releases, or what a rollback would take out
|
|
36
|
+
of production; read-only (no lock, no fetch)
|
|
34
37
|
install-plan [--out=<file>|-]
|
|
35
38
|
what install needs, as data (default <state dir>/install-plan.json);
|
|
36
39
|
prints the root command for install
|
|
@@ -57,7 +60,7 @@ Exit codes: 0 done · 1 failed (or refused) · 3 another deploy holds the lock
|
|
|
57
60
|
(a second signal ends the process at once: 130/129/143)
|
|
58
61
|
|
|
59
62
|
Machine mode (RFC 0008): stdout carries NDJSON events only
|
|
60
|
-
--json[=1] status, check, plan, run, env, rollback, install-plan, attach, cancel
|
|
63
|
+
--json[=1] status, check, plan, run, env, rollback, commits, install-plan, attach, cancel
|
|
61
64
|
--answers=stdin run/env: answer lines {"v":1,"type":"answer","id":"env.KEY","value":"…"} on stdin
|
|
62
65
|
--answer-timeout=<s> how long a prompt waits for its answer (1–3600, default 600)
|
|
63
66
|
--detach run/rollback: in their own session; returns the runId once the lock is held
|
|
@@ -118,7 +121,7 @@ function parse(argv) {
|
|
|
118
121
|
}
|
|
119
122
|
return { command, args, values, switches };
|
|
120
123
|
}
|
|
121
|
-
const COMMANDS = ['init', 'check', 'plan', 'run', 'env', 'rollback', 'status', 'install-plan', 'install', 'bootstrap', 'attach', 'cancel', 'ui'];
|
|
124
|
+
const COMMANDS = ['init', 'check', 'plan', 'run', 'env', 'rollback', 'status', 'commits', 'install-plan', 'install', 'bootstrap', 'attach', 'cancel', 'ui'];
|
|
122
125
|
/** The commands that take the deploy lock, and so write a run log under --json. */
|
|
123
126
|
const LOCKED = new Set(['run', 'env', 'rollback']);
|
|
124
127
|
const usage = (message, hint) => new DeployError(message, [], 'usage', hint);
|
|
@@ -407,6 +410,28 @@ function checkFlags(flags, json, env) {
|
|
|
407
410
|
if ((command === 'attach' || command === 'cancel') && !flags.args[0])
|
|
408
411
|
throw usage(`${command} <runId>`);
|
|
409
412
|
}
|
|
413
|
+
const SHA = /^[0-9a-f]{7,40}$/;
|
|
414
|
+
/** `commits`: two shas, or `--rollback` with the `--to` a rollback would take. */
|
|
415
|
+
function commitsRequest(flags) {
|
|
416
|
+
const sha = (name) => {
|
|
417
|
+
const value = flags.values.get(name);
|
|
418
|
+
if (value !== undefined && !SHA.test(value))
|
|
419
|
+
throw usage(`--${name}=${value}: a commit sha (7 to 40 lowercase hex digits)`);
|
|
420
|
+
return value;
|
|
421
|
+
};
|
|
422
|
+
const from = sha('from');
|
|
423
|
+
const to = sha('to');
|
|
424
|
+
if (flags.values.has('rollback'))
|
|
425
|
+
throw usage('--rollback is a switch: commits --rollback [--to=<sha>]');
|
|
426
|
+
if (flags.switches.has('rollback')) {
|
|
427
|
+
if (from !== undefined)
|
|
428
|
+
throw usage('commits --rollback takes no --from: it starts from what is deployed');
|
|
429
|
+
return { rollback: true, ...(to === undefined ? {} : { to }) };
|
|
430
|
+
}
|
|
431
|
+
if (from === undefined || to === undefined)
|
|
432
|
+
throw usage('commits --from=<sha> --to=<sha>, or commits --rollback [--to=<sha>]');
|
|
433
|
+
return { from, to };
|
|
434
|
+
}
|
|
410
435
|
/** The flags a detached child gets again — never an answer. */
|
|
411
436
|
function forwarded(flags) {
|
|
412
437
|
const out = [];
|
|
@@ -520,6 +545,7 @@ async function session(flags, host, cwd, reporter, machine) {
|
|
|
520
545
|
return await detach(ctx, detachRequest('rollback'), reporter);
|
|
521
546
|
return await rollback(ctx, flags.values.get('to'), options);
|
|
522
547
|
case 'status': return await status(ctx);
|
|
548
|
+
case 'commits': return await commitsCommand(ctx, commitsRequest(flags));
|
|
523
549
|
case 'install-plan': return await writeInstallPlan(host, ctx, cwd, flags.values.get('out'));
|
|
524
550
|
case 'attach': {
|
|
525
551
|
const runId = flags.args[0];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { DeployContext } from './context.js';
|
|
2
|
+
import { type CommitInfo, type Commits } from './protocol.js';
|
|
3
|
+
export declare const MAX_SUBJECT = 200;
|
|
4
|
+
export declare const MAX_AUTHOR = 100;
|
|
5
|
+
/** Per git call: a list of 50 capped commits is far below this; a huge one is cut, never read. */
|
|
6
|
+
export declare const MAX_GIT_OUTPUT_BYTES: number;
|
|
7
|
+
export declare const GIT_TIMEOUT_MS = 5000;
|
|
8
|
+
/** The plan's fetch reaches the network. */
|
|
9
|
+
export declare const FETCH_TIMEOUT_MS = 30000;
|
|
10
|
+
/** Where `plan` fetches the branch: never the tracking ref `run` merges from. Deleted after use. */
|
|
11
|
+
export declare const PREVIEW_REF = "refs/basalt-deploy/preview";
|
|
12
|
+
/** One line of the author's text: no escapes, controls, newlines or bidi overrides, at most `max` characters. */
|
|
13
|
+
export declare function cleanText(text: string, max: number): string;
|
|
14
|
+
/**
|
|
15
|
+
* `git log -z` with {@link FORMAT}: five fields per commit. A bad sha or a
|
|
16
|
+
* wrong field count is a parse that went wrong — the whole list is refused.
|
|
17
|
+
* A bad date is the author's to forge: only that date is dropped.
|
|
18
|
+
*/
|
|
19
|
+
export declare function parseLog(stdout: string): CommitInfo[] | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* What changes when the code goes from `from` to `to` (both full shas). The
|
|
22
|
+
* whole ancestry, never `--first-parent`: the commits a merge brings in go
|
|
23
|
+
* out too. Two lists, so a rewritten branch shows what it drops as well.
|
|
24
|
+
*/
|
|
25
|
+
export declare function commitRange(ctx: DeployContext, from: string, to: string): Promise<Commits>;
|
|
26
|
+
/** The subject of each commit, by sha, in one git call; undefined when git could not say. Missing commits are left out. */
|
|
27
|
+
export declare function commitSubjects(ctx: DeployContext, shas: string[]): Promise<Record<string, string> | undefined>;
|
|
28
|
+
/** The full sha of `rev`, a commit in this checkout; undefined when it is not one. */
|
|
29
|
+
export declare function resolveCommit(ctx: DeployContext, rev: string): Promise<string | undefined>;
|
|
30
|
+
/**
|
|
31
|
+
* What `run` would deploy, for `plan`: HEAD to the branch's tip on the
|
|
32
|
+
* remote. The tip is fetched into {@link PREVIEW_REF} — never into the
|
|
33
|
+
* tracking ref `run` merges from (`--refmap=` also stops git's
|
|
34
|
+
* opportunistic update of it) — and that ref is deleted again.
|
|
35
|
+
*/
|
|
36
|
+
export declare function incomingCommits(ctx: DeployContext, target: {
|
|
37
|
+
remote: string;
|
|
38
|
+
head: string;
|
|
39
|
+
}, skipFetch: boolean): Promise<Commits>;
|
package/dist/commits.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { sanitize } from './events.js';
|
|
2
|
+
import { COMMITS_LIMIT } from './protocol.js';
|
|
3
|
+
/**
|
|
4
|
+
* The commits between two releases, for the plan, the history and a rollback
|
|
5
|
+
* (RFC 0008 §4.3). Read-only and best effort: every function here returns
|
|
6
|
+
* "unavailable" with a reason instead of throwing, so a git that fails, hangs
|
|
7
|
+
* or prints too much never stops a deploy, a plan or a status.
|
|
8
|
+
*
|
|
9
|
+
* The text of a commit is the author's: data, never instructions. It is
|
|
10
|
+
* sanitised (escapes, controls, bidi) and capped here, and only ever rendered
|
|
11
|
+
* as plain text. git's own messages are never passed on: they can carry a
|
|
12
|
+
* remote URL with credentials.
|
|
13
|
+
*/
|
|
14
|
+
const FULL_SHA = /^[0-9a-f]{40}$/;
|
|
15
|
+
/** `%aI`: strict ISO-8601 with an offset. */
|
|
16
|
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[+-]\d{2}:\d{2}|Z)$/;
|
|
17
|
+
const BIDI = /[--]/g;
|
|
18
|
+
export const MAX_SUBJECT = 200;
|
|
19
|
+
export const MAX_AUTHOR = 100;
|
|
20
|
+
/** Per git call: a list of 50 capped commits is far below this; a huge one is cut, never read. */
|
|
21
|
+
export const MAX_GIT_OUTPUT_BYTES = 256 * 1024;
|
|
22
|
+
export const GIT_TIMEOUT_MS = 5_000;
|
|
23
|
+
/** The plan's fetch reaches the network. */
|
|
24
|
+
export const FETCH_TIMEOUT_MS = 30_000;
|
|
25
|
+
/** Where `plan` fetches the branch: never the tracking ref `run` merges from. Deleted after use. */
|
|
26
|
+
export const PREVIEW_REF = 'refs/basalt-deploy/preview';
|
|
27
|
+
/** No pager, colour, signature check, notes, mailmap or replace refs: the same plain output on every server. */
|
|
28
|
+
const GIT_CONFIG = ['-c', 'core.pager=cat', '-c', 'color.ui=false', '-c', 'log.showSignature=false', '-c', 'i18n.logOutputEncoding=UTF-8'];
|
|
29
|
+
const GIT_ENV = { GIT_OPTIONAL_LOCKS: '0', GIT_NO_REPLACE_OBJECTS: '1', GIT_PAGER: 'cat', GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_SSH_COMMAND: 'ssh -o BatchMode=yes' };
|
|
30
|
+
/** NUL between fields and (with `-z`) after each commit: no text of a commit can forge the framing. */
|
|
31
|
+
const FORMAT = '--format=%H%x00%P%x00%an%x00%aI%x00%s';
|
|
32
|
+
const LOG_FLAGS = ['--no-show-signature', '--no-notes', '--no-mailmap', '--no-decorate', '--no-color', '--topo-order', '-z', FORMAT];
|
|
33
|
+
async function git(ctx, args, timeoutMs = GIT_TIMEOUT_MS) {
|
|
34
|
+
let result;
|
|
35
|
+
try {
|
|
36
|
+
result = await ctx.host.exec('git', [...GIT_CONFIG, ...args], { cwd: ctx.dir, env: GIT_ENV, timeoutMs, maxOutputBytes: MAX_GIT_OUTPUT_BYTES });
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return { ok: false, reason: 'git-failed' };
|
|
40
|
+
}
|
|
41
|
+
if (result.limit)
|
|
42
|
+
return { ok: false, reason: result.limit };
|
|
43
|
+
return { ok: true, stdout: result.stdout, code: result.code };
|
|
44
|
+
}
|
|
45
|
+
/** One line of the author's text: no escapes, controls, newlines or bidi overrides, at most `max` characters. */
|
|
46
|
+
export function cleanText(text, max) {
|
|
47
|
+
const plain = sanitize(text).replace(BIDI, '').trim();
|
|
48
|
+
const chars = [...plain];
|
|
49
|
+
return chars.length <= max ? plain : `${chars.slice(0, max - 1).join('')}…`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* `git log -z` with {@link FORMAT}: five fields per commit. A bad sha or a
|
|
53
|
+
* wrong field count is a parse that went wrong — the whole list is refused.
|
|
54
|
+
* A bad date is the author's to forge: only that date is dropped.
|
|
55
|
+
*/
|
|
56
|
+
export function parseLog(stdout) {
|
|
57
|
+
const fields = stdout.split('\u0000');
|
|
58
|
+
if (fields.at(-1) === '')
|
|
59
|
+
fields.pop();
|
|
60
|
+
if (fields.length % 5 !== 0)
|
|
61
|
+
return undefined;
|
|
62
|
+
const commits = [];
|
|
63
|
+
for (let i = 0; i < fields.length; i += 5) {
|
|
64
|
+
const [sha, parents, author, at, subject] = fields.slice(i, i + 5);
|
|
65
|
+
const parentList = parents === '' ? [] : parents.split(' ');
|
|
66
|
+
if (!FULL_SHA.test(sha) || !parentList.every((p) => FULL_SHA.test(p)))
|
|
67
|
+
return undefined;
|
|
68
|
+
commits.push({
|
|
69
|
+
sha,
|
|
70
|
+
subject: cleanText(subject, MAX_SUBJECT),
|
|
71
|
+
author: cleanText(author, MAX_AUTHOR),
|
|
72
|
+
...(ISO_DATE.test(at) ? { at } : {}),
|
|
73
|
+
...(parentList.length > 1 ? { merge: true } : {}),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return commits;
|
|
77
|
+
}
|
|
78
|
+
async function list(ctx, include, exclude) {
|
|
79
|
+
const out = await git(ctx, ['log', ...LOG_FLAGS, `--max-count=${COMMITS_LIMIT}`, '--end-of-options', include, `^${exclude}`, '--']);
|
|
80
|
+
if (!out.ok)
|
|
81
|
+
return out.reason;
|
|
82
|
+
if (out.code !== 0)
|
|
83
|
+
return 'git-failed';
|
|
84
|
+
return parseLog(out.stdout) ?? 'malformed';
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* What changes when the code goes from `from` to `to` (both full shas). The
|
|
88
|
+
* whole ancestry, never `--first-parent`: the commits a merge brings in go
|
|
89
|
+
* out too. Two lists, so a rewritten branch shows what it drops as well.
|
|
90
|
+
*/
|
|
91
|
+
export async function commitRange(ctx, from, to) {
|
|
92
|
+
const unavailable = (reason) => ({ ok: false, reason });
|
|
93
|
+
if (!FULL_SHA.test(from) || !FULL_SHA.test(to))
|
|
94
|
+
return unavailable('malformed');
|
|
95
|
+
if (from === to)
|
|
96
|
+
return { ok: true, range: { from, to, relation: 'same', mergeBase: from, added: [], addedTotal: 0, removed: [], removedTotal: 0, truncated: false } };
|
|
97
|
+
// Below a shallow boundary the merge base and the counts are silently wrong.
|
|
98
|
+
const shallow = await git(ctx, ['rev-parse', '--is-shallow-repository']);
|
|
99
|
+
if (!shallow.ok)
|
|
100
|
+
return unavailable(shallow.reason);
|
|
101
|
+
if (shallow.code !== 0)
|
|
102
|
+
return unavailable('git-failed');
|
|
103
|
+
if (shallow.stdout.trim() === 'true')
|
|
104
|
+
return unavailable('shallow');
|
|
105
|
+
for (const sha of [from, to]) {
|
|
106
|
+
const exists = await git(ctx, ['cat-file', '-e', `${sha}^{commit}`]);
|
|
107
|
+
if (!exists.ok)
|
|
108
|
+
return unavailable(exists.reason);
|
|
109
|
+
// A sha a force-push and a gc took away, or never fetched here.
|
|
110
|
+
if (exists.code !== 0)
|
|
111
|
+
return unavailable('missing-commit');
|
|
112
|
+
}
|
|
113
|
+
const base = await git(ctx, ['merge-base', from, to]);
|
|
114
|
+
if (!base.ok)
|
|
115
|
+
return unavailable(base.reason);
|
|
116
|
+
if (base.code === 1)
|
|
117
|
+
return unavailable('unrelated');
|
|
118
|
+
const mergeBase = base.stdout.trim();
|
|
119
|
+
if (base.code !== 0 || !FULL_SHA.test(mergeBase))
|
|
120
|
+
return unavailable('git-failed');
|
|
121
|
+
const counts = await git(ctx, ['rev-list', '--left-right', '--count', '--end-of-options', `${from}...${to}`, '--']);
|
|
122
|
+
if (!counts.ok)
|
|
123
|
+
return unavailable(counts.reason);
|
|
124
|
+
const match = /^(\d+)\s+(\d+)$/.exec(counts.stdout.trim());
|
|
125
|
+
if (counts.code !== 0 || !match)
|
|
126
|
+
return unavailable('git-failed');
|
|
127
|
+
const removedTotal = Number(match[1]);
|
|
128
|
+
const addedTotal = Number(match[2]);
|
|
129
|
+
const added = addedTotal > 0 ? await list(ctx, to, from) : [];
|
|
130
|
+
if (typeof added === 'string')
|
|
131
|
+
return unavailable(added);
|
|
132
|
+
const removed = removedTotal > 0 ? await list(ctx, from, to) : [];
|
|
133
|
+
if (typeof removed === 'string')
|
|
134
|
+
return unavailable(removed);
|
|
135
|
+
const relation = addedTotal > 0 && removedTotal > 0 ? 'diverged' : addedTotal > 0 ? 'ahead' : removedTotal > 0 ? 'behind' : 'same';
|
|
136
|
+
return {
|
|
137
|
+
ok: true,
|
|
138
|
+
range: { from, to, relation, mergeBase, added, addedTotal, removed, removedTotal, truncated: added.length < addedTotal || removed.length < removedTotal },
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** The subject of each commit, by sha, in one git call; undefined when git could not say. Missing commits are left out. */
|
|
142
|
+
export async function commitSubjects(ctx, shas) {
|
|
143
|
+
const wanted = [...new Set(shas.filter((sha) => FULL_SHA.test(sha)))];
|
|
144
|
+
if (wanted.length === 0)
|
|
145
|
+
return {};
|
|
146
|
+
const out = await git(ctx, ['log', '--no-walk=unsorted', '--ignore-missing', ...LOG_FLAGS, '--end-of-options', ...wanted, '--']);
|
|
147
|
+
if (!out.ok || out.code !== 0)
|
|
148
|
+
return undefined;
|
|
149
|
+
const commits = parseLog(out.stdout);
|
|
150
|
+
if (!commits)
|
|
151
|
+
return undefined;
|
|
152
|
+
return Object.fromEntries(commits.map((c) => [c.sha, c.subject]));
|
|
153
|
+
}
|
|
154
|
+
/** The full sha of `rev`, a commit in this checkout; undefined when it is not one. */
|
|
155
|
+
export async function resolveCommit(ctx, rev) {
|
|
156
|
+
const out = await git(ctx, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${rev}^{commit}`]);
|
|
157
|
+
if (!out.ok || out.code !== 0)
|
|
158
|
+
return undefined;
|
|
159
|
+
const sha = out.stdout.trim();
|
|
160
|
+
return FULL_SHA.test(sha) ? sha : undefined;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* What `run` would deploy, for `plan`: HEAD to the branch's tip on the
|
|
164
|
+
* remote. The tip is fetched into {@link PREVIEW_REF} — never into the
|
|
165
|
+
* tracking ref `run` merges from (`--refmap=` also stops git's
|
|
166
|
+
* opportunistic update of it) — and that ref is deleted again.
|
|
167
|
+
*/
|
|
168
|
+
export async function incomingCommits(ctx, target, skipFetch) {
|
|
169
|
+
if (skipFetch)
|
|
170
|
+
return { ok: false, reason: 'skipped' };
|
|
171
|
+
const head = await resolveCommit(ctx, 'HEAD');
|
|
172
|
+
if (!head)
|
|
173
|
+
return { ok: false, reason: 'git-failed' };
|
|
174
|
+
const fetched = await git(ctx, ['fetch', '--quiet', '--no-tags', '--no-recurse-submodules', '--refmap=', '--', target.remote, `+${target.head}:${PREVIEW_REF}`], FETCH_TIMEOUT_MS);
|
|
175
|
+
try {
|
|
176
|
+
if (!fetched.ok)
|
|
177
|
+
return { ok: false, reason: fetched.reason === 'timeout' ? 'timeout' : 'not-fetched' };
|
|
178
|
+
if (fetched.code !== 0)
|
|
179
|
+
return { ok: false, reason: 'not-fetched' };
|
|
180
|
+
const tip = await resolveCommit(ctx, PREVIEW_REF);
|
|
181
|
+
if (!tip)
|
|
182
|
+
return { ok: false, reason: 'not-fetched' };
|
|
183
|
+
return await commitRange(ctx, head, tip);
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
await git(ctx, ['update-ref', '-d', PREVIEW_REF]);
|
|
187
|
+
}
|
|
188
|
+
}
|
package/dist/host.d.ts
CHANGED
|
@@ -198,11 +198,17 @@ export interface ExecOptions {
|
|
|
198
198
|
* here as decoded text, instead of going to the terminal (RFC 0008 §5.3).
|
|
199
199
|
*/
|
|
200
200
|
onOutput?: (text: string, stream: 'stdout' | 'stderr') => void;
|
|
201
|
+
/** Captured output only: the child is killed after this long (`limit: 'timeout'`). */
|
|
202
|
+
timeoutMs?: number;
|
|
203
|
+
/** Captured output only: the child is killed once stdout + stderr pass this many bytes (`limit: 'too-large'`). */
|
|
204
|
+
maxOutputBytes?: number;
|
|
201
205
|
}
|
|
202
206
|
export interface ExecResult {
|
|
203
207
|
code: number;
|
|
204
208
|
stdout: string;
|
|
205
209
|
stderr: string;
|
|
210
|
+
/** Set when `timeoutMs` or `maxOutputBytes` stopped the child: its output is partial. */
|
|
211
|
+
limit?: 'timeout' | 'too-large';
|
|
206
212
|
}
|
|
207
213
|
export interface TlsCertificate {
|
|
208
214
|
/** `subjectAltName` DNS names, lowercased (`*.example.com` included as written). */
|
package/dist/host.js
CHANGED
|
@@ -147,14 +147,42 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
147
147
|
child.stderr?.on('data', (chunk) => sink(decoders.stderr.write(chunk), 'stderr'));
|
|
148
148
|
}
|
|
149
149
|
else {
|
|
150
|
-
|
|
151
|
-
|
|
150
|
+
const max = options.maxOutputBytes;
|
|
151
|
+
let bytes = 0;
|
|
152
|
+
const capture = (key) => (chunk) => {
|
|
153
|
+
if (limit)
|
|
154
|
+
return;
|
|
155
|
+
bytes += chunk.length;
|
|
156
|
+
if (max !== undefined && bytes > max) {
|
|
157
|
+
stop('too-large');
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const text = max === undefined ? chunk.toString() : decoders[key].write(chunk);
|
|
161
|
+
if (key === 'stdout')
|
|
162
|
+
stdout += text;
|
|
163
|
+
else
|
|
164
|
+
stderr += text;
|
|
165
|
+
};
|
|
166
|
+
child.stdout?.on('data', capture('stdout'));
|
|
167
|
+
child.stderr?.on('data', capture('stderr'));
|
|
152
168
|
}
|
|
169
|
+
let limit;
|
|
170
|
+
const stop = (why) => {
|
|
171
|
+
if (limit)
|
|
172
|
+
return;
|
|
173
|
+
limit = why;
|
|
174
|
+
child.kill('SIGKILL');
|
|
175
|
+
};
|
|
176
|
+
const timer = options.timeoutMs !== undefined && !sink && !options.stream && !options.interactive
|
|
177
|
+
? setTimeout(() => stop('timeout'), options.timeoutMs)
|
|
178
|
+
: undefined;
|
|
153
179
|
let finished = false;
|
|
154
180
|
const done = (code) => {
|
|
155
181
|
if (finished)
|
|
156
182
|
return;
|
|
157
183
|
finished = true;
|
|
184
|
+
if (timer)
|
|
185
|
+
clearTimeout(timer);
|
|
158
186
|
if (fd !== undefined)
|
|
159
187
|
closeSync(fd);
|
|
160
188
|
if (sink) {
|
|
@@ -164,7 +192,14 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
164
192
|
sink(decoders.stdout.end(), 'stdout');
|
|
165
193
|
sink(decoders.stderr.end(), 'stderr');
|
|
166
194
|
}
|
|
167
|
-
|
|
195
|
+
if (!sink && options.maxOutputBytes !== undefined && !limit) {
|
|
196
|
+
stdout += decoders.stdout.end();
|
|
197
|
+
stderr += decoders.stderr.end();
|
|
198
|
+
}
|
|
199
|
+
if (limit)
|
|
200
|
+
resolve({ code: code === 0 ? 1 : code, stdout, stderr, limit });
|
|
201
|
+
else
|
|
202
|
+
resolve({ code, stdout, stderr });
|
|
168
203
|
};
|
|
169
204
|
child.on('error', (error) => { stderr += error.message; done(127); });
|
|
170
205
|
child.on('close', (code) => done(code ?? 1));
|
package/dist/pipeline.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type DeployContext, type Finding } from './context.js';
|
|
2
|
+
import type { Commits } from './protocol.js';
|
|
2
3
|
import { type PackageStatus } from './system.js';
|
|
3
4
|
/**
|
|
4
5
|
* The pipeline (RFC 0006 §4): preflight → fetch → env → infra → build →
|
|
@@ -91,9 +92,24 @@ export declare function backupDecision(config: DeployContext['config'], values:
|
|
|
91
92
|
why: string;
|
|
92
93
|
};
|
|
93
94
|
export declare function plan(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
95
|
+
/** One line for the terminal; the list itself is in the result (--json). */
|
|
96
|
+
export declare function describeCommits(commits: Commits): string;
|
|
94
97
|
/** `basalt-deploy env` — the .env and the infra only (first setup, before `install`). */
|
|
95
98
|
export declare function envCommand(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
96
99
|
export declare function run(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
97
100
|
/** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
|
|
98
101
|
export declare function rollback(ctx: DeployContext, to?: string, options?: RunOptions): Promise<number>;
|
|
99
102
|
export declare function status(ctx: DeployContext): Promise<number>;
|
|
103
|
+
/**
|
|
104
|
+
* `basalt-deploy commits --from=<sha> --to=<sha>` — what changed between two
|
|
105
|
+
* commits; `commits --rollback [--to=<sha>]` — what `rollback` would take
|
|
106
|
+
* out of production, to the commit it would choose. Read-only: no lock, no
|
|
107
|
+
* fetch. A list it cannot get is an answer (`unavailable`), not a failure.
|
|
108
|
+
*/
|
|
109
|
+
export declare function commitsCommand(ctx: DeployContext, request: {
|
|
110
|
+
from: string;
|
|
111
|
+
to: string;
|
|
112
|
+
} | {
|
|
113
|
+
rollback: true;
|
|
114
|
+
to?: string;
|
|
115
|
+
}): Promise<number>;
|
package/dist/pipeline.js
CHANGED
|
@@ -12,7 +12,8 @@ import { envValues } from './dotenv.js';
|
|
|
12
12
|
import { applyInfra, describeInfra, dockerPostgres, maintainServices, planInfra } from './infra.js';
|
|
13
13
|
import { appRoleOf, describeServices, dumpContainer, dumpUrlKey, externalOf, externalPostgres, grantTenantSchemas } from './services.js';
|
|
14
14
|
import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
|
|
15
|
-
import { clearHold,
|
|
15
|
+
import { clearHold, migrationNames, readHold, readReleases, recordRelease, rollbackTarget, writeHold } from './state.js';
|
|
16
|
+
import { commitRange, commitSubjects, incomingCommits, resolveCommit } from './commits.js';
|
|
16
17
|
import { acquireLock, describeHolder, readLock } from './lock.js';
|
|
17
18
|
import { auditOf } from './audit.js';
|
|
18
19
|
import { questionDescriptors } from './env-step.js';
|
|
@@ -534,6 +535,8 @@ export async function plan(ctx, options = {}) {
|
|
|
534
535
|
const { host, config, pm } = ctx;
|
|
535
536
|
const blocking = errors([...checked.findings, ...infra.findings]).length > 0;
|
|
536
537
|
const lines = await stepped(ctx, 'plan', async () => planLines(ctx, options, checked, env, infra), 'plan — nothing below has run');
|
|
538
|
+
const commits = await planCommits(ctx, options);
|
|
539
|
+
host.out.info(describeCommits(commits));
|
|
537
540
|
host.out.result?.('plan', {
|
|
538
541
|
findings: [...checked.findings, ...infra.findings],
|
|
539
542
|
lines: lines.map((line) => {
|
|
@@ -543,9 +546,31 @@ export async function plan(ctx, options = {}) {
|
|
|
543
546
|
// What env/run would ask now — the deploy's own environment answers first, as it does there.
|
|
544
547
|
questions: questionDescriptors(config, env.questions.filter((key) => host.env[key] === undefined)),
|
|
545
548
|
blocking,
|
|
549
|
+
commits,
|
|
546
550
|
});
|
|
547
551
|
return blocking ? 1 : 0;
|
|
548
552
|
}
|
|
553
|
+
/** What a run would deploy, marked when a rollback held that commit. Never a finding: a list it cannot get stops nothing. */
|
|
554
|
+
async function planCommits(ctx, options) {
|
|
555
|
+
const commits = await incomingCommits(ctx, gitTarget(ctx), options.skip?.includes('fetch') ?? false);
|
|
556
|
+
if (!commits.ok)
|
|
557
|
+
return commits;
|
|
558
|
+
const hold = await readHold(ctx);
|
|
559
|
+
return hold?.sha === commits.range.to && commits.range.relation !== 'same' ? { ok: true, range: { ...commits.range, held: true } } : commits;
|
|
560
|
+
}
|
|
561
|
+
/** One line for the terminal; the list itself is in the result (--json). */
|
|
562
|
+
export function describeCommits(commits) {
|
|
563
|
+
if (!commits.ok)
|
|
564
|
+
return `commits: the list is unavailable (${commits.reason})`;
|
|
565
|
+
const { range } = commits;
|
|
566
|
+
const span = `${range.from.slice(0, 7)} → ${range.to.slice(0, 7)}`;
|
|
567
|
+
switch (range.relation) {
|
|
568
|
+
case 'same': return `commits: nothing new (${range.to.slice(0, 7)})`;
|
|
569
|
+
case 'ahead': return `commits: ${range.addedTotal} to go out (${span})${range.held ? ' — held by a rollback' : ''}`;
|
|
570
|
+
case 'behind': return `commits: ${range.removedTotal} would leave (${span})`;
|
|
571
|
+
case 'diverged': return `commits: the branch was rewritten — ${range.addedTotal} new, ${range.removedTotal} only here (${span}); run refuses it (--ff-only)`;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
549
574
|
/** What `plan` prints, one line per thing a run would do. */
|
|
550
575
|
function planLines(ctx, options, checked, env, infra) {
|
|
551
576
|
const { host, config, pm } = ctx;
|
|
@@ -827,7 +852,7 @@ async function rollbackLocked(ctx, to, options) {
|
|
|
827
852
|
}
|
|
828
853
|
// The last healthy release before this one; on the first recorded deploy,
|
|
829
854
|
// the commit it was deployed over.
|
|
830
|
-
const target =
|
|
855
|
+
const target = rollbackTarget(releases, current, wanted);
|
|
831
856
|
if (!target || target === current)
|
|
832
857
|
throw new DeployError('no earlier release to go back to; pass --to=<sha>');
|
|
833
858
|
const document = await readEnv(ctx);
|
|
@@ -905,7 +930,49 @@ export async function status(ctx) {
|
|
|
905
930
|
hold: hold ?? null,
|
|
906
931
|
releases,
|
|
907
932
|
process: running,
|
|
933
|
+
...await subjectsOf(ctx, releases),
|
|
908
934
|
});
|
|
909
935
|
}
|
|
910
936
|
return 0;
|
|
911
937
|
}
|
|
938
|
+
async function subjectsOf(ctx, releases) {
|
|
939
|
+
const subjects = await commitSubjects(ctx, releases.map((r) => r.sha));
|
|
940
|
+
return subjects ? { subjects } : {};
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* `basalt-deploy commits --from=<sha> --to=<sha>` — what changed between two
|
|
944
|
+
* commits; `commits --rollback [--to=<sha>]` — what `rollback` would take
|
|
945
|
+
* out of production, to the commit it would choose. Read-only: no lock, no
|
|
946
|
+
* fetch. A list it cannot get is an answer (`unavailable`), not a failure.
|
|
947
|
+
*/
|
|
948
|
+
export async function commitsCommand(ctx, request) {
|
|
949
|
+
const { host } = ctx;
|
|
950
|
+
let result;
|
|
951
|
+
if ('rollback' in request) {
|
|
952
|
+
const current = await resolveCommit(ctx, 'HEAD');
|
|
953
|
+
const wanted = request.to === undefined ? undefined : await resolveCommit(ctx, request.to);
|
|
954
|
+
const target = current && (request.to === undefined || wanted) ? rollbackTarget(await readReleases(ctx), current, wanted) : undefined;
|
|
955
|
+
result = {
|
|
956
|
+
purpose: 'rollback',
|
|
957
|
+
...(current ? { from: current } : {}),
|
|
958
|
+
...(target ? { to: target } : {}),
|
|
959
|
+
commits: !current ? { ok: false, reason: 'git-failed' }
|
|
960
|
+
: request.to !== undefined && !wanted ? { ok: false, reason: 'missing-commit' }
|
|
961
|
+
: !target || target === current ? { ok: false, reason: 'no-previous' }
|
|
962
|
+
: await commitRange(ctx, current, target),
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
else {
|
|
966
|
+
const [from, to] = [await resolveCommit(ctx, request.from), await resolveCommit(ctx, request.to)];
|
|
967
|
+
result = { purpose: 'range', ...(from ? { from } : {}), ...(to ? { to } : {}), commits: from && to ? await commitRange(ctx, from, to) : { ok: false, reason: 'missing-commit' } };
|
|
968
|
+
}
|
|
969
|
+
host.out.info(describeCommits(result.commits));
|
|
970
|
+
if (result.commits.ok) {
|
|
971
|
+
for (const [label, list] of [['+', result.commits.range.added], ['-', result.commits.range.removed]]) {
|
|
972
|
+
for (const c of list)
|
|
973
|
+
host.out.info(`${label} ${c.sha.slice(0, 7)} ${c.subject} (${c.author}${c.at ? `, ${c.at}` : ''})${c.merge ? ' [merge]' : ''}`);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
host.out.result?.('commits', result);
|
|
977
|
+
return 0;
|
|
978
|
+
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -61,6 +61,56 @@ export interface Hold {
|
|
|
61
61
|
actor: string;
|
|
62
62
|
note: string;
|
|
63
63
|
}
|
|
64
|
+
/** The most commits a list carries; the totals say how many there were. */
|
|
65
|
+
export declare const COMMITS_LIMIT = 50;
|
|
66
|
+
/**
|
|
67
|
+
* One commit, as the server read it from git. Every string is the author's
|
|
68
|
+
* text: data, never instructions — sanitised and capped by the deploy, and
|
|
69
|
+
* rendered as plain text.
|
|
70
|
+
*/
|
|
71
|
+
export interface CommitInfo {
|
|
72
|
+
sha: string;
|
|
73
|
+
subject: string;
|
|
74
|
+
author: string;
|
|
75
|
+
/** ISO-8601, as the author's commit states it (absent when it does not parse). */
|
|
76
|
+
at?: string;
|
|
77
|
+
/** A merge commit (more than one parent). */
|
|
78
|
+
merge?: true;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* `same`: nothing changes. `ahead`: `to` only adds commits (a fast-forward).
|
|
82
|
+
* `behind`: `to` only removes commits (a rollback). `diverged`: both — the
|
|
83
|
+
* branch was rewritten (`run` refuses it: its merge is `--ff-only`).
|
|
84
|
+
*/
|
|
85
|
+
export type CommitRelation = 'same' | 'ahead' | 'behind' | 'diverged';
|
|
86
|
+
/** What changes when the code goes from `from` to `to`. */
|
|
87
|
+
export interface CommitRange {
|
|
88
|
+
from: string;
|
|
89
|
+
to: string;
|
|
90
|
+
relation: CommitRelation;
|
|
91
|
+
mergeBase?: string;
|
|
92
|
+
/** In `to`, not in `from` (`git log to ^from`): what goes out. Newest first, at most {@link COMMITS_LIMIT}. */
|
|
93
|
+
added: CommitInfo[];
|
|
94
|
+
addedTotal: number;
|
|
95
|
+
/** In `from`, not in `to`: what leaves. Newest first, at most {@link COMMITS_LIMIT}. */
|
|
96
|
+
removed: CommitInfo[];
|
|
97
|
+
removedTotal: number;
|
|
98
|
+
/** A list holds fewer commits than its total. */
|
|
99
|
+
truncated: boolean;
|
|
100
|
+
/** Plan only: `to` is the commit a rollback held — `run` refuses it without `--unhold`. */
|
|
101
|
+
held?: true;
|
|
102
|
+
}
|
|
103
|
+
/** Why there is no list. Never git's own message: it can carry a URL with credentials. */
|
|
104
|
+
export declare const COMMITS_UNAVAILABLE: readonly ['skipped', 'not-fetched', 'no-previous', 'missing-commit', 'shallow', 'unrelated', 'timeout', 'too-large', 'malformed', 'git-failed'];
|
|
105
|
+
export type CommitsUnavailable = typeof COMMITS_UNAVAILABLE[number];
|
|
106
|
+
/** A list of commits, or why there is none: getting it never stops a command. */
|
|
107
|
+
export type Commits = {
|
|
108
|
+
ok: true;
|
|
109
|
+
range: CommitRange;
|
|
110
|
+
} | {
|
|
111
|
+
ok: false;
|
|
112
|
+
reason: CommitsUnavailable;
|
|
113
|
+
};
|
|
64
114
|
export type PlanProxy = {
|
|
65
115
|
kind: 'none';
|
|
66
116
|
} | {
|
|
@@ -216,6 +266,8 @@ export interface StatusResult {
|
|
|
216
266
|
hold: Hold | null;
|
|
217
267
|
/** The last 10, newest first. */
|
|
218
268
|
releases: Release[];
|
|
269
|
+
/** The subject of each release's commit, by sha (`--json` only; absent when git could not say). */
|
|
270
|
+
subjects?: Record<string, string>;
|
|
219
271
|
process: {
|
|
220
272
|
kind: 'pm2';
|
|
221
273
|
name: string;
|
|
@@ -245,6 +297,16 @@ export interface PlanResult {
|
|
|
245
297
|
questions: PromptDescriptor[];
|
|
246
298
|
/** `plan` exits 1. */
|
|
247
299
|
blocking: boolean;
|
|
300
|
+
/** What a run would deploy: from the checkout's HEAD to the branch's tip on the remote. */
|
|
301
|
+
commits?: Commits;
|
|
302
|
+
}
|
|
303
|
+
/** `commits`: the commits between two releases, or what a rollback would take out of production. */
|
|
304
|
+
export interface CommitsResult {
|
|
305
|
+
/** `range`: `--from`/`--to`. `rollback`: from HEAD to the commit `rollback` would go back to. */
|
|
306
|
+
purpose: 'range' | 'rollback';
|
|
307
|
+
from?: string;
|
|
308
|
+
to?: string;
|
|
309
|
+
commits: Commits;
|
|
248
310
|
}
|
|
249
311
|
export interface RunResult {
|
|
250
312
|
sha: string;
|
|
@@ -297,6 +359,7 @@ export interface ResultPayloads {
|
|
|
297
359
|
env: EnvResult;
|
|
298
360
|
cancel: CancelResult;
|
|
299
361
|
'install-plan': InstallPlanResult;
|
|
362
|
+
commits: CommitsResult;
|
|
300
363
|
}
|
|
301
364
|
export type ResultCommand = keyof ResultPayloads;
|
|
302
365
|
export type ResultEvent = Envelope & {
|
package/dist/protocol.js
CHANGED
|
@@ -7,6 +7,13 @@
|
|
|
7
7
|
* import that runs code. A program that drives the CLI (the phase-2 local UI)
|
|
8
8
|
* imports it as `@basaltkit/deploy/protocol` without loading the CLI.
|
|
9
9
|
*/
|
|
10
|
+
/** The most commits a list carries; the totals say how many there were. */
|
|
11
|
+
export const COMMITS_LIMIT = 50;
|
|
12
|
+
/** Why there is no list. Never git's own message: it can carry a URL with credentials. */
|
|
13
|
+
export const COMMITS_UNAVAILABLE = [
|
|
14
|
+
'skipped', 'not-fetched', 'no-previous', 'missing-commit', 'shallow', 'unrelated',
|
|
15
|
+
'timeout', 'too-large', 'malformed', 'git-failed',
|
|
16
|
+
];
|
|
10
17
|
/** The protocol version: `--json` and `--json=1`. */
|
|
11
18
|
export const PROTOCOL_VERSION = 1;
|
|
12
19
|
/** The steps a command reports, a closed set (`step-start`/`step-end`). */
|
package/dist/state.d.ts
CHANGED
|
@@ -24,6 +24,12 @@ export declare function lastGood(releases: Release[], except: string): Release |
|
|
|
24
24
|
* unhealthy. `undefined` when there is none: the caller asks for `--to`.
|
|
25
25
|
*/
|
|
26
26
|
export declare function deployedOver(releases: Release[], current: string): string | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* The commit `rollback` goes back to: the one asked for, else the last
|
|
29
|
+
* healthy release before `current`, else the commit `current` was deployed
|
|
30
|
+
* over. What `rollback` does and what `commits --rollback` previews.
|
|
31
|
+
*/
|
|
32
|
+
export declare function rollbackTarget(releases: Release[], current: string, wanted?: string): string | undefined;
|
|
27
33
|
export declare const holdFile: (ctx: DeployContext) => string;
|
|
28
34
|
/** The hold — from `<stateDir>/hold.json`, else (after `install`) the checkout's `.basalt/hold.json`, like the release history. */
|
|
29
35
|
export declare function readHold(ctx: DeployContext): Promise<Hold | undefined>;
|
package/dist/state.js
CHANGED
|
@@ -61,6 +61,14 @@ export function deployedOver(releases, current) {
|
|
|
61
61
|
return undefined;
|
|
62
62
|
return target;
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* The commit `rollback` goes back to: the one asked for, else the last
|
|
66
|
+
* healthy release before `current`, else the commit `current` was deployed
|
|
67
|
+
* over. What `rollback` does and what `commits --rollback` previews.
|
|
68
|
+
*/
|
|
69
|
+
export function rollbackTarget(releases, current, wanted) {
|
|
70
|
+
return wanted ?? lastGood(releases, current)?.sha ?? deployedOver(releases, current);
|
|
71
|
+
}
|
|
64
72
|
export const holdFile = (ctx) => join(ctx.stateDir, 'hold.json');
|
|
65
73
|
/** Where the hold was kept before `install` moved the state out of the checkout. */
|
|
66
74
|
const legacyHold = (ctx) => join(ctx.dir, '.basalt', 'hold.json');
|