@hivemagnus/magnus 1.1.2 → 1.1.4
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 +13 -6
- package/dist/adopt.js +15 -3
- package/dist/cli.js +7 -0
- package/dist/database.d.ts +23 -2
- package/dist/database.js +167 -18
- package/dist/env-file.d.ts +5 -1
- package/dist/env-file.js +20 -5
- package/dist/health.d.ts +13 -0
- package/dist/health.js +36 -8
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/init.js +15 -7
- package/dist/install.d.ts +41 -3
- package/dist/install.js +112 -11
- package/dist/io.d.ts +10 -0
- package/dist/io.js +14 -2
- package/dist/main.d.ts +3 -1
- package/dist/main.js +32 -9
- package/dist/project.d.ts +77 -4
- package/dist/project.js +184 -17
- package/dist/release.d.ts +25 -3
- package/dist/release.js +70 -12
- package/dist/restore.d.ts +11 -0
- package/dist/restore.js +55 -0
- package/dist/rollback.d.ts +6 -0
- package/dist/rollback.js +79 -29
- package/dist/status.js +6 -2
- package/dist/supervisor.d.ts +21 -2
- package/dist/supervisor.js +74 -5
- package/dist/templates.d.ts +29 -3
- package/dist/templates.js +58 -7
- package/dist/upgrade.d.ts +33 -5
- package/dist/upgrade.js +415 -91
- package/package.json +20 -10
package/dist/rollback.js
CHANGED
|
@@ -1,54 +1,104 @@
|
|
|
1
|
-
/**
|
|
2
|
-
|
|
1
|
+
/**
|
|
2
|
+
* `magnus rollback`: switch back to the version that served before the last
|
|
3
|
+
* upgrade (or before an interrupted one), optionally restoring its dump.
|
|
4
|
+
*/
|
|
5
|
+
import { newestDumpBefore, restoreCommandFor, restoreDatabase } from './database.js';
|
|
3
6
|
import { waitForHealthy } from './health.js';
|
|
4
|
-
import { isInstalled } from './install.js';
|
|
7
|
+
import { isInstalled, migrationReport } from './install.js';
|
|
5
8
|
import { acquireLock, Project } from './project.js';
|
|
6
9
|
import { restartServices, stopServices } from './supervisor.js';
|
|
7
|
-
import { requirePrivileges, UpgradeError } from './upgrade.js';
|
|
10
|
+
import { knownOneWay, requirePrivileges, UpgradeError } from './upgrade.js';
|
|
11
|
+
/** Stop, restore; on failure start the services again on the untouched database. */
|
|
12
|
+
export async function stopAndRestore(io, project, file, yes) {
|
|
13
|
+
io.log(' stopping services for the restore');
|
|
14
|
+
await stopServices(io, project, { confirm: project.state.supervisor === 'none' && !yes });
|
|
15
|
+
try {
|
|
16
|
+
await restoreDatabase(io, project, file);
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
const restartedAt = io.now();
|
|
20
|
+
const restarted = await restartServices(io, project).then(() => waitForHealthy(io, project, {
|
|
21
|
+
version: project.linkedVersion() ?? project.state.current ?? '', startedAfter: restartedAt, timeoutMs: 120_000,
|
|
22
|
+
})).catch((restartError) => ({ ok: false, detail: restartError instanceof Error ? restartError.message : String(restartError) }));
|
|
23
|
+
throw new UpgradeError([
|
|
24
|
+
`The restore of ${file} failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
25
|
+
`The services were started again on the unchanged database (${restarted.ok ? 'healthy' : restarted.detail}).`,
|
|
26
|
+
`Check the dump with \`pg_restore --list ${file}\`, then retry: ${restoreCommandFor(project, file)}`,
|
|
27
|
+
].join('\n'));
|
|
28
|
+
}
|
|
29
|
+
io.log(` restored ${file}`);
|
|
30
|
+
}
|
|
8
31
|
export async function rollback(io, options) {
|
|
9
32
|
const project = Project.load(options.dir);
|
|
10
33
|
requirePrivileges(io, project);
|
|
11
|
-
const release = acquireLock(project.path('run', 'upgrade.lock'));
|
|
34
|
+
const release = acquireLock(project.path('run', 'upgrade.lock'), { breakLock: options.breakLock, command: 'magnus rollback' });
|
|
12
35
|
try {
|
|
13
|
-
const
|
|
14
|
-
const
|
|
36
|
+
const journal = project.state.inProgress;
|
|
37
|
+
const current = journal ? (project.linkedVersion() ?? project.state.current) : project.state.current;
|
|
38
|
+
const previous = journal ? journal.from : project.state.previous;
|
|
15
39
|
if (!current || !previous)
|
|
16
40
|
throw new UpgradeError('Nothing to roll back to: no previous version is recorded.');
|
|
17
41
|
if (!isInstalled(project, previous))
|
|
18
42
|
throw new UpgradeError(`versions/${previous} has been removed, so there is nothing to switch back to. Restore from a backup in ${project.path('backups')} instead.`);
|
|
19
|
-
|
|
20
|
-
|
|
43
|
+
if (journal)
|
|
44
|
+
io.log(`Rolling back the interrupted upgrade ${journal.from} -> ${journal.to} (stopped during "${journal.phase}")`);
|
|
45
|
+
const upgradeEntry = journal ? undefined
|
|
46
|
+
: project.state.history.findLast((entry) => entry.action === 'upgrade' && entry.to === current && entry.result === 'ok');
|
|
47
|
+
// What the database has that `previous` does not know, asked of `previous` itself.
|
|
48
|
+
const report = await migrationReport(io, project, previous).catch(() => null);
|
|
49
|
+
const recorded = journal?.migrations ?? upgradeEntry?.migrations ?? [];
|
|
50
|
+
const ahead = report ? report.unknown.map((m) => m.name) : recorded;
|
|
51
|
+
const oneWay = knownOneWay(project);
|
|
52
|
+
for (const name of journal?.oneWay ?? [])
|
|
53
|
+
oneWay.add(name);
|
|
54
|
+
const aheadOneWay = ahead.filter((name) => oneWay.has(name));
|
|
55
|
+
const firstAhead = report?.unknown.map((m) => m.appliedAt).filter((at) => Boolean(at)).sort()[0] ?? null;
|
|
56
|
+
const dump = journal?.backup ?? upgradeEntry?.backup ?? (ahead.length ? newestDumpBefore(project, firstAhead) : null);
|
|
21
57
|
let restore = false;
|
|
22
|
-
if (
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
if (!restore)
|
|
27
|
-
throw new UpgradeError('Stopped: the restore was not confirmed (pass --yes to confirm non-interactively).');
|
|
28
|
-
}
|
|
29
|
-
else if (upgradeEntry?.backup) {
|
|
30
|
-
io.warn(`${previous} usually works with the newer schema. If it does not, re-run with --restore-db, or restore by hand:\n ${upgradeEntry.restoreCommand ?? ''}`);
|
|
58
|
+
if (options.restoreDb) {
|
|
59
|
+
if (!dump) {
|
|
60
|
+
throw new UpgradeError(`--restore-db cannot be honoured: no dump is recorded for this upgrade${ahead.length ? '' : ' (it applied no migrations)'}. `
|
|
61
|
+
+ `Restore one from ${project.path('backups')} with \`magnus restore <file> --dir ${project.dir}\`, or roll back without --restore-db.`);
|
|
31
62
|
}
|
|
63
|
+
restore = options.yes || await io.confirm(`Restore the database from ${dump}? Changes made since then are lost`);
|
|
64
|
+
if (!restore)
|
|
65
|
+
throw new UpgradeError('Stopped: the restore was not confirmed (pass --yes to confirm non-interactively).');
|
|
32
66
|
}
|
|
33
|
-
if (
|
|
34
|
-
io.
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
67
|
+
else if (ahead.length > 0) {
|
|
68
|
+
io.warn(`The database has ${ahead.length} migration(s) that ${previous} does not know: ${ahead.join(', ')}.`);
|
|
69
|
+
if (aheadOneWay.length > 0 && !options.force) {
|
|
70
|
+
throw new UpgradeError([
|
|
71
|
+
`${aheadOneWay.join(', ')} ${aheadOneWay.length === 1 ? 'is' : 'are'} one-way: ${previous} cannot run on that schema.`,
|
|
72
|
+
dump ? `Roll back with the dump: magnus rollback --restore-db --dir ${project.dir} (restores ${dump})` : `Restore a dump from ${project.path('backups')} with \`magnus restore <file>\`.`,
|
|
73
|
+
'Or start it anyway with --force.',
|
|
74
|
+
].join('\n'));
|
|
75
|
+
}
|
|
76
|
+
if (dump)
|
|
77
|
+
io.warn(`${previous} usually works with the newer schema. If it does not, re-run with --restore-db, or restore by hand:\n ${restoreCommandFor(project, dump)}`);
|
|
38
78
|
}
|
|
79
|
+
if (restore && dump)
|
|
80
|
+
await stopAndRestore(io, project, dump, options.yes);
|
|
39
81
|
const restartedAt = io.now();
|
|
40
|
-
project.
|
|
82
|
+
if (project.linkedVersion() !== previous)
|
|
83
|
+
project.switchCurrent(previous);
|
|
41
84
|
project.state.current = previous;
|
|
42
|
-
project.state.previous = null;
|
|
85
|
+
project.state.previous = journal ? project.state.history.findLast((entry) => entry.to === previous && entry.result === 'ok')?.from ?? null : null;
|
|
86
|
+
delete project.state.inProgress;
|
|
43
87
|
project.save();
|
|
44
88
|
io.log(` switched ./current to ${previous}; restarting`);
|
|
45
|
-
|
|
46
|
-
|
|
89
|
+
let health;
|
|
90
|
+
try {
|
|
91
|
+
await restartServices(io, project);
|
|
92
|
+
health = await waitForHealthy(io, project, { version: previous, startedAfter: restartedAt, timeoutMs: options.healthTimeoutMs });
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
health = { ok: false, detail: `the restart failed: ${error instanceof Error ? error.message : String(error)}` };
|
|
96
|
+
}
|
|
47
97
|
project.record({ action: 'rollback', from: current, to: previous, at: io.now().toISOString(), result: health.ok ? 'ok' : 'failed',
|
|
48
|
-
migrations: [], ...(health.ok ? {} : { reason: health.detail }) });
|
|
98
|
+
migrations: [], ...(restore && dump ? { backup: dump } : {}), ...(health.ok ? {} : { reason: health.detail }) });
|
|
49
99
|
project.save();
|
|
50
100
|
if (!health.ok) {
|
|
51
|
-
io.warn(`Rolled back to ${previous}, but it is ${health.detail}
|
|
101
|
+
io.warn(`Rolled back to ${previous}, but it is ${health.detail}.${dump && !restore ? ` If the newer schema is the cause: ${restoreCommandFor(project, dump)}` : ''}`);
|
|
52
102
|
return 1;
|
|
53
103
|
}
|
|
54
104
|
io.log(`Rolled back from ${current} to ${previous}: ${health.detail}.`);
|
package/dist/status.js
CHANGED
|
@@ -3,7 +3,8 @@ import { existsSync, readdirSync } from 'node:fs';
|
|
|
3
3
|
import { compareVersions, latestVersion } from '@hivemagnus/magnus-contracts';
|
|
4
4
|
import { readRuntime } from './health.js';
|
|
5
5
|
import { Project } from './project.js';
|
|
6
|
-
import { fetchRegistryCatalog } from './release.js';
|
|
6
|
+
import { automaticCandidates, fetchRegistryCatalog } from './release.js';
|
|
7
|
+
import { journalMessage } from './upgrade.js';
|
|
7
8
|
export async function status(io, options) {
|
|
8
9
|
const project = Project.load(options.dir);
|
|
9
10
|
const versionsDir = project.path('versions');
|
|
@@ -15,7 +16,7 @@ export async function status(io, options) {
|
|
|
15
16
|
if (!options.offline && project.state.current) {
|
|
16
17
|
try {
|
|
17
18
|
const catalog = await fetchRegistryCatalog(io, options.registry);
|
|
18
|
-
latest = { sameMajor: latestVersion(catalog
|
|
19
|
+
latest = { sameMajor: latestVersion(automaticCandidates(catalog), { sameMajorAs: project.state.current }), any: latestVersion(automaticCandidates(catalog)) };
|
|
19
20
|
}
|
|
20
21
|
catch (error) {
|
|
21
22
|
latest = { sameMajor: null, any: null, error: error instanceof Error ? error.message : String(error) };
|
|
@@ -31,6 +32,7 @@ export async function status(io, options) {
|
|
|
31
32
|
installed,
|
|
32
33
|
serving: runtime ? { version: runtime.version, pid: runtime.pid, startedAt: runtime.startedAt } : null,
|
|
33
34
|
latest,
|
|
35
|
+
inProgress: project.state.inProgress ?? null,
|
|
34
36
|
history: project.state.history.slice(-5),
|
|
35
37
|
};
|
|
36
38
|
if (options.json) {
|
|
@@ -51,6 +53,8 @@ export async function status(io, options) {
|
|
|
51
53
|
io.log(` ${latest.any} is a new major version; see UPGRADING.md before \`magnus upgrade --to ${latest.any} --allow-major\``);
|
|
52
54
|
}
|
|
53
55
|
}
|
|
56
|
+
if (report.inProgress)
|
|
57
|
+
io.warn(journalMessage(project, report.inProgress));
|
|
54
58
|
for (const entry of report.history) {
|
|
55
59
|
io.log(` ${entry.at} ${entry.action} ${entry.from ?? '-'} -> ${entry.to}: ${entry.result}${entry.reason ? ` (${entry.reason})` : ''}`);
|
|
56
60
|
}
|
package/dist/supervisor.d.ts
CHANGED
|
@@ -1,9 +1,28 @@
|
|
|
1
1
|
import { type Io } from './io.js';
|
|
2
|
-
import type
|
|
2
|
+
import { type Project } from './project.js';
|
|
3
3
|
export declare function unitDirectory(project: Project, env: NodeJS.ProcessEnv): string;
|
|
4
4
|
export declare function systemctl(io: Io, project: Project, ...args: string[]): Promise<void>;
|
|
5
|
+
/**
|
|
6
|
+
* systemd needs Linux, and user units need a session bus: `sudo` or a
|
|
7
|
+
* plain ssh session without lingering has none, and every systemctl call
|
|
8
|
+
* would fail after the database was already migrated.
|
|
9
|
+
*/
|
|
10
|
+
export declare function checkSupervisor(io: Io, supervisor: Project['state']['supervisor'], scope: Project['state']['scope']): Promise<void>;
|
|
11
|
+
/**
|
|
12
|
+
* Rewrite units generated by an older engine with the current start limit
|
|
13
|
+
* and Node.js path (project copies and, for systemd, the installed ones).
|
|
14
|
+
* Units the operator wrote or changed beyond recognition are left alone.
|
|
15
|
+
*/
|
|
16
|
+
export declare function refreshUnits(io: Io, project: Project, nodePath?: string): string[];
|
|
5
17
|
export declare function manualRestartHint(project: Project): string;
|
|
6
18
|
/** Restart every component (server first, so the console reconnects to the new API). */
|
|
7
19
|
export declare function restartServices(io: Io, project: Project): Promise<void>;
|
|
8
|
-
|
|
20
|
+
/**
|
|
21
|
+
* Stop every component. Without a supervisor the operator stops them: wait
|
|
22
|
+
* until the server port stops answering (and, interactively, for a yes).
|
|
23
|
+
*/
|
|
24
|
+
export declare function stopServices(io: Io, project: Project, options?: {
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
confirm?: boolean;
|
|
27
|
+
}): Promise<void>;
|
|
9
28
|
export declare function enableServices(io: Io, project: Project): Promise<void>;
|
package/dist/supervisor.js
CHANGED
|
@@ -1,7 +1,10 @@
|
|
|
1
1
|
/** Starting, stopping and restarting the project's services. */
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
4
|
import { join } from 'node:path';
|
|
4
5
|
import { mustRun } from './io.js';
|
|
6
|
+
import { writeAtomic } from './project.js';
|
|
7
|
+
import { refreshUnit, UNIT_MARKER } from './templates.js';
|
|
5
8
|
export function unitDirectory(project, env) {
|
|
6
9
|
return project.state.scope === 'system'
|
|
7
10
|
? '/etc/systemd/system'
|
|
@@ -14,7 +17,54 @@ function unitNames(project, components = project.state.components) {
|
|
|
14
17
|
return components.map((component) => `${project.state.units[component]}.service`);
|
|
15
18
|
}
|
|
16
19
|
export async function systemctl(io, project, ...args) {
|
|
17
|
-
|
|
20
|
+
// Its own process group: a Ctrl-C during the upgrade never kills a restart halfway.
|
|
21
|
+
await mustRun(io, 'systemctl', systemctlArgs(project, args), { capture: true, detached: true });
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* systemd needs Linux, and user units need a session bus: `sudo` or a
|
|
25
|
+
* plain ssh session without lingering has none, and every systemctl call
|
|
26
|
+
* would fail after the database was already migrated.
|
|
27
|
+
*/
|
|
28
|
+
export async function checkSupervisor(io, supervisor, scope) {
|
|
29
|
+
if (supervisor !== 'systemd')
|
|
30
|
+
return;
|
|
31
|
+
if (io.platform !== 'linux')
|
|
32
|
+
throw new Error(`systemd units need Linux; on ${io.platform} use --supervisor none and run the processes under your own service manager.`);
|
|
33
|
+
const args = scope === 'user' ? ['--user', 'show-environment'] : ['show-environment'];
|
|
34
|
+
const result = await io.run('systemctl', args, { capture: true }).catch((error) => ({ code: 1, stdout: '', stderr: error instanceof Error ? error.message : String(error) }));
|
|
35
|
+
if (result.code !== 0) {
|
|
36
|
+
throw new Error([
|
|
37
|
+
`\`systemctl ${args.join(' ')}\` failed: ${(result.stderr || result.stdout).trim().split('\n').slice(-2).join(' ') || `exit ${result.code}`}.`,
|
|
38
|
+
scope === 'user'
|
|
39
|
+
? 'User units need the session bus of the account that owns the project: log in as that account (not through sudo or su), or run `loginctl enable-linger <account>` and use `machinectl shell <account>@`.'
|
|
40
|
+
: 'Is systemd running on this host?',
|
|
41
|
+
].join('\n'));
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Rewrite units generated by an older engine with the current start limit
|
|
46
|
+
* and Node.js path (project copies and, for systemd, the installed ones).
|
|
47
|
+
* Units the operator wrote or changed beyond recognition are left alone.
|
|
48
|
+
*/
|
|
49
|
+
export function refreshUnits(io, project, nodePath) {
|
|
50
|
+
const changed = [];
|
|
51
|
+
const dirs = [project.path('units'), ...(project.state.supervisor === 'systemd' ? [unitDirectory(project, io.env)] : [])];
|
|
52
|
+
for (const dir of dirs) {
|
|
53
|
+
for (const component of project.state.components) {
|
|
54
|
+
const file = join(dir, `${project.state.units[component]}.service`);
|
|
55
|
+
if (!existsSync(file))
|
|
56
|
+
continue;
|
|
57
|
+
const content = readFileSync(file, 'utf8');
|
|
58
|
+
if (!content.startsWith(UNIT_MARKER) || !content.includes(project.bin('current', component === 'server' ? 'magnus-server' : 'magnus-ui')))
|
|
59
|
+
continue;
|
|
60
|
+
const next = refreshUnit(content, nodePath);
|
|
61
|
+
if (next !== content) {
|
|
62
|
+
writeAtomic(file, next, 0o644);
|
|
63
|
+
changed.push(file);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return changed;
|
|
18
68
|
}
|
|
19
69
|
export function manualRestartHint(project) {
|
|
20
70
|
if (project.state.supervisor === 'none')
|
|
@@ -28,21 +78,40 @@ export async function restartServices(io, project) {
|
|
|
28
78
|
switch (project.state.supervisor) {
|
|
29
79
|
case 'systemd':
|
|
30
80
|
await systemctl(io, project, 'daemon-reload');
|
|
31
|
-
for (const unit of unitNames(project))
|
|
81
|
+
for (const unit of unitNames(project)) {
|
|
82
|
+
// StartLimitBurst guards unattended crash loops; an operator's upgrade, revert or restore
|
|
83
|
+
// restarts deliberately, so clear the counter first or a quick revert-then-restore is refused.
|
|
84
|
+
await systemctl(io, project, 'reset-failed', unit);
|
|
32
85
|
await systemctl(io, project, 'restart', unit);
|
|
86
|
+
}
|
|
33
87
|
return;
|
|
34
88
|
case 'none':
|
|
35
89
|
io.log(`Restart the Magnus server and console now so they run ./current: ${manualRestartHint(project)}. Waiting for them…`);
|
|
36
90
|
return;
|
|
37
91
|
}
|
|
38
92
|
}
|
|
39
|
-
|
|
93
|
+
/**
|
|
94
|
+
* Stop every component. Without a supervisor the operator stops them: wait
|
|
95
|
+
* until the server port stops answering (and, interactively, for a yes).
|
|
96
|
+
*/
|
|
97
|
+
export async function stopServices(io, project, options = {}) {
|
|
40
98
|
if (project.state.supervisor === 'systemd') {
|
|
41
99
|
for (const unit of unitNames(project).reverse())
|
|
42
100
|
await systemctl(io, project, 'stop', unit);
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
io.log(`Stop the Magnus server and console now (the processes started from ${project.path('units')}/*.service). Waiting for port ${project.state.ports.server} to close…`);
|
|
104
|
+
const deadline = io.now().getTime() + (options.timeoutMs ?? 300_000);
|
|
105
|
+
for (;;) {
|
|
106
|
+
const answer = await io.probe(`https://127.0.0.1:${project.state.ports.server}/api/v1/health`);
|
|
107
|
+
if (answer === null)
|
|
108
|
+
break;
|
|
109
|
+
if (io.now().getTime() >= deadline)
|
|
110
|
+
throw new Error(`The server on port ${project.state.ports.server} is still running; stop it and re-run.`);
|
|
111
|
+
await io.sleep(2_000);
|
|
43
112
|
}
|
|
44
|
-
|
|
45
|
-
|
|
113
|
+
if (options.confirm && !await io.confirm('Are the Magnus server and console both stopped?')) {
|
|
114
|
+
throw new Error('Stopped: the services were not confirmed stopped.');
|
|
46
115
|
}
|
|
47
116
|
}
|
|
48
117
|
export async function enableServices(io, project) {
|
package/dist/templates.d.ts
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
|
+
/** Generated files: systemd units, env files and the optional PostgreSQL/Redis compose file. */
|
|
2
|
+
import { type EnvEntry } from './env-file.js';
|
|
1
3
|
import type { Project } from './project.js';
|
|
2
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* npm install scripts the project's dependency tree needs (npm 12 blocks all
|
|
6
|
+
* others). A release's manifest carries its own list (`allowScripts`), which
|
|
7
|
+
* wins: the installing engine may be older than the release it installs.
|
|
8
|
+
*/
|
|
3
9
|
export declare const ALLOW_SCRIPTS: Readonly<Record<string, true>>;
|
|
4
10
|
export declare const SERVER_SECRET_NAMES: readonly ["API_SECRET", "JWT_SECRET", "NODE_MANAGER_SECRET", "AUDIT_HMAC_SECRET", "RESULT_SIGNING_SECRET", "LOG_INGEST_SIGNING_SECRET", "CREDENTIAL_ROTATION_KEY", "METRICS_TOKEN", "WEBHOOK_ENCRYPTION_KEY"];
|
|
5
11
|
export interface ServiceUnitOptions {
|
|
@@ -10,8 +16,20 @@ export interface ServiceUnitOptions {
|
|
|
10
16
|
afterUnits: string[];
|
|
11
17
|
/** Extra CA trusted by the server when it calls agents (the self-signed certificate on one host). */
|
|
12
18
|
extraCaFile?: string;
|
|
19
|
+
/** More directories the server writes to (an adopted install's MAGNUS_HOME and MAGNUS_BACKUP_DIR). */
|
|
20
|
+
extraWritable?: string[];
|
|
13
21
|
}
|
|
22
|
+
export declare const UNIT_MARKER = "# Generated by `magnus init`";
|
|
23
|
+
/** At most three failed starts in five minutes: a crash loop stops instead of filling the disk with dumps. */
|
|
24
|
+
export declare const START_LIMIT: string[];
|
|
14
25
|
export declare function serverUnit(options: ServiceUnitOptions): string;
|
|
26
|
+
/**
|
|
27
|
+
* Bring a unit generated by an older engine up to date without touching
|
|
28
|
+
* anything else in it: the start limit, and the Node.js binary in ExecStart.
|
|
29
|
+
*/
|
|
30
|
+
export declare function refreshUnit(content: string, nodePath?: string): string;
|
|
31
|
+
/** docker compose project name for a new project's PostgreSQL and Redis. */
|
|
32
|
+
export declare function composeProjectName(dir: string): string;
|
|
15
33
|
export declare function uiUnit(options: ServiceUnitOptions): string;
|
|
16
34
|
export interface DepsSettings {
|
|
17
35
|
postgresPort: number;
|
|
@@ -20,7 +38,7 @@ export interface DepsSettings {
|
|
|
20
38
|
redisPassword: string;
|
|
21
39
|
}
|
|
22
40
|
/** PostgreSQL 17 and Redis 7 on loopback, for hosts without their own. */
|
|
23
|
-
export declare function depsCompose(): string;
|
|
41
|
+
export declare function depsCompose(name?: string): string;
|
|
24
42
|
export declare function depsEnv(settings: DepsSettings): string;
|
|
25
43
|
export interface ServerEnvSettings {
|
|
26
44
|
databaseUrl: string;
|
|
@@ -35,8 +53,16 @@ export interface ServerEnvSettings {
|
|
|
35
53
|
/** Trusted when the server (or `magnus-server agents`) calls agents. */
|
|
36
54
|
extraCaFile?: string;
|
|
37
55
|
autoMigrate: boolean;
|
|
56
|
+
projectDir: string;
|
|
57
|
+
runtimeFile: string;
|
|
38
58
|
}
|
|
39
59
|
export declare function serverEnv(settings: ServerEnvSettings, secrets: Record<string, string>): string;
|
|
60
|
+
/**
|
|
61
|
+
* Where `magnus upgrade` looks for the serving version. Also in the env file,
|
|
62
|
+
* so a server started by hand or another supervisor (`--supervisor none`)
|
|
63
|
+
* writes the runtime file the health check reads.
|
|
64
|
+
*/
|
|
65
|
+
export declare function projectEnv(projectDir: string, runtimeFile: string): EnvEntry[];
|
|
40
66
|
export interface UiEnvSettings {
|
|
41
67
|
serverUrl: string;
|
|
42
68
|
serverCa?: string;
|
|
@@ -50,4 +76,4 @@ export interface UiEnvSettings {
|
|
|
50
76
|
}
|
|
51
77
|
export declare function uiEnv(settings: UiEnvSettings, apiSecret: string): string;
|
|
52
78
|
/** package.json of one installed version. */
|
|
53
|
-
export declare function versionPackageJson(version: string, dependencies: Record<string, string>, overrides?: Record<string, string | Record<string, string>>): string;
|
|
79
|
+
export declare function versionPackageJson(version: string, dependencies: Record<string, string>, overrides?: Record<string, string | Record<string, string>>, allowScripts?: Readonly<Record<string, boolean>>): string;
|
package/dist/templates.js
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
/** Generated files: systemd units, env files and the optional PostgreSQL/Redis compose file. */
|
|
2
2
|
import { generateSecret, renderEnv } from './env-file.js';
|
|
3
|
-
/**
|
|
3
|
+
/**
|
|
4
|
+
* npm install scripts the project's dependency tree needs (npm 12 blocks all
|
|
5
|
+
* others). A release's manifest carries its own list (`allowScripts`), which
|
|
6
|
+
* wins: the installing engine may be older than the release it installs.
|
|
7
|
+
*/
|
|
4
8
|
export const ALLOW_SCRIPTS = Object.freeze({
|
|
5
9
|
'@prisma/engines': true,
|
|
6
10
|
argon2: true,
|
|
@@ -22,13 +26,17 @@ export const SERVER_SECRET_NAMES = [
|
|
|
22
26
|
'METRICS_TOKEN',
|
|
23
27
|
'WEBHOOK_ENCRYPTION_KEY',
|
|
24
28
|
];
|
|
29
|
+
export const UNIT_MARKER = '# Generated by `magnus init`';
|
|
30
|
+
/** At most three failed starts in five minutes: a crash loop stops instead of filling the disk with dumps. */
|
|
31
|
+
export const START_LIMIT = ['StartLimitIntervalSec=300', 'StartLimitBurst=3'];
|
|
25
32
|
function unitHeader(description, afterUnits) {
|
|
26
33
|
return [
|
|
27
|
-
|
|
34
|
+
`${UNIT_MARKER}; \`magnus upgrade\` keeps it pointing at ./current.`,
|
|
28
35
|
'[Unit]',
|
|
29
36
|
`Description=${description}`,
|
|
30
37
|
`After=network-online.target${afterUnits.length ? ` ${afterUnits.join(' ')}` : ''}`,
|
|
31
38
|
'Wants=network-online.target',
|
|
39
|
+
...START_LIMIT,
|
|
32
40
|
'',
|
|
33
41
|
'[Service]',
|
|
34
42
|
'Type=simple',
|
|
@@ -59,9 +67,40 @@ export function serverUnit(options) {
|
|
|
59
67
|
`Environment=MAGNUS_RUNTIME_FILE=${project.path('run', 'server-runtime.json')}`,
|
|
60
68
|
...(options.extraCaFile ? [`Environment=NODE_EXTRA_CA_CERTS=${options.extraCaFile}`] : []),
|
|
61
69
|
`ExecStart=${options.nodePath} ${project.bin('current', 'magnus-server')} start --env-file ${project.envFile('server')}`,
|
|
62
|
-
...hardening(options, [project.dir]),
|
|
70
|
+
...hardening(options, [project.dir, ...(options.extraWritable ?? []).filter((path) => !path.startsWith(`${project.dir}/`))]),
|
|
63
71
|
].join('\n');
|
|
64
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Bring a unit generated by an older engine up to date without touching
|
|
75
|
+
* anything else in it: the start limit, and the Node.js binary in ExecStart.
|
|
76
|
+
*/
|
|
77
|
+
export function refreshUnit(content, nodePath) {
|
|
78
|
+
let lines = content.split('\n');
|
|
79
|
+
const unitAt = lines.indexOf('[Unit]');
|
|
80
|
+
if (unitAt >= 0 && !lines.some((line) => line.startsWith('StartLimitIntervalSec='))) {
|
|
81
|
+
const end = lines.findIndex((line, index) => index > unitAt && (line.startsWith('[') || line === ''));
|
|
82
|
+
lines.splice(end < 0 ? lines.length : end, 0, ...START_LIMIT);
|
|
83
|
+
}
|
|
84
|
+
if (nodePath)
|
|
85
|
+
lines = lines.map((line) => (line.startsWith('ExecStart=') ? line.replace(/^ExecStart=\S+/, `ExecStart=${nodePath}`) : line));
|
|
86
|
+
return lines.join('\n');
|
|
87
|
+
}
|
|
88
|
+
/** docker compose project name for a new project's PostgreSQL and Redis. */
|
|
89
|
+
export function composeProjectName(dir) {
|
|
90
|
+
const base = dir.split(/[\\/]/).filter(Boolean).pop() ?? 'magnus';
|
|
91
|
+
// Linear trim of the separators (no backtracking regex on a caller-supplied path).
|
|
92
|
+
let slug = base.toLowerCase().slice(0, 64).replace(/[^a-z0-9]+/g, '-');
|
|
93
|
+
let start = 0, end = slug.length;
|
|
94
|
+
while (start < end && slug[start] === '-')
|
|
95
|
+
start++;
|
|
96
|
+
while (end > start && slug[end - 1] === '-')
|
|
97
|
+
end--;
|
|
98
|
+
slug = slug.slice(start, end) || 'project';
|
|
99
|
+
let hash = 0;
|
|
100
|
+
for (const char of dir)
|
|
101
|
+
hash = (hash * 31 + char.charCodeAt(0)) >>> 0;
|
|
102
|
+
return `magnus-deps-${slug}-${hash.toString(36).slice(0, 6)}`;
|
|
103
|
+
}
|
|
65
104
|
export function uiUnit(options) {
|
|
66
105
|
const { project } = options;
|
|
67
106
|
const dataDir = project.path('ui-data');
|
|
@@ -74,9 +113,9 @@ export function uiUnit(options) {
|
|
|
74
113
|
].join('\n');
|
|
75
114
|
}
|
|
76
115
|
/** PostgreSQL 17 and Redis 7 on loopback, for hosts without their own. */
|
|
77
|
-
export function depsCompose() {
|
|
116
|
+
export function depsCompose(name = 'magnus-deps') {
|
|
78
117
|
return `# Generated by \`magnus init\`: PostgreSQL and Redis for Magnus, bound to loopback.
|
|
79
|
-
name:
|
|
118
|
+
name: ${name}
|
|
80
119
|
services:
|
|
81
120
|
postgres:
|
|
82
121
|
image: postgres:17-alpine
|
|
@@ -130,6 +169,7 @@ export function serverEnv(settings, secrets) {
|
|
|
130
169
|
{ name: 'NODE_ENV', value: 'production' },
|
|
131
170
|
{ name: 'MAGNUS_HOME', value: settings.home, comment: 'Server data: audit logs, credential rotation state.' },
|
|
132
171
|
{ name: 'MAGNUS_BACKUP_DIR', value: settings.backupDir, comment: 'Pre-migration database dumps.' },
|
|
172
|
+
...projectEnv(settings.projectDir, settings.runtimeFile),
|
|
133
173
|
{ name: 'DATABASE_URL', value: settings.databaseUrl },
|
|
134
174
|
{ name: 'REDIS_URL', value: settings.redisUrl },
|
|
135
175
|
] },
|
|
@@ -151,6 +191,17 @@ export function serverEnv(settings, secrets) {
|
|
|
151
191
|
] },
|
|
152
192
|
]);
|
|
153
193
|
}
|
|
194
|
+
/**
|
|
195
|
+
* Where `magnus upgrade` looks for the serving version. Also in the env file,
|
|
196
|
+
* so a server started by hand or another supervisor (`--supervisor none`)
|
|
197
|
+
* writes the runtime file the health check reads.
|
|
198
|
+
*/
|
|
199
|
+
export function projectEnv(projectDir, runtimeFile) {
|
|
200
|
+
return [
|
|
201
|
+
{ name: 'MAGNUS_PROJECT_DIR', value: projectDir, comment: 'Managed project (magnus-project.json).' },
|
|
202
|
+
{ name: 'MAGNUS_RUNTIME_FILE', value: runtimeFile, comment: 'Read by `magnus upgrade` to confirm which version is serving.' },
|
|
203
|
+
];
|
|
204
|
+
}
|
|
154
205
|
export function uiEnv(settings, apiSecret) {
|
|
155
206
|
return renderEnv('magnus-ui configuration, generated by `magnus init`. Keep this file private (0600).\n'
|
|
156
207
|
+ 'Every variable: `magnus-ui env-schema`.', [
|
|
@@ -173,7 +224,7 @@ export function uiEnv(settings, apiSecret) {
|
|
|
173
224
|
]);
|
|
174
225
|
}
|
|
175
226
|
/** package.json of one installed version. */
|
|
176
|
-
export function versionPackageJson(version, dependencies, overrides = {}) {
|
|
227
|
+
export function versionPackageJson(version, dependencies, overrides = {}, allowScripts = ALLOW_SCRIPTS) {
|
|
177
228
|
return `${JSON.stringify({
|
|
178
229
|
name: `magnus-project-${version}`,
|
|
179
230
|
version,
|
|
@@ -182,6 +233,6 @@ export function versionPackageJson(version, dependencies, overrides = {}) {
|
|
|
182
233
|
type: 'module',
|
|
183
234
|
dependencies,
|
|
184
235
|
...(Object.keys(overrides).length ? { overrides } : {}),
|
|
185
|
-
allowScripts
|
|
236
|
+
allowScripts,
|
|
186
237
|
}, null, 2)}\n`;
|
|
187
238
|
}
|
package/dist/upgrade.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { type ReleaseEnvChange } from '@hivemagnus/magnus-contracts';
|
|
2
|
-
import { type
|
|
3
|
-
import {
|
|
2
|
+
import { type Backup } from './database.js';
|
|
3
|
+
import type { Io } from './io.js';
|
|
4
|
+
import { Project, type UpgradeJournal } from './project.js';
|
|
4
5
|
import { type ReleaseCatalog } from './release.js';
|
|
5
6
|
export interface UpgradeOptions {
|
|
6
7
|
dir: string;
|
|
@@ -12,15 +13,42 @@ export interface UpgradeOptions {
|
|
|
12
13
|
source?: string;
|
|
13
14
|
registry: string;
|
|
14
15
|
healthTimeoutMs: number;
|
|
15
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* Finish an upgrade the journal says was interrupted; also set when an
|
|
18
|
+
* older engine hands a release it installed to this (newer) engine.
|
|
19
|
+
*/
|
|
16
20
|
resume: boolean;
|
|
21
|
+
/** Start the previous version after a failed upgrade even over one-way migrations. */
|
|
22
|
+
force?: boolean;
|
|
23
|
+
breakLock?: boolean;
|
|
24
|
+
/** Switch the Node.js the services run (and the upgrade uses); the units are rewritten. */
|
|
25
|
+
nodePath?: string;
|
|
17
26
|
}
|
|
18
27
|
export declare class UpgradeError extends Error {
|
|
19
28
|
}
|
|
29
|
+
export declare class InterruptedError extends UpgradeError {
|
|
30
|
+
}
|
|
31
|
+
/** Free space an npm install of one release needs. */
|
|
32
|
+
export declare const INSTALL_BYTES: number;
|
|
20
33
|
export declare function loadCatalog(io: Io, options: Pick<UpgradeOptions, 'source' | 'registry'>): Promise<ReleaseCatalog>;
|
|
21
34
|
export declare function requirePrivileges(io: Io, project: Project): void;
|
|
22
35
|
/** New required variables that the project's env files do not set yet. */
|
|
23
36
|
export declare function missingEnv(project: Project, required: readonly ReleaseEnvChange[]): ReleaseEnvChange[];
|
|
37
|
+
/** What the next command says about an interrupted upgrade. */
|
|
38
|
+
export declare function journalMessage(project: Project, journal: UpgradeJournal): string;
|
|
39
|
+
/** Free space for the npm install (and, when `dumpBytes` is given, the dump). Returns problems. */
|
|
40
|
+
export declare function diskProblems(io: Io, project: Project, needs: {
|
|
41
|
+
install: boolean;
|
|
42
|
+
dumpBytes: number | null;
|
|
43
|
+
}): string[];
|
|
24
44
|
export declare function upgrade(io: Io, options: UpgradeOptions): Promise<number>;
|
|
25
|
-
|
|
26
|
-
|
|
45
|
+
interface Prior {
|
|
46
|
+
backup: Backup;
|
|
47
|
+
oneWay: string[];
|
|
48
|
+
migrations: string[];
|
|
49
|
+
}
|
|
50
|
+
/** Every migration history marks one-way (the impact the manifest gave when it was applied). */
|
|
51
|
+
export declare function knownOneWay(project: Project): Set<string>;
|
|
52
|
+
/** Check, back up, migrate, switch, restart, verify; revert on failure. */
|
|
53
|
+
export declare function applyInstalled(io: Io, project: Project, current: string, target: string, options: UpgradeOptions, prior?: Prior): Promise<number>;
|
|
54
|
+
export {};
|