@hivemagnus/magnus 1.1.2 → 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/dist/install.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ReleaseManifest } from '@hivemagnus/magnus-contracts';
1
+ import { type ReleaseManifest } from '@hivemagnus/magnus-contracts';
2
2
  import { type Io } from './io.js';
3
3
  import type { Project } from './project.js';
4
4
  import { type ReleaseCatalog } from './release.js';
@@ -11,6 +11,18 @@ export declare function dependenciesFor(project: Project, manifest: ReleaseManif
11
11
  * @hivemagnus/magnus when it is newer than the release being installed.
12
12
  */
13
13
  export declare function overridesFor(manifest: ReleaseManifest, catalog: ReleaseCatalog, metaVersion: string): Record<string, string | Record<string, string>>;
14
+ /**
15
+ * npm for a Node.js binary: the npm-cli.js shipped next to it (so installs
16
+ * build native modules for the Node.js the services run), else npm on PATH.
17
+ */
18
+ export declare function npmFor(nodePath: string): {
19
+ command: string;
20
+ prefix: string[];
21
+ };
22
+ /** `node --version` of the binary the services run (without the v). */
23
+ export declare function nodeVersionOf(io: Io, nodePath: string): Promise<string>;
24
+ /** Remove half-finished installs (versions/*.tmp) left by an interrupted run. */
25
+ export declare function removeStaleStaging(project: Project): string[];
14
26
  export declare function isInstalled(project: Project, version: string): boolean;
15
27
  /**
16
28
  * npm install into versions/<X>.tmp, then rename, so a failed or interrupted
@@ -24,15 +36,41 @@ export declare function pruneVersions(project: Project, keep: number, compare: (
24
36
  export interface ServerCliOptions {
25
37
  capture?: boolean;
26
38
  env?: NodeJS.ProcessEnv;
39
+ detached?: boolean;
27
40
  }
28
- /** Run a version's magnus-server CLI against the project's server env file. */
41
+ /** Run a version's magnus-server CLI (with the services' Node.js) against the project's server env file. */
29
42
  export declare function serverCli(io: Io, project: Project, version: string, args: string[], options?: ServerCliOptions): Promise<import("./io.js").RunResult>;
30
43
  export interface PendingMigration {
31
44
  name: string;
32
45
  impact: 'fast' | 'slow' | 'one-way';
33
46
  note: string;
34
47
  }
35
- /** Pending migrations as seen by a version's server (its packaged migrations vs the database). */
48
+ export interface MigrationReport {
49
+ packaged: string[];
50
+ applied: string[];
51
+ pending: PendingMigration[];
52
+ /** Started but never finished. */
53
+ failed: string[];
54
+ /** Applied but not packaged with this version: the database is ahead of it. */
55
+ unknown: Array<{
56
+ name: string;
57
+ appliedAt: string | null;
58
+ }>;
59
+ databaseBytes: number | null;
60
+ postgresMajor: number | null;
61
+ }
62
+ /**
63
+ * Migration state as seen by a version's server (its packaged migrations vs
64
+ * the database). Servers before 1.1.3 report only packaged/applied/pending;
65
+ * the rest is derived from those or left unknown.
66
+ */
67
+ export declare function migrationReport(io: Io, project: Project, version: string): Promise<MigrationReport>;
36
68
  export declare function pendingMigrations(io: Io, project: Project, version: string): Promise<PendingMigration[]>;
69
+ /**
70
+ * Before the backup: the new version starts on this Node.js (`--version`
71
+ * prints its version, native modules load) and its configuration check
72
+ * passes. A check that crashes or prints no results counts as a failure.
73
+ */
74
+ export declare function smokeTest(io: Io, project: Project, version: string): Promise<string[]>;
37
75
  /** Give the service account the files it writes to (system scope only). */
38
76
  export declare function chownForService(io: Io, user: string, paths: string[]): Promise<void>;
package/dist/install.js CHANGED
@@ -1,9 +1,10 @@
1
1
  /** Installing one release into versions/<X.Y.Z> and running its server CLI. */
2
2
  import { chownSync, cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
3
- import { join } from 'node:path';
4
- import { mustRun } from './io.js';
3
+ import { dirname, join } from 'node:path';
4
+ import { isVersion } from '@hivemagnus/magnus-contracts';
5
+ import { CommandError, mustRun } from './io.js';
5
6
  import { CONTRACTS_PACKAGE, META_PACKAGE, ownPackage, SERVER_PACKAGE, UI_PACKAGE } from './release.js';
6
- import { versionPackageJson } from './templates.js';
7
+ import { ALLOW_SCRIPTS, versionPackageJson } from './templates.js';
7
8
  /** Exact pins (or local tarballs from --source) for one release. */
8
9
  export function dependenciesFor(project, manifest, catalog) {
9
10
  const pin = (name, version) => {
@@ -55,6 +56,37 @@ function metaVersionOf(catalog, spec) {
55
56
  return key.slice(key.lastIndexOf('@') + 1);
56
57
  return ownPackage().version;
57
58
  }
59
+ /**
60
+ * npm for a Node.js binary: the npm-cli.js shipped next to it (so installs
61
+ * build native modules for the Node.js the services run), else npm on PATH.
62
+ */
63
+ export function npmFor(nodePath) {
64
+ for (const cli of [join(dirname(nodePath), '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'), join(dirname(nodePath), 'node_modules', 'npm', 'bin', 'npm-cli.js')]) {
65
+ if (existsSync(cli))
66
+ return { command: nodePath, prefix: [cli] };
67
+ }
68
+ return { command: 'npm', prefix: [] };
69
+ }
70
+ /** `node --version` of the binary the services run (without the v). */
71
+ export async function nodeVersionOf(io, nodePath) {
72
+ const result = await io.run(nodePath, ['--version'], { capture: true }).catch((error) => {
73
+ throw new Error(`The Node.js the services run (${nodePath}) cannot be started: ${error instanceof Error ? error.message : String(error)}. Pass --node <path> to switch.`);
74
+ });
75
+ const version = result.stdout.trim().replace(/^v/, '');
76
+ if (result.code !== 0 || !isVersion(version))
77
+ throw new Error(`${nodePath} --version failed; pass --node <path to node> to switch the Node.js the services run.`);
78
+ return version;
79
+ }
80
+ /** Remove half-finished installs (versions/*.tmp) left by an interrupted run. */
81
+ export function removeStaleStaging(project) {
82
+ const dir = project.path('versions');
83
+ if (!existsSync(dir))
84
+ return [];
85
+ const stale = readdirSync(dir).filter((name) => name.endsWith('.tmp'));
86
+ for (const name of stale)
87
+ rmSync(join(dir, name), { recursive: true, force: true });
88
+ return stale;
89
+ }
58
90
  export function isInstalled(project, version) {
59
91
  return existsSync(project.bin(version, 'magnus-server'));
60
92
  }
@@ -74,9 +106,12 @@ export async function installVersion(io, project, manifest, catalog) {
74
106
  mkdirSync(staging, { recursive: true });
75
107
  const dependencies = dependenciesFor(project, manifest, catalog);
76
108
  const metaVersion = dependencies[META_PACKAGE]?.startsWith('file:') ? metaVersionOf(catalog, dependencies[META_PACKAGE]) : dependencies[META_PACKAGE] ?? manifest.version;
77
- writeFileSync(join(staging, 'package.json'), versionPackageJson(manifest.version, dependencies, overridesFor(manifest, catalog, metaVersion)));
109
+ // The release knows which install scripts its tree needs; this engine's list only covers releases without one.
110
+ const allowScripts = manifest.allowScripts ?? ALLOW_SCRIPTS;
111
+ writeFileSync(join(staging, 'package.json'), versionPackageJson(manifest.version, dependencies, overridesFor(manifest, catalog, metaVersion), allowScripts));
78
112
  io.log(` installing ${manifest.version} into versions/${manifest.version} (npm install; this takes a few minutes)`);
79
- await mustRun(io, 'npm', ['install', '--omit=dev', '--no-audit', '--no-fund', '--loglevel=error'], { cwd: staging, capture: true });
113
+ const npm = npmFor(project.nodePath());
114
+ await mustRun(io, npm.command, [...npm.prefix, 'install', '--omit=dev', '--no-audit', '--no-fund', '--loglevel=error'], { cwd: staging, capture: true, env: { ...io.env, PATH: `${dirname(project.nodePath())}:${io.env['PATH'] ?? ''}` } });
80
115
  renameSync(staging, target);
81
116
  }
82
117
  /** Copy the serving version's manifest and lockfile to the project root (what `current` pins). */
@@ -104,18 +139,84 @@ export function pruneVersions(project, keep, compare) {
104
139
  }
105
140
  return removed;
106
141
  }
107
- /** Run a version's magnus-server CLI against the project's server env file. */
142
+ /** Run a version's magnus-server CLI (with the services' Node.js) against the project's server env file. */
108
143
  export function serverCli(io, project, version, args, options = {}) {
109
- return mustRun(io, process.execPath, [project.bin(version, 'magnus-server'), ...args, '--env-file', project.envFile('server')], {
144
+ return mustRun(io, project.nodePath(), [project.bin(version, 'magnus-server'), ...args, '--env-file', project.envFile('server')], {
110
145
  cwd: project.dir,
111
146
  capture: options.capture,
112
- env: { ...io.env, MAGNUS_PROJECT_DIR: project.dir, MAGNUS_BACKUP_DIR: project.path('backups'), ...options.env },
147
+ detached: options.detached,
148
+ env: { ...io.env, MAGNUS_PROJECT_DIR: project.dir, MAGNUS_BACKUP_DIR: project.path('backups'), MAGNUS_BACKUP_KEEP: String(project.keepBackups()), ...options.env },
113
149
  });
114
150
  }
115
- /** Pending migrations as seen by a version's server (its packaged migrations vs the database). */
116
- export async function pendingMigrations(io, project, version) {
151
+ /**
152
+ * Migration state as seen by a version's server (its packaged migrations vs
153
+ * the database). Servers before 1.1.3 report only packaged/applied/pending;
154
+ * the rest is derived from those or left unknown.
155
+ */
156
+ export async function migrationReport(io, project, version) {
117
157
  const { stdout } = await serverCli(io, project, version, ['migrations', '--format', 'json'], { capture: true });
118
- return JSON.parse(stdout).pending;
158
+ const raw = JSON.parse(stdout);
159
+ const packaged = raw.packaged ?? [];
160
+ const applied = raw.applied ?? [];
161
+ const known = new Set(packaged);
162
+ return {
163
+ packaged,
164
+ applied,
165
+ pending: raw.pending,
166
+ failed: raw.failed ?? [],
167
+ unknown: raw.unknown ?? (packaged.length ? applied.filter((name) => !known.has(name)).map((name) => ({ name, appliedAt: null })) : []),
168
+ databaseBytes: typeof raw.databaseBytes === 'number' ? raw.databaseBytes : null,
169
+ postgresMajor: typeof raw.postgresMajor === 'number' ? raw.postgresMajor : null,
170
+ };
171
+ }
172
+ export async function pendingMigrations(io, project, version) {
173
+ return (await migrationReport(io, project, version)).pending;
174
+ }
175
+ /** Native modules the server and console load at startup, checked before anything changes. */
176
+ const NATIVE_MODULES = ['argon2', 'better-sqlite3', 'ssh2', 'sharp'];
177
+ /**
178
+ * Before the backup: the new version starts on this Node.js (`--version`
179
+ * prints its version, native modules load) and its configuration check
180
+ * passes. A check that crashes or prints no results counts as a failure.
181
+ */
182
+ export async function smokeTest(io, project, version) {
183
+ const problems = [];
184
+ const printed = await serverCli(io, project, version, ['--version'], { capture: true }).then((result) => result.stdout.trim())
185
+ .catch((error) => { problems.push(`magnus-server --version failed: ${error instanceof Error ? error.message : String(error)}`); return null; });
186
+ if (printed !== null && printed !== version)
187
+ problems.push(`magnus-server --version printed "${printed.split('\n')[0]}", expected ${version}`);
188
+ const script = `import { createRequire } from 'node:module';
189
+ const req = createRequire(process.argv[1] + '/');
190
+ const failed = [];
191
+ for (const name of ${JSON.stringify(NATIVE_MODULES)}) {
192
+ let path; try { path = req.resolve(name); } catch { continue; }
193
+ try { const mod = await import(path); if (name === 'better-sqlite3') new mod.default(':memory:').close(); } catch (error) { failed.push(name + ': ' + String(error && error.message || error).split('\\n')[0]); }
194
+ }
195
+ if (failed.length) { console.error(failed.join('\\n')); process.exit(1); }`;
196
+ const roots = [join(project.versionDir(version), 'node_modules', '@hivemagnus', 'magnus-server'),
197
+ ...(project.state.components.includes('ui') ? [join(project.versionDir(version), 'node_modules', '@hivemagnus', 'magnus-ui')] : [])];
198
+ for (const root of roots.filter((path) => existsSync(path))) {
199
+ const result = await io.run(project.nodePath(), ['--input-type=module', '-e', script, root], { capture: true, cwd: project.versionDir(version) })
200
+ .catch((error) => ({ code: 1, stdout: '', stderr: error instanceof Error ? error.message : String(error) }));
201
+ if (result.code !== 0)
202
+ problems.push(`native modules of ${root.split('/').pop()} do not load on Node.js ${project.nodePath()}: ${result.stderr.trim().split('\n').slice(0, 3).join('; ')}`);
203
+ }
204
+ const check = await serverCli(io, project, version, ['check', '--format', 'json'], { capture: true })
205
+ .then((result) => result.stdout)
206
+ .catch((error) => (error instanceof CommandError ? error.result?.stdout ?? '' : ''));
207
+ let results = null;
208
+ try {
209
+ const parsed = JSON.parse(check);
210
+ if (Array.isArray(parsed.results))
211
+ results = parsed.results;
212
+ }
213
+ catch { /* handled below */ }
214
+ if (!results)
215
+ problems.push('`magnus-server check` crashed or printed no results (run it by hand to see why)');
216
+ else
217
+ for (const result of results.filter((entry) => entry.status === 'fail'))
218
+ problems.push(`${result.name}: ${result.message}`);
219
+ return problems;
119
220
  }
120
221
  /** Give the service account the files it writes to (system scope only). */
121
222
  export async function chownForService(io, user, paths) {
package/dist/io.d.ts CHANGED
@@ -8,6 +8,11 @@ export interface RunOptions {
8
8
  /** Redirect stdout to this file descriptor (for dumps). */
9
9
  stdoutFd?: number;
10
10
  stdinFd?: number;
11
+ /**
12
+ * Own process group: a Ctrl-C in the terminal does not reach it. Used for
13
+ * migrations, which must never be interrupted halfway.
14
+ */
15
+ detached?: boolean;
11
16
  }
12
17
  export interface RunResult {
13
18
  code: number;
@@ -29,9 +34,14 @@ export interface Io {
29
34
  * process is up; the runtime file confirms which version it is.
30
35
  */
31
36
  probe(url: string): Promise<number | null>;
37
+ /** Free bytes for an unprivileged writer on the file system holding `path`, or null when unknown. */
38
+ freeBytes(path: string): number | null;
32
39
  env: NodeJS.ProcessEnv;
33
40
  nodeVersion: string;
34
41
  isRoot: boolean;
42
+ /** Effective user id (null where the platform has none). */
43
+ uid: number | null;
44
+ platform: NodeJS.Platform;
35
45
  }
36
46
  export declare class CommandError extends Error {
37
47
  readonly result?: RunResult | undefined;
package/dist/io.js CHANGED
@@ -3,6 +3,7 @@
3
3
  * a scripted host: commands, HTTP, clock, prompts and logging.
4
4
  */
5
5
  import { spawn } from 'node:child_process';
6
+ import { statfsSync } from 'node:fs';
6
7
  import { request as httpRequest } from 'node:http';
7
8
  import { request as httpsRequest } from 'node:https';
8
9
  import { createInterface } from 'node:readline/promises';
@@ -19,7 +20,7 @@ export function systemIo() {
19
20
  const stdin = options.stdinFd ?? (options.input !== undefined ? 'pipe' : 'ignore');
20
21
  const stdout = options.stdoutFd ?? (options.capture ? 'pipe' : 'inherit');
21
22
  const stderr = options.capture ? 'pipe' : 'inherit';
22
- const child = spawn(command, args, { cwd: options.cwd, env: options.env ?? process.env, stdio: [stdin, stdout, stderr] });
23
+ const child = spawn(command, args, { cwd: options.cwd, env: options.env ?? process.env, stdio: [stdin, stdout, stderr], detached: options.detached ?? false });
23
24
  let out = '';
24
25
  let err = '';
25
26
  child.stdout?.on('data', (chunk) => { out += String(chunk); });
@@ -56,9 +57,20 @@ export function systemIo() {
56
57
  req.on('error', () => resolve(null));
57
58
  req.end();
58
59
  }),
60
+ freeBytes: (path) => {
61
+ try {
62
+ const stats = statfsSync(path);
63
+ return Number(stats.bavail) * Number(stats.bsize);
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ },
59
69
  env: process.env,
60
70
  nodeVersion: process.version,
61
- isRoot: typeof process.getuid === 'function' && process.getuid() === 0,
71
+ isRoot: typeof process.geteuid === 'function' && process.geteuid() === 0,
72
+ uid: typeof process.geteuid === 'function' ? process.geteuid() : null,
73
+ platform: process.platform,
62
74
  };
63
75
  }
64
76
  /** Run and throw with the tail of stderr on a non-zero exit. */
package/dist/main.d.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  import type { Io } from './io.js';
2
- export declare const USAGE = "Usage: magnus <command> [options]\n\nCommands:\n init Create a managed project, install the pinned release and start it\n upgrade Upgrade the project (same major version unless --allow-major)\n rollback Switch back to the version that served before the last upgrade\n status Show installed and serving versions, history and available updates\n adopt Turn an existing npm install into a managed project\n version Print this tool's version\n\nCommon options:\n --dir DIR Project directory (default ~/.magnus, or /opt/magnus with --system)\n --registry URL npm registry (default MAGNUS_UPDATE_REGISTRY or https://registry.npmjs.org)\n --source DIR Install from packed tarballs in DIR instead of the registry\n --health-timeout SEC How long to wait for the new version to become healthy (default 180)\n --yes Confirm slow or one-way migrations and restores without asking\n\ninit:\n --version X.Y.Z Release to install (default: newest of this major)\n --system System units (root) instead of user units; needs --service-user\n --service-user NAME Account the system services run as\n --supervisor KIND systemd (default) or none (you start the processes yourself)\n --database-url URL Existing PostgreSQL (with --redis-url); otherwise PostgreSQL and\n --redis-url URL Redis run on loopback through docker compose\n --postgres-port N Loopback port for the bundled PostgreSQL (default 5432)\n --redis-port N Loopback port for the bundled Redis (default 6379)\n --server-port N Server port (default 4000)\n --ui-port N Console port (default 3000)\n --public-host NAME Host name for URLs and the certificate (default: this host's name)\n --admin-user NAME Console administrator (default admin)\n --admin-password PW Console password (default: generated and printed once)\n --tls-cert FILE Certificate and key (default: a self-signed certificate)\n --tls-key FILE\n --no-ui Install only the server\n --no-start Install and configure, but do not start\n --no-auto-migrate Write MAGNUS_AUTO_MIGRATE=false (default true for init projects)\n\nupgrade:\n --to X.Y.Z Target release (default: newest of the current major)\n --dry-run Show what would happen and check prerequisites; change nothing\n --allow-major Permit crossing a major version\n --generate-secrets Generate values for new required secret settings\n\nrollback:\n --restore-db Also restore the pre-upgrade database dump (data written since is lost)\n\nstatus:\n --json Machine-readable output\n --offline Skip the registry check\n\nadopt:\n --server-env-file F The env file your magnus-server runs with (required)\n --ui-env-file F The env file your magnus-ui runs with\n --version X.Y.Z Installed version (default: magnus-server --version)\n --install-units Install and enable the new units (otherwise only print the steps)\n";
2
+ export declare const USAGE = "Usage: magnus <command> [options]\n\nCommands:\n init Create a managed project, install the pinned release and start it\n upgrade Upgrade the project (same major version unless --allow-major)\n rollback Switch back to the version that served before the last upgrade\n restore Restore a database dump: stop the services, restore, start them again\n status Show installed and serving versions, history and available updates\n adopt Turn an existing npm install into a managed project\n version Print this tool's version\n\nCommon options:\n --dir DIR Project directory (default ~/.magnus, or /opt/magnus with --system)\n --registry URL npm registry (default MAGNUS_UPDATE_REGISTRY, then npm's configured registry)\n --source DIR Install from packed tarballs in DIR instead of the registry\n --health-timeout SEC How long to wait for the new version to become healthy (default 180)\n --yes Confirm slow or one-way migrations and restores without asking\n --break-lock Remove a lock left behind by a magnus command that no longer runs\n\ninit:\n --version X.Y.Z Release to install (default: newest of this major)\n --system System units (root) instead of user units; needs --service-user\n --service-user NAME Account the system services run as\n --supervisor KIND systemd (default) or none (you start the processes yourself)\n --database-url URL Existing PostgreSQL (with --redis-url); otherwise PostgreSQL and\n --redis-url URL Redis run on loopback through docker compose\n --postgres-port N Loopback port for the bundled PostgreSQL (default 5432)\n --redis-port N Loopback port for the bundled Redis (default 6379)\n --server-port N Server port (default 4000)\n --ui-port N Console port (default 3000)\n --public-host NAME Host name for URLs and the certificate (default: this host's name)\n --admin-user NAME Console administrator (default admin)\n --admin-password PW Console password (default: generated and printed once)\n --tls-cert FILE Certificate and key (default: a self-signed certificate)\n --tls-key FILE\n --no-ui Install only the server\n --no-start Install and configure, but do not start\n --no-auto-migrate Write MAGNUS_AUTO_MIGRATE=false (default true for init projects)\n\nupgrade:\n --to X.Y.Z Target release (default: newest of the current major)\n --dry-run Show what would happen and check prerequisites; change nothing\n --allow-major Permit crossing a major version\n --generate-secrets Generate values for new required secret settings\n --resume Finish an upgrade that was interrupted (see `magnus status`)\n --node PATH Node.js the services run and the upgrade uses (rewrites the units)\n --force After a failed upgrade, start the old version even over one-way migrations\n\nrollback:\n --restore-db Also restore the pre-upgrade database dump (data written since is lost)\n --force Start the previous version even over one-way migrations it does not know\n\nrestore FILE: A dump from backups/ (shown by upgrade, rollback and status)\n\nstatus:\n --json Machine-readable output\n --offline Skip the registry check\n\nadopt:\n --server-env-file F The env file your magnus-server runs with (required)\n --ui-env-file F The env file your magnus-ui runs with\n --version X.Y.Z Installed version (default: magnus-server --version)\n --install-units Install and enable the new units (otherwise only print the steps)\n";
3
3
  export declare class ArgsError extends Error {
4
4
  }
5
5
  interface Parsed {
6
6
  command: string;
7
7
  values: Map<string, string>;
8
8
  flags: Set<string>;
9
+ /** Positional arguments after the command (restore FILE). */
10
+ args: string[];
9
11
  }
10
12
  export declare function parseArgs(argv: readonly string[]): Parsed;
11
13
  export declare function run(io: Io, argv: readonly string[]): Promise<number>;
package/dist/main.js CHANGED
@@ -4,13 +4,15 @@
4
4
  * npx @hivemagnus/magnus init create and start a project in ~/.magnus
5
5
  * magnus upgrade [--to X.Y.Z] [--dry-run] upgrade it (never across a major by itself)
6
6
  * magnus rollback [--restore-db] switch back to the previous version
7
+ * magnus restore FILE restore a database dump (stops and restarts the services)
7
8
  * magnus status versions, health and available updates
8
9
  * magnus adopt --server-env-file FILE take over an existing npm install
9
10
  */
10
11
  import { adopt } from './adopt.js';
11
12
  import { init, defaultProjectDir } from './init.js';
12
13
  import { findProjectDir } from './project.js';
13
- import { ownPackage } from './release.js';
14
+ import { ownPackage, resolveRegistry } from './release.js';
15
+ import { restore } from './restore.js';
14
16
  import { rollback } from './rollback.js';
15
17
  import { status } from './status.js';
16
18
  import { upgrade } from './upgrade.js';
@@ -20,16 +22,18 @@ Commands:
20
22
  init Create a managed project, install the pinned release and start it
21
23
  upgrade Upgrade the project (same major version unless --allow-major)
22
24
  rollback Switch back to the version that served before the last upgrade
25
+ restore Restore a database dump: stop the services, restore, start them again
23
26
  status Show installed and serving versions, history and available updates
24
27
  adopt Turn an existing npm install into a managed project
25
28
  version Print this tool's version
26
29
 
27
30
  Common options:
28
31
  --dir DIR Project directory (default ~/.magnus, or /opt/magnus with --system)
29
- --registry URL npm registry (default MAGNUS_UPDATE_REGISTRY or https://registry.npmjs.org)
32
+ --registry URL npm registry (default MAGNUS_UPDATE_REGISTRY, then npm's configured registry)
30
33
  --source DIR Install from packed tarballs in DIR instead of the registry
31
34
  --health-timeout SEC How long to wait for the new version to become healthy (default 180)
32
35
  --yes Confirm slow or one-way migrations and restores without asking
36
+ --break-lock Remove a lock left behind by a magnus command that no longer runs
33
37
 
34
38
  init:
35
39
  --version X.Y.Z Release to install (default: newest of this major)
@@ -56,9 +60,15 @@ upgrade:
56
60
  --dry-run Show what would happen and check prerequisites; change nothing
57
61
  --allow-major Permit crossing a major version
58
62
  --generate-secrets Generate values for new required secret settings
63
+ --resume Finish an upgrade that was interrupted (see \`magnus status\`)
64
+ --node PATH Node.js the services run and the upgrade uses (rewrites the units)
65
+ --force After a failed upgrade, start the old version even over one-way migrations
59
66
 
60
67
  rollback:
61
68
  --restore-db Also restore the pre-upgrade database dump (data written since is lost)
69
+ --force Start the previous version even over one-way migrations it does not know
70
+
71
+ restore FILE: A dump from backups/ (shown by upgrade, rollback and status)
62
72
 
63
73
  status:
64
74
  --json Machine-readable output
@@ -74,13 +84,14 @@ export class ArgsError extends Error {
74
84
  }
75
85
  const VALUE_OPTIONS = new Set(['--dir', '--registry', '--source', '--health-timeout', '--version', '--service-user', '--supervisor',
76
86
  '--database-url', '--redis-url', '--postgres-port', '--redis-port', '--server-port', '--ui-port', '--public-host', '--admin-user',
77
- '--admin-password', '--tls-cert', '--tls-key', '--to', '--server-env-file', '--ui-env-file']);
87
+ '--admin-password', '--tls-cert', '--tls-key', '--to', '--server-env-file', '--ui-env-file', '--node']);
78
88
  const FLAG_OPTIONS = new Set(['--yes', '--system', '--no-ui', '--no-start', '--no-auto-migrate', '--dry-run', '--allow-major',
79
- '--generate-secrets', '--resume', '--restore-db', '--json', '--offline', '--install-units', '--help', '-h']);
80
- const COMMANDS = new Set(['init', 'upgrade', 'rollback', 'status', 'adopt', 'version', 'help']);
89
+ '--generate-secrets', '--resume', '--restore-db', '--json', '--offline', '--install-units', '--force', '--break-lock', '--help', '-h']);
90
+ const COMMANDS = new Set(['init', 'upgrade', 'rollback', 'restore', 'status', 'adopt', 'version', 'help']);
81
91
  export function parseArgs(argv) {
82
92
  const values = new Map();
83
93
  const flags = new Set();
94
+ const args = [];
84
95
  let command;
85
96
  for (let index = 0; index < argv.length; index++) {
86
97
  const arg = argv[index];
@@ -104,13 +115,16 @@ export function parseArgs(argv) {
104
115
  else if (!command && COMMANDS.has(name)) {
105
116
  command = name;
106
117
  }
118
+ else if (command === 'restore' && args.length === 0) {
119
+ args.push(name);
120
+ }
107
121
  else {
108
122
  throw new ArgsError(`unexpected argument ${name}`);
109
123
  }
110
124
  }
111
125
  if (flags.has('--help'))
112
126
  command = 'help';
113
- return { command: command ?? 'help', values, flags };
127
+ return { command: command ?? 'help', values, flags, args };
114
128
  }
115
129
  function port(values, name, fallback) {
116
130
  const raw = values.get(name);
@@ -134,13 +148,15 @@ function projectDir(io, values, system) {
134
148
  return values.get('--dir') ?? io.env['MAGNUS_PROJECT_DIR'] ?? findProjectDir(process.cwd()) ?? defaultProjectDir(io, system);
135
149
  }
136
150
  export async function run(io, argv) {
137
- const { command, values, flags } = parseArgs(argv);
138
- const registry = values.get('--registry') ?? io.env['MAGNUS_UPDATE_REGISTRY'] ?? 'https://registry.npmjs.org';
151
+ const { command, values, flags, args } = parseArgs(argv);
152
+ const registry = ['init', 'upgrade', 'status', 'adopt'].includes(command) ? await resolveRegistry(io, values.get('--registry')) : 'https://registry.npmjs.org';
139
153
  const healthTimeoutMs = Number(values.get('--health-timeout') ?? '180') * 1000;
140
154
  if (!Number.isFinite(healthTimeoutMs) || healthTimeoutMs <= 0)
141
155
  throw new ArgsError('--health-timeout must be a number of seconds');
142
156
  const source = values.get('--source');
143
157
  const yes = flags.has('--yes');
158
+ const breakLock = flags.has('--break-lock');
159
+ const force = flags.has('--force');
144
160
  switch (command) {
145
161
  case 'help':
146
162
  io.log(USAGE);
@@ -162,9 +178,16 @@ export async function run(io, argv) {
162
178
  return upgrade(io, {
163
179
  dir: projectDir(io, values, false), to: values.get('--to'), dryRun: flags.has('--dry-run'), allowMajor: flags.has('--allow-major'),
164
180
  yes, generateSecrets: flags.has('--generate-secrets'), source, registry, healthTimeoutMs, resume: flags.has('--resume'),
181
+ force, breakLock, nodePath: values.get('--node'),
165
182
  });
166
183
  case 'rollback':
167
- return rollback(io, { dir: projectDir(io, values, false), restoreDb: flags.has('--restore-db'), yes, healthTimeoutMs });
184
+ return rollback(io, { dir: projectDir(io, values, false), restoreDb: flags.has('--restore-db'), yes, healthTimeoutMs, force, breakLock });
185
+ case 'restore': {
186
+ const file = args[0];
187
+ if (!file)
188
+ throw new ArgsError('restore needs the dump file: magnus restore <file>');
189
+ return restore(io, { dir: projectDir(io, values, false), file, yes, healthTimeoutMs, breakLock });
190
+ }
168
191
  case 'status':
169
192
  return status(io, { dir: projectDir(io, values, false), json: flags.has('--json'), offline: flags.has('--offline'), registry });
170
193
  case 'adopt': {
package/dist/project.d.ts CHANGED
@@ -2,7 +2,7 @@ export declare const PROJECT_FILE = "magnus-project.json";
2
2
  export type Supervisor = 'systemd' | 'none';
3
3
  export type Component = 'server' | 'ui';
4
4
  export interface HistoryEntry {
5
- action: 'init' | 'adopt' | 'upgrade' | 'rollback';
5
+ action: 'init' | 'adopt' | 'upgrade' | 'rollback' | 'restore';
6
6
  from: string | null;
7
7
  to: string;
8
8
  at: string;
@@ -12,6 +12,22 @@ export interface HistoryEntry {
12
12
  backup?: string;
13
13
  restoreCommand?: string;
14
14
  reason?: string;
15
+ /** The subset of `migrations` that only a database restore undoes. */
16
+ oneWay?: string[];
17
+ }
18
+ /**
19
+ * Written before an upgrade touches the database and cleared when it ends, so
20
+ * an upgrade that was killed midway is noticed by the next command.
21
+ */
22
+ export interface UpgradeJournal {
23
+ phase: 'backup' | 'migrate' | 'check' | 'switch' | 'restart' | 'health' | 'revert';
24
+ from: string;
25
+ to: string;
26
+ backup?: string;
27
+ migrations: string[];
28
+ oneWay: string[];
29
+ startedAt: string;
30
+ pid: number;
15
31
  }
16
32
  export type DatabaseConfig = {
17
33
  kind: 'external';
@@ -36,8 +52,16 @@ export interface ProjectState {
36
52
  current: string | null;
37
53
  previous: string | null;
38
54
  keepVersions: number;
55
+ /** Dumps kept in backups/ (default 5); the newest of each label always stays. */
56
+ keepBackups?: number;
57
+ /** Node.js the units run (and the upgrade uses for npm and the server CLI); default: the units' ExecStart. */
58
+ nodePath?: string;
59
+ /** docker compose project of the bundled PostgreSQL and Redis (projects before 1.1.3: magnus-deps). */
60
+ composeProject?: string;
61
+ inProgress?: UpgradeJournal;
39
62
  history: HistoryEntry[];
40
63
  }
64
+ export declare const DEFAULT_KEEP_BACKUPS = 5;
41
65
  export declare class Project {
42
66
  readonly dir: string;
43
67
  state: ProjectState;
@@ -46,6 +70,10 @@ export declare class Project {
46
70
  static exists(dir: string): boolean;
47
71
  static load(dir: string): Project;
48
72
  save(): void;
73
+ /** Node.js binary the services run. */
74
+ nodePath(): string;
75
+ composeProject(): string;
76
+ keepBackups(): number;
49
77
  path(...segments: string[]): string;
50
78
  envFile(component: Component): string;
51
79
  versionDir(version: string): string;
@@ -56,8 +84,53 @@ export declare class Project {
56
84
  switchCurrent(version: string): void;
57
85
  record(entry: HistoryEntry): void;
58
86
  }
59
- export declare function writeAtomic(path: string, content: string, mode: number): void;
60
- /** Exclusive lock file; a lock left by a dead process is taken over. */
61
- export declare function acquireLock(path: string): () => void;
87
+ /**
88
+ * Write a temp file, fsync it, rename it over `path` and fsync the directory,
89
+ * so a crash leaves either the old or the new content, never a torn file.
90
+ */
91
+ export declare function writeAtomic(path: string, content: string, mode: number, owner?: {
92
+ uid: number;
93
+ gid: number;
94
+ }): void;
95
+ /** What a lock file records about its holder. */
96
+ export interface LockInfo {
97
+ pid: number;
98
+ /** Linux boot id: a pid from an earlier boot is meaningless. */
99
+ bootId: string;
100
+ /** Start time of the holder (clock ticks since boot), so a reused pid is not mistaken for it. */
101
+ startTime: string;
102
+ /** Shared with a handed-over child so it can take the lock without a gap. */
103
+ token: string;
104
+ command: string;
105
+ }
106
+ export declare function bootId(): string;
107
+ /** Field 22 of /proc/<pid>/stat; '' where /proc is unavailable. */
108
+ export declare function processStartTime(pid: number): string;
109
+ /**
110
+ * A lock file is the holder's pid on the first line (all older engines read
111
+ * only that), then the JSON details.
112
+ */
113
+ export declare function parseLock(content: string): LockInfo | null;
114
+ /** Whether the process a lock names is still the one that took it. */
115
+ export declare function lockHolderAlive(info: LockInfo): boolean;
116
+ export interface LockOptions {
117
+ /** Take over a lock whose token matches (the engine that handed over to this one). */
118
+ inheritToken?: string;
119
+ /** Remove any existing lock first (`--break-lock`). */
120
+ breakLock?: boolean;
121
+ command?: string;
122
+ }
123
+ export type Lock = (() => void) & {
124
+ token: string;
125
+ path: string;
126
+ };
127
+ /**
128
+ * Exclusive lock file. A lock whose holder is gone (dead pid, other boot,
129
+ * reused pid) is taken over; concurrent takeovers are safe because the stale
130
+ * file is first renamed to a private name and checked before it is removed.
131
+ */
132
+ export declare function acquireLock(path: string, options?: LockOptions): Lock;
133
+ /** Owner of a path (uid), or null. */
134
+ export declare function ownerOf(path: string): number | null;
62
135
  /** Walk up from `start` looking for magnus-project.json. */
63
136
  export declare function findProjectDir(start: string): string | null;