Skip to content

Commit fa998cc

Browse files
antfubotantfu
andauthored
fix(hub-ui-onboard): stop an install that never finishes (#488)
Co-authored-by: Anthony Fu <github@antfu.me>
1 parent 21fa576 commit fa998cc

8 files changed

Lines changed: 124 additions & 6 deletions

File tree

‎docs/content/1.guide/23.hub-ui-onboard.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ const onboarding = createOnboarding({
3939
- `scriptSrc`: `<base>embedded.js`, the URL to inject as `<script type="module">`.
4040
- `disabled` and `installed`: what the host needs to decide whether to inject the script at all (below).
4141

42-
`packages` are package specs as the package manager accepts them. The package manager comes from the lockfile (`npm`, `pnpm`, `yarn`, `bun`, `deno`), `dev: true` adds `-D`, and `cwd` (default `process.cwd()`) is the project that receives the dependency. In a workspace, point `cwd` at the package that runs the dev server. The packages are fixed at creation.
42+
`packages` are package specs as the package manager accepts them. The package manager comes from the lockfile (`npm`, `pnpm`, `yarn`, `bun`, `deno`), `dev: true` adds `-D`, and `cwd` (default `process.cwd()`) is the project that receives the dependency. In a workspace, point `cwd` at the package that runs the dev server. The packages are fixed at creation. An install that runs longer than `installTimeout` (default 5 minutes) is stopped, and the panel asks the user to run the command in a terminal ([DF9009](/errors/DF9009)).
4343

4444
## Confirm the install
4545

@@ -225,4 +225,4 @@ Frameworks with a `Request => Response` surface (Hono, Nitro, Deno) mount `onboa
225225

226226
## Errors
227227

228-
The Node side reports through `DF9000` to `DF9008`. An install failure or a throwing `onInstalled` also reaches the panel as `{ state: 'error', error: { code, message } }`, with a Retry button. See the [error reference](/errors).
228+
The Node side reports through `DF9000` to `DF9009`. An install failure or a throwing `onInstalled` also reaches the panel as `{ state: 'error', error: { code, message } }`, with a Retry button. See the [error reference](/errors).

‎docs/content/6.errors/DF9009.md‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
title: 'DF9009: Install Command Timed Out'
3+
description: 'The package manager did not finish in time, so the install was stopped.'
4+
---
5+
6+
## Message
7+
8+
> `{command}` did not finish within `{seconds}` seconds, so it was stopped.
9+
10+
## Cause
11+
12+
The Install button ran the project's package manager, and the package manager did not exit before the time limit. The limit is the `installTimeout` option of `createOnboarding()`. The default is 5 minutes. The onboarding then stopped the process, so the panel does not wait forever.
13+
14+
Usually the package manager hangs. For example, some pnpm 10 versions hang while they resolve some prerelease versions. A slow network or a very large install can also take longer than the limit.
15+
16+
## Fix
17+
18+
Run the command shown in the panel in a terminal to see where the package manager stops. Fix the cause, for example update the package manager, then click Retry. If the install is only slow, pass a larger `installTimeout` to `createOnboarding()`.
19+
20+
## Source
21+
22+
- [`packages/hub-ui-onboard/src/install.ts`](https://github.com/devframes/devframe/blob/main/packages/hub-ui-onboard/src/install.ts): `runInstall` stops the process and throws this when the time limit ends. The status route reports it as `{ state: 'error', error: { code, message } }`.

‎packages/hub-ui-onboard/src/diagnostics.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,5 +49,9 @@ export const diagnostics = defineDiagnostics({
4949
why: (p: { command: string, minutes: number }) => `Nobody allowed \`${p.command}\` within ${p.minutes} minutes. The install was refused.`,
5050
fix: 'Click Install again and answer in the terminal that runs the dev server. If the answer does not arrive, another program reads that terminal: pass an `onConfirm` function to `createOnboarding()`.',
5151
},
52+
DF9009: {
53+
why: (p: { command: string, seconds: number }) => `\`${p.command}\` did not finish within ${p.seconds} seconds, so it was stopped.`,
54+
fix: 'Run the command in a terminal to see where the package manager stops, then click Install again. If the install is only slow, raise `installTimeout`.',
55+
},
5256
},
5357
})

