Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/3.config/0.index.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,8 @@ Assets can be accessed in server logic and bundled in production. [Read more](/g

Dev server options. You can use `watch` to make the dev server reload if any file changes in specified paths.

By default, a reload closes the previous dev worker right away, which cuts the requests, streamed responses and WebSockets still open on it. Set `devServer.drain: true` to let it finish them while new requests go to the new worker. It is closed once they settle, or after 60 seconds (`drain: { timeout: 600_000 }` for a custom limit, `Infinity` for none).

### `watchOptions`

Watch options for development mode. See [chokidar](https://github.com/paulmillr/chokidar) for more information.
Expand Down
40 changes: 33 additions & 7 deletions src/core/dev-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { App, NodeMiddleware } from "h3";
import type { Listener, ListenOptions } from "listhen";
import { NodeDevWorker, type DevWorker, type WorkerAddress } from "./worker";
import type {
DevServerOptions,
Nitro,
NitroBuildInfo,
NitroDevServer,
Expand Down Expand Up @@ -47,6 +48,15 @@ export function createDevServer(nitro: Nitro): NitroDevServer {
};
}

function getDrainTimeout(drain: DevServerOptions["drain"]) {
if (!drain) {
return;
}
return typeof drain === "object" && drain.timeout !== undefined
? drain.timeout
: 60_000;
}

function lazyNodeMiddleware(load: () => Promise<NodeMiddleware>) {
let middlewarePromise: Promise<NodeMiddleware> | undefined;
return eventHandler(async (event) => {
Expand All @@ -69,6 +79,7 @@ class DevServer {
wsProxies: { route: string; proxy: HTTPProxy }[] = [];

workerError?: unknown;
currentWorkerId?: number;

building?: boolean = true; /* assume initial build will start soon */
buildError?: unknown;
Expand Down Expand Up @@ -99,7 +110,8 @@ class DevServer {
nitro.hooks.hook("dev:error", (cause: unknown) => {
this.buildError = cause;
this.building = false;
for (const worker of this.workers) {
const workers = [...this.workers];
for (const worker of workers) {
worker.close();
}
});
Expand Down Expand Up @@ -130,7 +142,7 @@ class DevServer {
Promise.all(this.listeners.map((l) => l.close())).then(() => {
this.listeners = [];
}),
Promise.all(this.workers.map((w) => w.close())).then(() => {
Promise.all([...this.workers].map((w) => w.close())).then(() => {
this.workers = [];
}),
Promise.resolve(this.watcher?.close()).then(() => {
Expand All @@ -145,12 +157,23 @@ class DevServer {
}

reload() {
for (const worker of this.workers) {
worker.close();
const drainTimeout = getDrainTimeout(this.nitro.options.devServer.drain);
const workers = [...this.workers];
for (const worker of workers) {
if (drainTimeout === undefined) {
worker.close();
} else {
worker.drain(drainTimeout);
}
}
const worker = new NodeDevWorker(++workerIdCtr, this.workerDir, {
this.workerError = undefined;
const id = ++workerIdCtr;
this.currentWorkerId = id;
const worker = new NodeDevWorker(id, this.workerDir, {
onClose: (worker, cause) => {
this.workerError = cause;
if (id === this.currentWorkerId) {
this.workerError = cause;
}
const index = this.workers.indexOf(worker);
if (index !== -1) {
this.workers.splice(index, 1);
Expand All @@ -169,7 +192,10 @@ class DevServer {
let retry = 0;
const maxRetries = isTest || isCI ? 100 : 10;
while (this.building || ++retry < maxRetries) {
if ((this.workers.length === 0 || this.buildError) && !this.building) {
if (
(this.workers.length === 0 || this.buildError || this.workerError) &&
!this.building
) {
return;
}
const activeWorker = this.workers.find((w) => w.ready);
Expand Down
50 changes: 48 additions & 2 deletions src/core/dev-server/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface DevWorker {
readonly ready: boolean;
readonly closed: boolean;
close(): Promise<void>;
drain(timeout: number): Promise<void>;
handleEvent: (event: H3Event) => Promise<void>;
handleUpgrade: (
req: IncomingMessage,
Expand All @@ -39,6 +40,10 @@ export class NodeDevWorker implements DevWorker {
#proxy?: HTTPProxy;
#worker?: Worker & { _exitCode?: number };

#draining = false;
#inflight = 0;
#onIdle?: () => void;

constructor(id: number, workerDir: string, hooks: WorkerHooks = {}) {
this.#id = id;
this.#workerDir = workerDir;
Expand All @@ -49,7 +54,11 @@ export class NodeDevWorker implements DevWorker {

get ready() {
return Boolean(
!this.closed && this.#address && this.#proxy && this.#worker
!this.closed &&
!this.#draining &&
this.#address &&
this.#proxy &&
this.#worker
);
}

Expand All @@ -60,13 +69,21 @@ export class NodeDevWorker implements DevWorker {
statusText: "Dev worker is unavailable",
});
}
await this.#proxy.handleEvent(event, { target: this.#address });
const settle = this.#track();
try {
await this.#proxy.handleEvent(event, { target: this.#address });
} finally {
settle();
}
}

handleUpgrade(req: IncomingMessage, socket: Socket, head: any) {
if (!this.ready) {
return;
}
if (!socket.destroyed) {
socket.once("close", this.#track());
}
return this.#proxy!.proxy.ws(
req,
socket,
Expand Down Expand Up @@ -109,11 +126,40 @@ export class NodeDevWorker implements DevWorker {
this.#worker = worker;
}

async drain(timeout: number) {
if (this.closed || this.#draining) {
return;
}
this.#draining = true;
if (this.#inflight > 0) {
await new Promise<void>((resolve) => {
const timer = Number.isFinite(timeout)
? setTimeout(resolve, Math.max(0, timeout))
: undefined;
this.#onIdle = () => {
clearTimeout(timer);
resolve();
};
});
}
await this.close();
}

#track() {
this.#inflight++;
return () => {
if (--this.#inflight === 0) {
this.#onIdle?.();
}
};
}

async close(cause?: unknown) {
if (this.closed) {
return;
}
this.closed = true;
this.#onIdle?.();
this.#hooks.onClose?.(this, cause);
this.#hooks = {};
const onError = (error: unknown) => consola.error(error);
Expand Down
10 changes: 10 additions & 0 deletions src/types/dev.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ import type { ListenOptions, Listener } from "listhen";

export interface DevServerOptions {
watch: string[];
/**
* Let the previous dev worker finish the requests and WebSockets it already
* accepted on reloads, and close it once they settle (or after `timeout` ms,
* default `60_000`).
*
* New requests go to the new worker.
*
* @default false
*/
drain?: boolean | { timeout?: number };
}

export interface NitroWorker {
Expand Down
1 change: 1 addition & 0 deletions test/dev-shutdown/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.nitro
.output
.output-worker-reload
Loading
Loading