@dbx-tools/cli-service 0.9.190 → 0.9.193

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/src/_host.ts CHANGED
@@ -5,6 +5,7 @@ import { dirname, join } from "node:path";
5
5
 
6
6
  import { parseArgv } from "@dbx-tools/cli-args";
7
7
  import { shutdownProcessTree } from "@dbx-tools/core";
8
+ import { boundedRetryDelay } from "@dbx-tools/shared-core";
8
9
  import * as systrayModule from "systray2";
9
10
  import type SysTrayType from "systray2";
10
11
  import type { MenuItem } from "systray2";
@@ -21,6 +22,12 @@ import type { CliServiceCommand, CliServiceDefinition, CliServiceMenuItem } from
21
22
 
22
23
  const CHILD_TERMINATE_TIMEOUT_MILLISECONDS = 30_000;
23
24
  const CHILD_KILL_TIMEOUT_MILLISECONDS = 5_000;
25
+ // Startup entries do not supervise the host, so the host restarts a managed
26
+ // command that exits early (for example, before VPN or network is up at login).
27
+ const DEFAULT_RESTART_BACKOFF: ServiceRestartBackoff = {
28
+ delaysMilliseconds: [1_000, 2_000, 5_000, 10_000, 30_000, 60_000],
29
+ stableMilliseconds: 60_000,
30
+ };
24
31
  const CliServiceHostOptionsSchema = z.object({
25
32
  serviceConfig: z
26
33
  .string()
@@ -40,9 +47,17 @@ type ServiceTray = Pick<SysTrayType, "ready" | "onClick" | "onError" | "onExit">
40
47
  readonly process?: ChildProcess | null;
41
48
  };
42
49
 
50
+ interface ServiceRestartBackoff {
51
+ /** Delays between consecutive early exits; the last entry repeats. */
52
+ readonly delaysMilliseconds: readonly number[];
53
+ /** Uptime after which an exit is treated as a fresh failure rather than consecutive. */
54
+ readonly stableMilliseconds: number;
55
+ }
56
+
43
57
  interface CliServiceHostDependencies {
44
58
  readonly createTray?: () => ServiceTray;
45
59
  readonly listenForControl?: typeof listenForServiceControl;
60
+ readonly restartBackoff?: ServiceRestartBackoff;
46
61
  }
47
62
 
48
63
  function systrayConstructor(): typeof SysTrayType {
@@ -60,8 +75,14 @@ export class CliServiceHost {
60
75
  private readonly requestStop: () => void;
61
76
  private readonly createServiceTray: () => ServiceTray;
62
77
  private readonly listenForControl: typeof listenForServiceControl;
78
+ private readonly restartBackoff: ServiceRestartBackoff;
63
79
  private tray?: ServiceTray;
80
+ private auth?: ChildProcess;
81
+ private authRestartTimer?: ReturnType<typeof setTimeout>;
82
+ private authRestartAttempt = 0;
64
83
  private service?: ChildProcess;
84
+ private restartTimer?: ReturnType<typeof setTimeout>;
85
+ private restartAttempt = 0;
65
86
  private control?: Awaited<ReturnType<typeof listenForServiceControl>>;
66
87
  private stopping = false;
67
88
 
@@ -76,6 +97,7 @@ export class CliServiceHost {
76
97
  this.requestStop = requestStop;
77
98
  this.createServiceTray = dependencies.createTray ?? (() => this.createTray());
78
99
  this.listenForControl = dependencies.listenForControl ?? listenForServiceControl;
100
+ this.restartBackoff = dependencies.restartBackoff ?? DEFAULT_RESTART_BACKOFF;
79
101
  }
80
102
 
81
103
  async start(): Promise<void> {
@@ -86,11 +108,9 @@ export class CliServiceHost {
86
108
  () => this.status(),
87
109
  this.requestStop,
88
110
  );
89
- this.service = this.definition.command
90
- ? this.startProcess(this.definition.command, true)
91
- : undefined;
92
111
  this.tray = this.createServiceTray();
93
112
  void this.initializeTray(this.tray);
113
+ this.startManagedCommand();
94
114
  } catch (error) {
95
115
  await this.stop();
96
116
  throw error;
@@ -100,6 +120,10 @@ export class CliServiceHost {
100
120
  async stop(): Promise<void> {
101
121
  if (this.stopping) return;
102
122
  this.stopping = true;
123
+ clearTimeout(this.authRestartTimer);
124
+ this.authRestartTimer = undefined;
125
+ clearTimeout(this.restartTimer);
126
+ this.restartTimer = undefined;
103
127
  if (this.control) {
104
128
  await closeServiceControl(this.control, this.paths.controlAddress);
105
129
  this.control = undefined;
@@ -108,12 +132,69 @@ export class CliServiceHost {
108
132
  await stopTray(this.tray);
109
133
  this.tray = undefined;
110
134
  }
135
+ if (this.auth) {
136
+ await stopProcess(this.auth);
137
+ this.auth = undefined;
138
+ }
111
139
  if (this.service) {
112
140
  await stopProcess(this.service);
113
141
  this.service = undefined;
114
142
  }
115
143
  }
116
144
 
145
+ private startManagedCommand(): void {
146
+ const authCommand =
147
+ this.definition.waitForAuth !== "false" ? this.definition.authCommand : undefined;
148
+ if (authCommand) {
149
+ this.startAuthPreflight(authCommand);
150
+ return;
151
+ }
152
+ if (this.definition.command) this.startService(this.definition.command);
153
+ }
154
+
155
+ private startAuthPreflight(command: CliServiceCommand): void {
156
+ const child = this.startProcess(command);
157
+ this.auth = child;
158
+ child.once("error", () => {
159
+ if (this.auth !== child) return;
160
+ this.auth = undefined;
161
+ this.requestStop();
162
+ });
163
+ child.once("exit", (code, signal) => {
164
+ if (this.stopping || this.auth !== child) return;
165
+ this.auth = undefined;
166
+ if (code === 0) {
167
+ this.authRestartAttempt = 0;
168
+ void logMessage(this.paths.hostLog, "authentication preflight succeeded");
169
+ if (this.definition.command) this.startService(this.definition.command);
170
+ return;
171
+ }
172
+ this.scheduleAuthRestart(command, signal ?? String(code));
173
+ });
174
+ }
175
+
176
+ private scheduleAuthRestart(command: CliServiceCommand, reason: string): void {
177
+ const delay = boundedRetryDelay(
178
+ this.authRestartAttempt,
179
+ this.restartBackoff.delaysMilliseconds,
180
+ );
181
+ this.authRestartAttempt += 1;
182
+ void logMessage(
183
+ this.paths.hostLog,
184
+ `authentication preflight exited (${reason}); retrying in ${delay / 1000}s`,
185
+ );
186
+ this.authRestartTimer = setTimeout(() => {
187
+ this.authRestartTimer = undefined;
188
+ if (this.stopping) return;
189
+ try {
190
+ this.startAuthPreflight(command);
191
+ } catch (error) {
192
+ void logError(this.paths.hostLog, error);
193
+ this.requestStop();
194
+ }
195
+ }, delay);
196
+ }
197
+
117
198
  private status(): ServiceControlResponse {
118
199
  return {
119
200
  running: true,
@@ -146,7 +227,49 @@ export class CliServiceHost {
146
227
  }
147
228
  }
148
229
 
149
- private startProcess(command: CliServiceCommand, managed: boolean): ChildProcess {
230
+ private startService(command: CliServiceCommand): void {
231
+ const startedAt = Date.now();
232
+ const child = this.startProcess(command);
233
+ this.service = child;
234
+ // A spawn failure (missing or non-executable binary) will not fix itself.
235
+ child.once("error", () => {
236
+ if (this.service !== child) return;
237
+ this.service = undefined;
238
+ this.requestStop();
239
+ });
240
+ child.once("exit", (code, signal) => {
241
+ if (this.stopping || this.service !== child) return;
242
+ this.service = undefined;
243
+ this.scheduleServiceRestart(command, Date.now() - startedAt, signal ?? String(code));
244
+ });
245
+ }
246
+
247
+ private scheduleServiceRestart(
248
+ command: CliServiceCommand,
249
+ uptimeMilliseconds: number,
250
+ reason: string,
251
+ ): void {
252
+ const { delaysMilliseconds, stableMilliseconds } = this.restartBackoff;
253
+ if (uptimeMilliseconds >= stableMilliseconds) this.restartAttempt = 0;
254
+ const delay = boundedRetryDelay(this.restartAttempt, delaysMilliseconds);
255
+ this.restartAttempt += 1;
256
+ void logMessage(
257
+ this.paths.hostLog,
258
+ `managed service exited (${reason}); restarting in ${delay / 1000}s`,
259
+ );
260
+ this.restartTimer = setTimeout(() => {
261
+ this.restartTimer = undefined;
262
+ if (this.stopping) return;
263
+ try {
264
+ this.startService(command);
265
+ } catch (error) {
266
+ void logError(this.paths.hostLog, error);
267
+ this.requestStop();
268
+ }
269
+ }, delay);
270
+ }
271
+
272
+ private startProcess(command: CliServiceCommand): ChildProcess {
150
273
  if (!command.executable) {
151
274
  throw new Error("installed service commands require an executable");
152
275
  }
@@ -159,13 +282,6 @@ export class CliServiceHost {
159
282
  closeSync(logDescriptor);
160
283
  child.once("error", (error) => {
161
284
  void logError(this.paths.hostLog, error);
162
- if (managed) this.requestStop();
163
- });
164
- child.once("exit", (code, signal) => {
165
- if (!this.stopping && managed) {
166
- void logMessage(this.paths.hostLog, `managed service exited (${signal ?? String(code)})`);
167
- this.requestStop();
168
- }
169
285
  });
170
286
  return child;
171
287
  }
@@ -217,7 +333,7 @@ export class CliServiceHost {
217
333
  title: item.label,
218
334
  tooltip: "",
219
335
  click: () => {
220
- const child = this.startProcess(item.command, false);
336
+ const child = this.startProcess(item.command);
221
337
  child.unref();
222
338
  },
223
339
  };
@@ -233,7 +349,7 @@ export class CliServiceHost {
233
349
  arguments: ["url.dll,FileProtocolHandler", url],
234
350
  }
235
351
  : { executable: "xdg-open", arguments: [url] };
236
- const child = this.startProcess(command, false);
352
+ const child = this.startProcess(command);
237
353
  child.unref();
238
354
  }
239
355
  }
package/src/cli.ts CHANGED
@@ -12,10 +12,16 @@ import { spawn } from "@dbx-tools/core";
12
12
  import { Command } from "commander";
13
13
 
14
14
  import type { CliServiceDefinition } from "./definition.ts";
15
- import { CliService, CliServiceInstallOptionsSchema, type CliServiceLifecycle } from "./service.ts";
15
+ import {
16
+ CliService,
17
+ CliServiceInstallOptionsSchema,
18
+ type CliServiceInstallOptions,
19
+ type CliServiceLifecycle,
20
+ } from "./service.ts";
16
21
 
17
22
  /** Static definition or action-time factory used by a service command group. */
18
- export type CliServiceDefinitionSource = CliServiceDefinition | (() => CliServiceDefinition);
23
+ export type CliServiceDefinitionSource =
24
+ CliServiceDefinition | ((options?: CliServiceInstallOptions) => CliServiceDefinition);
19
25
 
20
26
  /** Injectable lifecycle and output boundary for service CLI tests and composition. */
21
27
  export interface CliServiceCliDependencies {
@@ -41,7 +47,7 @@ export function buildServiceCommand(
41
47
  dependencies: CliServiceCliDependencies = DEFAULT_DEPENDENCIES,
42
48
  ): Command {
43
49
  const definition = resolveDefinition(source);
44
- const service = () => dependencies.create(definition());
50
+ const service = (options?: CliServiceInstallOptions) => dependencies.create(definition(options));
45
51
  const execute = dependencies.execute ?? DEFAULT_DEPENDENCIES.execute;
46
52
  const command = new Command("service")
47
53
  .enablePositionalOptions()
@@ -56,7 +62,8 @@ export function buildServiceCommand(
56
62
  CliServiceInstallOptionsSchema,
57
63
  );
58
64
  install.action(async () => {
59
- await service().install(parseArgs(install, CliServiceInstallOptionsSchema));
65
+ const options = parseArgs(install, CliServiceInstallOptionsSchema);
66
+ await service(options).install(options);
60
67
  });
61
68
 
62
69
  command
@@ -114,6 +121,8 @@ export function buildServiceCommand(
114
121
  return command;
115
122
  }
116
123
 
117
- function resolveDefinition(source: CliServiceDefinitionSource): () => CliServiceDefinition {
124
+ function resolveDefinition(
125
+ source: CliServiceDefinitionSource,
126
+ ): (options?: CliServiceInstallOptions) => CliServiceDefinition {
118
127
  return typeof source === "function" ? source : () => source;
119
128
  }
package/src/definition.ts CHANGED
@@ -15,6 +15,16 @@ import { serviceTrayIcon } from "./icon.ts";
15
15
 
16
16
  const SAFE_URL_PROTOCOLS = new Set(["http:", "https:", "mailto:"]);
17
17
 
18
+ /** Controls whether a service waits for its optional authentication preflight. */
19
+ export const CliServiceWaitForAuthSchema = z
20
+ .enum(["auto", "true", "false"])
21
+ .describe(
22
+ "Authentication readiness mode: auto waits when the service provides an applicable auth preflight, true requires it, and false skips it.",
23
+ );
24
+
25
+ /** Controls whether a service waits for its optional authentication preflight. */
26
+ export type CliServiceWaitForAuth = z.infer<typeof CliServiceWaitForAuthSchema>;
27
+
18
28
  function isSafeUrl(value: string): boolean {
19
29
  try {
20
30
  return SAFE_URL_PROTOCOLS.has(new URL(value).protocol);
@@ -121,6 +131,10 @@ export const CliServiceDefinitionSchema = z
121
131
  pythonPackage: CliServicePythonPackageSchema.optional().describe(
122
132
  "Python runtime package installed into a service-owned uv environment.",
123
133
  ),
134
+ waitForAuth: CliServiceWaitForAuthSchema.optional(),
135
+ authCommand: CliServiceCommandSchema.optional().describe(
136
+ "Optional authentication preflight that must exit successfully before the managed command starts.",
137
+ ),
124
138
  command: CliServiceCommandSchema.optional(),
125
139
  menu: z.array(CliServiceMenuItemSchema).readonly().optional(),
126
140
  })
@@ -155,9 +169,10 @@ export function defineService(
155
169
  ): CliServiceDefinition {
156
170
  const pkg = resolveServicePackage(packageReference);
157
171
  const defaults = servicePackageDefaults(pkg);
158
- const { command, ...definition } = options;
172
+ const { authCommand, command, ...definition } = options;
159
173
  return CliServiceDefinitionSchema.parse({
160
174
  ...definition,
175
+ authCommand: resolveServiceCommand(authCommand),
161
176
  command: resolveServiceCommand(command),
162
177
  packageName: pkg.name,
163
178
  id: definition.id ?? defaults.id,
@@ -165,6 +180,7 @@ export function defineService(
165
180
  version: definition.version ?? pkg.version,
166
181
  icon: definition.icon ?? serviceTrayIcon(),
167
182
  isTemplateIcon: definition.isTemplateIcon ?? process.platform === "darwin",
183
+ waitForAuth: definition.waitForAuth ?? "auto",
168
184
  });
169
185
  }
170
186
 
package/src/service.ts CHANGED
@@ -41,6 +41,7 @@ import {
41
41
  type ServiceLaunch,
42
42
  } from "./_startup.ts";
43
43
  import {
44
+ CliServiceWaitForAuthSchema,
44
45
  CliServiceDefinitionSchema,
45
46
  type CliServiceCommand,
46
47
  type CliServiceDefinition,
@@ -124,6 +125,7 @@ export const CliServiceInstallOptionsSchema = z
124
125
  .default(false)
125
126
  .describe("Install Python packages from the uv cache without network access.")
126
127
  .meta({ env: [], short: false }),
128
+ waitForAuth: CliServiceWaitForAuthSchema.default("auto").meta({ env: [], short: false }),
127
129
  })
128
130
  .strict()
129
131
  .describe("Options for installing a current-user CLI service.");
@@ -373,6 +375,7 @@ export class CliService implements CliServiceLifecycle {
373
375
  const definition = CliServiceDefinitionSchema.parse({
374
376
  ...this.definition,
375
377
  version: this.definition.version ?? owner.version,
378
+ waitForAuth: options.waitForAuth ?? this.definition.waitForAuth ?? "auto",
376
379
  });
377
380
  if (!definition.version) throw new Error(`${definition.name} has no installable version`);
378
381
  const pythonPackage = definition.pythonPackage
@@ -405,6 +408,20 @@ export class CliService implements CliServiceLifecycle {
405
408
  artifactBinDirectory,
406
409
  )
407
410
  : undefined;
411
+ if (definition.waitForAuth === "true" && !definition.authCommand) {
412
+ throw new Error(`${definition.name} does not provide an authentication preflight`);
413
+ }
414
+ const authCommand =
415
+ definition.waitForAuth !== "false" && definition.authCommand
416
+ ? await this.installCommand(
417
+ definition,
418
+ owner,
419
+ definition.authCommand,
420
+ "auth",
421
+ pythonEnvironment,
422
+ artifactBinDirectory,
423
+ )
424
+ : undefined;
408
425
  const menu: CliServiceMenuItem[] = [];
409
426
  for (const [index, item] of (definition.menu ?? []).entries()) {
410
427
  menu.push(
@@ -426,6 +443,7 @@ export class CliService implements CliServiceLifecycle {
426
443
  return CliServiceDefinitionSchema.parse({
427
444
  ...definition,
428
445
  ...(pythonPackage ? { pythonPackage } : {}),
446
+ authCommand,
429
447
  ...(command ? { command } : {}),
430
448
  ...(menu.length > 0 ? { menu } : {}),
431
449
  });