@basaltkit/deploy 0.2.1 → 0.3.1

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/dist/checks.js CHANGED
@@ -49,11 +49,11 @@ export async function tlsFindings(ctx) {
49
49
  }
50
50
  return findings;
51
51
  }
52
- function minimumVersion(range) {
52
+ export function minimumVersion(range) {
53
53
  const match = range ? /(\d+)\.(\d+)(?:\.(\d+))?/.exec(range) : null;
54
54
  return match ? [Number(match[1]), Number(match[2]), Number(match[3] ?? 0)] : undefined;
55
55
  }
56
- const below = (version, minimum) => {
56
+ export const below = (version, minimum) => {
57
57
  for (let i = 0; i < 3; i++) {
58
58
  if ((version[i] ?? 0) !== (minimum[i] ?? 0))
59
59
  return (version[i] ?? 0) < (minimum[i] ?? 0);
package/dist/cli.js CHANGED
@@ -1,12 +1,21 @@
1
1
  import { createRequire } from 'node:module';
2
2
  import { isAbsolute, join, resolve } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
+ import { bootstrap } from './bootstrap.js';
5
+ import { check } from './check.js';
6
+ import { init } from './init.js';
4
7
  import { applyOverrides, DeployConfigError, parseOverrides, validateConfig } from './config.js';
5
8
  import { DeployError, detectPackageManager, resolveStateDir } from './context.js';
6
9
  import { nodeHost } from './host.js';
7
10
  import { envCommand, install, plan, rollback, run, SKIPPABLE, status } from './pipeline.js';
8
11
  export const USAGE = `basalt-deploy — deploy this Basalt app on this server (RFC 0006)
9
12
 
13
+ basalt-deploy init --domain=<host> [--tenants=subdomain|none] [--branch=<b>] [--proxy=apache|caddy|none] [--server]
14
+ writes deploy.config.ts from the project (and, with --server, this server)
15
+ sudo "$(command -v node)" node_modules/@basaltkit/deploy/dist/bin.js bootstrap --user=<name> [--dry-run]
16
+ a fresh Ubuntu/Debian server, once: Docker, Node, pnpm, swap, ufw,
17
+ Caddy; then pnpm install, env and install for that user
18
+ basalt-deploy check the config is valid and types check; no server needed
10
19
  basalt-deploy plan what a run would do; changes nothing
11
20
  basalt-deploy run fetch, .env, infra, build, backup, migrate, restart, health
12
21
  basalt-deploy env the .env and the dedicated infra only (first setup)
@@ -98,8 +107,32 @@ export async function main(argv, host = nodeHost(), cwd = process.cwd()) {
98
107
  if (flags.switches.has('no-fetch'))
99
108
  skip.push('fetch');
100
109
  try {
101
- let config = await loadConfig(cwd, flags.values.get('config') ?? 'deploy.config.ts');
110
+ const file = flags.values.get('config') ?? 'deploy.config.ts';
111
+ if (flags.command === 'bootstrap') {
112
+ // Runs before node_modules exist: the config only when it loads.
113
+ const config = await loadConfig(cwd, file).catch(() => undefined);
114
+ const proxy = flags.values.get('proxy') ?? config?.proxy?.kind ?? 'none';
115
+ if (proxy !== 'apache' && proxy !== 'caddy' && proxy !== 'none')
116
+ throw new DeployError('--proxy is apache, caddy or none');
117
+ return await bootstrap(host, cwd, {
118
+ user: flags.values.get('user') ?? host.env['SUDO_USER'],
119
+ proxy,
120
+ swapGb: Number(flags.values.get('swap-gb') ?? config?.bootstrap?.swapGb ?? 4),
121
+ firewall: !flags.switches.has('no-firewall') && config?.bootstrap?.firewall !== false,
122
+ dryRun: flags.switches.has('dry-run'),
123
+ });
124
+ }
125
+ if (flags.command === 'init') {
126
+ const written = await init(host, cwd, flags.values, flags.switches);
127
+ if (written !== 0)
128
+ return written;
129
+ const created = validateConfig(await loadConfig(cwd, file));
130
+ return await check(host, cwd, file, created);
131
+ }
132
+ let config = await loadConfig(cwd, file);
102
133
  validateConfig(config);
134
+ if (flags.command === 'check')
135
+ return await check(host, cwd, file, config);
103
136
  const overridesPath = flags.values.get('overrides') ?? `/etc/basalt/${config.app}.json`;
104
137
  const overrides = await host.readFile(overridesPath);
105
138
  if (overrides !== undefined)
package/dist/compose.d.ts CHANGED
@@ -20,6 +20,20 @@ interface ServiceState {
20
20
  /** `docker compose ps` of the project, one entry per container. */
21
21
  export declare function composeServices(ctx: DeployContext, sha: string): Promise<ServiceState[] | undefined>;
22
22
  export declare function composePreflight(ctx: DeployContext, sha: string): Promise<Finding[]>;
23
+ /**
24
+ * Containers the project does not own, on its networks (RFC 0007 §4.3). The
25
+ * networks exist once the project does: on a fresh server it is created first
26
+ * (`up --no-start`), with this commit's images.
27
+ */
28
+ export declare function attachContainers(ctx: DeployContext, sha: string): Promise<string[]>;
29
+ /**
30
+ * Volumes the compose file declares `external` (data meant to outlive the
31
+ * project, e.g. ClamAV signatures) are created empty when missing — compose
32
+ * refuses to start, or to run a job, without them.
33
+ */
34
+ export declare function externalVolumes(ctx: DeployContext, sha: string): Promise<string[]>;
35
+ /** The one-off jobs, before `up` (RFC 0007 §4.4); a failure stops the release before anything is replaced. */
36
+ export declare function runJobs(ctx: DeployContext, sha: string): Promise<string[]>;
23
37
  /** `docker build` of every image not built yet for this commit. */
24
38
  export declare function composeBuild(ctx: DeployContext, sha: string): Promise<void>;
25
39
  export declare function composeRelease(ctx: DeployContext, sha: string): Promise<string>;
@@ -36,5 +50,7 @@ export declare function composeHealthy(ctx: DeployContext, sha: string): Promise
36
50
  }>;
37
51
  /** Removes `<tag>:<sha>` of the configured images for commits outside `keep`. Nothing else. */
38
52
  export declare function pruneImages(ctx: DeployContext, keep: string[]): Promise<string[]>;
53
+ /** Text from `verify.logs` in a service's logs since `since` (RFC 0007 §6). */
54
+ export declare function logFindings(ctx: DeployContext, sha: string, since: Date): Promise<string[]>;
39
55
  export declare function composeStatus(ctx: DeployContext, sha: string): Promise<string[]>;
40
56
  export {};
package/dist/compose.js CHANGED
@@ -55,6 +55,9 @@ export async function composePreflight(ctx, sha) {
55
55
  if (config.code !== 0) {
56
56
  findings.push({ id: 'compose', level: 'error', message: `docker compose rejects ${rt.file}: ${config.stderr.trim().split('\n')[0] ?? ''}` });
57
57
  }
58
+ else {
59
+ findings.push(...await nameFindings(ctx, sha));
60
+ }
58
61
  // C1 under compose: the published port belongs to docker-proxy (root), so a
59
62
  // listener with no visible pid is not foreign by itself — it is ours when
60
63
  // the upstream service of THIS project publishes it.
@@ -73,6 +76,121 @@ export async function composePreflight(ctx, sha) {
73
76
  }
74
77
  return findings;
75
78
  }
79
+ /**
80
+ * Every service and container the config names exists — names no type can
81
+ * know. An unknown one is an error that lists the ones that do exist.
82
+ */
83
+ async function nameFindings(ctx, sha) {
84
+ const rt = composeOf(ctx);
85
+ const listed = await ctx.host.exec('docker', composeArgs(ctx, 'config', '--services'), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
86
+ const services = listed.stdout.split('\n').map((s) => s.trim()).filter(Boolean);
87
+ if (listed.code !== 0 || services.length === 0)
88
+ return [];
89
+ const findings = [];
90
+ const named = [
91
+ ['runtime.upstream.service', rt.upstream.service],
92
+ ...(rt.jobs ?? []).map((j) => ['runtime.jobs[].service', j.service]),
93
+ ...Object.keys(ctx.config.verify?.logs ?? {}).map((s) => ['verify.logs', s]),
94
+ ];
95
+ for (const [where, name] of named) {
96
+ if (services.includes(name))
97
+ continue;
98
+ const near = services.find((s) => s.startsWith(name.slice(0, 3)) || name.startsWith(s.slice(0, 3)));
99
+ findings.push({ id: 'compose', level: 'error', message: `${where}: "${name}" is not a service of ${rt.file}${near ? ` — did you mean "${near}"?` : ''} (services: ${services.join(', ')})` });
100
+ }
101
+ for (const container of Object.keys(rt.attach ?? {})) {
102
+ const state = await ctx.host.exec('docker', ['inspect', '--format', '{{.State.Running}}', container]);
103
+ if (state.stdout.trim() !== 'true') {
104
+ findings.push(state.code === 0
105
+ ? { id: 'compose', level: 'error', message: `runtime.attach: ${container} is not running`, fix: `docker start ${container}` }
106
+ : { id: 'compose', level: 'error', message: `runtime.attach: ${container} does not exist` });
107
+ }
108
+ }
109
+ return findings;
110
+ }
111
+ /**
112
+ * Containers the project does not own, on its networks (RFC 0007 §4.3). The
113
+ * networks exist once the project does: on a fresh server it is created first
114
+ * (`up --no-start`), with this commit's images.
115
+ */
116
+ export async function attachContainers(ctx, sha) {
117
+ const attach = composeOf(ctx).attach ?? {};
118
+ const pairs = Object.entries(attach).flatMap(([container, networks]) => networks.map((n) => ({ container, network: `${ctx.config.app}_${n}` })));
119
+ if (pairs.length === 0)
120
+ return [];
121
+ const exists = async (network) => (await ctx.host.exec('docker', ['network', 'inspect', network, '--format', '{{range .Containers}}{{.Name}} {{end}}'])).code === 0;
122
+ const missing = [];
123
+ for (const network of new Set(pairs.map((p) => p.network)))
124
+ if (!(await exists(network)))
125
+ missing.push(network);
126
+ if (missing.length > 0) {
127
+ const created = await ctx.host.exec('docker', composeArgs(ctx, 'up', '--no-start'), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
128
+ if (created.code !== 0)
129
+ throw new DeployError(`creating the ${ctx.config.app} project for its networks (${missing.join(', ')}): ${created.stderr.trim().split('\n')[0] ?? ''}`);
130
+ }
131
+ const connected = [];
132
+ for (const { container, network } of pairs) {
133
+ const members = await ctx.host.exec('docker', ['network', 'inspect', network, '--format', '{{range .Containers}}{{.Name}} {{end}}']);
134
+ if (members.code !== 0)
135
+ throw new DeployError(`network ${network} does not exist — is "${network.slice(ctx.config.app.length + 1)}" a network of ${composeOf(ctx).file}?`);
136
+ if (members.stdout.split(/\s+/).includes(container))
137
+ continue;
138
+ const connect = await ctx.host.exec('docker', ['network', 'connect', network, container]);
139
+ if (connect.code !== 0)
140
+ throw new DeployError(`docker network connect ${network} ${container}: ${connect.stderr.trim().split('\n')[0] ?? ''}`);
141
+ connected.push(`${container} → ${network}`);
142
+ }
143
+ return connected.length ? [`attached: ${connected.join(', ')}`] : [];
144
+ }
145
+ /**
146
+ * Volumes the compose file declares `external` (data meant to outlive the
147
+ * project, e.g. ClamAV signatures) are created empty when missing — compose
148
+ * refuses to start, or to run a job, without them.
149
+ */
150
+ export async function externalVolumes(ctx, sha) {
151
+ const config = await ctx.host.exec('docker', composeArgs(ctx, 'config', '--format', 'json'), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
152
+ if (config.code !== 0)
153
+ return [];
154
+ let parsed = {};
155
+ try {
156
+ parsed = JSON.parse(config.stdout);
157
+ }
158
+ catch {
159
+ return [];
160
+ }
161
+ const created = [];
162
+ for (const [key, volume] of Object.entries(parsed.volumes ?? {})) {
163
+ if (!volume.external)
164
+ continue;
165
+ const name = volume.name ?? key;
166
+ if ((await ctx.host.exec('docker', ['volume', 'inspect', name])).code === 0)
167
+ continue;
168
+ const made = await ctx.host.exec('docker', ['volume', 'create', name]);
169
+ if (made.code !== 0)
170
+ throw new DeployError(`docker volume create ${name}: ${made.stderr.trim().split('\n')[0] ?? ''}`);
171
+ created.push(name);
172
+ }
173
+ return created.length ? [`external volume(s) created: ${created.join(', ')}`] : [];
174
+ }
175
+ /** The one-off jobs, before `up` (RFC 0007 §4.4); a failure stops the release before anything is replaced. */
176
+ export async function runJobs(ctx, sha) {
177
+ const lines = [];
178
+ for (const job of composeOf(ctx).jobs ?? []) {
179
+ if (job.once) {
180
+ const seen = await ctx.host.exec('docker', composeArgs(ctx, 'run', '--rm', '--no-deps', '--entrypoint', 'sh', job.service, '-c', `ls ${job.once.exists}`), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
181
+ if (seen.code === 0) {
182
+ lines.push(`job ${job.service}: already done (${job.once.exists})`);
183
+ continue;
184
+ }
185
+ }
186
+ ctx.host.out.info(`docker compose run --rm ${job.service}${job.command ? ` ${job.command.join(' ')}` : ''}`);
187
+ const ran = await ctx.host.exec('docker', composeArgs(ctx, 'run', '--rm', '--no-deps', job.service, ...(job.command ?? [])), { cwd: ctx.dir, env: composeEnv(ctx, sha), stream: true });
188
+ if (ran.code !== 0)
189
+ throw new DeployError(`job ${job.service} failed (exit ${ran.code})`);
190
+ lines.push(`job ${job.service}: done`);
191
+ }
192
+ return lines;
193
+ }
76
194
  /** `docker build` of every image not built yet for this commit. */
77
195
  export async function composeBuild(ctx, sha) {
78
196
  const rt = composeOf(ctx);
@@ -95,6 +213,8 @@ export async function composeRelease(ctx, sha) {
95
213
  if ((await ctx.host.exec('docker', ['image', 'inspect', ref])).code !== 0)
96
214
  throw new DeployError(`the image ${ref} does not exist — nothing to start`);
97
215
  }
216
+ for (const line of [...await externalVolumes(ctx, sha), ...await attachContainers(ctx, sha), ...await runJobs(ctx, sha)])
217
+ ctx.host.out.ok(line);
98
218
  const up = await ctx.host.exec('docker', composeArgs(ctx, 'up', '-d'), { cwd: ctx.dir, env: composeEnv(ctx, sha), stream: true });
99
219
  if (up.code !== 0)
100
220
  throw new DeployError(`docker compose up failed (exit ${up.code})`);
@@ -142,6 +262,20 @@ export async function pruneImages(ctx, keep) {
142
262
  }
143
263
  return removed;
144
264
  }
265
+ /** Text from `verify.logs` in a service's logs since `since` (RFC 0007 §6). */
266
+ export async function logFindings(ctx, sha, since) {
267
+ const problems = [];
268
+ for (const [service, patterns] of Object.entries(ctx.config.verify?.logs ?? {})) {
269
+ const logs = await ctx.host.exec('docker', composeArgs(ctx, 'logs', '--no-color', '--since', since.toISOString(), service), { cwd: ctx.dir, env: composeEnv(ctx, sha) });
270
+ const text = `${logs.stdout}${logs.stderr}`;
271
+ const found = patterns.filter((p) => text.includes(p));
272
+ if (found.length > 0) {
273
+ const line = text.split('\n').find((l) => found.some((p) => l.includes(p)))?.trim() ?? '';
274
+ problems.push(`${service} logs ${found.join(', ')}: ${line.slice(0, 200)}`);
275
+ }
276
+ }
277
+ return problems;
278
+ }
145
279
  export async function composeStatus(ctx, sha) {
146
280
  const services = await composeServices(ctx, sha);
147
281
  if (services === undefined)