@nathanstephenson/flow 0.1.1 → 0.1.2

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.
@@ -5,6 +5,7 @@ import { packageName, privatePath } from "./install-guard.js";
5
5
  import { readHost } from "../daemon/ownership.js";
6
6
  import { backgroundHostArgs, getHostStatus, HostRefusal, launchBackground, processAlive, requestHostStop, requireRestartable, waitUntil } from "./host-control.js";
7
7
  import { InstallationProcessUncertain, replacePackage } from "./install-process.js";
8
+ import { assertSystemdOwner, restoreSystemd, resumeSystemdAdmission, systemctl, SystemdCommandFailed } from "./systemd-update.js";
8
9
  import { newerStableVersion } from "../daemon/release-checker.js";
9
10
  export function npmExecutable() {
10
11
  for (const directory of (process.env.PATH ?? '').split(delimiter)) {
@@ -76,15 +77,31 @@ export async function update(install, lease, args, options = {}) {
76
77
  }
77
78
  const target = options.expectedVersion ?? 'latest';
78
79
  const preserveConcretePort = options.preserveConcreteHostPort === true;
80
+ const managed = options.systemd;
81
+ if (managed)
82
+ await assertSystemdOwner(managed, managed.updater, process.pid);
79
83
  let host = readHost(lease.root);
80
84
  if (host && processAlive(host.pid)) {
81
85
  const status = await getHostStatus(host);
82
- requireRestartable(status);
86
+ if (managed) {
87
+ if (status.mode !== 'foreground')
88
+ throw new Error('systemd updates require a foreground Session Host');
89
+ if (preserveConcretePort && status.settings.port === 0)
90
+ throw new Error('Systemd web updates require a fixed service port for browser reconnection');
91
+ await assertSystemdOwner(managed, managed.service, host.pid);
92
+ }
93
+ else
94
+ requireRestartable(status);
83
95
  host = { ...host, ...status };
84
96
  }
85
97
  else
86
98
  host = undefined;
87
- const transaction = await install.beginUpdate(lease, previous, host);
99
+ if (managed && !host)
100
+ throw new Error('Start the configured systemd Session Host before updating');
101
+ const transaction = await install.beginUpdate(lease, previous, host, managed?.hostArgs);
102
+ const restoreHost = (host, version) => managed
103
+ ? restoreSystemd(lease.root, managed, transaction, host, version)
104
+ : restore(install, transaction, lease.root, host, version, preserveConcretePort);
88
105
  let needsRestoration = false, replacing = false;
89
106
  const repair = () => `Flow startup remains blocked by ${install.barrierPath}. Stop all Flow and npm processes for this prefix. Reinstall ${packageName}@${previous} with the matching npm and prefix ${JSON.stringify(prefix)}. Verify the package files manually, then remove ${install.barrierPath} and start the Session Host again.`;
90
107
  async function replace(version, expected) {
@@ -93,7 +110,7 @@ export async function update(install, lease, args, options = {}) {
93
110
  await replacePackage(npm, prefix, `${packageName}@${version}`);
94
111
  const installed = await verify(install, transaction, expected);
95
112
  if (host && needsRestoration) {
96
- await restore(install, transaction, lease.root, host, installed, preserveConcretePort);
113
+ await restoreHost(host, installed);
97
114
  needsRestoration = false;
98
115
  }
99
116
  await transaction.complete();
@@ -103,7 +120,9 @@ export async function update(install, lease, args, options = {}) {
103
120
  if (host) {
104
121
  needsRestoration = true;
105
122
  try {
106
- await requestHostStop(host, args.includes('--force'));
123
+ await requestHostStop(host, args.includes('--force'), !!managed);
124
+ if (managed)
125
+ await systemctl(managed, 'stop', managed.service);
107
126
  }
108
127
  catch (error) {
109
128
  if (error instanceof HostRefusal)
@@ -121,11 +140,22 @@ export async function update(install, lease, args, options = {}) {
121
140
  if (error instanceof InstallationProcessUncertain)
122
141
  throw new Error(`${String(error)}. ${repair()}`);
123
142
  if (!replacing) {
124
- if (needsRestoration && host && processAlive(host.pid))
143
+ if (needsRestoration && host && processAlive(host.pid)) {
144
+ if (managed && error instanceof SystemdCommandFailed && error.completed) {
145
+ try {
146
+ await resumeSystemdAdmission(managed, host);
147
+ }
148
+ catch (failure) {
149
+ throw new Error(`${String(error)}; could not resume admission: ${String(failure)}. No package files were changed. ${repair()}`);
150
+ }
151
+ await transaction.complete();
152
+ throw new Error(`${String(error)}. No package files were changed; the original Session Host is accepting requests again.`);
153
+ }
125
154
  throw new Error(`${String(error)}. No package files were changed; wait for the stopping host to exit. ${repair()}`);
155
+ }
126
156
  if (needsRestoration && host) {
127
157
  try {
128
- await restore(install, transaction, lease.root, host, previous, preserveConcretePort);
158
+ await restoreHost(host, previous);
129
159
  }
130
160
  catch (failure) {
131
161
  throw new Error(`${String(error)}; restoration failed: ${String(failure)}. ${repair()}`);
@@ -1,3 +1,4 @@
1
+ import { systemdUpdate, launchSystemdUpdate, SystemdLaunchUncertain } from "./systemd-update.js";
1
2
  import { randomUUID } from 'node:crypto';
2
3
  import { closeSync, constants, fchmodSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmdirSync, unlinkSync, writeFileSync, } from 'node:fs';
3
4
  import { join } from 'node:path';
@@ -117,6 +118,10 @@ function publicError(error) {
117
118
  .replace(/((?:token|secret|password)[=:]\s*)[^\s;,]+/gi, '$1[redacted]')
118
119
  .slice(0, 2000);
119
120
  }
121
+ export function claimWebUpdate(root, id) {
122
+ transitionOperation(root, current => current?.id === id && ['updating', 'unverified'].includes(current.state)
123
+ ? { ...current, state: 'updating', pid: process.pid } : current);
124
+ }
120
125
  /** Called by the detached `flow update` helper after restoration/recovery has settled. */
121
126
  export function finishWebUpdate(root, id, result, error) {
122
127
  transitionOperation(root, current => {
@@ -218,6 +223,12 @@ export class WebUpdateController {
218
223
  return operation;
219
224
  });
220
225
  launchedOperationId = id;
226
+ const managed = systemdUpdate(this.options.root);
227
+ if (managed) {
228
+ await launchSystemdUpdate(this.options.root, managed, { id, version: confirmedVersion, force: false });
229
+ helperStarted = true;
230
+ return await this.status(false);
231
+ }
221
232
  const log = openSync(join(this.options.root, 'web-update.log'), constants.O_WRONLY | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
222
233
  let child;
223
234
  try {
@@ -257,7 +268,7 @@ export class WebUpdateController {
257
268
  transitionOperation(this.options.root, operation => {
258
269
  if (!operation || operation.id !== operationId || !['updating', 'unverified'].includes(operation.state) || operation.pid !== undefined)
259
270
  return operation;
260
- return { ...operation, state: 'failed', finishedAt: new Date(this.now()).toISOString(), message: publicError(error) };
271
+ return { ...operation, state: error instanceof SystemdLaunchUncertain ? 'unverified' : 'failed', finishedAt: new Date(this.now()).toISOString(), message: publicError(error) };
261
272
  });
262
273
  }
263
274
  throw error;
@@ -275,8 +286,16 @@ export class WebUpdateController {
275
286
  }
276
287
  }
277
288
  eligibility() {
278
- if (this.options.mode !== 'background') {
279
- return { state: 'unsupported', reason: 'Web updates require a background Session Host. Start Flow with `flow serve start`.' };
289
+ let managed;
290
+ try {
291
+ managed = systemdUpdate(this.options.root);
292
+ }
293
+ catch (error) {
294
+ return { state: 'unsupported', reason: publicError(error) };
295
+ }
296
+ if ((managed && (this.options.mode !== 'foreground' || process.env.FLOW_SYSTEMD_HOST !== '1')) ||
297
+ (!managed && this.options.mode !== 'background')) {
298
+ return { state: 'unsupported', reason: 'Web updates require a background Session Host or configured systemd updater. Start Flow with `flow serve start`, or follow docs/systemd-updates.md.' };
280
299
  }
281
300
  if (!this.options.installation || !this.options.bootstrapEntry) {
282
301
  return { state: 'unsupported', reason: this.options.unsupportedReason ?? 'This installation cannot update itself. Use npm to update Flow manually.' };
@@ -15,13 +15,29 @@ export async function hostControlRoute(request, response, path, control, admissi
15
15
  send(response, 409, { error: 'Session Host instance changed' });
16
16
  return;
17
17
  }
18
+ if (body.resume === true) {
19
+ if (process.env.FLOW_SYSTEMD_HOST !== '1' || !admission.resume()) {
20
+ send(response, 409, { error: 'Only a quiesced systemd Session Host can resume admission' });
21
+ return;
22
+ }
23
+ send(response, 202, { stopping: false });
24
+ return;
25
+ }
18
26
  if (!admission.isStopping() && (admission.hasPending() || control.hasActiveWork()) && body.force !== true) {
19
27
  send(response, 409, { error: 'Session Host has active work; use --force to interrupt it' });
20
28
  return;
21
29
  }
22
- admission.stop();
30
+ if (body.quiesce === true && process.env.FLOW_SYSTEMD_HOST !== '1') {
31
+ send(response, 409, { error: 'Session Host is not configured for systemd updates' });
32
+ return;
33
+ }
34
+ if (body.quiesce === true)
35
+ admission.quiesce();
36
+ else
37
+ admission.stop();
23
38
  send(response, 202, { stopping: true });
24
- setImmediate(() => { void control.stop().catch(error => console.error(error)); });
39
+ if (body.quiesce !== true)
40
+ setImmediate(() => { void control.stop().catch(error => console.error(error)); });
25
41
  }
26
42
  catch (error) {
27
43
  send(response, 400, { error: String(error) });
@@ -28,6 +28,7 @@ const ICON_LINKS = `<link rel="icon" href="/favicon.svg" type="image/svg+xml">
28
28
  export async function serve(options) {
29
29
  const address = options.address ?? "127.0.0.1";
30
30
  let stopping = false;
31
+ let quiesced = false;
31
32
  const pending = new Set();
32
33
  const sockets = new Set();
33
34
  const track = (work) => { pending.add(work); void work.finally(() => pending.delete(work)); };
@@ -50,7 +51,19 @@ export async function serve(options) {
50
51
  return;
51
52
  }
52
53
  void hostControlRoute(request, response, path, options.control, {
53
- isStopping: () => stopping, hasPending: () => pending.size > 0, stop: () => { stopping = true; },
54
+ isStopping: () => stopping, hasPending: () => pending.size > 0,
55
+ stop: () => { stopping = true; quiesced = false; },
56
+ quiesce: () => { if (!stopping) {
57
+ stopping = true;
58
+ quiesced = true;
59
+ } },
60
+ resume: () => {
61
+ if (!quiesced)
62
+ return false;
63
+ stopping = false;
64
+ quiesced = false;
65
+ return true;
66
+ },
54
67
  });
55
68
  return;
56
69
  }
@@ -85,6 +98,7 @@ export async function serve(options) {
85
98
  ...(options.oidc === undefined ? {} : { oidc: options.oidc }),
86
99
  stopAdmission: async (interrupt, timeoutMs = 10000) => {
87
100
  stopping = true;
101
+ quiesced = false;
88
102
  for (const socket of sockets)
89
103
  socket.destroy();
90
104
  let timer;
@@ -99,6 +113,8 @@ export async function serve(options) {
99
113
  }
100
114
  },
101
115
  close: () => {
116
+ stopping = true;
117
+ quiesced = false;
102
118
  for (const socket of sockets)
103
119
  socket.destroy();
104
120
  options.mcpAuth?.dispose();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathanstephenson/flow",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",