@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 +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 +49 -14
package/dist/project.js
CHANGED
|
@@ -11,9 +11,11 @@
|
|
|
11
11
|
* run/upgrade.lock, run/server-runtime.json
|
|
12
12
|
* units/ generated systemd units (or compose.yml)
|
|
13
13
|
*/
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
14
|
+
import { randomBytes } from 'node:crypto';
|
|
15
|
+
import { chownSync, closeSync, copyFileSync, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync, writeSync, } from 'node:fs';
|
|
16
|
+
import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
|
|
16
17
|
export const PROJECT_FILE = 'magnus-project.json';
|
|
18
|
+
export const DEFAULT_KEEP_BACKUPS = 5;
|
|
17
19
|
export class Project {
|
|
18
20
|
dir;
|
|
19
21
|
state;
|
|
@@ -31,13 +33,42 @@ export class Project {
|
|
|
31
33
|
const path = Project.file(dir);
|
|
32
34
|
if (!existsSync(path))
|
|
33
35
|
throw new Error(`No Magnus project at ${dir} (missing ${PROJECT_FILE}). Create one with \`magnus init\` or \`magnus adopt\`.`);
|
|
34
|
-
|
|
36
|
+
let state;
|
|
37
|
+
try {
|
|
38
|
+
state = JSON.parse(readFileSync(path, 'utf8'));
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
throw new Error(`${path} is not valid JSON (${error instanceof Error ? error.message : String(error)}). `
|
|
42
|
+
+ `${existsSync(`${path}.bak`) ? `The previous state is in ${path}.bak: check it and copy it over.` : 'Repair the file by hand.'}`);
|
|
43
|
+
}
|
|
35
44
|
if (state.schema !== 1)
|
|
36
45
|
throw new Error(`${path} has schema ${String(state.schema)}; this version of magnus understands schema 1. Upgrade with \`npx @hivemagnus/magnus@latest\`.`);
|
|
37
46
|
return new Project(resolve(dir), state);
|
|
38
47
|
}
|
|
39
48
|
save() {
|
|
40
|
-
|
|
49
|
+
const file = Project.file(this.dir);
|
|
50
|
+
if (existsSync(file))
|
|
51
|
+
copyFileSync(file, `${file}.bak`);
|
|
52
|
+
writeAtomic(file, `${JSON.stringify(this.state, null, 2)}\n`, 0o644);
|
|
53
|
+
}
|
|
54
|
+
/** Node.js binary the services run. */
|
|
55
|
+
nodePath() {
|
|
56
|
+
if (this.state.nodePath)
|
|
57
|
+
return this.state.nodePath;
|
|
58
|
+
try {
|
|
59
|
+
const unit = readFileSync(this.path('units', `${this.state.units.server}.service`), 'utf8');
|
|
60
|
+
const exec = /^ExecStart=(\S+)/m.exec(unit)?.[1];
|
|
61
|
+
if (exec)
|
|
62
|
+
return exec;
|
|
63
|
+
}
|
|
64
|
+
catch { /* no generated unit */ }
|
|
65
|
+
return process.execPath;
|
|
66
|
+
}
|
|
67
|
+
composeProject() {
|
|
68
|
+
return this.state.composeProject ?? 'magnus-deps';
|
|
69
|
+
}
|
|
70
|
+
keepBackups() {
|
|
71
|
+
return this.state.keepBackups ?? DEFAULT_KEEP_BACKUPS;
|
|
41
72
|
}
|
|
42
73
|
path(...segments) {
|
|
43
74
|
return join(this.dir, ...segments);
|
|
@@ -82,11 +113,61 @@ export class Project {
|
|
|
82
113
|
this.state.history.splice(0, this.state.history.length - 50);
|
|
83
114
|
}
|
|
84
115
|
}
|
|
85
|
-
|
|
116
|
+
function fsyncPath(path, flags) {
|
|
117
|
+
let fd;
|
|
118
|
+
try {
|
|
119
|
+
fd = openSync(path, flags);
|
|
120
|
+
fsyncSync(fd);
|
|
121
|
+
}
|
|
122
|
+
catch { /* directories cannot be opened for fsync on every platform */ }
|
|
123
|
+
finally {
|
|
124
|
+
if (fd !== undefined)
|
|
125
|
+
closeSync(fd);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Write a temp file, fsync it, rename it over `path` and fsync the directory,
|
|
130
|
+
* so a crash leaves either the old or the new content, never a torn file.
|
|
131
|
+
*/
|
|
132
|
+
export function writeAtomic(path, content, mode, owner) {
|
|
86
133
|
mkdirSync(dirname(path), { recursive: true });
|
|
87
134
|
const temporary = `${path}.${process.pid}.tmp`;
|
|
88
|
-
|
|
135
|
+
const fd = openSync(temporary, 'w', mode);
|
|
136
|
+
try {
|
|
137
|
+
writeSync(fd, content);
|
|
138
|
+
fsyncSync(fd);
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
closeSync(fd);
|
|
142
|
+
}
|
|
143
|
+
if (owner) {
|
|
144
|
+
try {
|
|
145
|
+
// Only root can give a file away; elsewhere the owner already matches.
|
|
146
|
+
if (typeof process.geteuid === 'function' && process.geteuid() === 0) {
|
|
147
|
+
chownSync(temporary, owner.uid, owner.gid);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
catch { /* keep the writer as owner */ }
|
|
151
|
+
}
|
|
89
152
|
renameSync(temporary, path);
|
|
153
|
+
fsyncPath(dirname(path), 'r');
|
|
154
|
+
}
|
|
155
|
+
function readOptional(path) {
|
|
156
|
+
try {
|
|
157
|
+
return readFileSync(path, 'utf8').trim();
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
return '';
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
export function bootId() {
|
|
164
|
+
return readOptional('/proc/sys/kernel/random/boot_id');
|
|
165
|
+
}
|
|
166
|
+
/** Field 22 of /proc/<pid>/stat; '' where /proc is unavailable. */
|
|
167
|
+
export function processStartTime(pid) {
|
|
168
|
+
const stat = readOptional(`/proc/${pid}/stat`);
|
|
169
|
+
const fields = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
|
|
170
|
+
return fields[19] ?? '';
|
|
90
171
|
}
|
|
91
172
|
function processAlive(pid) {
|
|
92
173
|
try {
|
|
@@ -97,27 +178,113 @@ function processAlive(pid) {
|
|
|
97
178
|
return error.code === 'EPERM';
|
|
98
179
|
}
|
|
99
180
|
}
|
|
100
|
-
/**
|
|
101
|
-
|
|
181
|
+
/**
|
|
182
|
+
* A lock file is the holder's pid on the first line (all older engines read
|
|
183
|
+
* only that), then the JSON details.
|
|
184
|
+
*/
|
|
185
|
+
export function parseLock(content) {
|
|
186
|
+
const [first = '', ...rest] = content.trim().split('\n');
|
|
187
|
+
if (!/^\d+$/.test(first.trim()))
|
|
188
|
+
return null;
|
|
189
|
+
const pid = Number(first.trim());
|
|
190
|
+
try {
|
|
191
|
+
const info = JSON.parse(rest.join('\n') || '{}');
|
|
192
|
+
return { pid, bootId: info.bootId ?? '', startTime: info.startTime ?? '', token: info.token ?? '', command: info.command ?? '' };
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
return { pid, bootId: '', startTime: '', token: '', command: '' };
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
/** Whether the process a lock names is still the one that took it. */
|
|
199
|
+
export function lockHolderAlive(info) {
|
|
200
|
+
if (info.bootId && bootId() && info.bootId !== bootId())
|
|
201
|
+
return false;
|
|
202
|
+
if (!processAlive(info.pid))
|
|
203
|
+
return false;
|
|
204
|
+
if (info.startTime && processStartTime(info.pid) && processStartTime(info.pid) !== info.startTime)
|
|
205
|
+
return false;
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
function lockContent(token, command) {
|
|
209
|
+
const info = { bootId: bootId(), startTime: processStartTime(process.pid), token, command };
|
|
210
|
+
return `${process.pid}\n${JSON.stringify(info)}\n`;
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Exclusive lock file. A lock whose holder is gone (dead pid, other boot,
|
|
214
|
+
* reused pid) is taken over; concurrent takeovers are safe because the stale
|
|
215
|
+
* file is first renamed to a private name and checked before it is removed.
|
|
216
|
+
*/
|
|
217
|
+
export function acquireLock(path, options = {}) {
|
|
102
218
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
103
|
-
|
|
219
|
+
const token = randomBytes(16).toString('hex');
|
|
220
|
+
const command = options.command ?? 'magnus';
|
|
221
|
+
const make = () => {
|
|
222
|
+
const release = (() => {
|
|
223
|
+
// Never remove a lock another process (a handed-over child) has taken since.
|
|
224
|
+
if (parseLock(readOptional(path))?.token === token)
|
|
225
|
+
rmSync(path, { force: true });
|
|
226
|
+
});
|
|
227
|
+
release.token = token;
|
|
228
|
+
release.path = path;
|
|
229
|
+
return release;
|
|
230
|
+
};
|
|
231
|
+
if (options.breakLock)
|
|
232
|
+
rmSync(path, { force: true });
|
|
233
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
104
234
|
try {
|
|
105
235
|
const fd = openSync(path, 'wx', 0o600);
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
236
|
+
try {
|
|
237
|
+
writeSync(fd, lockContent(token, command));
|
|
238
|
+
fsyncSync(fd);
|
|
239
|
+
}
|
|
240
|
+
finally {
|
|
241
|
+
closeSync(fd);
|
|
242
|
+
}
|
|
243
|
+
return make();
|
|
109
244
|
}
|
|
110
245
|
catch (error) {
|
|
111
246
|
if (error.code !== 'EEXIST')
|
|
112
247
|
throw error;
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
248
|
+
}
|
|
249
|
+
const content = readOptional(path);
|
|
250
|
+
const holder = parseLock(content);
|
|
251
|
+
if (holder && options.inheritToken && holder.token === options.inheritToken) {
|
|
252
|
+
writeAtomic(path, lockContent(token, command), 0o600);
|
|
253
|
+
return make();
|
|
254
|
+
}
|
|
255
|
+
if (holder && lockHolderAlive(holder)) {
|
|
256
|
+
throw new Error(`Another magnus command (pid ${holder.pid}${holder.command ? `, ${holder.command}` : ''}) holds the lock ${path}. `
|
|
257
|
+
+ 'Wait for it to finish. If that process is not a magnus command, re-run with --break-lock.');
|
|
258
|
+
}
|
|
259
|
+
// Stale: move it to a private name, then make sure it is the file we judged.
|
|
260
|
+
const grabbed = join(dirname(path), `.${basename(path)}.${process.pid}.${token.slice(0, 8)}.stale`);
|
|
261
|
+
try {
|
|
262
|
+
renameSync(path, grabbed);
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
if (error.code === 'ENOENT')
|
|
266
|
+
continue;
|
|
267
|
+
throw error;
|
|
268
|
+
}
|
|
269
|
+
if (readOptional(grabbed) !== content) {
|
|
270
|
+
// Another process replaced the stale lock with a live one first: put it back.
|
|
271
|
+
try {
|
|
272
|
+
linkSync(grabbed, path);
|
|
116
273
|
}
|
|
117
|
-
|
|
274
|
+
catch { /* a third lock exists; it wins */ }
|
|
118
275
|
}
|
|
276
|
+
rmSync(grabbed, { force: true });
|
|
277
|
+
}
|
|
278
|
+
throw new Error(`Could not take the lock ${path}; another magnus command keeps taking it.`);
|
|
279
|
+
}
|
|
280
|
+
/** Owner of a path (uid), or null. */
|
|
281
|
+
export function ownerOf(path) {
|
|
282
|
+
try {
|
|
283
|
+
return statSync(path).uid;
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
return null;
|
|
119
287
|
}
|
|
120
|
-
throw new Error(`Could not take ${path}`);
|
|
121
288
|
}
|
|
122
289
|
/** Walk up from `start` looking for magnus-project.json. */
|
|
123
290
|
export function findProjectDir(start) {
|
package/dist/release.d.ts
CHANGED
|
@@ -7,8 +7,14 @@ export declare const CONTRACTS_PACKAGE = "@hivemagnus/magnus-contracts";
|
|
|
7
7
|
export declare const AGENT_PACKAGE = "@hivemagnus/magnus-agent";
|
|
8
8
|
/** Packages a project installs; the agent runs on managed hosts, not here. */
|
|
9
9
|
export declare const PROJECT_PACKAGES: readonly ["@hivemagnus/magnus-server", "@hivemagnus/magnus-ui", "@hivemagnus/magnus-contracts"];
|
|
10
|
-
/**
|
|
11
|
-
|
|
10
|
+
/**
|
|
11
|
+
* Upgrade-engine protocol; a newer target engine takes over migrate and switch.
|
|
12
|
+
* 2: the in-progress journal, lock hand-over (MAGNUS_LOCK_TOKEN) and the
|
|
13
|
+
* clean-schema restore.
|
|
14
|
+
*/
|
|
15
|
+
export declare const ENGINE_PROTOCOL = 2;
|
|
16
|
+
/** First release whose meta package carries a manifest; older ones get a synthetic one. */
|
|
17
|
+
export declare const MANIFEST_SINCE = "1.1.0";
|
|
12
18
|
export declare function ownPackage(): {
|
|
13
19
|
version: string;
|
|
14
20
|
magnusRelease: ReleaseManifest;
|
|
@@ -19,7 +25,20 @@ export interface ReleaseCatalog {
|
|
|
19
25
|
manifests: Map<string, ReleaseManifest>;
|
|
20
26
|
/** Tarballs by `name@version` when installing from --source. */
|
|
21
27
|
tarballs: Map<string, string>;
|
|
28
|
+
/** Versions whose manifest exists but is newer than this engine understands. */
|
|
29
|
+
unparsable?: Set<string>;
|
|
30
|
+
deprecated?: Set<string>;
|
|
31
|
+
/** The registry's `latest` dist-tag: automatic targets never go past it. */
|
|
32
|
+
latest?: string | null;
|
|
33
|
+
}
|
|
34
|
+
export declare class TooOldError extends Error {
|
|
22
35
|
}
|
|
36
|
+
export declare const TOO_OLD_HINT = "this engine is too old to read it; run the newest one: npx @hivemagnus/magnus@latest upgrade";
|
|
37
|
+
/**
|
|
38
|
+
* The registry to use: --registry, MAGNUS_UPDATE_REGISTRY, then npm's own
|
|
39
|
+
* configuration (.npmrc), then the public registry.
|
|
40
|
+
*/
|
|
41
|
+
export declare function resolveRegistry(io: Io, explicit: string | undefined, npm?: () => Promise<string | null>): Promise<string>;
|
|
23
42
|
export declare function fetchRegistryCatalog(io: Io, registry: string, packageName?: string): Promise<ReleaseCatalog>;
|
|
24
43
|
/** npm pack names files `<scope>-<name>-<version>.tgz`. */
|
|
25
44
|
export declare function tarballName(packageName: string, version: string): string;
|
|
@@ -29,8 +48,11 @@ export declare function sourceCatalog(io: Io, sourceDir: string, registry: strin
|
|
|
29
48
|
/**
|
|
30
49
|
* The manifest for a version. Releases before the meta package existed
|
|
31
50
|
* (1.0.x) have none: their components share the release version and this
|
|
32
|
-
* engine drives them.
|
|
51
|
+
* engine drives them. A later release without a readable manifest is never
|
|
52
|
+
* guessed at: its manifest is newer than this engine, or the release is broken.
|
|
33
53
|
*/
|
|
34
54
|
export declare function releaseFor(catalog: ReleaseCatalog, version: string): ReleaseManifest;
|
|
35
55
|
export declare function pickTarget(catalog: ReleaseCatalog, current: string, requested?: string): string;
|
|
56
|
+
/** Versions an automatic upgrade may pick: not deprecated, and not past dist-tags.latest. */
|
|
57
|
+
export declare function automaticCandidates(catalog: ReleaseCatalog): string[];
|
|
36
58
|
export declare function newerMajor(catalog: ReleaseCatalog, current: string): string | null;
|
package/dist/release.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
import { existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
8
8
|
import { dirname, join, resolve } from 'node:path';
|
|
9
9
|
import { fileURLToPath } from 'node:url';
|
|
10
|
-
import { compareVersions, latestVersion,
|
|
10
|
+
import { compareVersions, latestVersion, readPackument, releaseManifestSchema, } from '@hivemagnus/magnus-contracts';
|
|
11
11
|
import { mustRun } from './io.js';
|
|
12
12
|
export const META_PACKAGE = '@hivemagnus/magnus';
|
|
13
13
|
export const SERVER_PACKAGE = '@hivemagnus/magnus-server';
|
|
@@ -16,13 +16,37 @@ export const CONTRACTS_PACKAGE = '@hivemagnus/magnus-contracts';
|
|
|
16
16
|
export const AGENT_PACKAGE = '@hivemagnus/magnus-agent';
|
|
17
17
|
/** Packages a project installs; the agent runs on managed hosts, not here. */
|
|
18
18
|
export const PROJECT_PACKAGES = [SERVER_PACKAGE, UI_PACKAGE, CONTRACTS_PACKAGE];
|
|
19
|
-
/**
|
|
20
|
-
|
|
19
|
+
/**
|
|
20
|
+
* Upgrade-engine protocol; a newer target engine takes over migrate and switch.
|
|
21
|
+
* 2: the in-progress journal, lock hand-over (MAGNUS_LOCK_TOKEN) and the
|
|
22
|
+
* clean-schema restore.
|
|
23
|
+
*/
|
|
24
|
+
export const ENGINE_PROTOCOL = 2;
|
|
25
|
+
/** First release whose meta package carries a manifest; older ones get a synthetic one. */
|
|
26
|
+
export const MANIFEST_SINCE = '1.1.0';
|
|
21
27
|
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
|
22
28
|
export function ownPackage() {
|
|
23
29
|
const raw = JSON.parse(readFileSync(join(packageRoot, 'package.json'), 'utf8'));
|
|
24
30
|
return { version: raw.version, magnusRelease: releaseManifestSchema.parse(raw.magnusRelease) };
|
|
25
31
|
}
|
|
32
|
+
export class TooOldError extends Error {
|
|
33
|
+
}
|
|
34
|
+
export const TOO_OLD_HINT = 'this engine is too old to read it; run the newest one: npx @hivemagnus/magnus@latest upgrade';
|
|
35
|
+
/**
|
|
36
|
+
* The registry to use: --registry, MAGNUS_UPDATE_REGISTRY, then npm's own
|
|
37
|
+
* configuration (.npmrc), then the public registry.
|
|
38
|
+
*/
|
|
39
|
+
export async function resolveRegistry(io, explicit, npm = () => npmConfigRegistry(io)) {
|
|
40
|
+
const chosen = explicit ?? io.env['MAGNUS_UPDATE_REGISTRY']?.trim();
|
|
41
|
+
if (chosen)
|
|
42
|
+
return chosen;
|
|
43
|
+
return (await npm().catch(() => null)) || 'https://registry.npmjs.org';
|
|
44
|
+
}
|
|
45
|
+
async function npmConfigRegistry(io) {
|
|
46
|
+
const result = await io.run('npm', ['config', 'get', 'registry'], { capture: true });
|
|
47
|
+
const value = result.code === 0 ? result.stdout.trim() : '';
|
|
48
|
+
return /^https?:\/\//.test(value) ? value : null;
|
|
49
|
+
}
|
|
26
50
|
export async function fetchRegistryCatalog(io, registry, packageName = META_PACKAGE) {
|
|
27
51
|
const url = `${registry.replace(/\/+$/, '')}/${packageName.replace('/', '%2f')}`;
|
|
28
52
|
let response;
|
|
@@ -31,15 +55,25 @@ export async function fetchRegistryCatalog(io, registry, packageName = META_PACK
|
|
|
31
55
|
response = await io.fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(20_000) });
|
|
32
56
|
}
|
|
33
57
|
catch (error) {
|
|
34
|
-
|
|
58
|
+
const proxy = io.env['HTTPS_PROXY'] || io.env['https_proxy'] || io.env['HTTP_PROXY'] || io.env['http_proxy'];
|
|
59
|
+
throw new Error(`Cannot reach the npm registry (${url}): ${error instanceof Error ? error.message : String(error)}`
|
|
60
|
+
+ `${proxy && !io.env['NODE_USE_ENV_PROXY'] ? '. A proxy is configured: run with NODE_USE_ENV_PROXY=1 so Node.js uses it.' : ''}`);
|
|
61
|
+
}
|
|
62
|
+
if (response.status === 404) {
|
|
63
|
+
throw new Error(`The registry ${registry} has no ${packageName} (404 for ${url}). Check --registry or MAGNUS_UPDATE_REGISTRY, or use --source with packed tarballs.`);
|
|
35
64
|
}
|
|
36
|
-
if (response.status === 404)
|
|
37
|
-
return { versions: [], manifests: new Map(), tarballs: new Map() };
|
|
38
65
|
if (!response.ok)
|
|
39
66
|
throw new Error(`The npm registry answered ${response.status} for ${url}`);
|
|
40
67
|
const packument = await response.json();
|
|
41
|
-
const
|
|
42
|
-
return {
|
|
68
|
+
const read = readPackument(packument);
|
|
69
|
+
return {
|
|
70
|
+
versions: Object.keys(packument.versions ?? {}),
|
|
71
|
+
manifests: new Map(read.manifests.map((m) => [m.version, m])),
|
|
72
|
+
tarballs: new Map(),
|
|
73
|
+
unparsable: new Set(read.unparsable),
|
|
74
|
+
deprecated: new Set(read.deprecated),
|
|
75
|
+
latest: read.latest,
|
|
76
|
+
};
|
|
43
77
|
}
|
|
44
78
|
/** npm pack names files `<scope>-<name>-<version>.tgz`. */
|
|
45
79
|
export function tarballName(packageName, version) {
|
|
@@ -51,6 +85,7 @@ export async function readSourceCatalog(io, sourceDir) {
|
|
|
51
85
|
throw new Error(`--source ${dir} does not exist`);
|
|
52
86
|
const tarballs = new Map();
|
|
53
87
|
const manifests = new Map();
|
|
88
|
+
const unparsable = new Set();
|
|
54
89
|
const versions = [];
|
|
55
90
|
for (const file of readdirSync(dir).filter((name) => name.endsWith('.tgz')).sort()) {
|
|
56
91
|
const path = join(dir, file);
|
|
@@ -59,12 +94,16 @@ export async function readSourceCatalog(io, sourceDir) {
|
|
|
59
94
|
tarballs.set(`${pkg.name}@${pkg.version}`, path);
|
|
60
95
|
if (pkg.name === META_PACKAGE) {
|
|
61
96
|
versions.push(pkg.version);
|
|
97
|
+
if (pkg.magnusRelease === undefined)
|
|
98
|
+
continue;
|
|
62
99
|
const parsed = releaseManifestSchema.safeParse(pkg.magnusRelease);
|
|
63
100
|
if (parsed.success)
|
|
64
101
|
manifests.set(pkg.version, parsed.data);
|
|
102
|
+
else
|
|
103
|
+
unparsable.add(pkg.version);
|
|
65
104
|
}
|
|
66
105
|
}
|
|
67
|
-
return { versions, manifests, tarballs };
|
|
106
|
+
return { versions, manifests, tarballs, unparsable };
|
|
68
107
|
}
|
|
69
108
|
/** Registry history plus local tarballs; local entries win. The registry is optional here. */
|
|
70
109
|
export async function sourceCatalog(io, sourceDir, registry) {
|
|
@@ -72,21 +111,34 @@ export async function sourceCatalog(io, sourceDir, registry) {
|
|
|
72
111
|
const remote = await fetchRegistryCatalog(io, registry).catch(() => null);
|
|
73
112
|
if (!remote)
|
|
74
113
|
return local;
|
|
114
|
+
const unparsable = new Set([...(remote.unparsable ?? [])].filter((version) => !local.manifests.has(version)));
|
|
115
|
+
for (const version of local.unparsable ?? [])
|
|
116
|
+
unparsable.add(version);
|
|
75
117
|
return {
|
|
76
118
|
versions: [...new Set([...remote.versions, ...local.versions])],
|
|
77
119
|
manifests: new Map([...remote.manifests, ...local.manifests]),
|
|
78
120
|
tarballs: local.tarballs,
|
|
121
|
+
unparsable,
|
|
122
|
+
deprecated: remote.deprecated,
|
|
123
|
+
// Local tarballs are what the operator asked for; the registry tag does not cap them.
|
|
124
|
+
latest: null,
|
|
79
125
|
};
|
|
80
126
|
}
|
|
81
127
|
/**
|
|
82
128
|
* The manifest for a version. Releases before the meta package existed
|
|
83
129
|
* (1.0.x) have none: their components share the release version and this
|
|
84
|
-
* engine drives them.
|
|
130
|
+
* engine drives them. A later release without a readable manifest is never
|
|
131
|
+
* guessed at: its manifest is newer than this engine, or the release is broken.
|
|
85
132
|
*/
|
|
86
133
|
export function releaseFor(catalog, version) {
|
|
87
134
|
const found = catalog.manifests.get(version);
|
|
88
135
|
if (found)
|
|
89
136
|
return found;
|
|
137
|
+
if (catalog.unparsable?.has(version))
|
|
138
|
+
throw new TooOldError(`The release manifest of ${version} uses a newer format: ${TOO_OLD_HINT}`);
|
|
139
|
+
if (compareVersions(version, MANIFEST_SINCE) >= 0) {
|
|
140
|
+
throw new TooOldError(`${META_PACKAGE}@${version} has no release manifest this engine can read; ${TOO_OLD_HINT}`);
|
|
141
|
+
}
|
|
90
142
|
const own = ownPackage().magnusRelease;
|
|
91
143
|
return releaseManifestSchema.parse({
|
|
92
144
|
schema: 1,
|
|
@@ -105,10 +157,16 @@ export function pickTarget(catalog, current, requested) {
|
|
|
105
157
|
}
|
|
106
158
|
return requested;
|
|
107
159
|
}
|
|
108
|
-
const latest = latestVersion(catalog
|
|
160
|
+
const latest = latestVersion(automaticCandidates(catalog), { sameMajorAs: current });
|
|
109
161
|
return latest && compareVersions(latest, current) > 0 ? latest : current;
|
|
110
162
|
}
|
|
163
|
+
/** Versions an automatic upgrade may pick: not deprecated, and not past dist-tags.latest. */
|
|
164
|
+
export function automaticCandidates(catalog) {
|
|
165
|
+
const cap = catalog.latest;
|
|
166
|
+
return catalog.versions.filter((version) => !catalog.deprecated?.has(version)
|
|
167
|
+
&& (!cap || compareVersions(version, cap) <= 0));
|
|
168
|
+
}
|
|
111
169
|
export function newerMajor(catalog, current) {
|
|
112
|
-
const latest = latestVersion(catalog
|
|
170
|
+
const latest = latestVersion(automaticCandidates(catalog));
|
|
113
171
|
return latest && compareVersions(latest, current) > 0 && latest.split('.')[0] !== current.split('.')[0] ? latest : null;
|
|
114
172
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Io } from './io.js';
|
|
2
|
+
export interface RestoreOptions {
|
|
3
|
+
dir: string;
|
|
4
|
+
file: string;
|
|
5
|
+
yes: boolean;
|
|
6
|
+
healthTimeoutMs: number;
|
|
7
|
+
breakLock?: boolean;
|
|
8
|
+
}
|
|
9
|
+
/** The version a dump was taken from, when its label says so (pre-upgrade-A-to-B, pre-migrate-B). */
|
|
10
|
+
export declare function dumpVersion(file: string): string | null;
|
|
11
|
+
export declare function restore(io: Io, options: RestoreOptions): Promise<number>;
|
package/dist/restore.js
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** `magnus restore <dump>`: stop the services, restore the dump into a clean schema, start them again. */
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { waitForHealthy } from './health.js';
|
|
5
|
+
import { acquireLock, Project } from './project.js';
|
|
6
|
+
import { stopAndRestore } from './rollback.js';
|
|
7
|
+
import { restartServices } from './supervisor.js';
|
|
8
|
+
import { requirePrivileges, UpgradeError } from './upgrade.js';
|
|
9
|
+
/** The version a dump was taken from, when its label says so (pre-upgrade-A-to-B, pre-migrate-B). */
|
|
10
|
+
export function dumpVersion(file) {
|
|
11
|
+
let label = '';
|
|
12
|
+
try {
|
|
13
|
+
label = JSON.parse(readFileSync(`${file}.json`, 'utf8')).label ?? '';
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
label = file;
|
|
17
|
+
}
|
|
18
|
+
return /pre-upgrade-(\d+\.\d+\.\d+)-to-/.exec(label)?.[1] ?? null;
|
|
19
|
+
}
|
|
20
|
+
export async function restore(io, options) {
|
|
21
|
+
const project = Project.load(options.dir);
|
|
22
|
+
requirePrivileges(io, project);
|
|
23
|
+
const file = resolve(options.file);
|
|
24
|
+
if (!existsSync(file))
|
|
25
|
+
throw new UpgradeError(`${file} does not exist`);
|
|
26
|
+
const release = acquireLock(project.path('run', 'upgrade.lock'), { breakLock: options.breakLock, command: 'magnus restore' });
|
|
27
|
+
try {
|
|
28
|
+
const current = project.linkedVersion() ?? project.state.current;
|
|
29
|
+
if (!current)
|
|
30
|
+
throw new UpgradeError(`${project.dir} has no serving version.`);
|
|
31
|
+
const from = dumpVersion(file);
|
|
32
|
+
if (from && from !== current) {
|
|
33
|
+
io.warn(`${file} was taken while ${from} was serving, but ./current is ${current}. Roll back first (\`magnus rollback --restore-db\`) unless you know ${current} runs on it.`);
|
|
34
|
+
}
|
|
35
|
+
if (!options.yes && !await io.confirm(`Replace the database with ${file} and restart ${current}? Changes made since the dump are lost`)) {
|
|
36
|
+
throw new UpgradeError('Stopped: the restore was not confirmed (pass --yes to confirm non-interactively).');
|
|
37
|
+
}
|
|
38
|
+
await stopAndRestore(io, project, file, options.yes);
|
|
39
|
+
const restartedAt = io.now();
|
|
40
|
+
await restartServices(io, project);
|
|
41
|
+
const health = await waitForHealthy(io, project, { version: current, startedAfter: restartedAt, timeoutMs: options.healthTimeoutMs });
|
|
42
|
+
project.record({ action: 'restore', from: current, to: current, at: io.now().toISOString(), result: health.ok ? 'ok' : 'failed', migrations: [], backup: file,
|
|
43
|
+
...(health.ok ? {} : { reason: health.detail }) });
|
|
44
|
+
project.save();
|
|
45
|
+
if (!health.ok) {
|
|
46
|
+
io.warn(`Restored ${file}, but ${current} is ${health.detail}.`);
|
|
47
|
+
return 1;
|
|
48
|
+
}
|
|
49
|
+
io.log(`Restored ${file}; ${health.detail}.`);
|
|
50
|
+
return 0;
|
|
51
|
+
}
|
|
52
|
+
finally {
|
|
53
|
+
release();
|
|
54
|
+
}
|
|
55
|
+
}
|
package/dist/rollback.d.ts
CHANGED
|
@@ -1,8 +1,14 @@
|
|
|
1
1
|
import type { Io } from './io.js';
|
|
2
|
+
import { Project } from './project.js';
|
|
2
3
|
export interface RollbackOptions {
|
|
3
4
|
dir: string;
|
|
4
5
|
restoreDb: boolean;
|
|
5
6
|
yes: boolean;
|
|
6
7
|
healthTimeoutMs: number;
|
|
8
|
+
/** Start the previous version even when the database has one-way migrations it does not know. */
|
|
9
|
+
force?: boolean;
|
|
10
|
+
breakLock?: boolean;
|
|
7
11
|
}
|
|
12
|
+
/** Stop, restore; on failure start the services again on the untouched database. */
|
|
13
|
+
export declare function stopAndRestore(io: Io, project: Project, file: string, yes: boolean): Promise<void>;
|
|
8
14
|
export declare function rollback(io: Io, options: RollbackOptions): Promise<number>;
|