Skip to content

Repository files navigation

@ynode/bootify

Copyright (c) 2026 Michael Welter me@mikinho.com

npm version License: MIT

A Fastify bootstrap plugin that incorporates standardized @ynode patterns for clustering, configuration, and lifecycle management.

Purpose

@ynode/bootify eliminates the boilerplate code typically found in the entry points of @ynode applications. It consolidates:

  • Cluster Management: Automatically handles master/worker process forks using @ynode/cluster.
  • Signal Handling: Manages supported graceful shutdown signals (SIGINT, SIGTERM, SIGQUIT, SIGUSR2) and zero-downtime reloads (SIGHUP) without competing with the cluster primary.
  • Fastify Initialization: Creates the server instance with standard configurations (like proxiable and autoshutdown).

Installation

Requires Node.js 20.19.0 or newer.

npm install @ynode/bootify

Usage

In your main entry file (e.g., src/web.js), simply import bootify and your configuration.

#!/usr/bin/env node

import { bootify } from "@ynode/bootify";
import config from "./config.js"; // Your yargs configuration
import pkg from "../package.json" with { type: "json" };

try {
    await bootify({
        config,
        pkg,
        // Lazy-load your application logic
        app: () => import("./app.js"),
        hooks: {
            onBeforeListen: async ({ fastify }) => {
                fastify.log.info("Preparing to listen...");
            },
            onAfterListen: async ({ address }) => {
                console.log(`Listening at ${address}`);
            },
            onShutdown: async ({ signal }) => {
                console.log(`Shutdown triggered by ${signal}`);
            },
        },
    });
} catch (ex) {
    console.error(ex);
    process.exitCode = 1;
}

Configuration Object (config)

The config object is typically the resolved output of yargs. It supports the following reserved properties:

  • cluster: Configuration for @ynode/cluster (can be a boolean or object). This object is passed through to @ynode/cluster options. When omitted, clustering defaults to enabled; set cluster: false to force single-process mode. Other values are rejected after the optional configuration validator runs.
  • environment: Optional environment label included in the startup listen message.
  • pidfile: Path to write the PID file (optional).
  • http2: Enable HTTP/2 support (boolean).
  • trustProxy: Forwarded/real client IP trust setting passed directly to Fastify trustProxy.
  • rewrite: An object map for URL rewriting. Keys are exact request paths and values must be non-empty absolute internal paths; malformed, external, relative, whitespace-containing, and fragment targets are rejected at startup. When a rewrite target carries its own query string, the request's query string is merged into it ({"/a": "/b?x=1"} + /a?y=2/b?x=1&y=2).
  • sleep: An inactivity period in seconds or an idle-only @ynode/autoshutdown options object such as { sleep: 1800, grace: 30, jitter: 5, closeTimeout: 10000 }. Idle shutdown only applies to cluster workers; with cluster: false the option is validated but has no effect, and Bootify logs a warning at startup.
  • listen: The binding address can be a number (3000), a string (e.g., "3000", "127.0.0.1:8080", "[::1]:8080"), or a Unix socket path string. You can also pass an object like { port: 3000, host: "0.0.0.0" } or { path: "/tmp/app.sock" }.
  • listenRetry: Optional startup retry policy { retries?: number, delay?: number }. Defaults to { retries: 5, delay: 15000 }.

With @ynode/cluster 1.4.0+, you can configure TTY command mode and reload commands via cluster.tty. Starting with @ynode/cluster 1.8.0+, @ynode/bootify automatically intercepts and responds to the built-in telemetry queries (/status, /ping, /version) without any additional boilerplate.

The older top-level tty option remains supported for compatibility, but new applications should use config.cluster.tty.

For example:

cluster: {
  enabled: true,
  tty: {
    enabled: true,
    commands: true,
    reloadCommand: "/rl"
  }
}

Workers also expose the current pool metadata as Fastify decorations: clusterCount (active workers, including 0 while shutdown drains the pool), clusterMinWorkers, clusterMaxWorkers, and clusterMode. Cluster count broadcasts include these values after worker, scale, reload, and retirement transitions.

Bootify deliberately owns the boundary between Autoshutdown and Cluster:

  • config.sleep may configure sleep, grace, ignoreUrls, ignore, jitter, force, hookTimeout, closeTimeout, onShutdownStart, and onShutdownComplete.
  • Worker exitProcess is always enabled so a closed worker cannot remain connected and count as healthy capacity.
  • reportLoad, heartbeatInterval, and memoryLimit are rejected in config.sleep. Configure load and memory policy through config.cluster so Cluster is the sole heartbeat, retirement, and replacement owner.
  • Unsupported nested keys fail before Bootify forks workers, preventing crash loops caused by configuration typos.

Production Configuration Example

For a production deployment behind a reverse proxy, combine trustProxy, explicit listen, and a bounded listenRetry policy:

{
  trustProxy: true,
  listen: { host: "0.0.0.0", port: 8080, backlog: 511 },
  listenRetry: { retries: 8, delay: 5000 }
}
  • trustProxy: true ensures request.ip respects forwarded headers.
  • Explicit listen avoids accidental ephemeral port binding.
  • listenRetry helps absorb short dependency/network startup windows.

Unix Domain Sockets & proxiable