‎packages/hub-ui-onboard/src/index.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import { confirmInTerminal } from './terminal-confirm'
1717
export type * from './types'
1818

1919
const STATE_FILE = 'hub-ui-onboard.json'
20+
const DEFAULT_INSTALL_TIMEOUT = 5 * 60 * 1000
2021

2122
/** `devframes` → `/devframes/`, same rule as `normalizeHubBase` in `@devframes/hub`. */
2223
function normalizeBase(base: string): string {
@@ -128,7 +129,12 @@ export function createOnboarding(options: CreateOnboardingOptions): Onboarding {
128129
const base = normalizeBase(options.base ?? '/__devframes/')
129130
const cwd = options.cwd ?? process.cwd()
130131
const stateFile = join(options.stateDir ?? join(cwd, 'node_modules/.devframe'), STATE_FILE)
131-
const plan = { cwd, packages: options.packages, dev: options.dev ?? true }
132+
const plan = {
133+
cwd,
134+
packages: options.packages,
135+
dev: options.dev ?? true,
136+
timeout: options.installTimeout ?? DEFAULT_INSTALL_TIMEOUT,
137+
}
132138
const branding = options.branding ?? {}
133139
const messages = {
134140
...defaultMessages(branding.productName?.trim() || 'Devframes'),

‎packages/hub-ui-onboard/src/install.ts‎

Lines changed: 47 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { ResolvedCommand } from 'package-manager-detector'
2+
import type { Result } from 'tinyexec'
23
import { existsSync } from 'node:fs'
34
import { join } from 'node:path'
45
import process from 'node:process'
@@ -10,6 +11,8 @@ export interface InstallPlan {
1011
cwd: string
1112
packages: string[]
1213
dev: boolean
14+
/** Stop the install after this many milliseconds. */
15+
timeout: number
1316
}
1417

1518
/** The `add` command for the project's package manager, `npm` when none is detected. */
@@ -28,19 +31,40 @@ export async function resolveInstallCommand(plan: InstallPlan): Promise<Resolved
2831

2932
/**
3033
* Run the install and make sure that each named package landed in
31-
* `<cwd>/node_modules`. Throws a `DF9001` / `DF9002` diagnostic on failure.
34+
* `<cwd>/node_modules`. Throws a `DF9001` / `DF9002` / `DF9009` diagnostic on failure.
3235
*/
3336
export async function runInstall(plan: InstallPlan, command: ResolvedCommand): Promise<void> {
34-
const result = await exec(command.command, command.args, {
37+
const commandLine = [command.command, ...command.args].join(' ')
38+
const child = exec(command.command, command.args, {
3539
// `CI` keeps every package manager non-interactive: nobody can answer a prompt here.
3640
nodeOptions: {
3741
cwd: plan.cwd,
3842
env: { ...process.env, CI: '1' },
3943
},
4044
})
45+
// A hung package manager never exits. Stop it and fail at once: a child
46+
// process can keep the output pipes open after the kill. The kill can also
47+
// end the install with an exit code first, so the timeout error wins.
48+
let timer: ReturnType<typeof setTimeout> | undefined
49+
let killed: Promise<void> | undefined
50+
const timedOut = new Promise<undefined>((resolve) => {
51+
timer = setTimeout(() => {
52+
killed = killTree(child)
53+
void killed.then(() => resolve(undefined))
54+
}, plan.timeout)
55+
})
56+
const result = await Promise.race([child, timedOut]).finally(() => clearTimeout(timer))
57+
// `result` is `undefined` only when the timeout won the race.
58+
if (killed || !result) {
59+
await killed
60+
throw diagnostics.DF9009({
61+
command: commandLine,
62+
seconds: Math.round(plan.timeout / 1000),
63+
})
64+
}
4165
if (result.exitCode !== 0) {
4266
throw diagnostics.DF9001({
43-
command: [command.command, ...command.args].join(' '),
67+
command: commandLine,
4468
exitCode: result.exitCode,
4569
stderr: result.stderr.trim().slice(-2048),
4670
})
@@ -51,6 +75,26 @@ export async function runInstall(plan: InstallPlan, command: ResolvedCommand): P
5175
}
5276
}
5377

78+
/**
79+
* Kill the install with everything it started. On Windows, tinyexec runs a
80+
* package manager's `.cmd` shim through `cmd.exe`, and a kill does not reach
81+
* child processes, so `taskkill /T /F` ends the whole tree.
82+
*/
83+
async function killTree(child: Result): Promise<void> {
84+
const pid = child.process?.pid
85+
if (process.platform === 'win32' && pid !== undefined) {
86+
const result = await exec('taskkill', [
87+
'/pid',
88+
String(pid),
89+
'/T',
90+
'/F',
91+
]).then(r => r, () => undefined)
92+
if (result?.exitCode === 0)
93+
return
94+
}
95+
child.kill()
96+
}
97+
5498
/**
5599
* `true` when every named package is already in `<cwd>/node_modules`, so the
56100
* onboarding has nothing to install. Path, URL and alias specs cannot be

‎packages/hub-ui-onboard/src/types.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,12 @@ export interface CreateOnboardingOptions {
5555
stateDir?: string
5656
/** Install as a devDependency. Default: `true`. */
5757
dev?: boolean
58+
/**
59+
* Stop the install when it runs longer than this many milliseconds, and
60+
* show an error that asks the user to run the command in a terminal.
61+
* Default: `300_000` (5 minutes).
62+
*/
63+
installTimeout?: number
5864
branding?: OnboardingBranding
5965
messages?: Partial<OnboardingMessages>
6066
/**
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { mkdtempSync, rmSync } from 'node:fs'
2+
import { tmpdir } from 'node:os'
3+
import { join } from 'node:path'
4+
import process from 'node:process'
5+
import { afterEach, describe, expect, it } from 'vitest'
6+
import { runInstall } from '../src/install'
7+
8+
const dirs: string[] = []
9+
afterEach(() => {
10+
for (const dir of dirs.splice(0))
11+
rmSync(dir, { recursive: true, force: true, maxRetries: 10 })
12+
})
13+
14+
describe('runInstall', () => {
15+
it('stops a package manager that hangs', async () => {
16+
const cwd = mkdtempSync(join(tmpdir(), 'onboard-install-'))
17+
dirs.push(cwd)
18+
// Stands in for a hung package manager; a grandchild keeps the pipes open for 3 s.
19+
const script = 'require("child_process").spawn(process.execPath, ["-e", "setTimeout(() => {}, 3000)"], { stdio: "inherit" }); setInterval(() => {}, 1000)'
20+
const started = Date.now()
21+
await expect(runInstall(
22+
{
23+
cwd,
24+
packages: ['foo'],
25+
dev: true,
26+
timeout: 300,
27+
},
28+
{
29+
command: process.execPath,
30+
args: ['-e', script],
31+
},
32+
)).rejects.toMatchObject({ code: 'DF9009' })
33+
expect(Date.now() - started).toBeLessThan(5000)
34+
})
35+
})

‎tests/__snapshots__/tsnapi/@devframes/hub-ui-onboard/index.snapshot.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ export interface CreateOnboardingOptions {
88
cwd?: string;
99
stateDir?: string;
1010
dev?: boolean;
11+
installTimeout?: number;
1112
branding?: OnboardingBranding;
1213
messages?: Partial<OnboardingMessages>;
1314
onInstalled?: () => void | OnboardingHandler | Promise<void | OnboardingHandler>;

0 commit comments

Comments
 (0)