@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/README.md +119 -9
- package/dist/backup.js +4 -3
- package/dist/bootstrap.d.ts +35 -0
- package/dist/bootstrap.js +148 -0
- package/dist/caddy.d.ts +24 -0
- package/dist/caddy.js +154 -0
- package/dist/check.d.ts +12 -0
- package/dist/check.js +54 -0
- package/dist/checks.d.ts +2 -0
- package/dist/checks.js +2 -2
- package/dist/cli.js +34 -1
- package/dist/compose.d.ts +16 -0
- package/dist/compose.js +134 -0
- package/dist/config.d.ts +305 -49
- package/dist/config.js +57 -5
- package/dist/env-check.d.ts +1 -1
- package/dist/env-check.js +1 -1
- package/dist/env-step.js +5 -4
- package/dist/host.d.ts +2 -0
- package/dist/host.js +3 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/infra.d.ts +12 -1
- package/dist/infra.js +50 -12
- package/dist/init.d.ts +76 -0
- package/dist/init.js +501 -0
- package/dist/pipeline.js +86 -21
- package/dist/services.d.ts +62 -0
- package/dist/services.js +195 -0
- package/package.json +1 -1
package/dist/pipeline.js
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
1
1
|
import { basename, dirname, join } from 'node:path';
|
|
2
2
|
import { apacheInstall, apachePreflight, vhostPaths } from './apache.js';
|
|
3
|
+
import { caddyInstall, caddyPaths, caddyPreflight } from './caddy.js';
|
|
3
4
|
import { backupDatabase, restoreCommand } from './backup.js';
|
|
4
5
|
import { lockfileFindings, tlsFindings, toolingFindings } from './checks.js';
|
|
5
|
-
import { composeBuild, composeEnv, composeHealthy, composeOf, composePreflight, composeRelease, composeStatus, pruneImages } from './compose.js';
|
|
6
|
-
import { processName } from './config.js';
|
|
6
|
+
import { composeBuild, composeEnv, composeHealthy, composeOf, composePreflight, composeRelease, composeStatus, logFindings, pruneImages } from './compose.js';
|
|
7
|
+
import { definedEntries, processName } from './config.js';
|
|
7
8
|
import { DeployError, errors, INSTALL_COMMAND, report, RUN_COMMAND } from './context.js';
|
|
8
9
|
import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
|
|
9
10
|
import { answerQuestions, describeEnv, envFile, envMirrors, mirrorFindings, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
|
|
10
11
|
import { envValues } from './dotenv.js';
|
|
11
|
-
import { applyInfra, describeInfra, planInfra } from './infra.js';
|
|
12
|
+
import { applyInfra, describeInfra, dockerPostgres, maintainServices, planInfra } from './infra.js';
|
|
13
|
+
import { appRoleOf, describeServices, dumpContainer, dumpUrlKey, externalOf, externalPostgres, grantTenantSchemas } from './services.js';
|
|
12
14
|
import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
|
|
13
15
|
import { lastGood, migrationNames, readReleases, recordRelease } from './state.js';
|
|
14
16
|
export const SKIPPABLE = ['fetch', 'backup', 'tls'];
|
|
@@ -78,14 +80,17 @@ export async function preflight(ctx, options = {}) {
|
|
|
78
80
|
findings.push(...await mirrorFindings(ctx));
|
|
79
81
|
if (ctx.config.proxy?.kind === 'apache')
|
|
80
82
|
findings.push(...await apachePreflight(ctx, port));
|
|
83
|
+
if (ctx.config.proxy?.kind === 'caddy')
|
|
84
|
+
findings.push(...await caddyPreflight(ctx, port));
|
|
81
85
|
if (!options.skip?.includes('tls'))
|
|
82
86
|
findings.push(...await tlsFindings(ctx));
|
|
83
87
|
findings.push(...await backupFindings(ctx, values, options));
|
|
84
88
|
return { findings, port, values };
|
|
85
89
|
}
|
|
86
|
-
/**
|
|
90
|
+
/** The dump's container running — found now, not after the build, minutes later. */
|
|
87
91
|
async function backupFindings(ctx, values, options) {
|
|
88
92
|
const container = ctx.config.backup?.container;
|
|
93
|
+
// An external infra.postgres is checked with the rest of the infra.
|
|
89
94
|
if (!container || !backupDecision(ctx.config, values, options.skip ?? []).run)
|
|
90
95
|
return [];
|
|
91
96
|
const running = await ctx.host.exec('docker', ['inspect', '--format', '{{.State.Running}}', container]);
|
|
@@ -161,7 +166,7 @@ const migratesAnything = (config) => Boolean(config.migrate?.command) || migrate
|
|
|
161
166
|
/** The `.env` as the migration and the dump see it: `migrate.env` on top (host URLs for container names). */
|
|
162
167
|
export function migrationValues(config, values) {
|
|
163
168
|
const extra = config.migrate?.env?.(values) ?? {};
|
|
164
|
-
return new Map([...values, ...
|
|
169
|
+
return new Map([...values, ...definedEntries(extra)]);
|
|
165
170
|
}
|
|
166
171
|
/**
|
|
167
172
|
* Whether the pre-migration dump runs, and why not when it does not. Unsaid,
|
|
@@ -181,7 +186,9 @@ export function backupDecision(config, values, skip = []) {
|
|
|
181
186
|
return { run: false, why: 'nothing to migrate' };
|
|
182
187
|
if (config.infra?.kind === 'docker' && config.infra.postgres)
|
|
183
188
|
return { run: true };
|
|
184
|
-
|
|
189
|
+
if (dumpContainer(config))
|
|
190
|
+
return { run: true };
|
|
191
|
+
const url = migrationValues(config, values).get(dumpUrlKey(config)) ?? '';
|
|
185
192
|
return /^postgres(ql)?:\/\//.test(url) ? { run: true } : { run: false, why: 'no Postgres database in the .env' };
|
|
186
193
|
}
|
|
187
194
|
// ── the building blocks ────────────────────────────────────────────────────
|
|
@@ -209,6 +216,8 @@ async function build(ctx, values, sha) {
|
|
|
209
216
|
await run(frozen, { unset: ['NODE_ENV'] });
|
|
210
217
|
for (const config of ctx.config.build?.prisma ?? [])
|
|
211
218
|
await run(['exec', 'prisma', 'generate', '--config', config], { env: values });
|
|
219
|
+
if (ctx.config.build?.script)
|
|
220
|
+
await run(['run', ctx.config.build.script], { env: values });
|
|
212
221
|
if (ctx.config.build?.web)
|
|
213
222
|
await run(['--dir', ctx.config.build.web, 'run', 'build'], { env: values });
|
|
214
223
|
if (isCompose(ctx))
|
|
@@ -294,9 +303,34 @@ async function healthy(ctx, port) {
|
|
|
294
303
|
} while (host.now().getTime() < deadline);
|
|
295
304
|
return false;
|
|
296
305
|
}
|
|
306
|
+
/** `verify.logs` and `verify.http` (RFC 0007 §6); throws what failed, which rolls the release back. */
|
|
307
|
+
async function verifyDeclared(ctx, sha, port, since) {
|
|
308
|
+
const verify = ctx.config.verify;
|
|
309
|
+
if (!verify)
|
|
310
|
+
return;
|
|
311
|
+
const problems = [];
|
|
312
|
+
if (verify.logs && Object.keys(verify.logs).length) {
|
|
313
|
+
if (!isCompose(ctx))
|
|
314
|
+
throw new DeployError('verify.logs reads compose service logs: it needs runtime: compose(…)');
|
|
315
|
+
const found = await logFindings(ctx, sha, since);
|
|
316
|
+
problems.push(...found);
|
|
317
|
+
if (found.length === 0)
|
|
318
|
+
ctx.host.out.ok(`logs of ${Object.keys(verify.logs).join(', ')}: clean since the release`);
|
|
319
|
+
}
|
|
320
|
+
for (const check of verify.http ?? []) {
|
|
321
|
+
const expect = check.expect ?? 200;
|
|
322
|
+
const answer = await ctx.host.httpGet(`http://127.0.0.1:${port}${check.path}`, { host: ctx.config.domain });
|
|
323
|
+
if ('status' in answer && answer.status === expect)
|
|
324
|
+
ctx.host.out.ok(`${check.path}: ${expect}`);
|
|
325
|
+
else
|
|
326
|
+
problems.push(`${check.path}: ${'status' in answer ? `HTTP ${answer.status}` : answer.error}, expected ${expect}`);
|
|
327
|
+
}
|
|
328
|
+
if (problems.length > 0)
|
|
329
|
+
throw new DeployError(`verify: ${problems.join('; ')}`);
|
|
330
|
+
}
|
|
297
331
|
async function publicHealthy(ctx) {
|
|
298
332
|
const { config } = ctx;
|
|
299
|
-
if (config.health?.public === false || config.proxy?.kind !== 'apache')
|
|
333
|
+
if (config.health?.public === false || (config.proxy?.kind !== 'apache' && config.proxy?.kind !== 'caddy'))
|
|
300
334
|
return undefined;
|
|
301
335
|
const url = `https://${config.domain}${config.proxy.apiPrefix.replace(/\/$/, '')}${config.health?.path ?? '/health'}`;
|
|
302
336
|
const answer = await ctx.host.httpGet(url, { timeoutMs: 10_000 });
|
|
@@ -308,7 +342,7 @@ async function publicHealthy(ctx) {
|
|
|
308
342
|
id: 'health',
|
|
309
343
|
level: 'error',
|
|
310
344
|
message: `the app answers on 127.0.0.1 but not at ${url} (${'status' in answer ? `HTTP ${answer.status}` : answer.error}) — the proxy, DNS or TLS, not the code`,
|
|
311
|
-
fix: 'the [C1]/[C2]/[vhost] findings above, then: apachectl -S',
|
|
345
|
+
fix: config.proxy.kind === 'caddy' ? 'the [C1]/[C2]/[C8] findings above, then: journalctl -u caddy -n 50' : 'the [C1]/[C2]/[vhost] findings above, then: apachectl -S',
|
|
312
346
|
};
|
|
313
347
|
}
|
|
314
348
|
/** Puts the code on disk back to `sha` and rebuilds it. Does not restart anything. */
|
|
@@ -326,12 +360,27 @@ function reportEnv(ctx, plan) {
|
|
|
326
360
|
for (const line of lines)
|
|
327
361
|
ctx.host.out.info(line);
|
|
328
362
|
}
|
|
329
|
-
async function infraStep(ctx, infra) {
|
|
363
|
+
async function infraStep(ctx, infra, values) {
|
|
330
364
|
stopOnErrors(ctx, await applyInfra(ctx, infra), 'infra');
|
|
331
|
-
|
|
332
|
-
|
|
365
|
+
const external = externalOf(ctx.config);
|
|
366
|
+
const adopted = [external?.postgres?.container, external?.redis?.container, external?.minio?.container].filter(Boolean);
|
|
367
|
+
if (infra.services.length > 0)
|
|
368
|
+
ctx.host.out.ok(`${infra.services.map((s) => s.container).join(', ')} healthy; credentials accepted`);
|
|
369
|
+
else if (adopted.length > 0)
|
|
370
|
+
ctx.host.out.ok(`${adopted.join(', ')} running (external)`);
|
|
333
371
|
else
|
|
334
|
-
ctx.host.out.ok(
|
|
372
|
+
ctx.host.out.ok('nothing to start (external infra)');
|
|
373
|
+
for (const line of await maintainServices(ctx, infra, values))
|
|
374
|
+
ctx.host.out.ok(line);
|
|
375
|
+
}
|
|
376
|
+
/** The app role on every company schema, after the companies' migrations (RFC 0007 §11.3). */
|
|
377
|
+
async function tenantGrants(ctx, infra, values) {
|
|
378
|
+
const role = appRoleOf(ctx.config);
|
|
379
|
+
if (!role || !ctx.config.migrate?.tenants)
|
|
380
|
+
return;
|
|
381
|
+
const pg = ctx.config.infra?.kind === 'docker' ? dockerPostgres(infra) : externalPostgres(ctx, values);
|
|
382
|
+
if (pg)
|
|
383
|
+
ctx.host.out.ok(await grantTenantSchemas(ctx, pg, role));
|
|
335
384
|
}
|
|
336
385
|
async function validateStep(ctx, values) {
|
|
337
386
|
stopOnErrors(ctx, await validate(ctx, values), 'validate');
|
|
@@ -350,18 +399,25 @@ export async function plan(ctx, options = {}) {
|
|
|
350
399
|
options.skip?.includes('fetch') ? 'fetch: skipped' : `fetch: git fetch ${config.remote ?? 'origin'} ${config.branch ?? 'main'} && git merge --ff-only`,
|
|
351
400
|
...describeEnv(env).map((l) => `env: ${l}`),
|
|
352
401
|
...describeInfra(infra).map((l) => `infra: ${l}`),
|
|
353
|
-
|
|
402
|
+
...describeServices(config).map((l) => `infra: ${l}`),
|
|
403
|
+
`build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.script ? `, ${pm} run ${config.build.script}` : ''}${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)` : ''}`,
|
|
354
404
|
...(config.hooks?.infra ?? []).map((h) => `infra hook: ${h.join(' ')}`),
|
|
355
405
|
`validate: ${config.env.schema ?? '(no schema configured)'} against the new .env`,
|
|
356
406
|
((decision) => decision.run
|
|
357
|
-
? `backup: pg_dump${config
|
|
407
|
+
? `backup: pg_dump${dumpContainer(config) ? ` inside ${dumpContainer(config)}` : ''} → ${config.backup?.dir ?? 'backups/predeploy'} (keep ${config.backup?.keep ?? 10})`
|
|
358
408
|
: `backup: skipped (${decision.why})`)(backupDecision(config, checked.values, options.skip ?? [])),
|
|
359
409
|
`migrate: ${[config.migrate?.command?.join(' ') ?? '', migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
|
|
410
|
+
...(isCompose(ctx) && composeOf(ctx).attach ? [`attach: ${Object.entries(composeOf(ctx).attach ?? {}).map(([c, n]) => `${c} → ${n.join(', ')}`).join('; ')}`] : []),
|
|
411
|
+
...(isCompose(ctx) ? (composeOf(ctx).jobs ?? []).map((j) => `job: ${j.service}${j.command ? ` ${j.command.join(' ')}` : ''}${j.once ? ` (unless ${j.once.exists} exists)` : ''}`) : []),
|
|
360
412
|
`release: ${describeRelease(ctx, checked.port)}`,
|
|
361
|
-
`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'}` : ''}`,
|
|
413
|
+
`health: http://127.0.0.1:${checked.port}${config.health?.path ?? '/health'} (Host: ${config.domain})${(config.proxy?.kind === 'apache' || config.proxy?.kind === 'caddy') && config.health?.public !== false ? `, then https://${config.domain}${config.proxy.apiPrefix}${config.health?.path ?? '/health'}` : ''}`,
|
|
362
414
|
];
|
|
363
415
|
for (const hook of config.hooks?.verify ?? [])
|
|
364
416
|
lines.push(`verify hook: ${hook.join(' ')}`);
|
|
417
|
+
if (config.verify?.logs)
|
|
418
|
+
lines.push(`verify: no ${[...new Set(Object.values(config.verify.logs).flat())].join(' / ')} in the logs of ${Object.keys(config.verify.logs).join(', ')}`);
|
|
419
|
+
for (const check of config.verify?.http ?? [])
|
|
420
|
+
lines.push(`verify: ${check.path} answers ${check.expect ?? 200}`);
|
|
365
421
|
for (const line of lines)
|
|
366
422
|
host.out.info(line);
|
|
367
423
|
return errors([...checked.findings, ...infra.findings]).length > 0 ? 1 : 0;
|
|
@@ -378,7 +434,7 @@ export async function envCommand(ctx) {
|
|
|
378
434
|
throw new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`);
|
|
379
435
|
reportEnv(ctx, env);
|
|
380
436
|
await writeEnv(ctx, env);
|
|
381
|
-
await step(ctx, 'infra', () => infraStep(ctx, infra));
|
|
437
|
+
await step(ctx, 'infra', () => infraStep(ctx, infra, env.values));
|
|
382
438
|
await step(ctx, 'validate', () => validateStep(ctx, env.values));
|
|
383
439
|
ctx.host.out.ok(isCompose(ctx) ? `${envFile(ctx)} ready` : `.env ready (PORT=${port})`);
|
|
384
440
|
return 0;
|
|
@@ -417,7 +473,7 @@ export async function run(ctx, options = {}) {
|
|
|
417
473
|
reportEnv(ctx, prepared.env);
|
|
418
474
|
await writeEnv(ctx, prepared.env);
|
|
419
475
|
values = prepared.env.values;
|
|
420
|
-
await step(ctx, 'infra', async () => { await infraStep(ctx, infra); await runHooks(ctx, 'infra', values, sha); });
|
|
476
|
+
await step(ctx, 'infra', async () => { await infraStep(ctx, infra, values); await runHooks(ctx, 'infra', values, sha); });
|
|
421
477
|
await step(ctx, 'build', async () => { await build(ctx, values, sha); await settleLockfile(ctx, lockfileSaid); });
|
|
422
478
|
await step(ctx, 'validate', () => validateStep(ctx, values));
|
|
423
479
|
const backup = backupDecision(config, values, skip);
|
|
@@ -429,7 +485,7 @@ export async function run(ctx, options = {}) {
|
|
|
429
485
|
host.out.step('backup');
|
|
430
486
|
host.out.info(`skipped: ${backup.why}`);
|
|
431
487
|
}
|
|
432
|
-
await step(ctx, 'migrate', async () => { await migrate(ctx, values); await settleLockfile(ctx, lockfileSaid); });
|
|
488
|
+
await step(ctx, 'migrate', async () => { await migrate(ctx, values); await tenantGrants(ctx, infra, values); await settleLockfile(ctx, lockfileSaid); });
|
|
433
489
|
}
|
|
434
490
|
catch (error) {
|
|
435
491
|
if (sha !== previous)
|
|
@@ -456,6 +512,7 @@ export async function run(ctx, options = {}) {
|
|
|
456
512
|
await recordRelease(ctx, record);
|
|
457
513
|
return 1;
|
|
458
514
|
};
|
|
515
|
+
const releasedAt = host.now();
|
|
459
516
|
try {
|
|
460
517
|
host.out.ok(await step(ctx, 'release', () => release(ctx, values, sha)));
|
|
461
518
|
}
|
|
@@ -466,15 +523,20 @@ export async function run(ctx, options = {}) {
|
|
|
466
523
|
if (!health.ok)
|
|
467
524
|
return recover(health.why);
|
|
468
525
|
host.out.ok(`http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
|
|
469
|
-
|
|
526
|
+
// Through the proxy, under the health step: a failure here is the proxy,
|
|
527
|
+
// DNS or TLS — reported at the end, never rolled back.
|
|
528
|
+
const publicProblem = await publicHealthy(ctx);
|
|
529
|
+
if (config.hooks?.verify?.length || config.verify) {
|
|
470
530
|
try {
|
|
471
|
-
await step(ctx, 'verify', () =>
|
|
531
|
+
await step(ctx, 'verify', async () => {
|
|
532
|
+
await runHooks(ctx, 'verify', values, sha);
|
|
533
|
+
await verifyDeclared(ctx, sha, port, releasedAt);
|
|
534
|
+
});
|
|
472
535
|
}
|
|
473
536
|
catch (error) {
|
|
474
537
|
return recover(error.message);
|
|
475
538
|
}
|
|
476
539
|
}
|
|
477
|
-
const publicProblem = await publicHealthy(ctx);
|
|
478
540
|
record.status = publicProblem ? 'public-unreachable' : 'ok';
|
|
479
541
|
// `pnpm run start`, launched by PM2 in the checkout, may rewrite it too.
|
|
480
542
|
await settleLockfile(ctx, lockfileSaid);
|
|
@@ -637,6 +699,9 @@ export async function install(ctx, user) {
|
|
|
637
699
|
if (config.proxy?.kind === 'apache' && config.proxy.managed !== false) {
|
|
638
700
|
await step(ctx, `Apache vhost ${vhostPaths(ctx).file}`, () => apacheInstall(ctx, port, join(stateDir, 'install-backups')));
|
|
639
701
|
}
|
|
702
|
+
if (config.proxy?.kind === 'caddy' && config.proxy.managed !== false) {
|
|
703
|
+
await step(ctx, `Caddy site ${caddyPaths(ctx).site}`, () => caddyInstall(ctx, port, join(stateDir, 'install-backups')));
|
|
704
|
+
}
|
|
640
705
|
if (config.infra?.kind === 'docker') {
|
|
641
706
|
const groups = (await host.exec('id', ['-nG', user])).stdout.split(/\s+/);
|
|
642
707
|
if (groups.includes('docker')) {
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { type AppRole, type Bucket, type DeployConfig } from './config.js';
|
|
2
|
+
import { type DeployContext, type Finding } from './context.js';
|
|
3
|
+
import type { EnvChange } from './dotenv.js';
|
|
4
|
+
/**
|
|
5
|
+
* What every deploy keeps true of the app's services, dedicated or not
|
|
6
|
+
* (RFC 0007 §4): the external containers are running, the app's database role
|
|
7
|
+
* exists with the `.env`'s password and its grants, the buckets exist with
|
|
8
|
+
* their policies. Each is idempotent and says what it did.
|
|
9
|
+
*
|
|
10
|
+
* Credentials never reach a command line: `docker exec -e NAME` (no value)
|
|
11
|
+
* copies them from this process's environment, SQL with a password goes on
|
|
12
|
+
* stdin.
|
|
13
|
+
*/
|
|
14
|
+
/** Where to reach Postgres as its owner, inside the container. */
|
|
15
|
+
export interface PostgresHandle {
|
|
16
|
+
container: string;
|
|
17
|
+
user: string;
|
|
18
|
+
database: string;
|
|
19
|
+
password: string;
|
|
20
|
+
/** Over TCP (proves the password) or the local socket (as the image allows). */
|
|
21
|
+
tcp: boolean;
|
|
22
|
+
/** The owner's URL, from which the app role's URL is derived. */
|
|
23
|
+
url: string | undefined;
|
|
24
|
+
}
|
|
25
|
+
export interface MinioHandle {
|
|
26
|
+
container: string;
|
|
27
|
+
user: string;
|
|
28
|
+
password: string;
|
|
29
|
+
}
|
|
30
|
+
export declare const externalOf: (config: DeployConfig) => import("./config.js").ExternalInfra<import("./config.js").EnvShape> | undefined;
|
|
31
|
+
/** The container the pre-migration dump runs in, with external infra: `backup.container`, else `infra.postgres.container`. */
|
|
32
|
+
export declare const dumpContainer: (config: DeployConfig) => string | undefined;
|
|
33
|
+
/** The `.env` key of the URL the dump connects with: `backup.urlKey`, else the external Postgres's owner URL. */
|
|
34
|
+
export declare const dumpUrlKey: (config: DeployConfig) => string;
|
|
35
|
+
/** The app role, wherever it is declared. */
|
|
36
|
+
export declare function appRoleOf(config: DeployConfig): AppRole | undefined;
|
|
37
|
+
/** The external containers, each running — before anything is built. */
|
|
38
|
+
export declare function externalFindings(ctx: DeployContext): Promise<Finding[]>;
|
|
39
|
+
export declare function externalPostgres(ctx: DeployContext, values: Map<string, string>): PostgresHandle | undefined;
|
|
40
|
+
/**
|
|
41
|
+
* The app role's URL, when the `.env` has none yet: the owner's, with the
|
|
42
|
+
* role's name and a new password. Kept from then on — the role follows it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function appRoleEnv(ctx: DeployContext, values: Map<string, string>, ownerUrl: string | undefined): EnvChange[];
|
|
45
|
+
/**
|
|
46
|
+
* The role exists, logs in with the `.env`'s password, and gets DML on what the
|
|
47
|
+
* owner creates in `public` (default privileges — never on existing tables: an
|
|
48
|
+
* app may keep some append-only, as Globex's audit log is).
|
|
49
|
+
*/
|
|
50
|
+
export declare function ensureAppRole(ctx: DeployContext, pg: PostgresHandle, role: AppRole, values: Map<string, string>): Promise<string>;
|
|
51
|
+
/**
|
|
52
|
+
* After the companies' migrations (RFC 0007 §11.3): every `tenant_*` schema
|
|
53
|
+
* gets the role's DML on what it has and what its owner creates later. A new
|
|
54
|
+
* company without them is an outage the role only finds at runtime.
|
|
55
|
+
*/
|
|
56
|
+
export declare function grantTenantSchemas(ctx: DeployContext, pg: PostgresHandle, role: AppRole): Promise<string>;
|
|
57
|
+
/** Credentials of a running MinIO: its own, never the config's. */
|
|
58
|
+
export declare function minioHandle(ctx: DeployContext, container: string): Promise<MinioHandle>;
|
|
59
|
+
/** Each bucket exists; versioning on where asked; the expiry rule added once. */
|
|
60
|
+
export declare function ensureBuckets(ctx: DeployContext, minio: MinioHandle, buckets: Bucket[]): Promise<string>;
|
|
61
|
+
/** What `plan` says about the services: the external containers, the role, the buckets. */
|
|
62
|
+
export declare function describeServices(config: DeployConfig): string[];
|
package/dist/services.js
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { bucketName } from './config.js';
|
|
2
|
+
import { DeployError } from './context.js';
|
|
3
|
+
export const externalOf = (config) => (config.infra?.kind === 'external' ? config.infra : undefined);
|
|
4
|
+
/** The container the pre-migration dump runs in, with external infra: `backup.container`, else `infra.postgres.container`. */
|
|
5
|
+
export const dumpContainer = (config) => config.backup?.container ?? externalOf(config)?.postgres?.container;
|
|
6
|
+
/** The `.env` key of the URL the dump connects with: `backup.urlKey`, else the external Postgres's owner URL. */
|
|
7
|
+
export const dumpUrlKey = (config) => config.backup?.urlKey ?? externalOf(config)?.postgres?.urlKey ?? 'DATABASE_URL';
|
|
8
|
+
/** The app role, wherever it is declared. */
|
|
9
|
+
export function appRoleOf(config) {
|
|
10
|
+
if (config.infra?.kind === 'docker')
|
|
11
|
+
return config.infra.postgres?.appRole;
|
|
12
|
+
return externalOf(config)?.postgres?.appRole;
|
|
13
|
+
}
|
|
14
|
+
/** The external containers, each running — before anything is built. */
|
|
15
|
+
export async function externalFindings(ctx) {
|
|
16
|
+
const services = externalOf(ctx.config);
|
|
17
|
+
if (!services)
|
|
18
|
+
return [];
|
|
19
|
+
const findings = [];
|
|
20
|
+
for (const [service, container] of [['postgres', services.postgres?.container], ['redis', services.redis?.container], ['minio', services.minio?.container]]) {
|
|
21
|
+
if (!container)
|
|
22
|
+
continue;
|
|
23
|
+
const state = await ctx.host.exec('docker', ['inspect', '--format', '{{.State.Running}}', container]);
|
|
24
|
+
if (state.stdout.trim() === 'true')
|
|
25
|
+
continue;
|
|
26
|
+
findings.push({
|
|
27
|
+
id: 'infra',
|
|
28
|
+
level: 'error',
|
|
29
|
+
message: state.code === 0 ? `${service}: ${container} is not running` : `${service}: ${container} does not exist (or docker is not available to this user)`,
|
|
30
|
+
fix: state.code === 0 ? `docker start ${container}` : 'a new server is prepared with basalt-deploy bootstrap; adopt a container under another name with infra.<service>.container',
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
return findings;
|
|
34
|
+
}
|
|
35
|
+
export function externalPostgres(ctx, values) {
|
|
36
|
+
const pg = externalOf(ctx.config)?.postgres;
|
|
37
|
+
if (!pg)
|
|
38
|
+
return undefined;
|
|
39
|
+
const key = pg.urlKey ?? 'DATABASE_URL';
|
|
40
|
+
const raw = values.get(key);
|
|
41
|
+
if (!raw)
|
|
42
|
+
throw new DeployError(`infra.postgres: ${key} is not set in the .env — it holds the owner's URL`);
|
|
43
|
+
const url = new URL(raw);
|
|
44
|
+
return {
|
|
45
|
+
container: pg.container,
|
|
46
|
+
user: decodeURIComponent(url.username),
|
|
47
|
+
database: decodeURIComponent(url.pathname.replace(/^\//, '')),
|
|
48
|
+
password: decodeURIComponent(url.password),
|
|
49
|
+
tcp: false,
|
|
50
|
+
url: raw,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The app role's URL, when the `.env` has none yet: the owner's, with the
|
|
55
|
+
* role's name and a new password. Kept from then on — the role follows it.
|
|
56
|
+
*/
|
|
57
|
+
export function appRoleEnv(ctx, values, ownerUrl) {
|
|
58
|
+
const role = appRoleOf(ctx.config);
|
|
59
|
+
if (!role || values.get(role.urlKey) || !ownerUrl)
|
|
60
|
+
return [];
|
|
61
|
+
const url = new URL(ownerUrl);
|
|
62
|
+
url.username = role.name;
|
|
63
|
+
url.password = ctx.host.randomHex(24);
|
|
64
|
+
return [{ kind: 'set', key: role.urlKey, value: url.toString(), reason: `password of the ${role.name} role (new)` }];
|
|
65
|
+
}
|
|
66
|
+
const ident = (name) => `"${name.replace(/"/g, '""')}"`;
|
|
67
|
+
const literal = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
68
|
+
async function psql(ctx, pg, sql, as) {
|
|
69
|
+
const user = as?.user ?? pg.user;
|
|
70
|
+
const password = as?.password ?? pg.password;
|
|
71
|
+
const args = ['exec', '-i', '-e', 'PGPASSWORD', pg.container, 'psql', '-v', 'ON_ERROR_STOP=1', '-qtA', ...(pg.tcp || as ? ['-h', '127.0.0.1'] : []), '-U', user, '-d', pg.database];
|
|
72
|
+
return ctx.host.exec('docker', args, { env: { PGPASSWORD: password }, stdin: sql });
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The role exists, logs in with the `.env`'s password, and gets DML on what the
|
|
76
|
+
* owner creates in `public` (default privileges — never on existing tables: an
|
|
77
|
+
* app may keep some append-only, as Globex's audit log is).
|
|
78
|
+
*/
|
|
79
|
+
export async function ensureAppRole(ctx, pg, role, values) {
|
|
80
|
+
const raw = values.get(role.urlKey);
|
|
81
|
+
if (!raw)
|
|
82
|
+
throw new DeployError(`appRole ${role.name}: ${role.urlKey} is not set in the .env`);
|
|
83
|
+
const password = decodeURIComponent(new URL(raw).password);
|
|
84
|
+
const exists = (await psql(ctx, pg, `SELECT 1 FROM pg_roles WHERE rolname = ${literal(role.name)};\n`)).stdout.trim() === '1';
|
|
85
|
+
// Proven over TCP before anything is changed: an ALTER ROLE … PASSWORD on
|
|
86
|
+
// every deploy would write the password to any statement log.
|
|
87
|
+
const works = exists && (await psql(ctx, pg, 'SELECT 1;\n', { user: role.name, password })).code === 0;
|
|
88
|
+
const sql = [
|
|
89
|
+
...(exists ? [] : [`CREATE ROLE ${ident(role.name)} LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`]),
|
|
90
|
+
...(works ? [] : [`ALTER ROLE ${ident(role.name)} WITH LOGIN PASSWORD ${literal(password)};`]),
|
|
91
|
+
`GRANT CONNECT ON DATABASE ${ident(pg.database)} TO ${ident(role.name)};`,
|
|
92
|
+
`GRANT USAGE ON SCHEMA public TO ${ident(role.name)};`,
|
|
93
|
+
`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(pg.user)} IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${ident(role.name)};`,
|
|
94
|
+
`ALTER DEFAULT PRIVILEGES FOR ROLE ${ident(pg.user)} IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO ${ident(role.name)};`,
|
|
95
|
+
].join('\n');
|
|
96
|
+
const result = await psql(ctx, pg, `${sql}\n`);
|
|
97
|
+
if (result.code !== 0)
|
|
98
|
+
throw new DeployError(`appRole ${role.name}: ${result.stderr.trim().split('\n')[0] ?? 'psql failed'}`);
|
|
99
|
+
return `role ${role.name}: ${exists ? (works ? 'in place' : 'password set from the .env') : 'created'}; grants in place`;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* After the companies' migrations (RFC 0007 §11.3): every `tenant_*` schema
|
|
103
|
+
* gets the role's DML on what it has and what its owner creates later. A new
|
|
104
|
+
* company without them is an outage the role only finds at runtime.
|
|
105
|
+
*/
|
|
106
|
+
export async function grantTenantSchemas(ctx, pg, role) {
|
|
107
|
+
const r = ident(role.name);
|
|
108
|
+
const owner = ident(pg.user);
|
|
109
|
+
const sql = `DO $basalt$
|
|
110
|
+
DECLARE s text; n int := 0;
|
|
111
|
+
BEGIN
|
|
112
|
+
FOR s IN SELECT nspname FROM pg_namespace WHERE nspname LIKE 'tenant\\_%' LOOP
|
|
113
|
+
EXECUTE format('GRANT USAGE ON SCHEMA %I TO ${r.replace(/%/g, '%%')}', s);
|
|
114
|
+
EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA %I TO ${r.replace(/%/g, '%%')}', s);
|
|
115
|
+
EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO ${r.replace(/%/g, '%%')}', s);
|
|
116
|
+
EXECUTE format('ALTER DEFAULT PRIVILEGES FOR ROLE ${owner.replace(/%/g, '%%')} IN SCHEMA %I GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO ${r.replace(/%/g, '%%')}', s);
|
|
117
|
+
n := n + 1;
|
|
118
|
+
END LOOP;
|
|
119
|
+
RAISE NOTICE 'basalt: % schema(s)', n;
|
|
120
|
+
END
|
|
121
|
+
$basalt$;
|
|
122
|
+
SELECT count(*) FROM pg_namespace WHERE nspname LIKE 'tenant\\_%';
|
|
123
|
+
`;
|
|
124
|
+
const result = await psql(ctx, pg, sql);
|
|
125
|
+
if (result.code !== 0)
|
|
126
|
+
throw new DeployError(`appRole ${role.name} on the company schemas: ${result.stderr.trim().split('\n').pop() ?? 'psql failed'}`);
|
|
127
|
+
return `role ${role.name}: granted on ${result.stdout.trim().split('\n').pop() ?? '0'} company schema(s)`;
|
|
128
|
+
}
|
|
129
|
+
/** Credentials of a running MinIO: its own, never the config's. */
|
|
130
|
+
export async function minioHandle(ctx, container) {
|
|
131
|
+
const result = await ctx.host.exec('docker', ['inspect', container, '--format', '{{json .Config.Env}}']);
|
|
132
|
+
if (result.code !== 0)
|
|
133
|
+
throw new DeployError(`minio: cannot inspect ${container}`);
|
|
134
|
+
const env = new Map(JSON.parse(result.stdout.trim() || '[]').map((e) => [e.slice(0, e.indexOf('=')), e.slice(e.indexOf('=') + 1)]));
|
|
135
|
+
const user = env.get('MINIO_ROOT_USER');
|
|
136
|
+
const password = env.get('MINIO_ROOT_PASSWORD');
|
|
137
|
+
if (!user || !password)
|
|
138
|
+
throw new DeployError(`minio: ${container} has no MINIO_ROOT_USER/MINIO_ROOT_PASSWORD`);
|
|
139
|
+
return { container, user, password };
|
|
140
|
+
}
|
|
141
|
+
/** Each bucket exists; versioning on where asked; the expiry rule added once. */
|
|
142
|
+
export async function ensureBuckets(ctx, minio, buckets) {
|
|
143
|
+
if (buckets.length === 0)
|
|
144
|
+
return '';
|
|
145
|
+
const alias = `http://${encodeURIComponent(minio.user)}:${encodeURIComponent(minio.password)}@127.0.0.1:9000`;
|
|
146
|
+
const mc = (args) => ctx.host.exec('docker', ['exec', '-e', 'MC_HOST_local', minio.container, 'mc', ...args], { env: { MC_HOST_local: alias } });
|
|
147
|
+
const fail = (what, result) => new DeployError(`minio: ${what}: ${result.stderr.trim().split('\n')[0] ?? 'mc failed'}`);
|
|
148
|
+
const made = await mc(['mb', '-p', ...buckets.map((b) => `local/${bucketName(b)}`)]);
|
|
149
|
+
if (made.code !== 0)
|
|
150
|
+
throw fail('creating the buckets', made);
|
|
151
|
+
const said = [];
|
|
152
|
+
for (const bucket of buckets) {
|
|
153
|
+
if (typeof bucket === 'string') {
|
|
154
|
+
said.push(bucket);
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
157
|
+
const notes = [];
|
|
158
|
+
if (bucket.versioned) {
|
|
159
|
+
const versioned = await mc(['version', 'enable', `local/${bucket.name}`]);
|
|
160
|
+
if (versioned.code !== 0)
|
|
161
|
+
throw fail(`versioning ${bucket.name}`, versioned);
|
|
162
|
+
notes.push('versioned');
|
|
163
|
+
}
|
|
164
|
+
if (bucket.expireDays !== undefined) {
|
|
165
|
+
// `mc ilm rule add` adds ANOTHER rule every time: read the rules first.
|
|
166
|
+
const rules = await mc(['ilm', 'rule', 'ls', '--json', `local/${bucket.name}`]);
|
|
167
|
+
const present = new RegExp(`"Expiration":\\s*\\{[^}]*"Days":\\s*${bucket.expireDays}\\b`).test(rules.stdout);
|
|
168
|
+
if (!present) {
|
|
169
|
+
const added = await mc(['ilm', 'rule', 'add', '--expire-days', String(bucket.expireDays), `local/${bucket.name}`]);
|
|
170
|
+
if (added.code !== 0)
|
|
171
|
+
throw fail(`expiry on ${bucket.name}`, added);
|
|
172
|
+
}
|
|
173
|
+
notes.push(`${bucket.expireDays}-day expiry${present ? '' : ' (added)'}`);
|
|
174
|
+
}
|
|
175
|
+
said.push(notes.length ? `${bucket.name} (${notes.join(', ')})` : bucket.name);
|
|
176
|
+
}
|
|
177
|
+
return `buckets: ${said.join(', ')}`;
|
|
178
|
+
}
|
|
179
|
+
/** What `plan` says about the services: the external containers, the role, the buckets. */
|
|
180
|
+
export function describeServices(config) {
|
|
181
|
+
const lines = [];
|
|
182
|
+
const external = externalOf(config);
|
|
183
|
+
for (const [service, container] of [['postgres', external?.postgres?.container], ['redis', external?.redis?.container], ['minio', external?.minio?.container]]) {
|
|
184
|
+
if (container)
|
|
185
|
+
lines.push(`${service}: ${container} (external, kept running by its owner)`);
|
|
186
|
+
}
|
|
187
|
+
const role = appRoleOf(config);
|
|
188
|
+
if (role)
|
|
189
|
+
lines.push(`role ${role.name}: created if missing, password from ${role.urlKey}, DML grants${config.migrate?.tenants ? ' (company schemas too, after the migration)' : ''}`);
|
|
190
|
+
const buckets = [...(external?.minio?.buckets ?? []), ...(config.infra?.kind === 'docker' ? config.infra.minio?.buckets ?? [] : [])];
|
|
191
|
+
const policies = buckets.filter((b) => typeof b === 'object' && (b.versioned || b.expireDays));
|
|
192
|
+
if (policies.length)
|
|
193
|
+
lines.push(`buckets: ${policies.map((b) => typeof b === 'object' ? `${b.name} (${[b.versioned ? 'versioned' : '', b.expireDays ? `${b.expireDays}-day expiry` : ''].filter(Boolean).join(', ')})` : b).join(', ')}`);
|
|
194
|
+
return lines;
|
|
195
|
+
}
|