bootify applies proxiable to the raw server instance. For Unix Domain Socket listeners such as "/tmp/app.sock" or { path: "/tmp/app.sock" }, it removes orphaned socket files before binding, makes the bound socket proxy-accessible, and ensures the socket is unlinked during process cleanup. TCP listeners are unaffected.

API

bootify(options)

Initializes the application lifecycle. bootify validates option shapes early and throws TypeError for invalid input.

Options

Property Type Description
app Function A function called as app(fastify, config) that returns either a Fastify plugin or module with default; invalid returns throw a TypeError.
config Object The configuration object (usually from argv).
pkg Object Optional parsed content of package.json (auto-loaded from process.cwd() when omitted).
validator Function Optional function to validate config before starting.
hooks Object Optional lifecycle hooks: onBeforeListen, onAfterListen, and onShutdown.
tty Object Backward-compatible top-level Cluster TTY options; prefer config.cluster.tty.

Hook Contexts

  • onBeforeListen(context): Receives { fastify, config, pkg }.
  • onAfterListen(context): Receives { fastify, config, pkg, address }.
  • onShutdown(context): Receives { fastify, config, pkg, signal } and runs exactly once for signal, reload, startup-cleanup, idle-Autoshutdown, and direct Fastify-close paths. Non-signal triggers include idle_timer, startup-error, and fastify-close.

Every hook context also includes lifecycle, the same public lifecycle handle exposed to application code as fastify.bootify.

Runtime Lifecycle Handle

fastify.bootify is available before the application factory runs and is also exposed as context.lifecycle in every Bootify hook. It does not change bootify()'s existing void | BootifyManager return contract.

Member Type Behavior
phase "starting" | "listening" | "shutting-down" | "closed" Live read-only lifecycle phase.
address string | null Bound address after listen succeeds; retained after close for diagnostics.
shutdownSignal AbortSignal Aborts exactly once when shutdown begins, before onShutdown runs.
shutdown(trigger?) Promise<void> Starts Bootify's bounded, once-only shutdown path. The default trigger is "programmatic"; custom triggers must be non-empty strings.
export default async function application(fastify) {
    fastify.bootify.shutdownSignal.addEventListener("abort", () => {
        queueConsumer.stopAcceptingWork();
    });

    // Trigger shutdown from a control channel that is not part of the HTTP
    // workload Fastify must drain.
    controlChannel.once("shutdown", () => {
        void fastify.bootify.shutdown("control-channel").catch((err) => {
            fastify.log.error({ err }, "Programmatic shutdown failed");
        });
    });
}

Concurrent shutdown requests join the same underlying close and worker-disconnect sequence, and onShutdown still runs exactly once with the first trigger. In cluster workers, a successful programmatic shutdown disconnects the worker after Fastify closes; in single-process mode it closes Fastify without calling process.exit().

Do not await shutdown() from an HTTP request that the same Fastify instance must drain: fastify.close() waits for that request to finish, so the request and shutdown would wait on each other until the configured shutdown timeout. Finish the response first and trigger shutdown after the request settles, or use a process/control channel as above.

Return Value

bootify(options) resolves to one of:

  • void: when clustering is disabled or executing in a worker process.
  • BootifyManager: when running as clustered master.
  • BootifyManager.reload(): Promise<void> for zero-downtime reload.
  • BootifyManager.getMetrics() for cluster worker/load metrics.
  • BootifyManager.close(): Promise<void> for programmatic cluster shutdown.
  • BootifyManager.on/once/off(...) for cluster lifecycle events.

Signal and Shutdown Semantics

In clustered mode, @ynode/cluster is the sole primary-process owner of supported SIGINT, SIGTERM, and SIGQUIT signals. Bootify workers run onShutdown exactly once, close Fastify, disconnect from the primary, and exit. Idle Autoshutdown uses Node's voluntary worker disconnect semantics, allowing a smart pool to shrink without being treated as a crash. A worker shutdown that exceeds config.cluster.shutdownTimeout exits non-zero so the primary can complete its bounded escalation.

Cluster-initiated worker retirement, including zero-downtime reload, closes all HTTP connections before Fastify enters closing state so clients reconnect to a healthy replacement worker instead of reusing a retiring worker that may return 5xx responses. Direct OS-signal shutdowns use the gentler idle-connection drain path so active responses can complete when the whole service is stopping.

SIGQUIT now performs graceful shutdown. Applications that need a core dump should invoke process.abort() explicitly from an operationally controlled path rather than installing a second handler for the same signal.

Calling BootifyManager.close() also removes Bootify's process-level SIGHUP and exit listeners, preventing reload requests after programmatic shutdown has begun.

Startup Semantics

bootify uses a process-level startup state machine:

  • idle: no startup attempt is active.
  • starting: a startup attempt is in progress.
  • started: startup succeeded and the process is now locked to a single boot lifecycle.

Behavior:

  • A second call while starting throws bootify() is already starting in this process.
  • A call after successful startup (started) throws bootify() can only be called once per process.
  • If startup fails, state is reset back to idle and a later retry is allowed.
  • Startup cleanup is bounded by config.cluster.shutdownTimeout. A shutdown received during a listen retry cancels the pending delay and prevents another listen attempt.

License

This project is licensed under the MIT License.

About

A standardized Fastify application bootstrapper with built-in cluster management, graceful shutdown, and configuration wiring for the @ynode ecosystem.

Resources

Contributing

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages