@north-light/api 0.3.760 → 0.3.761
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/clients/attach/config.js +2 -1
- package/dist/commands/api-client.d.ts +0 -5
- package/dist/commands/api-client.js +1 -12
- package/dist/commands/sys/import/move.d.ts +1 -34
- package/dist/commands/sys/import/move.js +5 -205
- package/dist/commands/sys/import/start.d.ts +0 -3
- package/dist/commands/sys/import/start.js +15 -51
- package/dist/commands/sys/signin.js +13 -54
- package/dist/core/command.d.ts +1 -1
- package/dist/core/worktree-mutation-async.js +11 -3
- package/dist/core/worktree-scripts.d.ts +13 -0
- package/dist/core/worktree-scripts.js +72 -0
- package/dist/core/worktree-sweep.js +10 -1
- package/dist/daemon/machine-link/config.d.ts +0 -24
- package/dist/daemon/machine-link/config.js +1 -27
- package/dist/daemon/manage.d.ts +1 -1
- package/package.json +1 -1
- package/dist/commands/sys/import/retry.d.ts +0 -1
- package/dist/commands/sys/import/retry.js +0 -38
- package/dist/daemon/machine-link/move-notify.d.ts +0 -4
- package/dist/daemon/machine-link/move-notify.js +0 -15
|
@@ -95,7 +95,8 @@ export function loadUserKeybindings(agentDir = defaultAgentDir()) {
|
|
|
95
95
|
const ATTACH_KEYBINDING_OVERRIDES = {
|
|
96
96
|
'tui.input.newLine': { defaultKeys: ['shift+enter', 'alt+enter'], description: 'Insert new line' },
|
|
97
97
|
// Ctrl+K/U/D/J/G scroll the transcript (crtr.attach.scroll.*), so the editor gives them up.
|
|
98
|
-
|
|
98
|
+
// Cmd+Delete arrives as super+backspace (CSI 127;9u) when the terminal or tmux sends it distinctly.
|
|
99
|
+
'tui.editor.deleteToLineStart': { defaultKeys: ['super+backspace'], description: 'Delete to line start' },
|
|
99
100
|
'tui.editor.deleteToLineEnd': { defaultKeys: [], description: 'Delete to line end' },
|
|
100
101
|
'tui.editor.deleteCharForward': { defaultKeys: ['delete'], description: 'Delete character forward' },
|
|
101
102
|
};
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { CrtrClient } from '../api/index.js';
|
|
2
|
-
import { CrtrError } from '../core/errors.js';
|
|
3
2
|
import type { CanvasSource } from '../core/canvas/source.js';
|
|
4
3
|
import type { NodeStatus, SubscriptionRef } from '../core/canvas/types.js';
|
|
5
4
|
import type { Scope } from '../types.js';
|
|
@@ -46,10 +45,6 @@ export declare function remoteTarget(): {
|
|
|
46
45
|
* a node on a Mac moved into Northlight (`machine.json`; its machine daemon serves no `/v1`) or a fleet node (`CRTR_API_URL` names the control plane).
|
|
47
46
|
* `remoteTarget()` reports undefined for it because the transport is a local socket. */
|
|
48
47
|
export declare function relayReachesControlPlane(): boolean;
|
|
49
|
-
/** A move whose cloud run reached `done` but whose computer has not switched over: the account holds the records, the local daemon stays drained,
|
|
50
|
-
* and no command may run against either side until `crtr sys signin` finishes it (design D14). The record is deleted only once the machine-role daemon
|
|
51
|
-
* is up (`finishMove`, or that daemon's own start), so a `machine.json` written before a failed restart does not lift this. */
|
|
52
|
-
export declare function moveUnfinished(): CrtrError | undefined;
|
|
53
48
|
/** The local-socket `CrtrClient` every CLI verb uses. Autostart is on by
|
|
54
49
|
* default: on a cold socket the injected `onColdSocket` hook fires
|
|
55
50
|
* `ensureDaemon()` (spawns crtrd detached via the branded host), then the
|
|
@@ -20,7 +20,7 @@ import { gunzipSync } from 'node:zlib';
|
|
|
20
20
|
import { CrtrClient, ApiError } from '../api/index.js';
|
|
21
21
|
import { localClient } from '../api/node-transport.js';
|
|
22
22
|
import { northlightFetch, notSignedIn, readPersonCredential } from '../core/directory/person-credential.js';
|
|
23
|
-
import {
|
|
23
|
+
import { readMachineConfig } from '../daemon/machine-link/config.js';
|
|
24
24
|
import { northlightUnreachable } from '../core/directory/reach.js';
|
|
25
25
|
import { apiErrorToCliError } from '../core/io.js';
|
|
26
26
|
import { autostartDisabled, daemonAutostartStartupFailure, ensureDaemon } from '../daemon/manage.js';
|
|
@@ -169,12 +169,6 @@ function asApiError(error) {
|
|
|
169
169
|
const next = typeof error.details?.['next'] === 'string' ? error.details['next'] : undefined;
|
|
170
170
|
return new ApiError(error.exitCode === ExitCode.NETWORK ? 503 : 401, error.code, error.message, { error: error.code, message: error.message, ...(next === undefined ? {} : { next }) });
|
|
171
171
|
}
|
|
172
|
-
/** A move whose cloud run reached `done` but whose computer has not switched over: the account holds the records, the local daemon stays drained,
|
|
173
|
-
* and no command may run against either side until `crtr sys signin` finishes it (design D14). The record is deleted only once the machine-role daemon
|
|
174
|
-
* is up (`finishMove`, or that daemon's own start), so a `machine.json` written before a failed restart does not lift this. */
|
|
175
|
-
export function moveUnfinished() {
|
|
176
|
-
return isMoveCommitted() ? moveUnfinishedError() : undefined;
|
|
177
|
-
}
|
|
178
172
|
/** The local-socket `CrtrClient` every CLI verb uses. Autostart is on by
|
|
179
173
|
* default: on a cold socket the injected `onColdSocket` hook fires
|
|
180
174
|
* `ensureDaemon()` (spawns crtrd detached via the branded host), then the
|
|
@@ -190,11 +184,6 @@ export function moveUnfinished() {
|
|
|
190
184
|
* Both callers use the shared startup policy so a valid on-disk migration
|
|
191
185
|
* cannot outlast the initiating CLI command. */
|
|
192
186
|
export function cliClient(opts) {
|
|
193
|
-
if (opts?.local !== true) {
|
|
194
|
-
const unfinished = moveUnfinished();
|
|
195
|
-
if (unfinished !== undefined)
|
|
196
|
-
throw unfinished;
|
|
197
|
-
}
|
|
198
187
|
if (opts?.local === true && relayReachesControlPlane()) {
|
|
199
188
|
throw new CrtrError('no_local_daemon', 'this node reaches Northlight\'s shared control plane, not a daemon on this computer', ExitCode.USAGE, {
|
|
200
189
|
next: 'Ask the person to run this in their own terminal on this computer.',
|
|
@@ -1,6 +1,4 @@
|
|
|
1
1
|
import { ImportCloud } from '../../../core/import/export/cloud.js';
|
|
2
|
-
import { type MoveRecord } from '../../../daemon/machine-link/config.js';
|
|
3
|
-
import { type SignInPrompt } from '../../../core/directory/person-credential.js';
|
|
4
2
|
/** The directory a sign-in or move uses when none is typed: `runtime/machine.json`'s, else the stored sign-in's, else Northlight's (design D5). */
|
|
5
3
|
export declare function defaultDirectoryUrl(): string;
|
|
6
4
|
/** End the daemon's drain and confirm the daemon answers `drained: false`, retrying a lost answer: the daemon persists its drain before it waits for
|
|
@@ -26,37 +24,6 @@ export interface ExportStep {
|
|
|
26
24
|
}
|
|
27
25
|
/** One export: open the run (or use hosting's), upload blobs, drain, dump, upload rows and stores, load, wait for `done`. `step.name` is the step in
|
|
28
26
|
* progress, so a failure can name it. The drain ends here when the run did not reach `done`, and stays on when it did. */
|
|
29
|
-
export declare function exportRun(kind: '
|
|
30
|
-
/** Activation, the second commit boundary: the asking node's message first (stored in the account as mail; the node can wake only once the machine
|
|
31
|
-
* link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
|
|
32
|
-
* crtrd in machine role, and the move record's deletion. Safe to repeat. */
|
|
33
|
-
export declare function finishMove(move: MoveRecord): Promise<void>;
|
|
27
|
+
export declare function exportRun(kind: 'hosted', cloud: ImportCloud, existingRun: string | undefined, step: ExportStep, onStarted?: (runId: string) => void, onFailed?: () => void): Promise<string>;
|
|
34
28
|
/** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
|
|
35
29
|
export declare function registerThisMac(directoryUrl: string): Promise<void>;
|
|
36
|
-
/** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the
|
|
37
|
-
* sign-in is revoked and deleted, the move record goes, and `notify` (a node) is told through the local daemon. After `done` the move record says
|
|
38
|
-
* `committed` and activation is retried three times over a minute; still failing, the record, the sign-in and the drain stay for `crtr sys signin`. */
|
|
39
|
-
export declare function runMove(opts: {
|
|
40
|
-
directoryUrl: string;
|
|
41
|
-
apiUrl?: string;
|
|
42
|
-
notify: string | null;
|
|
43
|
-
}): Promise<{
|
|
44
|
-
runId: string;
|
|
45
|
-
account: string;
|
|
46
|
-
timings: string;
|
|
47
|
-
}>;
|
|
48
|
-
/** Where an earlier move stands before a new sign-in or move starts, and when the local daemon starts. A `running` record whose exporter is alive
|
|
49
|
-
* refuses; one whose exporter died is settled against the control plane, and only its positive answer moves it: a run that reached `done` becomes
|
|
50
|
-
* `committed` (returned, so the caller finishes the switch-over); a run still loading there refuses until it settles; a run that failed or never
|
|
51
|
-
* loaded is a failed move, undone here (record deleted and drain ended and confirmed, sign-in revoked, the asking node told). Any other outcome —
|
|
52
|
-
* the control plane unreachable or refusing, no working sign-in — leaves the record and the drain as they are and throws. With no working sign-in
|
|
53
|
-
* `show` signs back in first, and only to the account that owns the move (another account is refused, nothing written); without `show` (the daemon) it throws `not_signed_in`.
|
|
54
|
-
* Answers the committed record, or undefined when no move is left (an `activated` record only awaits its notification, which the machine daemon sends). */
|
|
55
|
-
export declare function settleEarlierMove(show?: (prompt: SignInPrompt & {
|
|
56
|
-
complete: string;
|
|
57
|
-
}) => void): Promise<MoveRecord | undefined>;
|
|
58
|
-
/** The local daemon's start is a starter of the move record (design-crtr-northlight-signin component 4): a `running` record whose exporter died (a crash,
|
|
59
|
-
* a reboot) leaves the daemon drained and the asking node untold until someone runs `crtr sys signin`, so the daemon settles it itself once it serves.
|
|
60
|
-
* Retries every minute while the settle cannot finish (the control plane unreachable, the run still loading); a run that reached `done` stays `committed`
|
|
61
|
-
* for `crtr sys signin`. Returns when there is nothing to settle, the exporter is alive, or `stopped()` says the daemon is closing. */
|
|
62
|
-
export declare function settleMoveAtDaemonStart(stopped: () => boolean, onRetry: (error: unknown) => void): Promise<void>;
|
|
@@ -1,26 +1,21 @@
|
|
|
1
|
-
// The exporter's run (design-import "Exporter")
|
|
2
|
-
// component 4): `exportRun` uploads, drains, dumps and loads one run; `runMove` wraps it for a computer with the move record, the two commit
|
|
3
|
-
// boundaries (the cloud run reaching `done`; activation) and the messages to the node that asked; `finishMove` is activation, shared with
|
|
4
|
-
// `crtr sys signin` finishing an unfinished switch-over.
|
|
1
|
+
// The hosted exporter's run (design-import "Exporter"): `exportRun` uploads, drains, dumps and loads one run. `registerThisMac` is `crtr sys signin`'s directory registration.
|
|
5
2
|
import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
|
|
6
3
|
import { tmpdir } from 'node:os';
|
|
7
4
|
import { join } from 'node:path';
|
|
8
5
|
import { CrtrError, general } from '../../../core/errors.js';
|
|
9
6
|
import { ExitCode } from '../../../types.js';
|
|
10
7
|
import { cliClient } from '../../api-client.js';
|
|
11
|
-
import {
|
|
8
|
+
import { STORE_FILE, STORE_ORDER } from '../../../core/import/export/cloud.js';
|
|
12
9
|
import { Uploader, localObjects, reviewSourceObject } from '../../../core/import/export/files.js';
|
|
13
10
|
import { BODIES_TABLE, bundleKeys } from '../../../core/import/bundle/layout.js';
|
|
14
11
|
import { crtrVersion } from '../../../shared/crtr-version.js';
|
|
15
12
|
import { nodeArchive } from '../../../core/import/export/archive.js';
|
|
16
13
|
import { buildSourceJson } from '../../../core/import/export/source.js';
|
|
17
|
-
import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId
|
|
18
|
-
import {
|
|
19
|
-
import { notifyMoveFinished } from '../../../daemon/machine-link/move-notify.js';
|
|
14
|
+
import { runDaemonBodiesDump, runDaemonImportDump, runDaemonInstallId } from '../../../daemon/manage.js';
|
|
15
|
+
import { readMachineConfig } from '../../../daemon/machine-link/config.js';
|
|
20
16
|
import { registerSignedInMac } from '../../../core/directory/join.js';
|
|
21
|
-
import {
|
|
17
|
+
import { personBearer, readPersonCredential } from '../../../core/directory/person-credential.js';
|
|
22
18
|
import { NORTHLIGHT_DIRECTORY_URL } from '../../../core/directory/issuer.js';
|
|
23
|
-
import { isPidAlive } from '../../../core/canvas/pid.js';
|
|
24
19
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
25
20
|
/** The directory a sign-in or move uses when none is typed: `runtime/machine.json`'s, else the stored sign-in's, else Northlight's (design D5). */
|
|
26
21
|
export function defaultDirectoryUrl() {
|
|
@@ -198,29 +193,6 @@ export async function exportRun(kind, cloud, existingRun, step, onStarted = () =
|
|
|
198
193
|
}
|
|
199
194
|
}
|
|
200
195
|
}
|
|
201
|
-
/** Activation, the second commit boundary: the asking node's message first (stored in the account as mail; the node can wake only once the machine
|
|
202
|
-
* link is up), then the machine credential (re-minted with `rotate` when an earlier attempt already minted one), `machine.json`, a restart of
|
|
203
|
-
* crtrd in machine role, and the move record's deletion. Safe to repeat. */
|
|
204
|
-
export async function finishMove(move) {
|
|
205
|
-
await notifyMoveFinished(move);
|
|
206
|
-
const cloud = new ImportCloud(move.apiUrl, () => personBearer(move.directoryUrl));
|
|
207
|
-
let credential;
|
|
208
|
-
try {
|
|
209
|
-
credential = await cloud.machineCredential(move.runId);
|
|
210
|
-
}
|
|
211
|
-
catch (error) {
|
|
212
|
-
if (!(error instanceof CrtrError) || error.details?.['code'] !== 'credential_exists')
|
|
213
|
-
throw error;
|
|
214
|
-
credential = await cloud.machineCredential(move.runId, true);
|
|
215
|
-
}
|
|
216
|
-
writeMachineCredential(credential.credential);
|
|
217
|
-
writeMachineConfig({ apiUrl: move.apiUrl, environmentId: credential.environment_id, runId: move.runId, directoryUrl: move.directoryUrl, account: move.account });
|
|
218
|
-
await registerThisMac(move.directoryUrl);
|
|
219
|
-
await stopAllDaemons();
|
|
220
|
-
await spawnDaemon();
|
|
221
|
-
// Only now has the computer switched over: until the machine-role daemon is up the record keeps every command at `move_unfinished`.
|
|
222
|
-
deleteMoveRecord();
|
|
223
|
-
}
|
|
224
196
|
/** Register this computer as a directory runtime under the person's sign-in, unless it already is one. Runs before the machine-role daemon starts, so it finds the key. A refusal is printed, not thrown, so the move still finishes against a directory that does not accept it yet. */
|
|
225
197
|
export async function registerThisMac(directoryUrl) {
|
|
226
198
|
try {
|
|
@@ -231,175 +203,3 @@ export async function registerThisMac(directoryUrl) {
|
|
|
231
203
|
process.stderr.write(`this computer was not registered with the directory: ${error instanceof Error ? error.message : String(error)}\nRun \`crtr sys signin\` again to register it.\n`);
|
|
232
204
|
}
|
|
233
205
|
}
|
|
234
|
-
const ACTIVATION_ATTEMPTS = 3;
|
|
235
|
-
const ACTIVATION_GAP_MS = 30_000;
|
|
236
|
-
/** Move this computer into the signed-in person's account. Before the cloud run reaches `done`, any failure undoes the move: the drain ends, the
|
|
237
|
-
* sign-in is revoked and deleted, the move record goes, and `notify` (a node) is told through the local daemon. After `done` the move record says
|
|
238
|
-
* `committed` and activation is retried three times over a minute; still failing, the record, the sign-in and the drain stay for `crtr sys signin`. */
|
|
239
|
-
export async function runMove(opts) {
|
|
240
|
-
const step = { name: 'sign-in', timings: [] };
|
|
241
|
-
let move;
|
|
242
|
-
let runId = '';
|
|
243
|
-
let base;
|
|
244
|
-
try {
|
|
245
|
-
const account = await personAccount(opts.directoryUrl);
|
|
246
|
-
const apiUrl = opts.apiUrl ?? await controlPlaneUrl(opts.directoryUrl);
|
|
247
|
-
const cloud = new ImportCloud(apiUrl, () => personBearer(opts.directoryUrl));
|
|
248
|
-
base = { apiUrl, directoryUrl: opts.directoryUrl, account, notify: opts.notify, notified: false, pid: process.pid };
|
|
249
|
-
await exportRun('machine', cloud, undefined, step, (id) => { runId = id; writeMoveRecord({ ...base, runId: id, state: 'running' }); }, deleteMoveRecord);
|
|
250
|
-
}
|
|
251
|
-
catch (error) {
|
|
252
|
-
// Once `load` was sent and its outcome is unknown, the record and the drain stay: the next starter (`crtr sys signin`, the local daemon's start)
|
|
253
|
-
// asks the control plane and settles the move.
|
|
254
|
-
if (error instanceof CrtrError && error.code === 'move_outcome_unknown')
|
|
255
|
-
throw error;
|
|
256
|
-
throw await undoMove(step.name, error, opts.notify);
|
|
257
|
-
}
|
|
258
|
-
// The run is `done`: from here nothing may undo the move, so a failed record write is reported as it is and the `running` record settles to `committed` later.
|
|
259
|
-
move = { ...base, runId, state: 'committed' };
|
|
260
|
-
writeMoveRecord(move);
|
|
261
|
-
let last;
|
|
262
|
-
const activating = Date.now();
|
|
263
|
-
for (let attempt = 1; attempt <= ACTIVATION_ATTEMPTS; attempt++) {
|
|
264
|
-
try {
|
|
265
|
-
await finishMove(move);
|
|
266
|
-
step.timings.push(`restart=${((Date.now() - activating) / 1000).toFixed(1)}s`);
|
|
267
|
-
process.stderr.write(`restart ${((Date.now() - activating) / 1000).toFixed(1)}s\n`);
|
|
268
|
-
return { runId: move.runId, account: move.account.display, timings: step.timings.join(' ') };
|
|
269
|
-
}
|
|
270
|
-
catch (error) {
|
|
271
|
-
last = error;
|
|
272
|
-
process.stderr.write(`switch-over attempt ${attempt} failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
273
|
-
if (attempt < ACTIVATION_ATTEMPTS)
|
|
274
|
-
await sleep(ACTIVATION_GAP_MS);
|
|
275
|
-
move = readMoveRecord() ?? move;
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
throw moveUnfinishedError(last instanceof Error ? last.message : String(last));
|
|
279
|
-
}
|
|
280
|
-
/** Undo a move that never reached `done` (the drain is already confirmed ended), tell the asking node, and return the error to throw. */
|
|
281
|
-
async function undoMove(step, error, notify) {
|
|
282
|
-
const reason = error instanceof Error ? error.message : String(error);
|
|
283
|
-
const still = error instanceof CrtrError && error.code === 'drain_not_ended' ? 'crtr is still local, but its pause could not be ended: run `crtr sys import resume`' : 'crtr is still local and working as before';
|
|
284
|
-
const failed = `The move to Northlight failed at ${step}: ${reason}. ${still}.`;
|
|
285
|
-
const revokeFailure = await dropMove(failed, notify);
|
|
286
|
-
const code = error instanceof CrtrError && error.code !== 'error' ? error.code : (error instanceof CrtrError && typeof error.details?.['code'] === 'string' ? error.details['code'] : 'move_failed');
|
|
287
|
-
return new CrtrError(code, `the move to Northlight failed at ${step}: ${reason}. ${still}, and ${signedOutText(revokeFailure)}`, ExitCode.GENERAL);
|
|
288
|
-
}
|
|
289
|
-
/** What the person is told about the sign-in a failed move removes: revoked at Northlight, or removed here only. */
|
|
290
|
-
const signedOutText = (revokeFailure) => revokeFailure === undefined ? 'this computer is signed out.' : `this computer's sign-in was removed here but could not be revoked at Northlight (${revokeFailure}); revoke it on your Northlight account page.`;
|
|
291
|
-
/** The shared end of a failed move: delete the record, sign this computer out, and tell the node that asked (a failed revoke is added to its
|
|
292
|
-
* message). Returns why the sign-in could not be revoked at Northlight, or undefined when it was revoked or already ended: the secret is deleted here either way,
|
|
293
|
-
* so a failed revoke leaves one that is still valid there. */
|
|
294
|
-
async function dropMove(message, notify) {
|
|
295
|
-
deleteMoveRecord();
|
|
296
|
-
let revokeFailure;
|
|
297
|
-
try {
|
|
298
|
-
await signOut();
|
|
299
|
-
}
|
|
300
|
-
catch (error) {
|
|
301
|
-
forgetSignIn();
|
|
302
|
-
revokeFailure = error instanceof Error ? error.message : String(error);
|
|
303
|
-
process.stderr.write(`could not revoke the sign-in at Northlight: ${revokeFailure}\n`);
|
|
304
|
-
}
|
|
305
|
-
if (notify === null)
|
|
306
|
-
return revokeFailure;
|
|
307
|
-
try {
|
|
308
|
-
await cliClient({ local: true }).sendMessage(notify, { from: null, body: `${message} Tell the person the move failed.${revokeFailure === undefined ? '' : ` ${signedOutText(revokeFailure)}`}` });
|
|
309
|
-
}
|
|
310
|
-
catch (sendError) {
|
|
311
|
-
process.stderr.write(`could not message ${notify}: ${sendError instanceof Error ? sendError.message : String(sendError)}\n`);
|
|
312
|
-
}
|
|
313
|
-
return revokeFailure;
|
|
314
|
-
}
|
|
315
|
-
/** Where an earlier move stands before a new sign-in or move starts, and when the local daemon starts. A `running` record whose exporter is alive
|
|
316
|
-
* refuses; one whose exporter died is settled against the control plane, and only its positive answer moves it: a run that reached `done` becomes
|
|
317
|
-
* `committed` (returned, so the caller finishes the switch-over); a run still loading there refuses until it settles; a run that failed or never
|
|
318
|
-
* loaded is a failed move, undone here (record deleted and drain ended and confirmed, sign-in revoked, the asking node told). Any other outcome —
|
|
319
|
-
* the control plane unreachable or refusing, no working sign-in — leaves the record and the drain as they are and throws. With no working sign-in
|
|
320
|
-
* `show` signs back in first, and only to the account that owns the move (another account is refused, nothing written); without `show` (the daemon) it throws `not_signed_in`.
|
|
321
|
-
* Answers the committed record, or undefined when no move is left (an `activated` record only awaits its notification, which the machine daemon sends). */
|
|
322
|
-
export async function settleEarlierMove(show) {
|
|
323
|
-
const move = readMoveRecord();
|
|
324
|
-
if (move === undefined || move.state === 'activated')
|
|
325
|
-
return undefined;
|
|
326
|
-
const signBackIn = async () => {
|
|
327
|
-
await signIn(move.directoryUrl, show, { accept: async (approved) => approved.account.id === move.account.id ? undefined
|
|
328
|
-
: new CrtrError('signin_other_account', `This computer's move belongs to the Northlight account ${move.account.display}. Sign in to that account.`, ExitCode.USAGE) });
|
|
329
|
-
};
|
|
330
|
-
if (move.state === 'committed') {
|
|
331
|
-
if (show !== undefined) {
|
|
332
|
-
try {
|
|
333
|
-
await personAccount(move.directoryUrl);
|
|
334
|
-
}
|
|
335
|
-
catch (error) {
|
|
336
|
-
if (!(error instanceof CrtrError && error.code === 'not_signed_in'))
|
|
337
|
-
throw error;
|
|
338
|
-
await signBackIn();
|
|
339
|
-
}
|
|
340
|
-
}
|
|
341
|
-
return move;
|
|
342
|
-
}
|
|
343
|
-
if (move.pid > 0 && isPidAlive(move.pid)) {
|
|
344
|
-
throw new CrtrError('move_running', `a move to Northlight is already running (process ${move.pid}).`, ExitCode.USAGE, { next: 'Wait for it to finish; the node that asked is messaged when it does.' });
|
|
345
|
-
}
|
|
346
|
-
const ask = () => new ImportCloud(move.apiUrl, () => personBearer(move.directoryUrl)).get(move.runId);
|
|
347
|
-
let run;
|
|
348
|
-
try {
|
|
349
|
-
run = await ask();
|
|
350
|
-
}
|
|
351
|
-
catch (error) {
|
|
352
|
-
if (!(error instanceof CrtrError && error.code === 'not_signed_in') || show === undefined)
|
|
353
|
-
throw error;
|
|
354
|
-
await signBackIn();
|
|
355
|
-
run = await ask();
|
|
356
|
-
}
|
|
357
|
-
if (run.state === 'done') {
|
|
358
|
-
const committed = { ...move, state: 'committed' };
|
|
359
|
-
writeMoveRecord(committed);
|
|
360
|
-
return committed;
|
|
361
|
-
}
|
|
362
|
-
if (run.state === 'loading' || run.state === 'committed') {
|
|
363
|
-
throw new CrtrError('move_running', 'Northlight is still loading this computer\'s records from an earlier move.', ExitCode.USAGE, { next: 'Retry in a minute.' });
|
|
364
|
-
}
|
|
365
|
-
if (run.state !== 'failed' && run.state !== 'rolled_back' && run.state !== 'uploading') {
|
|
366
|
-
throw new CrtrError('move_outcome_unknown', 'Northlight did not report a settled outcome for this move.', ExitCode.GENERAL, { next: 'Run `crtr sys signin` to settle the move.' });
|
|
367
|
-
}
|
|
368
|
-
const step = run.failure?.step ?? 'an earlier step';
|
|
369
|
-
const reason = run.failure == null ? 'the process that was moving this computer stopped before Northlight had the records' : run.failure.message;
|
|
370
|
-
deleteMoveRecord();
|
|
371
|
-
try {
|
|
372
|
-
await endDrainConfirmed(cliClient({ local: true }));
|
|
373
|
-
}
|
|
374
|
-
catch (error) {
|
|
375
|
-
throw await undoMove(step, new CrtrError('drain_not_ended', `${reason} (and ${error instanceof Error ? error.message : String(error)})`, ExitCode.GENERAL), move.notify);
|
|
376
|
-
}
|
|
377
|
-
await dropMove(`The move to Northlight failed at ${step}: ${reason}. crtr is still local and working as before.`, move.notify);
|
|
378
|
-
return undefined;
|
|
379
|
-
}
|
|
380
|
-
const DAEMON_SETTLE_GAP_MS = 60_000;
|
|
381
|
-
/** The daemon answers its own socket only once startup is done, which is a moment after the settle is scheduled. */
|
|
382
|
-
const DAEMON_SETTLE_FIRST_MS = 5_000;
|
|
383
|
-
/** The local daemon's start is a starter of the move record (design-crtr-northlight-signin component 4): a `running` record whose exporter died (a crash,
|
|
384
|
-
* a reboot) leaves the daemon drained and the asking node untold until someone runs `crtr sys signin`, so the daemon settles it itself once it serves.
|
|
385
|
-
* Retries every minute while the settle cannot finish (the control plane unreachable, the run still loading); a run that reached `done` stays `committed`
|
|
386
|
-
* for `crtr sys signin`. Returns when there is nothing to settle, the exporter is alive, or `stopped()` says the daemon is closing. */
|
|
387
|
-
export async function settleMoveAtDaemonStart(stopped, onRetry) {
|
|
388
|
-
await sleep(DAEMON_SETTLE_FIRST_MS);
|
|
389
|
-
while (!stopped()) {
|
|
390
|
-
const move = readMoveRecord();
|
|
391
|
-
if (move === undefined || move.state !== 'running' || (move.pid > 0 && isPidAlive(move.pid)))
|
|
392
|
-
return;
|
|
393
|
-
try {
|
|
394
|
-
await settleEarlierMove();
|
|
395
|
-
return;
|
|
396
|
-
}
|
|
397
|
-
catch (error) {
|
|
398
|
-
onRetry(error);
|
|
399
|
-
// No working sign-in: only the person signing back in (`crtr sys signin`) can settle it, so asking again every minute cannot help.
|
|
400
|
-
if (error instanceof CrtrError && error.code === 'not_signed_in')
|
|
401
|
-
return;
|
|
402
|
-
}
|
|
403
|
-
await sleep(DAEMON_SETTLE_GAP_MS);
|
|
404
|
-
}
|
|
405
|
-
}
|
|
@@ -1,4 +1 @@
|
|
|
1
|
-
/** Set by `crtr sys signin` on the detached exporter it starts from inside a node: the signin process, which the exporter outlives before it drains,
|
|
2
|
-
* so it is never in a broker's process tree. */
|
|
3
|
-
export declare const WAIT_FOR_PID_ENV = "CRTR_IMPORT_WAIT_PID";
|
|
4
1
|
export declare const sysImportBranch: import("../../../core/command.js").BranchDef;
|
|
@@ -1,36 +1,25 @@
|
|
|
1
1
|
// `crtr sys import start`: the source side of an import (design-import, "Exporter"). Uploads blobs, drains the daemon, dumps the rows and file
|
|
2
|
-
// stores, uploads them, asks the control plane to load, and
|
|
2
|
+
// stores, uploads them, asks the control plane to load, and (`./move.ts`).
|
|
3
3
|
import { defineBranch, defineLeaf } from '../../../core/command.js';
|
|
4
4
|
import { general, usage } from '../../../core/errors.js';
|
|
5
5
|
import { ImportCloud } from '../../../core/import/export/cloud.js';
|
|
6
6
|
import { ensureSignedIn } from '../../../core/directory/person-credential.js';
|
|
7
|
-
import { isPidAlive } from '../../../core/canvas/pid.js';
|
|
8
7
|
import { showSignIn } from '../signin.js';
|
|
9
8
|
import { insideBroker } from '../join.js';
|
|
10
|
-
import { defaultDirectoryUrl, exportRun
|
|
9
|
+
import { defaultDirectoryUrl, exportRun } from './move.js';
|
|
11
10
|
import { resume } from './resume.js';
|
|
12
|
-
import { retry } from './retry.js';
|
|
13
|
-
/** Set by `crtr sys signin` on the detached exporter it starts from inside a node: the signin process, which the exporter outlives before it drains,
|
|
14
|
-
* so it is never in a broker's process tree. */
|
|
15
|
-
export const WAIT_FOR_PID_ENV = 'CRTR_IMPORT_WAIT_PID';
|
|
16
|
-
async function waitForExit(pid) {
|
|
17
|
-
while (isPidAlive(pid))
|
|
18
|
-
await new Promise((resolve) => setTimeout(resolve, 200));
|
|
19
|
-
}
|
|
20
11
|
const start = defineLeaf({
|
|
21
12
|
name: 'start',
|
|
22
|
-
description: 'export this runtime into the person\'s Northlight account',
|
|
23
|
-
whenToUse: '
|
|
13
|
+
description: 'export this hosted runtime into the person\'s Northlight account',
|
|
14
|
+
whenToUse: 'hosting runs it inside a hosted runtime to move that runtime\'s canvas into Northlight: from a plain terminal, not from inside a node',
|
|
24
15
|
help: {
|
|
25
16
|
name: 'sys import start',
|
|
26
17
|
summary: 'upload blobs, pause the daemon, dump rows and file stores, and have the control plane load them',
|
|
27
|
-
guide: 'Order: open the run, upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, upload the rows, request the load and wait for `done` or `failed`, printing each step\'s time. Before `done`, a failure ends the drain and this runtime carries on as before
|
|
18
|
+
guide: 'Order: open the run (hosting already did, with `--run`), upload blobs and request files, drain the daemon (turns in flight settle for up to 10 minutes), upload them again, dump every table and the file stores, archive running nodes\' files, upload the rows, request the load and wait for `done` or `failed`, printing each step\'s time. Before `done`, a failure ends the drain and this runtime carries on as before. On `done` the daemon stays drained until hosting quiesces it (`crtr sys import resume` ends it). The run\'s import token is read from the environment variable `CRTR_IMPORT_TOKEN`.',
|
|
28
19
|
params: [
|
|
29
|
-
{ kind: 'flag', name: 'kind', type: 'enum', choices: ['
|
|
30
|
-
{ kind: 'flag', name: 'api-url', type: 'string', required:
|
|
31
|
-
{ kind: 'flag', name: 'run', type: 'string', required: false, constraint: 'An import run hosting opened for this runtime
|
|
32
|
-
{ kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https) the person signs in against, with `--kind machine`. Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
|
|
33
|
-
{ kind: 'flag', name: 'notify', type: 'string', required: false, constraint: 'With `--kind machine`: a node id told by message when the move fails or finishes.' },
|
|
20
|
+
{ kind: 'flag', name: 'kind', type: 'enum', choices: ['hosted'], required: true, constraint: '`hosted`, the only kind: a hosted runtime (also archives running nodes\' files).' },
|
|
21
|
+
{ kind: 'flag', name: 'api-url', type: 'string', required: true, constraint: 'Control plane base URL (http or https) hosting opened the run on.' },
|
|
22
|
+
{ kind: 'flag', name: 'run', type: 'string', required: false, constraint: 'An import run hosting opened for this runtime; its import token is read from `CRTR_IMPORT_TOKEN`.' },
|
|
34
23
|
],
|
|
35
24
|
output: [
|
|
36
25
|
{ name: 'run_id', type: 'string', required: true, constraint: 'The import run.' },
|
|
@@ -40,41 +29,16 @@ const start = defineLeaf({
|
|
|
40
29
|
outputKind: 'object',
|
|
41
30
|
effects: [
|
|
42
31
|
'Drains the local daemon (no new wake or cron fire); the drain is a `runtime_state` row, so it survives a daemon restart. Ended on a failure before `done`; kept after `done`.',
|
|
43
|
-
'Machine: writes `runtime/import/move.json` (0600) from the run\'s start until the switch-over, then deletes it. On `done`: writes `runtime/machine.json` and `runtime/secrets/machine-credential` (0600) and restarts the daemon in machine role. On a failure before `done`: revokes and deletes the stored sign-in.',
|
|
44
|
-
'Machine with `--notify`: sends that node one message when the move fails or finishes.',
|
|
45
32
|
'Opens a temporary directory holding the opened file stores (0600), removed before the command ends.',
|
|
46
33
|
],
|
|
47
34
|
},
|
|
48
35
|
run: async (input) => {
|
|
49
|
-
const kind = input['kind'];
|
|
50
36
|
const existingRun = input['run'] === undefined ? undefined : String(input['run']);
|
|
51
|
-
const apiUrl = input.apiUrl
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (apiUrl === undefined)
|
|
55
|
-
throw usage('--kind hosted needs --api-url: the control plane hosting opened the run on');
|
|
56
|
-
if (notify !== null)
|
|
57
|
-
throw usage('--notify names the node that asked for a computer\'s move: use it only with --kind machine');
|
|
58
|
-
}
|
|
59
|
-
else if (existingRun !== undefined) {
|
|
60
|
-
throw usage('--run takes an existing run, which only a hosted import has: use --kind hosted');
|
|
61
|
-
}
|
|
62
|
-
const waitFor = Number(process.env[WAIT_FOR_PID_ENV] ?? '');
|
|
63
|
-
if (Number.isInteger(waitFor) && waitFor > 0)
|
|
64
|
-
await waitForExit(waitFor);
|
|
37
|
+
const apiUrl = String(input.apiUrl ?? '');
|
|
38
|
+
if (apiUrl === '')
|
|
39
|
+
throw usage('--kind hosted needs --api-url: the control plane hosting opened the run on');
|
|
65
40
|
if (insideBroker())
|
|
66
41
|
throw general('import_inside_node: run this from a plain terminal; a node\'s broker ends with the daemon restart', { code: 'import_inside_node' });
|
|
67
|
-
if (kind === 'machine') {
|
|
68
|
-
const earlier = await settleEarlierMove(showSignIn);
|
|
69
|
-
if (earlier !== undefined) {
|
|
70
|
-
await finishMove(earlier);
|
|
71
|
-
return { run_id: earlier.runId, state: 'done', timings: '' };
|
|
72
|
-
}
|
|
73
|
-
const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
|
|
74
|
-
await ensureSignedIn(directoryUrl, showSignIn);
|
|
75
|
-
const moved = await runMove({ directoryUrl, ...(apiUrl === undefined ? {} : { apiUrl }), notify });
|
|
76
|
-
return { run_id: moved.runId, state: 'done', timings: moved.timings };
|
|
77
|
-
}
|
|
78
42
|
const token = (existingRun === undefined ? await ensureSignedIn(defaultDirectoryUrl(), showSignIn) : process.env['CRTR_IMPORT_TOKEN'] ?? '').trim();
|
|
79
43
|
if (token === '')
|
|
80
44
|
throw usage('set CRTR_IMPORT_TOKEN to the run\'s import token');
|
|
@@ -86,8 +50,8 @@ const start = defineLeaf({
|
|
|
86
50
|
});
|
|
87
51
|
export const sysImportBranch = defineBranch({
|
|
88
52
|
name: 'import',
|
|
89
|
-
description: 'move this runtime into the person\'s Northlight account',
|
|
90
|
-
whenToUse: 'importing
|
|
91
|
-
help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database
|
|
92
|
-
children: [start, resume
|
|
53
|
+
description: 'move this hosted runtime into the person\'s Northlight account',
|
|
54
|
+
whenToUse: 'importing a hosted runtime into Northlight',
|
|
55
|
+
help: { name: 'sys import', summary: 'export this runtime to Northlight', model: 'The exporter pauses the local daemon, uploads a bundle the control plane loads into the shared database.' },
|
|
56
|
+
children: [start, resume],
|
|
93
57
|
});
|
|
@@ -1,19 +1,14 @@
|
|
|
1
1
|
// `crtr sys signin` / `crtr sys signout`: the person's own sign-in on this computer (proposal-mac-cli-auth, option A).
|
|
2
2
|
import { spawn } from 'node:child_process';
|
|
3
|
-
import { mkdirSync, openSync } from 'node:fs';
|
|
4
|
-
import { dirname, join } from 'node:path';
|
|
5
3
|
import { defineLeaf } from '../../core/command.js';
|
|
6
4
|
import { CrtrError } from '../../core/errors.js';
|
|
7
5
|
import { controlPlaneUrl, personAccount, personBearer, readPersonCredential, signIn, signOut } from '../../core/directory/person-credential.js';
|
|
8
|
-
import { hasLocalCanvas,
|
|
9
|
-
import { probeDaemonHealth,
|
|
6
|
+
import { hasLocalCanvas, readMachineConfig, readOrCreateInstallId, writeMachineConfig, writeMachineCredential } from '../../daemon/machine-link/config.js';
|
|
7
|
+
import { probeDaemonHealth, spawnDaemon, stopAllDaemons } from '../../daemon/manage.js';
|
|
10
8
|
import { hostname } from 'node:os';
|
|
11
9
|
import { northlightUnreachable } from '../../core/directory/reach.js';
|
|
12
|
-
import { envNodeId } from '../../shared/env.js';
|
|
13
10
|
import { ExitCode } from '../../types.js';
|
|
14
|
-
import {
|
|
15
|
-
import { defaultDirectoryUrl, finishMove, registerThisMac, runMove, settleEarlierMove } from './import/move.js';
|
|
16
|
-
import { WAIT_FOR_PID_ENV } from './import/start.js';
|
|
11
|
+
import { defaultDirectoryUrl, registerThisMac } from './import/move.js';
|
|
17
12
|
/** Open the confirm page in the person's browser; a failure to open it is harmless because the code and address are printed too. */
|
|
18
13
|
function openBrowser(url) {
|
|
19
14
|
const [command, args] = process.platform === 'darwin' ? ['open', [url]] : ['xdg-open', [url]];
|
|
@@ -50,19 +45,6 @@ function sameAccountOnly(machine) {
|
|
|
50
45
|
return new CrtrError('signin_unchecked', `the control plane did not say which account owns this computer (HTTP ${response.status}); nothing was written.`, ExitCode.GENERAL, { next: 'Retry `crtr sys signin`.' });
|
|
51
46
|
};
|
|
52
47
|
}
|
|
53
|
-
/** Start the move in a process of its own: a node's tool call cannot run it, because the drain waits for that very turn to end and the restart
|
|
54
|
-
* ends the broker it runs under. The exporter waits for this process to exit, so it is outside every broker's process tree when it drains. */
|
|
55
|
-
function startDetachedMove(notify) {
|
|
56
|
-
const log = join(dirname(moveRecordPath()), 'move.log');
|
|
57
|
-
mkdirSync(dirname(log), { recursive: true });
|
|
58
|
-
const fd = openSync(log, 'a', 0o600);
|
|
59
|
-
const env = sanitizedDaemonEnv();
|
|
60
|
-
for (const key of ['CRTR_API_SOCKET', 'CRTR_API_TOKEN', 'CRTR_API_URL'])
|
|
61
|
-
delete env[key];
|
|
62
|
-
env[WAIT_FOR_PID_ENV] = String(process.pid);
|
|
63
|
-
const args = [...process.execArgv, process.argv[1], 'sys', 'import', 'start', '--kind', 'machine', ...(notify === undefined ? [] : ['--notify', notify])];
|
|
64
|
-
spawn(process.execPath, args, { detached: true, stdio: ['ignore', fd, fd], env }).unref();
|
|
65
|
-
}
|
|
66
48
|
/** A computer with no `machine.json` and no local canvas becomes a fleet machine: `POST /v1/machines`, then `machine.json`, the credential, the directory registration and the machine daemon.
|
|
67
49
|
* The stored sign-in is reused when present, so running this again after `northlight_unreachable` resumes at registration. */
|
|
68
50
|
export async function registerFreshComputer(directoryUrl) {
|
|
@@ -94,47 +76,32 @@ export async function registerFreshComputer(directoryUrl) {
|
|
|
94
76
|
await spawnDaemon();
|
|
95
77
|
return { account: account.display };
|
|
96
78
|
}
|
|
97
|
-
const MOVING = (account) => `Signed in as ${account}. crtr is now moving this computer's records to Northlight; every agent here pauses for seconds to minutes. End your turn now; this conversation carries on when the move finishes.`;
|
|
98
79
|
export const sysSigninLeaf = defineLeaf({
|
|
99
80
|
name: 'signin',
|
|
100
81
|
description: 'sign this computer\'s crtr in to the person\'s Northlight account and register it as one of their machines',
|
|
101
|
-
whenToUse: 'the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in`
|
|
82
|
+
whenToUse: 'the person agreed to sign in to Northlight (a Northlight command needs the account, or they asked), or a command answered `not_signed_in`',
|
|
102
83
|
help: {
|
|
103
84
|
name: 'sys signin',
|
|
104
|
-
summary: 'pair this computer with the person\'s Northlight account in the browser,
|
|
105
|
-
guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that.
|
|
85
|
+
summary: 'pair this computer with the person\'s Northlight account in the browser, register it as one of their machines, and register it with the directory',
|
|
86
|
+
guide: 'Prints a code and opens the directory\'s confirm page; the person signs in or signs up there if asked, checks the code and clicks Allow. The command waits for that. A computer already registered accepts only the account it was registered under. A computer holding a local canvas and no `runtime/machine.json` is refused with `local_canvas_unsupported`: moving a local canvas into Northlight is no longer supported. A computer is also registered with the directory: a signing key is made here (the private key never leaves this computer) and only its public half goes to the directory, under the same sign-in. A computer already registered keeps its registration; one signed in earlier without it is registered by running this again. The sign-in ends after 90 days without use, when revoked on the account page, or with `crtr sys signout`.',
|
|
106
87
|
params: [
|
|
107
88
|
{ kind: 'flag', name: 'directory-url', type: 'string', required: false, constraint: 'Directory base URL (http or https). Default: the one in `runtime/machine.json`, else the stored sign-in\'s, else Northlight\'s.' },
|
|
108
89
|
],
|
|
109
90
|
output: [
|
|
110
91
|
{ name: 'account', type: 'string', required: true, constraint: 'The account this computer is now signed in as.' },
|
|
111
|
-
{ name: 'moved', type: 'boolean', required: false, constraint: 'Present when this command moved the records, or finished an earlier move\'s switch-over.' },
|
|
112
|
-
{ name: 'moving', type: 'boolean', required: false, constraint: 'Present when the move runs on in its own process (run from inside a node): end the turn; the node is messaged when it finishes or fails.' },
|
|
113
92
|
],
|
|
114
93
|
outputKind: 'object',
|
|
115
94
|
effects: [
|
|
116
95
|
'Calls the directory (`POST /v1/developer/logins`, then polls `/v1/developer/logins/poll`) and, once approved, writes `runtime/secrets/person-credential` (0600) and replaces the cached bearer. A declined, abandoned or refused sign-in writes nothing and leaves an existing sign-in as it was.',
|
|
117
|
-
'
|
|
118
|
-
'On a computer
|
|
119
|
-
'On a computer with no local records: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.',
|
|
120
|
-
'On a moved computer: restarts the daemon so it reconnects to Northlight.',
|
|
96
|
+
'On a computer with no `machine.json`: registers it with `POST /v1/machines`, writes `runtime/machine.json` and `runtime/secrets/machine-credential`, and starts the machine daemon. Run again after `northlight_unreachable`, it resumes at registration with the stored sign-in.',
|
|
97
|
+
'On a registered computer: restarts the daemon so it reconnects to Northlight.',
|
|
121
98
|
'Unless this computer is already registered: calls `PUT <directory>/v1/runtimes/registration` with the sign-in bearer and a new public ES256 key, then writes `runtime/secrets/runtime-client.json` (0600) holding the private key and the returned runtime identity.',
|
|
122
99
|
],
|
|
123
100
|
},
|
|
124
101
|
run: async (input) => {
|
|
125
|
-
|
|
126
|
-
if (readMachineConfig() !== undefined || hasLocalCanvas())
|
|
102
|
+
if (readMachineConfig() !== undefined)
|
|
127
103
|
await spawnDaemon();
|
|
128
104
|
const directoryUrl = input.directoryUrl === undefined ? defaultDirectoryUrl() : String(input.directoryUrl);
|
|
129
|
-
const unfinished = await settleEarlierMove(showSignIn);
|
|
130
|
-
if (unfinished !== undefined) {
|
|
131
|
-
if (insideBroker()) {
|
|
132
|
-
startDetachedMove(undefined);
|
|
133
|
-
return { account: unfinished.account.display, moving: true };
|
|
134
|
-
}
|
|
135
|
-
await finishMove(unfinished);
|
|
136
|
-
return { account: unfinished.account.display, moved: true };
|
|
137
|
-
}
|
|
138
105
|
const machine = readMachineConfig();
|
|
139
106
|
if (machine !== undefined) {
|
|
140
107
|
const { account } = await signIn(directoryUrl, showSignIn, { accept: sameAccountOnly(machine) });
|
|
@@ -143,19 +110,11 @@ export const sysSigninLeaf = defineLeaf({
|
|
|
143
110
|
await spawnDaemon();
|
|
144
111
|
return { account };
|
|
145
112
|
}
|
|
146
|
-
if (
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
if (insideBroker()) {
|
|
150
|
-
startDetachedMove(envNodeId());
|
|
151
|
-
return { account, moving: true };
|
|
152
|
-
}
|
|
153
|
-
await runMove({ directoryUrl, notify: null });
|
|
154
|
-
return { account, moved: true };
|
|
113
|
+
if (hasLocalCanvas())
|
|
114
|
+
throw new CrtrError('local_canvas_unsupported', 'this computer holds a local crtr canvas, and moving one into Northlight is no longer supported.', ExitCode.USAGE, { next: 'Remove the local canvas (the `pg`, `canvas.db` and `canvas.db.imported` entries under the runtime folder) to sign this computer in fresh.' });
|
|
115
|
+
return await registerFreshComputer(directoryUrl);
|
|
155
116
|
},
|
|
156
|
-
render: (r) => r['
|
|
157
|
-
? `<signin account="${r['account']}" moving="true">${MOVING(String(r['account']))}</signin>`
|
|
158
|
-
: `<signin account="${r['account']}"${r['moved'] === true ? ' moved="true"' : ''}/>`,
|
|
117
|
+
render: (r) => `<signin account="${r['account']}"/>`,
|
|
159
118
|
});
|
|
160
119
|
/** Restart crtrd on a moved computer after sign-out; the machine daemon, finding no sign-in, stops every agent and cron on this computer and only
|
|
161
120
|
* then answers `/healthz` with `signed_in: false`. Answers whether it did. */
|
package/dist/core/command.d.ts
CHANGED
|
@@ -130,7 +130,7 @@ export interface RootDef {
|
|
|
130
130
|
kind: 'root';
|
|
131
131
|
help: RootHelp;
|
|
132
132
|
subtrees: BranchDef[];
|
|
133
|
-
/** Why a moved computer could not read the account's provider commands (`not_signed_in`, `northlight_unreachable
|
|
133
|
+
/** Why a moved computer could not read the account's provider commands (`not_signed_in`, `northlight_unreachable`). The tree
|
|
134
134
|
* was built without them, so a top-level name it lacks may be one of those commands: the dispatcher raises this instead of `unknown_path`. */
|
|
135
135
|
providerCatalogFailure?: ApiError | CrtrError;
|
|
136
136
|
}
|
|
@@ -8,6 +8,7 @@ import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
|
|
|
8
8
|
import { gitAsync } from './git.js';
|
|
9
9
|
import { WORKTREE_LOCK_WAIT_MS, canonicalPath, checkoutPathForBranchInList, isManagedWorktreeBase, managedWorktreesRoot, managedWorktreePath, persistClosedWorktreeState, worktreeLockPathForCommonDir, WorktreeError, branchIsPushedAtCurrentTip } from './worktree.js';
|
|
10
10
|
import { proveBranchContained } from './worktree-containment.js';
|
|
11
|
+
import { runWorktreeScript } from './worktree-scripts.js';
|
|
11
12
|
import { refDeleteTransactionStdin } from './worktree-landing.js';
|
|
12
13
|
import { deleteTrashAsync, removeWorktreeCheckoutAsync } from './worktree-remove.js';
|
|
13
14
|
// A function, not a constant: `runtime/nodes.ts` imports this module and sits in an import cycle with `worktree.ts`, so a module-level read of its exports would run before they exist.
|
|
@@ -116,7 +117,7 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
|
|
|
116
117
|
throw new WorktreeError('managed_worktree_base', `cwd ${repoRoot} is a managed worktree and cannot be used as a managed worktree base`, 'Pass `--cwd` pointing at the repository’s primary checkout and keep `--worktree` set to the desired existing local base branch, including the parent branch.');
|
|
117
118
|
}
|
|
118
119
|
const commonDir = await commonGitDir(repoRoot);
|
|
119
|
-
|
|
120
|
+
const wt = await withExclusiveDirectoryLockAsync(worktreeLockPathForCommonDir(commonDir), async () => {
|
|
120
121
|
const baseSha = await resolveLandableBase(repoRoot, baseRef);
|
|
121
122
|
const path = managedWorktreePath(nodeId);
|
|
122
123
|
const branch = `crtr/${nodeId}`;
|
|
@@ -124,7 +125,7 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
|
|
|
124
125
|
throw new WorktreeError('worktree_path_exists', `managed worktree path already exists: ${path}`, 'Remove the stale path or choose a fresh node id.');
|
|
125
126
|
if ((await gitAsync(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`], repoRoot)).status === 0)
|
|
126
127
|
throw new WorktreeError('worktree_branch_exists', `managed worktree branch already exists: ${branch}`, 'Remove the stale branch or choose a fresh node id.');
|
|
127
|
-
const
|
|
128
|
+
const created = { state: 'open', path, branch, repo_root: repoRoot, base_ref: baseRef, base_sha: baseSha, created: new Date().toISOString() };
|
|
128
129
|
await runGit(repoRoot, ['branch', branch, baseSha], 'worktree_branch_create_failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.');
|
|
129
130
|
const added = await gitAsync(['worktree', 'add', path, branch], repoRoot);
|
|
130
131
|
if (added.status !== 0) {
|
|
@@ -132,8 +133,15 @@ export async function createManagedWorktreeAsync(cwd, nodeId, baseRef = 'main')
|
|
|
132
133
|
throw new WorktreeError('worktree_add_failed', 'git worktree add failed', 'Inspect the git error, fix the repository/worktree state, then retry spawning with --worktree.', detailOf(added));
|
|
133
134
|
}
|
|
134
135
|
seedExclude(repoRoot, commonDir);
|
|
135
|
-
return
|
|
136
|
+
return created;
|
|
136
137
|
}, { timeoutMs: lockWaitMs(), timeoutError: () => new WorktreeError('worktree_lock_timeout', `timed out waiting to create a managed worktree in ${commonDir}`, 'Wait for the other managed-worktree operation to finish, then retry.') });
|
|
138
|
+
// Outside the repository lock: a script may take minutes. A failed setup fails creation and the half-prepared checkout is removed the normal way.
|
|
139
|
+
const setup = await runWorktreeScript('worktree-setup', basename(wt.path), wt);
|
|
140
|
+
if (setup.status === 'failed') {
|
|
141
|
+
await rollbackManagedWorktreeAsync(wt);
|
|
142
|
+
throw new WorktreeError('worktree_setup_failed', '.dev/worktree-setup failed', 'Fix the repository\'s .dev/worktree-setup on its base branch, then retry spawning with --worktree.', setup.detail);
|
|
143
|
+
}
|
|
144
|
+
return wt;
|
|
137
145
|
}
|
|
138
146
|
async function cleanTip(wt) {
|
|
139
147
|
if (wt.state !== 'open' || !existsSync(wt.path))
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ManagedWorktree } from './canvas/index.js';
|
|
2
|
+
export type WorktreeScript = 'worktree-setup' | 'worktree-teardown';
|
|
3
|
+
/** Fixed, not configurable. */
|
|
4
|
+
export declare const WORKTREE_SCRIPT_TIMEOUT_MS: number;
|
|
5
|
+
export type WorktreeScriptResult = {
|
|
6
|
+
status: 'absent';
|
|
7
|
+
} | {
|
|
8
|
+
status: 'ok';
|
|
9
|
+
} | {
|
|
10
|
+
status: 'failed';
|
|
11
|
+
detail: string;
|
|
12
|
+
};
|
|
13
|
+
export declare function runWorktreeScript(script: WorktreeScript, nodeId: string, wt: ManagedWorktree, timeoutMs?: number): Promise<WorktreeScriptResult>;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// A repository's optional `.dev/worktree-setup` and `.dev/worktree-teardown` executables.
|
|
2
|
+
//
|
|
3
|
+
// crtr decides WHEN they run (after a managed worktree is created, and as the first step of its sweep); the
|
|
4
|
+
// repository decides WHAT they do. Each script is read from the worktree's base branch in the primary checkout,
|
|
5
|
+
// never from the worktree itself, so a node's own commits cannot change what crtr executes. A missing file is no step.
|
|
6
|
+
// Async only: the sweep runs on the daemon's event loop.
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { chmod, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { gitAsync } from './git.js';
|
|
12
|
+
/** Fixed, not configurable. */
|
|
13
|
+
export const WORKTREE_SCRIPT_TIMEOUT_MS = 5 * 60_000;
|
|
14
|
+
const STDERR_TAIL_LINES = 20;
|
|
15
|
+
function tail(text) {
|
|
16
|
+
return text.trim().split('\n').slice(-STDERR_TAIL_LINES).join('\n');
|
|
17
|
+
}
|
|
18
|
+
export async function runWorktreeScript(script, nodeId, wt, timeoutMs = WORKTREE_SCRIPT_TIMEOUT_MS) {
|
|
19
|
+
const ref = `refs/heads/${wt.base_ref}`;
|
|
20
|
+
const spec = `${ref}:.dev/${script}`;
|
|
21
|
+
const exists = await gitAsync(['cat-file', '-e', spec], wt.repo_root);
|
|
22
|
+
if (exists.status !== 0)
|
|
23
|
+
return { status: 'absent' };
|
|
24
|
+
const body = await gitAsync(['show', spec], wt.repo_root);
|
|
25
|
+
if (body.status !== 0)
|
|
26
|
+
return { status: 'failed', detail: `could not read .dev/${script} from ${ref}: ${body.stderr.trim()}` };
|
|
27
|
+
const dir = await mkdtemp(join(tmpdir(), 'crtr-worktree-script-'));
|
|
28
|
+
try {
|
|
29
|
+
const file = join(dir, script);
|
|
30
|
+
await writeFile(file, body.stdout);
|
|
31
|
+
await chmod(file, 0o755);
|
|
32
|
+
return await new Promise((resolve) => {
|
|
33
|
+
const child = spawn(file, [], {
|
|
34
|
+
cwd: wt.path,
|
|
35
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
36
|
+
env: {
|
|
37
|
+
...process.env,
|
|
38
|
+
CRTR_NODE_ID: nodeId,
|
|
39
|
+
CRTR_WORKTREE_PATH: wt.path,
|
|
40
|
+
CRTR_REPO_ROOT: wt.repo_root,
|
|
41
|
+
CRTR_BASE_REF: wt.base_ref,
|
|
42
|
+
COMPOSE_PROJECT_NAME: `crtr-${nodeId}`,
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
let stderr = '';
|
|
46
|
+
let timedOut = false;
|
|
47
|
+
let settled = false;
|
|
48
|
+
const finish = (result) => {
|
|
49
|
+
if (settled)
|
|
50
|
+
return;
|
|
51
|
+
settled = true;
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
resolve(result);
|
|
54
|
+
};
|
|
55
|
+
const timer = setTimeout(() => {
|
|
56
|
+
timedOut = true;
|
|
57
|
+
child.kill('SIGKILL');
|
|
58
|
+
finish({ status: 'failed', detail: `.dev/${script} timed out after ${Math.round(timeoutMs / 1000)}s\n${tail(stderr)}`.trim() });
|
|
59
|
+
}, timeoutMs);
|
|
60
|
+
child.stderr.on('data', (chunk) => { stderr = (stderr + chunk.toString('utf8')).slice(-16_384); });
|
|
61
|
+
child.on('error', (err) => finish({ status: 'failed', detail: `could not run .dev/${script}: ${err.message}` }));
|
|
62
|
+
child.on('close', (code, signal) => {
|
|
63
|
+
if (timedOut)
|
|
64
|
+
return;
|
|
65
|
+
finish(code === 0 ? { status: 'ok' } : { status: 'failed', detail: `.dev/${script} exited ${code ?? `by ${signal}`}\n${tail(stderr)}`.trim() });
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
await rm(dir, { recursive: true, force: true });
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -13,12 +13,13 @@
|
|
|
13
13
|
// call on a large repository is not short.
|
|
14
14
|
import { createHash } from 'node:crypto';
|
|
15
15
|
import { existsSync, realpathSync } from 'node:fs';
|
|
16
|
-
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
16
|
+
import { basename, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
17
17
|
import { completeCleanup, getNode, recordSweepAttempt, resumableNodeCwds } from './canvas/index.js';
|
|
18
18
|
import { withExclusiveDirectoryLockAsync } from './exclusive-lock.js';
|
|
19
19
|
import { gitAsync } from './git.js';
|
|
20
20
|
import { proveBranchContained, upstreamTip } from './worktree-containment.js';
|
|
21
21
|
import { refDeleteTransactionStdin } from './worktree-landing.js';
|
|
22
|
+
import { runWorktreeScript } from './worktree-scripts.js';
|
|
22
23
|
import { deleteTrashAsync, removeWorktreeCheckoutAsync } from './worktree-remove.js';
|
|
23
24
|
import { WORKTREE_LOCK_WAIT_MS, canonicalPath, checkoutPathForBranchInList, samePath, worktreeLockPathForCommonDir } from './worktree.js';
|
|
24
25
|
/** Escalating recheck interval, in minutes, indexed by consecutive refusal. The
|
|
@@ -256,6 +257,14 @@ export async function sweepManagedWorktreeOnHost(wt, guard, dependentCwds) {
|
|
|
256
257
|
// before each removal, where spawn admission into the checkout is excluded.
|
|
257
258
|
if (existsSync(wt.path) && await checkoutHasDependents(dependentCwds, wt.path))
|
|
258
259
|
return { outcome: CHECKOUT_IN_USE, observed: none };
|
|
260
|
+
// The repository's teardown comes before every Git disposal step, outside the repository lock (it may take minutes). A failure keeps the checkout so a person can rerun it.
|
|
261
|
+
if (existsSync(wt.path)) {
|
|
262
|
+
const teardown = await runWorktreeScript('worktree-teardown', basename(wt.path), wt);
|
|
263
|
+
if (teardown.status === 'failed')
|
|
264
|
+
return { outcome: { status: 'refused', reason: 'teardown_failed', detail: teardown.detail }, observed: none };
|
|
265
|
+
if (!await guard.stillEligible())
|
|
266
|
+
return { outcome: NODE_REVIVED, observed: none };
|
|
267
|
+
}
|
|
259
268
|
const cwd = existsSync(wt.path) ? wt.path : wt.repo_root;
|
|
260
269
|
if (!existsSync(cwd)) {
|
|
261
270
|
return { outcome: { status: 'refused', reason: 'repo_unavailable', detail: `neither the recorded checkout nor repository root exists, so ${wt.branch} cannot be proved absent` }, observed: none };
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { CrtrError } from '../../core/errors.js';
|
|
2
1
|
/** The Northlight account, as the directory names it (`account` of the sign-in poll). */
|
|
3
2
|
export interface NorthlightAccount {
|
|
4
3
|
id: string;
|
|
@@ -20,29 +19,6 @@ export declare function readMachineConfig(): MachineConfig | undefined;
|
|
|
20
19
|
export declare function writeMachineConfig(config: MachineConfig): void;
|
|
21
20
|
export declare function readMachineCredential(): string;
|
|
22
21
|
export declare function writeMachineCredential(secret: string): void;
|
|
23
|
-
/** A move to Northlight in progress. `running`: the cloud run has not reached `done`, so a failure undoes the move. `committed`: the account holds the
|
|
24
|
-
* records and only the switch-over (machine credential, `machine.json`, restart) is left. `activated`: the machine-role daemon is up, so the switch-over is
|
|
25
|
-
* complete and commands run; the record stays only until `notified` — the asking node's message is stored in the account — is true, then it is deleted. */
|
|
26
|
-
export interface MoveRecord {
|
|
27
|
-
runId: string;
|
|
28
|
-
apiUrl: string;
|
|
29
|
-
directoryUrl: string;
|
|
30
|
-
account: NorthlightAccount;
|
|
31
|
-
notify: string | null;
|
|
32
|
-
state: 'running' | 'committed' | 'activated';
|
|
33
|
-
notified: boolean;
|
|
34
|
-
/** The exporter's process, so a later `crtr sys signin` can tell a running move from one whose exporter was killed. */
|
|
35
|
-
pid: number;
|
|
36
|
-
}
|
|
37
|
-
export declare const moveRecordPath: () => string;
|
|
38
|
-
/** The move record, or undefined when no move is running or unfinished. A present but malformed file throws. */
|
|
39
|
-
export declare function readMoveRecord(): MoveRecord | undefined;
|
|
40
|
-
export declare function writeMoveRecord(record: MoveRecord): void;
|
|
41
|
-
export declare function deleteMoveRecord(): void;
|
|
42
|
-
/** Whether a move's records are in the Northlight account but this computer has not switched over (the record says `committed`). */
|
|
43
|
-
export declare const isMoveCommitted: () => boolean;
|
|
44
|
-
/** The one `move_unfinished` error: every command, `crtr sys import resume` and a move whose switch-over failed answer it alike (exit code USAGE, as `not_signed_in`). */
|
|
45
|
-
export declare const moveUnfinishedError: (reason?: string) => CrtrError;
|
|
46
22
|
/** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
|
|
47
23
|
export declare const installIdPath: () => string;
|
|
48
24
|
export declare function readOrCreateInstallId(): string;
|
|
@@ -3,14 +3,11 @@
|
|
|
3
3
|
// `runtime/secrets/machine-credential` (mode 0600). A Mac with no `machine.json` is a local control plane, not a machine.
|
|
4
4
|
// Also the move record `runtime/import/move.json` (0600): where a move to Northlight that `crtr sys signin` started stands, from before the drain until the
|
|
5
5
|
// computer has switched over (design-crtr-northlight-signin component 4).
|
|
6
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync,
|
|
6
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
7
7
|
import { randomBytes } from 'node:crypto';
|
|
8
8
|
import { dirname, join } from 'node:path';
|
|
9
9
|
import { runtimeRoot, secretsDir } from '../../core/layout.js';
|
|
10
10
|
import { joinedIssuer } from '../../core/directory/join.js';
|
|
11
|
-
import { CrtrError } from '../../core/errors.js';
|
|
12
|
-
import { atomicWriteJson } from '../../core/fs-utils.js';
|
|
13
|
-
import { ExitCode } from '../../types.js';
|
|
14
11
|
export const machineConfigPath = () => join(runtimeRoot(), 'machine.json');
|
|
15
12
|
export const machineCredentialPath = () => join(secretsDir(), 'machine-credential');
|
|
16
13
|
/** The machine config, or undefined when this install is not an imported machine. A present but malformed file throws. */
|
|
@@ -40,29 +37,6 @@ export function writeMachineCredential(secret) {
|
|
|
40
37
|
writeFileSync(path, `${secret}\n`, { mode: 0o600 });
|
|
41
38
|
chmodSync(path, 0o600);
|
|
42
39
|
}
|
|
43
|
-
export const moveRecordPath = () => join(runtimeRoot(), 'import', 'move.json');
|
|
44
|
-
/** The move record, or undefined when no move is running or unfinished. A present but malformed file throws. */
|
|
45
|
-
export function readMoveRecord() {
|
|
46
|
-
const path = moveRecordPath();
|
|
47
|
-
if (!existsSync(path))
|
|
48
|
-
return undefined;
|
|
49
|
-
const raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
50
|
-
if (typeof raw.runId !== 'string' || typeof raw.apiUrl !== 'string' || typeof raw.directoryUrl !== 'string' || (raw.state !== 'running' && raw.state !== 'committed' && raw.state !== 'activated')
|
|
51
|
-
|| typeof raw.account?.id !== 'string' || typeof raw.account.display !== 'string')
|
|
52
|
-
throw new Error(`${path} is not a move record`);
|
|
53
|
-
return { runId: raw.runId, apiUrl: raw.apiUrl, directoryUrl: raw.directoryUrl, account: { id: raw.account.id, display: raw.account.display },
|
|
54
|
-
notify: typeof raw.notify === 'string' ? raw.notify : null, state: raw.state, notified: raw.notified === true, pid: typeof raw.pid === 'number' ? raw.pid : 0 };
|
|
55
|
-
}
|
|
56
|
-
export function writeMoveRecord(record) {
|
|
57
|
-
atomicWriteJson(moveRecordPath(), record, { mode: 0o600 });
|
|
58
|
-
}
|
|
59
|
-
export function deleteMoveRecord() {
|
|
60
|
-
rmSync(moveRecordPath(), { force: true });
|
|
61
|
-
}
|
|
62
|
-
/** Whether a move's records are in the Northlight account but this computer has not switched over (the record says `committed`). */
|
|
63
|
-
export const isMoveCommitted = () => readMoveRecord()?.state === 'committed';
|
|
64
|
-
/** The one `move_unfinished` error: every command, `crtr sys import resume` and a move whose switch-over failed answer it alike (exit code USAGE, as `not_signed_in`). */
|
|
65
|
-
export const moveUnfinishedError = (reason) => new CrtrError('move_unfinished', `crtr's records are already in your Northlight account, but this computer has not switched over${reason === undefined ? '.' : `: ${reason}`}`, ExitCode.USAGE, { next: 'Run `crtr sys signin` to finish.' });
|
|
66
40
|
/** This computer's install id, kept under `runtime/` so it exists before any daemon: the machine registration names it, and a reinstall that keeps `runtime/` registers the same machine again. */
|
|
67
41
|
export const installIdPath = () => join(runtimeRoot(), 'install-id');
|
|
68
42
|
export function readOrCreateInstallId() {
|
package/dist/daemon/manage.d.ts
CHANGED
|
@@ -48,7 +48,7 @@ export interface DaemonExportSqliteResult {
|
|
|
48
48
|
userVersion: number;
|
|
49
49
|
}
|
|
50
50
|
/** Run the selected generation's `crtrd-cli import-dump`: the row files of the running canvas into `out`/rows. */
|
|
51
|
-
export declare function runDaemonImportDump(out: string, kind: '
|
|
51
|
+
export declare function runDaemonImportDump(out: string, kind: 'hosted'): Promise<DumpResult>;
|
|
52
52
|
/** Run `crtrd-cli import-dump <out> bodies`: every `bodies` row into `out`/rows/bodies (the pre-pause dump; the later `runDaemonImportDump` adds the rows written since). */
|
|
53
53
|
export declare function runDaemonBodiesDump(out: string): Promise<{
|
|
54
54
|
parts: string[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@north-light/api",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.761",
|
|
4
4
|
"description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/api/index.js",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const retry: import("../../../core/command.js").LeafDef;
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
// `crtr sys import retry <run_id>`: loads a failed import again from the bundle its failure kept.
|
|
2
|
-
import { defineLeaf } from '../../../core/command.js';
|
|
3
|
-
import { usage } from '../../../core/errors.js';
|
|
4
|
-
import { ImportCloud } from '../../../core/import/export/cloud.js';
|
|
5
|
-
import { controlPlaneUrl, personBearer } from '../../../core/directory/person-credential.js';
|
|
6
|
-
import { awaitRunOutcome, defaultDirectoryUrl } from './move.js';
|
|
7
|
-
export const retry = defineLeaf({
|
|
8
|
-
name: 'retry',
|
|
9
|
-
description: 'load a failed import again from the bundle it already uploaded',
|
|
10
|
-
whenToUse: 'an import failed while Northlight was loading it (a refused or conflicting row) and the cause is fixed: no new upload and no new confirm code',
|
|
11
|
-
help: {
|
|
12
|
-
name: 'sys import retry',
|
|
13
|
-
summary: 're-queue a failed run so Northlight loads its kept upload again, then wait for the outcome',
|
|
14
|
-
guide: 'Works for a run that failed before its copy committed and whose upload is under 7 days old (Northlight deletes older ones; run the import again then). The bundle is what was uploaded, so rows this computer changed since are not in it. Prints the final state, or the new failure.',
|
|
15
|
-
params: [
|
|
16
|
-
{ kind: 'positional', name: 'run_id', type: 'string', required: true, constraint: 'The failed import run (`imp_…`).' },
|
|
17
|
-
{ kind: 'flag', name: 'api-url', type: 'string', required: false, constraint: 'Control plane base URL; default is the one the sign-in is for.' },
|
|
18
|
-
],
|
|
19
|
-
output: [
|
|
20
|
-
{ name: 'run_id', type: 'string', required: true, constraint: 'The import run.' },
|
|
21
|
-
{ name: 'state', type: 'string', required: true, constraint: 'Final state of the run, `done`.' },
|
|
22
|
-
],
|
|
23
|
-
outputKind: 'object',
|
|
24
|
-
effects: ['Moves the run from `failed` back to `loading` on the control plane; nothing local changes.'],
|
|
25
|
-
},
|
|
26
|
-
run: async (input) => {
|
|
27
|
-
const runId = String(input['run_id'] ?? '');
|
|
28
|
-
if (runId === '')
|
|
29
|
-
throw usage('name the failed run: crtr sys import retry <run_id>');
|
|
30
|
-
const directoryUrl = defaultDirectoryUrl();
|
|
31
|
-
const apiUrl = input.apiUrl === undefined ? await controlPlaneUrl(directoryUrl) : String(input.apiUrl);
|
|
32
|
-
const cloud = new ImportCloud(apiUrl, () => personBearer(directoryUrl));
|
|
33
|
-
await cloud.retry(runId);
|
|
34
|
-
await awaitRunOutcome(cloud, runId, undefined);
|
|
35
|
-
return { run_id: runId, state: 'done' };
|
|
36
|
-
},
|
|
37
|
-
render: (r) => `<import run="${r['run_id']}" state="${r['state']}"/>`,
|
|
38
|
-
});
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import { type MoveRecord } from './config.js';
|
|
2
|
-
/** Tell the node that asked for the move that it finished, through the control plane with the person's bearer (`POST /v1/nodes/:id/messages`): the node
|
|
3
|
-
* now lives in the account, so the message is stored there as mail and wakes it once the machine link is up. Then the record says `notified`. */
|
|
4
|
-
export declare function notifyMoveFinished(move: MoveRecord): Promise<MoveRecord>;
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
// src/daemon/machine-link/move-notify.ts — telling the node that asked for a move to Northlight that it finished (design-crtr-northlight-signin component 4).
|
|
2
|
-
import { CrtrClient } from '../../api/index.js';
|
|
3
|
-
import { northlightFetch } from '../../core/directory/person-credential.js';
|
|
4
|
-
import { writeMoveRecord } from './config.js';
|
|
5
|
-
/** Tell the node that asked for the move that it finished, through the control plane with the person's bearer (`POST /v1/nodes/:id/messages`): the node
|
|
6
|
-
* now lives in the account, so the message is stored there as mail and wakes it once the machine link is up. Then the record says `notified`. */
|
|
7
|
-
export async function notifyMoveFinished(move) {
|
|
8
|
-
if (move.notified || move.notify === null)
|
|
9
|
-
return move;
|
|
10
|
-
await new CrtrClient({ baseUrl: move.apiUrl, fetch: northlightFetch(move.directoryUrl, move.apiUrl) }).sendMessage(move.notify, { from: null,
|
|
11
|
-
body: `The move to Northlight finished; crtr on this computer now runs with the account ${move.account.display}. Retry the command that needed the account and carry on.` });
|
|
12
|
-
const notified = { ...move, notified: true };
|
|
13
|
-
writeMoveRecord(notified);
|
|
14
|
-
return notified;
|
|
15
|
-
}
|