@hivemagnus/magnus 1.1.1 → 1.1.3

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 CHANGED
@@ -55,15 +55,22 @@ magnus upgrade [--to X.Y.Z] [--yes] [--generate-secrets] [--allow-major] [--sour
55
55
 
56
56
  An upgrade:
57
57
 
58
- 1. Checks the registry and the Node.js engines.
58
+ 1. Checks the registry and the Node.js the services run (`--node PATH` switches it).
59
59
  2. Refuses a downgrade or a major-version change (unless `--allow-major`).
60
- 3. Checks for new required settings.
60
+ 3. Checks for new required settings, free disk space and the systemd session bus.
61
61
  4. Installs the release into `versions/<X>`.
62
- 5. Dumps PostgreSQL, migrates and checks.
63
- 6. Switches `./current`, restarts and waits for the new version to serve.
64
- 7. If the new version is unhealthy, switches back and prints the database restore command.
62
+ 5. Runs the new version's configuration check and a start-up test, before the database is touched.
63
+ 6. Dumps PostgreSQL and migrates.
64
+ 7. Switches `./current`, restarts and waits for the new version to serve.
65
+ 8. If the new version is unhealthy, switches back and prints the database restore command.
65
66
 
66
- Slow or one-way migrations need `--yes`.
67
+ Slow or one-way migrations need `--yes`. An upgrade that is interrupted is recorded in
68
+ `magnus-project.json`; finish it with `magnus upgrade --resume` or go back with `magnus rollback`.
69
+
70
+ ```bash
71
+ magnus rollback [--restore-db] [--force] # back to the previous version
72
+ magnus restore <dump> # stop, restore into a clean schema, start again
73
+ ```
67
74
 
68
75
  `magnus-server upgrade` hands the same command to the project it was installed into.
69
76
 
package/dist/adopt.js CHANGED
@@ -5,13 +5,13 @@
5
5
  * at ./current. Nothing running is touched unless --install-units is given.
6
6
  */
7
7
  import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
8
- import { join, resolve } from 'node:path';
8
+ import { isAbsolute, join, resolve } from 'node:path';
9
9
  import { isVersion } from '@hivemagnus/magnus-contracts';
10
10
  import { readEnvFile } from './env-file.js';
11
11
  import { installVersion, publishPins } from './install.js';
12
12
  import { acquireLock, Project } from './project.js';
13
13
  import { releaseFor } from './release.js';
14
- import { enableServices, unitDirectory } from './supervisor.js';
14
+ import { checkSupervisor, enableServices, unitDirectory } from './supervisor.js';
15
15
  import { serverUnit, uiUnit } from './templates.js';
16
16
  import { loadCatalog, UpgradeError } from './upgrade.js';
17
17
  import { defaultProjectDir } from './init.js';
@@ -32,6 +32,14 @@ export async function adopt(io, options) {
32
32
  const dir = resolve(options.dir ?? defaultProjectDir(io, options.system));
33
33
  if (Project.exists(dir))
34
34
  throw new UpgradeError(`${dir} already holds a Magnus project.`);
35
+ if (options.supervisor === 'systemd') {
36
+ if (io.platform !== 'linux')
37
+ throw new UpgradeError(`systemd units need Linux; on ${io.platform} pass --supervisor none.`);
38
+ if (options.installUnits)
39
+ await checkSupervisor(io, 'systemd', options.system ? 'system' : 'user').catch((error) => {
40
+ throw new UpgradeError(error instanceof Error ? error.message : String(error));
41
+ });
42
+ }
35
43
  const version = options.version ?? await detectVersion(io);
36
44
  if (!version)
37
45
  throw new UpgradeError('Could not detect the installed version; pass --version X.Y.Z (the output of `magnus-server --version`).');
@@ -51,6 +59,8 @@ export async function adopt(io, options) {
51
59
  current: null,
52
60
  previous: null,
53
61
  keepVersions: 3,
62
+ keepBackups: 5,
63
+ nodePath: process.execPath,
54
64
  history: [],
55
65
  };
56
66
  mkdirSync(dir, { recursive: true });
@@ -67,7 +77,9 @@ export async function adopt(io, options) {
67
77
  project.record({ action: 'adopt', from: null, to: version, at: io.now().toISOString(), result: 'ok', migrations: [] });
68
78
  publishPins(project, version);
69
79
  project.save();
70
- const unitOptions = { project, nodePath: process.execPath, serviceUser: options.serviceUser, afterUnits: [] };
80
+ // An adopted install keeps its data where it was: the system units must be allowed to write there.
81
+ const extraWritable = ['MAGNUS_HOME', 'MAGNUS_BACKUP_DIR'].map((name) => serverEnv[name]).filter((path) => Boolean(path && isAbsolute(path)));
82
+ const unitOptions = { project, nodePath: project.nodePath(), serviceUser: options.serviceUser, afterUnits: [], extraWritable };
71
83
  const units = { 'magnus-server.service': serverUnit(unitOptions) };
72
84
  if (uiEnvFile)
73
85
  units['magnus-ui.service'] = uiUnit(unitOptions);
package/dist/cli.js CHANGED
@@ -1,7 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  /** Entry point of the `magnus` command; see main.ts for the commands. */
3
+ import { spawnSync } from 'node:child_process';
3
4
  import { systemIo } from './io.js';
4
5
  import { ArgsError, run } from './main.js';
6
+ // Node.js fetch ignores HTTP(S)_PROXY unless NODE_USE_ENV_PROXY is set at startup.
7
+ const proxy = process.env['HTTPS_PROXY'] || process.env['https_proxy'] || process.env['HTTP_PROXY'] || process.env['http_proxy'];
8
+ if (proxy && !process.env['NODE_USE_ENV_PROXY']) {
9
+ const child = spawnSync(process.execPath, process.argv.slice(1), { stdio: 'inherit', env: { ...process.env, NODE_USE_ENV_PROXY: '1' } });
10
+ process.exit(child.status ?? 1);
11
+ }
5
12
  run(systemIo(), process.argv.slice(2)).then((code) => process.exit(code), (error) => {
6
13
  if (error instanceof ArgsError) {
7
14
  console.error(`magnus: ${error.message}. Run \`magnus --help\` for usage.`);
@@ -4,12 +4,33 @@ export interface Backup {
4
4
  file: string;
5
5
  restoreCommand: string;
6
6
  }
7
+ export declare function shellQuote(value: string): string;
8
+ /** What to run to restore a dump: stops the services, restores into a clean schema, starts them again. */
7
9
  export declare function restoreCommandFor(project: Project, file: string): string;
10
+ /** First server release with `magnus-server restore` (and the clean-schema restore). */
11
+ export declare const SERVER_RESTORE_SINCE = "1.1.3";
12
+ /** Bytes the database occupies (an upper bound for its dump), or null when it cannot be asked. */
13
+ export declare function databaseBytes(io: Io, project: Project): Promise<number | null>;
14
+ /**
15
+ * Keep the newest `keep` dumps in backups/; older ones go, except the newest
16
+ * dump of each label (the one a rollback of that step restores) and any file
17
+ * in `protect`.
18
+ */
19
+ export declare function pruneBackups(dir: string, keep: number, protect?: readonly string[]): string[];
8
20
  /**
9
21
  * Dump before migrating. Compose databases are dumped with the container's own
10
22
  * pg_dump (always the server's version); external ones through the target
11
- * server's `magnus-server backup`, which checks the pg_dump version.
23
+ * server's `magnus-server backup`, which checks the pg_dump version. Either
24
+ * dump is read back with `pg_restore --list` before it counts.
12
25
  */
13
26
  export declare function backupDatabase(io: Io, project: Project, version: string, label: string): Promise<Backup>;
14
- /** Restore a dump. The services must be stopped first. */
27
+ /**
28
+ * Restore a dump into a clean schema (see restoreSwapSql in
29
+ * @hivemagnus/magnus-contracts). The services must be stopped first.
30
+ */
15
31
  export declare function restoreDatabase(io: Io, project: Project, file: string): Promise<void>;
32
+ /**
33
+ * Newest dump taken before `before` (the first migration this version does
34
+ * not know was applied then), for restore guidance when history has none.
35
+ */
36
+ export declare function newestDumpBefore(project: Project, before: string | null): string | null;
package/dist/database.js CHANGED
@@ -1,29 +1,83 @@
1
1
  /** Pre-migration dumps and restores for both database kinds a project can use. */
2
- import { closeSync, chmodSync, mkdirSync, openSync, statSync, writeFileSync } from 'node:fs';
3
- import { join } from 'node:path';
2
+ import { closeSync, chmodSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
+ import { basename, dirname, join } from 'node:path';
4
+ import { compareVersions, restoreAsideSchema, restoreFinishSql, restoreRevertSql, restoreSwapSql } from '@hivemagnus/magnus-contracts';
4
5
  import { readEnvFile } from './env-file.js';
5
6
  import { mustRun } from './io.js';
6
- import { serverCli } from './install.js';
7
- function shellQuote(value) {
8
- return `'${value.replace(/'/g, `'\\''`)}'`;
7
+ import { isInstalled, serverCli } from './install.js';
8
+ export function shellQuote(value) {
9
+ return /^[A-Za-z0-9_./:@%+,=-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
9
10
  }
10
11
  function composeArgs(project) {
11
12
  const db = project.state.database;
12
13
  if (db.kind !== 'compose')
13
14
  throw new Error('not a compose database');
14
- return ['compose', '-f', project.path(db.composeFile), '--env-file', project.path('config', 'deps.env')];
15
+ return ['compose', '-p', project.composeProject(), '-f', project.path(db.composeFile), '--env-file', project.path('config', 'deps.env')];
15
16
  }
17
+ /** What to run to restore a dump: stops the services, restores into a clean schema, starts them again. */
16
18
  export function restoreCommandFor(project, file) {
19
+ return `magnus restore ${shellQuote(file)} --dir ${shellQuote(project.dir)}`;
20
+ }
21
+ /** First server release with `magnus-server restore` (and the clean-schema restore). */
22
+ export const SERVER_RESTORE_SINCE = '1.1.3';
23
+ /** Compose databases: psql in the container. */
24
+ async function composePsql(io, project, sql) {
17
25
  const db = project.state.database;
18
- if (db.kind === 'compose') {
19
- return `docker ${composeArgs(project).map(shellQuote).join(' ')} exec -T ${db.service} pg_restore --clean --if-exists --no-owner -U ${db.user} -d ${db.database} < ${shellQuote(file)}`;
20
- }
21
- return `pg_restore --clean --if-exists --no-owner -d "$DATABASE_URL" ${shellQuote(file)}`;
26
+ if (db.kind !== 'compose')
27
+ throw new Error('not a compose database');
28
+ await mustRun(io, 'docker', [...composeArgs(project), 'exec', '-T', db.service, 'psql', '-v', 'ON_ERROR_STOP=1', '-q', '-U', db.user, '-d', db.database, '-c', sql], { capture: true });
29
+ }
30
+ async function composeRun(io, project, args, options = {}) {
31
+ const db = project.state.database;
32
+ if (db.kind !== 'compose')
33
+ throw new Error('not a compose database');
34
+ return mustRun(io, 'docker', [...composeArgs(project), 'exec', '-T', db.service, ...args], options);
35
+ }
36
+ /** Bytes the database occupies (an upper bound for its dump), or null when it cannot be asked. */
37
+ export async function databaseBytes(io, project) {
38
+ const db = project.state.database;
39
+ if (db.kind !== 'compose')
40
+ return null;
41
+ const result = await composeRun(io, project, ['psql', '-tA', '-U', db.user, '-d', db.database, '-c', 'SELECT pg_database_size(current_database())'], { capture: true })
42
+ .catch(() => null);
43
+ const bytes = Number(result?.stdout.trim());
44
+ return Number.isFinite(bytes) && bytes > 0 ? bytes : null;
45
+ }
46
+ /**
47
+ * Keep the newest `keep` dumps in backups/; older ones go, except the newest
48
+ * dump of each label (the one a rollback of that step restores) and any file
49
+ * in `protect`.
50
+ */
51
+ export function pruneBackups(dir, keep, protect = []) {
52
+ if (!existsSync(dir) || keep < 1)
53
+ return [];
54
+ const dumps = readdirSync(dir).filter((name) => name.endsWith('.dump')).map((name) => {
55
+ const file = join(dir, name);
56
+ let meta = {};
57
+ try {
58
+ meta = JSON.parse(readFileSync(`${file}.json`, 'utf8'));
59
+ }
60
+ catch { /* no metadata */ }
61
+ return { file, label: meta.label ?? basename(file), at: Date.parse(meta.createdAt ?? '') || statSync(file).mtimeMs };
62
+ }).sort((a, b) => b.at - a.at);
63
+ const seen = new Set();
64
+ const removed = [];
65
+ dumps.forEach((dump, index) => {
66
+ const newest = !seen.has(dump.label);
67
+ seen.add(dump.label);
68
+ if (index < keep || newest || protect.includes(dump.file))
69
+ return;
70
+ rmSync(dump.file, { force: true });
71
+ rmSync(`${dump.file}.json`, { force: true });
72
+ removed.push(dump.file);
73
+ });
74
+ return removed;
22
75
  }
23
76
  /**
24
77
  * Dump before migrating. Compose databases are dumped with the container's own
25
78
  * pg_dump (always the server's version); external ones through the target
26
- * server's `magnus-server backup`, which checks the pg_dump version.
79
+ * server's `magnus-server backup`, which checks the pg_dump version. Either
80
+ * dump is read back with `pg_restore --list` before it counts.
27
81
  */
28
82
  export async function backupDatabase(io, project, version, label) {
29
83
  const db = project.state.database;
@@ -39,34 +93,129 @@ export async function backupDatabase(io, project, version, label) {
39
93
  const file = join(dir, `${io.now().toISOString().replace(/[:.]/g, '-')}-${label.replace(/[^A-Za-z0-9._-]+/g, '_')}.dump`);
40
94
  const fd = openSync(file, 'w', 0o600);
41
95
  try {
42
- await mustRun(io, 'docker', [...composeArgs(project), 'exec', '-T', db.service, 'pg_dump', '--format=custom', '--no-owner', '-U', db.user, '-d', db.database], { stdoutFd: fd, capture: false });
96
+ await composeRun(io, project, ['pg_dump', '--format=custom', '--no-owner', '-U', db.user, '-d', db.database], { stdoutFd: fd });
97
+ }
98
+ catch (error) {
99
+ rmSync(file, { force: true });
100
+ throw error;
43
101
  }
44
102
  finally {
45
103
  closeSync(fd);
46
104
  }
47
- if (statSync(file).size === 0)
105
+ if (!existsSync(file) || statSync(file).size === 0) {
106
+ rmSync(file, { force: true });
48
107
  throw new Error(`pg_dump wrote nothing to ${file}`);
108
+ }
49
109
  chmodSync(file, 0o600);
110
+ const input = openSync(file, 'r');
111
+ try {
112
+ await composeRun(io, project, ['pg_restore', '--list'], { stdinFd: input, capture: true });
113
+ }
114
+ catch (error) {
115
+ rmSync(file, { force: true });
116
+ throw new Error(`the dump ${file} is not readable by pg_restore: ${error instanceof Error ? error.message : String(error)}`);
117
+ }
118
+ finally {
119
+ closeSync(input);
120
+ }
50
121
  const restoreCommand = restoreCommandFor(project, file);
51
122
  writeFileSync(`${file}.json`, `${JSON.stringify({ createdAt: io.now().toISOString(), label, restoreCommand }, null, 2)}\n`, { mode: 0o600 });
123
+ pruneBackups(dir, project.keepBackups(), [file]);
52
124
  return { file, restoreCommand };
53
125
  }
54
- /** Restore a dump. The services must be stopped first. */
126
+ /** Newest installed version whose server CLI can restore (1.1.3+). */
127
+ function restoringVersion(project, compare = compareVersions) {
128
+ const dir = project.path('versions');
129
+ if (!existsSync(dir))
130
+ return null;
131
+ const versions = readdirSync(dir).filter((name) => /^\d+\.\d+\.\d+$/.test(name) && isInstalled(project, name)
132
+ && compare(name, SERVER_RESTORE_SINCE) >= 0).sort(compare);
133
+ return versions.at(-1) ?? null;
134
+ }
135
+ /**
136
+ * Restore a dump into a clean schema (see restoreSwapSql in
137
+ * @hivemagnus/magnus-contracts). The services must be stopped first.
138
+ */
55
139
  export async function restoreDatabase(io, project, file) {
140
+ if (!existsSync(file))
141
+ throw new Error(`${file} does not exist`);
56
142
  const db = project.state.database;
143
+ const aside = restoreAsideSchema(io.now());
57
144
  if (db.kind === 'compose') {
145
+ const check = openSync(file, 'r');
146
+ try {
147
+ await composeRun(io, project, ['pg_restore', '--list'], { stdinFd: check, capture: true });
148
+ }
149
+ catch (error) {
150
+ throw new Error(`${file} is not a readable dump: ${error instanceof Error ? error.message : String(error)}`);
151
+ }
152
+ finally {
153
+ closeSync(check);
154
+ }
155
+ await composePsql(io, project, restoreSwapSql(aside));
58
156
  const fd = openSync(file, 'r');
59
157
  try {
60
- await mustRun(io, 'docker', [...composeArgs(project), 'exec', '-T', db.service, 'pg_restore', '--clean', '--if-exists', '--no-owner', '-U', db.user, '-d', db.database], { stdinFd: fd });
158
+ await composeRun(io, project, ['pg_restore', '--single-transaction', '--exit-on-error', '--no-owner', '-U', db.user, '-d', db.database], { stdinFd: fd, capture: true });
159
+ }
160
+ catch (error) {
161
+ await composePsql(io, project, restoreRevertSql(aside)).catch(() => {
162
+ throw new Error(`pg_restore failed and the original schema could not be put back; it is kept as ${aside}. ${error instanceof Error ? error.message : String(error)}`);
163
+ });
164
+ throw new Error(`pg_restore failed; the database is unchanged. ${error instanceof Error ? error.message : String(error)}`);
61
165
  }
62
166
  finally {
63
167
  closeSync(fd);
64
168
  }
169
+ await composePsql(io, project, restoreFinishSql(aside));
170
+ return;
171
+ }
172
+ const version = restoringVersion(project);
173
+ if (version) {
174
+ await serverCli(io, project, version, ['restore', file, '--yes']);
65
175
  return;
66
176
  }
67
- const url = new URL(readEnvFile(project.envFile('server'))['DATABASE_URL'] ?? '');
68
- // Keep the password out of the process list.
177
+ // Only servers before 1.1.3 are installed: the same steps with the host's client tools
178
+ // (next to MAGNUS_PG_DUMP, so pg_restore is as new as the pg_dump that wrote the file).
179
+ const serverEnv = readEnvFile(project.envFile('server'));
180
+ const url = new URL(serverEnv['MAGNUS_MIGRATE_DATABASE_URL'] ?? serverEnv['DATABASE_URL'] ?? '');
69
181
  const password = decodeURIComponent(url.password);
70
182
  url.password = '';
71
- await mustRun(io, 'pg_restore', ['--clean', '--if-exists', '--no-owner', '-d', url.toString(), file], { env: { ...io.env, ...(password ? { PGPASSWORD: password } : {}) } });
183
+ const env = { ...io.env, ...(password ? { PGPASSWORD: password } : {}) };
184
+ const pgDump = serverEnv['MAGNUS_PG_DUMP'] ?? io.env['MAGNUS_PG_DUMP'];
185
+ const tool = (name) => (pgDump?.includes('/') ? join(dirname(pgDump), name) : name);
186
+ await mustRun(io, tool('pg_restore'), ['--list', file], { capture: true, env });
187
+ const psql = (sql) => mustRun(io, tool('psql'), ['-v', 'ON_ERROR_STOP=1', '-q', '-d', url.toString(), '-c', sql], { capture: true, env });
188
+ await psql(restoreSwapSql(aside));
189
+ try {
190
+ await mustRun(io, tool('pg_restore'), ['--single-transaction', '--exit-on-error', '--no-owner', '-d', url.toString(), file], { capture: true, env });
191
+ }
192
+ catch (error) {
193
+ await psql(restoreRevertSql(aside)).catch(() => {
194
+ throw new Error(`pg_restore failed and the original schema could not be put back; it is kept as ${aside}.`);
195
+ });
196
+ throw new Error(`pg_restore failed; the database is unchanged. ${error instanceof Error ? error.message : String(error)}`);
197
+ }
198
+ await psql(restoreFinishSql(aside));
199
+ }
200
+ /**
201
+ * Newest dump taken before `before` (the first migration this version does
202
+ * not know was applied then), for restore guidance when history has none.
203
+ */
204
+ export function newestDumpBefore(project, before) {
205
+ const dir = project.path('backups');
206
+ if (!existsSync(dir))
207
+ return null;
208
+ const limit = before ? Date.parse(before) : Number.POSITIVE_INFINITY;
209
+ let best = null;
210
+ for (const name of readdirSync(dir).filter((entry) => entry.endsWith('.dump'))) {
211
+ const file = join(dir, name);
212
+ let at = statSync(file).mtimeMs;
213
+ try {
214
+ at = Date.parse(JSON.parse(readFileSync(`${file}.json`, 'utf8')).createdAt) || at;
215
+ }
216
+ catch { /* mtime */ }
217
+ if (at <= limit && (!best || at > best.at))
218
+ best = { file, at };
219
+ }
220
+ return best?.file ?? null;
72
221
  }
@@ -10,5 +10,9 @@ export declare function renderEnv(header: string, sections: Array<{
10
10
  title: string;
11
11
  entries: EnvEntry[];
12
12
  }>): string;
13
- /** Append entries whose names are not already present; existing values are never changed. */
13
+ /**
14
+ * Append entries whose names are not already present; existing values are
15
+ * never changed. The file is replaced atomically (same mode and owner) and
16
+ * the previous content is kept as `<file>.bak`.
17
+ */
14
18
  export declare function appendMissing(path: string, entries: EnvEntry[], note: string): string[];
package/dist/env-file.js CHANGED
@@ -1,11 +1,18 @@
1
1
  /** Minimal env-file handling: read, append missing keys, generate secrets. */
2
2
  import { randomBytes } from 'node:crypto';
3
- import { existsSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import { copyFileSync, existsSync, readFileSync, statSync } from 'node:fs';
4
4
  import { parseEnv } from 'node:util';
5
+ import { writeAtomic } from './project.js';
5
6
  export function readEnvFile(path) {
6
7
  if (!existsSync(path))
7
8
  return {};
8
- return parseEnv(readFileSync(path, 'utf8'));
9
+ try {
10
+ return parseEnv(readFileSync(path, 'utf8'));
11
+ }
12
+ catch (error) {
13
+ throw new Error(`Cannot read the env file ${path}: ${error instanceof Error ? error.message : String(error)}. `
14
+ + `${existsSync(`${path}.bak`) ? `The version before the last change is in ${path}.bak.` : 'Fix the file and re-run.'}`);
15
+ }
9
16
  }
10
17
  /** 64 hex characters: comfortably above every 32-character secret minimum. */
11
18
  export function generateSecret() {
@@ -26,7 +33,11 @@ export function renderEnv(header, sections) {
26
33
  }
27
34
  return `${lines.join('\n')}\n`;
28
35
  }
29
- /** Append entries whose names are not already present; existing values are never changed. */
36
+ /**
37
+ * Append entries whose names are not already present; existing values are
38
+ * never changed. The file is replaced atomically (same mode and owner) and
39
+ * the previous content is kept as `<file>.bak`.
40
+ */
30
41
  export function appendMissing(path, entries, note) {
31
42
  const existing = readEnvFile(path);
32
43
  const missing = entries.filter((entry) => existing[entry.name] === undefined);
@@ -36,7 +47,11 @@ export function appendMissing(path, entries, note) {
36
47
  ...(entry.comment ? [`# ${entry.comment}`] : []),
37
48
  `${entry.name}=${quote(entry.value)}`,
38
49
  ])].join('\n');
39
- const current = existsSync(path) ? readFileSync(path, 'utf8') : '';
40
- writeFileSync(path, `${current.replace(/\n*$/, '\n')}${block}\n`, { mode: 0o600 });
50
+ const present = existsSync(path);
51
+ const current = present ? readFileSync(path, 'utf8') : '';
52
+ const stats = present ? statSync(path) : null;
53
+ if (present)
54
+ copyFileSync(path, `${path}.bak`);
55
+ writeAtomic(path, `${current.replace(/\n*$/, '\n')}${block}\n`, stats ? stats.mode & 0o777 : 0o600, stats ? { uid: stats.uid, gid: stats.gid } : undefined);
41
56
  return missing.map((entry) => entry.name);
42
57
  }
package/dist/health.d.ts CHANGED
@@ -4,15 +4,28 @@ export interface RuntimeInfo {
4
4
  version: string;
5
5
  pid: number;
6
6
  port: number;
7
+ /** Bind address (1.1.3+). */
8
+ host?: string;
7
9
  startedAt: string;
8
10
  }
9
11
  export declare function runtimeFile(project: Project): string;
12
+ /**
13
+ * Every place a server of this project may write its runtime file: the
14
+ * project's run/ (the units set MAGNUS_RUNTIME_FILE), the env file's
15
+ * MAGNUS_RUNTIME_FILE, and MAGNUS_HOME/run (a server started without either).
16
+ */
17
+ export declare function runtimeFiles(project: Project): string[];
18
+ /** The most recently started server among the runtime files. */
10
19
  export declare function readRuntime(project: Project): RuntimeInfo | null;
20
+ /** Loopback for wildcard binds, otherwise the address the server listens on. */
21
+ export declare function probeHost(host: string | undefined): string;
11
22
  export interface WaitOptions {
12
23
  version: string;
13
24
  /** The runtime file must name a process started after this instant. */
14
25
  startedAfter: Date;
15
26
  timeoutMs: number;
27
+ /** Stop waiting early (an interrupted upgrade). */
28
+ abort?: () => boolean;
16
29
  }
17
30
  export interface HealthResult {
18
31
  ok: boolean;
package/dist/health.js CHANGED
@@ -1,19 +1,45 @@
1
1
  /** Waiting until a (re)started version is really serving. */
2
2
  import { existsSync, readFileSync } from 'node:fs';
3
+ import { isAbsolute, join } from 'node:path';
3
4
  import { compareVersions } from '@hivemagnus/magnus-contracts';
5
+ import { readEnvFile } from './env-file.js';
4
6
  export function runtimeFile(project) {
5
7
  return project.path('run', 'server-runtime.json');
6
8
  }
7
- export function readRuntime(project) {
8
- const file = runtimeFile(project);
9
- if (!existsSync(file))
10
- return null;
9
+ /**
10
+ * Every place a server of this project may write its runtime file: the
11
+ * project's run/ (the units set MAGNUS_RUNTIME_FILE), the env file's
12
+ * MAGNUS_RUNTIME_FILE, and MAGNUS_HOME/run (a server started without either).
13
+ */
14
+ export function runtimeFiles(project) {
15
+ let env = {};
11
16
  try {
12
- return JSON.parse(readFileSync(file, 'utf8'));
17
+ env = readEnvFile(project.envFile('server'));
13
18
  }
14
- catch {
15
- return null;
19
+ catch { /* the upgrade reports unreadable env files itself */ }
20
+ const home = env['MAGNUS_HOME'] ? (isAbsolute(env['MAGNUS_HOME']) ? env['MAGNUS_HOME'] : project.path(env['MAGNUS_HOME'])) : project.path('data');
21
+ return [...new Set([runtimeFile(project), ...(env['MAGNUS_RUNTIME_FILE'] ? [env['MAGNUS_RUNTIME_FILE']] : []), join(home, 'run', 'server-runtime.json')])];
22
+ }
23
+ /** The most recently started server among the runtime files. */
24
+ export function readRuntime(project) {
25
+ let newest = null;
26
+ for (const file of runtimeFiles(project)) {
27
+ if (!existsSync(file))
28
+ continue;
29
+ try {
30
+ const info = JSON.parse(readFileSync(file, 'utf8'));
31
+ if (!newest || Date.parse(info.startedAt) > Date.parse(newest.startedAt))
32
+ newest = info;
33
+ }
34
+ catch { /* being rewritten */ }
16
35
  }
36
+ return newest;
37
+ }
38
+ /** Loopback for wildcard binds, otherwise the address the server listens on. */
39
+ export function probeHost(host) {
40
+ if (!host || host === '0.0.0.0' || host === '::' || host === '*' || host === 'localhost')
41
+ return '127.0.0.1';
42
+ return host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
17
43
  }
18
44
  /**
19
45
  * Healthy means: the runtime file reports the expected version from a process
@@ -39,6 +65,8 @@ export async function waitForHealthy(io, project, options) {
39
65
  const legacy = compareVersions(options.version, RUNTIME_FILE_SINCE) < 0;
40
66
  let last = 'no answer yet';
41
67
  while (io.now().getTime() < deadline) {
68
+ if (options.abort?.())
69
+ return { ok: false, detail: `interrupted: ${last}` };
42
70
  const reported = readRuntime(project);
43
71
  // Older servers do not write the runtime file: wait until the process that wrote it (a newer one) is gone.
44
72
  const runtime = legacy
@@ -53,7 +81,7 @@ export async function waitForHealthy(io, project, options) {
53
81
  else if (runtime.version !== options.version)
54
82
  last = `serving ${runtime.version}, expected ${options.version}`;
55
83
  else {
56
- const server = await io.probe(`https://127.0.0.1:${project.state.ports.server}/api/v1/health`);
84
+ const server = await io.probe(`https://${probeHost(runtime.host)}:${runtime.port || project.state.ports.server}/api/v1/health`);
57
85
  if (server !== 200)
58
86
  last = `/api/v1/health answered ${server ?? 'nothing'}`;
59
87
  else if (!project.state.components.includes('ui'))
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@ export { run, parseArgs, USAGE, ArgsError } from './main.js';
3
3
  export { Project, findProjectDir, acquireLock, type ProjectState, type HistoryEntry } from './project.js';
4
4
  export { upgrade, applyInstalled, missingEnv, UpgradeError, type UpgradeOptions } from './upgrade.js';
5
5
  export { rollback, type RollbackOptions } from './rollback.js';
6
+ export { restore, type RestoreOptions } from './restore.js';
6
7
  export { init, type InitOptions } from './init.js';
7
8
  export { adopt, type AdoptOptions } from './adopt.js';
8
9
  export { status, type StatusOptions } from './status.js';
package/dist/index.js CHANGED
@@ -3,6 +3,7 @@ export { run, parseArgs, USAGE, ArgsError } from './main.js';
3
3
  export { Project, findProjectDir, acquireLock } from './project.js';
4
4
  export { upgrade, applyInstalled, missingEnv, UpgradeError } from './upgrade.js';
5
5
  export { rollback } from './rollback.js';
6
+ export { restore } from './restore.js';
6
7
  export { init } from './init.js';
7
8
  export { adopt } from './adopt.js';
8
9
  export { status } from './status.js';
package/dist/init.js CHANGED
@@ -14,8 +14,8 @@ import { chownForService, installVersion, publishPins, serverCli } from './insta
14
14
  import { mustRun } from './io.js';
15
15
  import { acquireLock, Project } from './project.js';
16
16
  import { ownPackage, releaseFor } from './release.js';
17
- import { enableServices, restartServices, unitDirectory } from './supervisor.js';
18
- import { depsCompose, depsEnv, serverEnv, serverUnit, uiEnv, uiUnit } from './templates.js';
17
+ import { checkSupervisor, enableServices, restartServices, unitDirectory } from './supervisor.js';
18
+ import { composeProjectName, depsCompose, depsEnv, serverEnv, serverUnit, uiEnv, uiUnit } from './templates.js';
19
19
  import { loadCatalog, UpgradeError } from './upgrade.js';
20
20
  export function defaultProjectDir(io, system) {
21
21
  return system ? '/opt/magnus' : join(io.env['HOME'] ?? '.', '.magnus');
@@ -33,12 +33,12 @@ async function selfSignedCertificate(io, dir, host) {
33
33
  }
34
34
  async function hashPassword(io, project, version, password) {
35
35
  // argon2 comes with the server install; nothing extra is downloaded.
36
- const { stdout } = await mustRun(io, process.execPath, ['--input-type=module', '-e',
36
+ const { stdout } = await mustRun(io, project.nodePath(), ['--input-type=module', '-e',
37
37
  "import argon2 from 'argon2'; console.log(await argon2.hash(process.env.MAGNUS_INIT_PASSWORD, { type: argon2.argon2id }))"], { cwd: project.versionDir(version), capture: true, env: { ...io.env, MAGNUS_INIT_PASSWORD: password } });
38
38
  return stdout.trim();
39
39
  }
40
40
  async function startDeps(io, project) {
41
- const args = ['compose', '-f', project.path('deps.compose.yml'), '--env-file', project.path('config', 'deps.env'), 'up', '-d', '--wait'];
41
+ const args = ['compose', '-p', project.composeProject(), '-f', project.path('deps.compose.yml'), '--env-file', project.path('config', 'deps.env'), 'up', '-d', '--wait'];
42
42
  io.log(' starting PostgreSQL and Redis (docker compose)');
43
43
  await mustRun(io, 'docker', args, { capture: true });
44
44
  }
@@ -50,6 +50,10 @@ export async function init(io, options) {
50
50
  const dir = resolve(options.dir ?? defaultProjectDir(io, options.system));
51
51
  if (Project.exists(dir))
52
52
  throw new UpgradeError(`${dir} already holds a Magnus project. Use \`magnus upgrade\` or \`magnus status\`.`);
53
+ // Before anything is written: systemd needs Linux and (user units) a session bus.
54
+ await checkSupervisor(io, options.supervisor, options.system ? 'system' : 'user').catch((error) => {
55
+ throw new UpgradeError(`${error instanceof Error ? error.message : String(error)} Or pass --supervisor none.`);
56
+ });
53
57
  const catalog = await loadCatalog(io, options);
54
58
  const own = ownPackage();
55
59
  const version = options.version
@@ -78,6 +82,9 @@ export async function init(io, options) {
78
82
  current: null,
79
83
  previous: null,
80
84
  keepVersions: 3,
85
+ keepBackups: 5,
86
+ nodePath: process.execPath,
87
+ ...(deps ? { composeProject: composeProjectName(dir) } : {}),
81
88
  history: [],
82
89
  };
83
90
  mkdirSync(dir, { recursive: true, mode: 0o755 });
@@ -93,7 +100,7 @@ export async function init(io, options) {
93
100
  if (deps) {
94
101
  const postgresPassword = randomBytes(24).toString('hex');
95
102
  const redisPassword = randomBytes(24).toString('hex');
96
- writeFileSync(project.path('deps.compose.yml'), depsCompose());
103
+ writeFileSync(project.path('deps.compose.yml'), depsCompose(project.composeProject()));
97
104
  writeFileSync(project.path('config', 'deps.env'), depsEnv({ postgresPort: options.postgresPort, redisPort: options.redisPort, postgresPassword, redisPassword }), { mode: 0o600 });
98
105
  databaseUrl ??= `postgresql://magnus:${postgresPassword}@127.0.0.1:${options.postgresPort}/magnus`;
99
106
  redisUrl ??= `redis://:${redisPassword}@127.0.0.1:${options.redisPort}`;
@@ -107,6 +114,7 @@ export async function init(io, options) {
107
114
  writeFileSync(project.envFile('server'), serverEnv({
108
115
  databaseUrl: databaseUrl, redisUrl: redisUrl, port: options.serverPort, publicUrl: `https://${host}:${options.serverPort}`,
109
116
  uiOrigin, tlsCert: tls.cert, tlsKey: tls.key, home: project.path('data'), backupDir: project.path('backups'), autoMigrate: options.autoMigrate,
117
+ projectDir: project.dir, runtimeFile: project.path('run', 'server-runtime.json'),
110
118
  ...(tls.selfSigned ? { extraCaFile: tls.cert } : {}),
111
119
  }, {}), { mode: 0o600 });
112
120
  const password = options.adminPassword ?? randomBytes(12).toString('base64url');
@@ -119,7 +127,7 @@ export async function init(io, options) {
119
127
  }, apiSecret), { mode: 0o600 });
120
128
  }
121
129
  io.log(' applying database migrations');
122
- await serverCli(io, project, version, ['migrate']);
130
+ await serverCli(io, project, version, ['migrate'], { detached: true });
123
131
  project.switchCurrent(version);
124
132
  project.state.current = version;
125
133
  project.record({ action: 'init', from: null, to: version, at: io.now().toISOString(), result: 'ok', migrations: [] });
@@ -133,7 +141,7 @@ export async function init(io, options) {
133
141
  }
134
142
  const afterUnits = deps ? ['docker.service'] : [];
135
143
  // With the self-signed certificate, agents on this host can reuse it; the server must trust it to call them.
136
- const unitOptions = { project, nodePath: process.execPath, serviceUser: options.serviceUser, afterUnits,
144
+ const unitOptions = { project, nodePath: project.nodePath(), serviceUser: options.serviceUser, afterUnits,
137
145
  ...(tls.selfSigned ? { extraCaFile: tls.cert } : {}) };
138
146
  const units = { [`${state.units.server}.service`]: serverUnit(unitOptions) };
139
147
  if (options.ui)