Skip to content

Releases

v0.3.1

Choose a tag to compare

@github-actions github-actions released this 01 Dec 10:29
0780f44

Added

  • The pharn.dev link says how much traffic each commit served, so "no errors since the deploy" can
    be told from "no requests since the deploy" (CORE-527). Each interval's request now carries an
    optional traffic list: per commit, requests (spans the collector received, one per incoming
    HTTP request) and dropped (spans the agent dropped), with lowerBound: true when dropped is
    above 0. Counts only: no path, method or status. A commit that served requests and raised no
    error is still sent, once per interval, with an empty groups list; a process with no request
    data (no HTTP, or none in the interval) sends no traffic entry rather than 0. Counted in
    phargus serve from the spans and drop counters the agent already writes: no new work in the
    agent. docs/schema/production-errors.v1.json stays version 1: traffic is optional and
    groups may now be empty. New types PharnPayloadTraffic and PharnTrafficInput;
    buildPharnPayload takes the counts as an optional third argument.

  • A Next.js server error's frames can be mapped inside the function that threw (CORE-550). Next
    writes a .map next to every server chunk, but output: 'standalone' and a Vercel function leave
    them out; addNextServerSourceMapsToTraces(distDir), run from next.config's
    compiler.runAfterProductionCompile, adds each traced chunk's map to Next's file traces and strips
    its sourcesContent. mapErrorFramesInProcess(frames) then maps frames in the calling process
    (no worker pool, no phargus serve) to the repository path and line, and leaves a frame it cannot
    map at its built position with unmapped: true; reportNextError now maps its frames with it, so
    an error sent from a function names lib/thrower.ts and its line. Both are new exports of
    @pharn-dev/phargus/analyzer, with DEFAULT_MAX_IN_PROCESS_MAP_BYTES (8 MiB). Checked on Next.js
    16.4.6 under output: 'standalone' and on a Vercel preview deployment (docs/LIMITS.md section 8).

  • A Next.js error on a serverless function reaches pharn.dev. reportNextError(error, request, context) from @pharn-dev/phargus/pharn, called in onRequestError in instrumentation.ts,
    builds the allow-listed payload for that one error and starts one request without making the
    hook wait: the promise goes to the platform's waitUntil (@vercel/request-context, no
    dependency), else it runs on its own with a 5 s timeout, so a route handler's 500 is not delayed.
    It reads PHARGUS_PHARN_KEY (no key: nothing sent, no fetch), takes the commit from
    VERCEL_GIT_COMMIT_SHA (or PHARGUS_COMMIT), sends frames mapped in-process where the chunk's
    map was shipped and otherwise at their built position flagged unmapped, sends nothing from a
    non-production VERCEL_ENV unless PHARGUS_PHARN_PREVIEW_KEY is set, keeps at most 10 requests in flight, and never throws. It does not need
    @pharn-dev/phargus/agent, so no sampler or request tracing starts. examples/nextjs-app/serverless
    is a real Next.js 16 app showing it, installed on its own.

  • An optional link sends error groups to pharn.dev. It is off until a key is set: phargus serve
    reads PHARGUS_PHARN_KEY (and PHARGUS_PHARN_URL for a test intake) from the environment, and
    the agent ignores both. Every 10 seconds it sends one request with the errors seen since the last,
    grouped by signature: per group the class, code, origin, frames (repository-relative path, line,
    column, function, and unmapped; a frame that is not in-app is sent with its function name
    only), commit, count, first and last seen, and once the Node.js version. Never the message, stack
    text, request paths or absolute paths: the payload is built from an allow-list and matches
    docs/schema/production-errors.v1.json, the schema pharn.dev validates. HTTPS only (http: to
    loopback for tests), no redirects, the key only in an Authorization header, a bounded queue with
    retries and backoff, a 5-minute pause after a 401 or 403 (reported once), and pharn.dropped on
    the counts: line. New entry point @pharn-dev/phargus/pharn: createPharnExporter (the
    collector listener), createPharnSender and buildPharnPayload (for an in-process reporter),
    DEFAULT_PHARN_URL. A collector listener can now take an error callback, called for every error
    the collector keeps, not only the 10 a window lists. A test reads the built agent and fails if it
    holds code that opens a connection.

  • An error has a signature that survives a deploy. Every error a collector window lists carries
    signature: v1: and the SHA-256 of its class and the repository path and function name of its
    3 innermost in-app frames, with no line, column, message or code, so an edit above a frame keeps
    it and a renamed function gets a new one. Without in-app frames (a collector with no repository
    root) it falls back to file basenames. A weak signature carries signatureFlags (anonymous,
    unmapped, no-in-app-frames); windows read back from disk get it recomputed. The algorithm is
    specified in docs/API.md so a receiver can recompute it, and docs/LIMITS.md says when two
    bugs merge and one splits. New collector exports: errorSignature, groupErrors (count, first
    and last seen per signature) and types ErrorSignature, ErrorSignatureFlag, ErrorGroup,
    SignableError.

  • Error frames name the source file and line, not the built file. The collector maps each error's
    frames through source maps, off its stream pipeline: createCollector({ symbolizeErrorFrames })
    takes a function, and createErrorFrameSymbolizer({ repoRoot }) from
    @pharn-dev/phargus/analyzer builds one that runs on the symbolization worker, with its caps
    (32 MiB per built file or map by default, DEFAULT_MAX_ERROR_MAP_BYTES) and reads confined to the
    repository root. phargus serve --repo-root <dir> (or PHARGUS_REPO_ROOT) turns it on. Each
    frame then carries inApp, a repository-relative path (in-app frames only: never a full path)
    and, when it could not be mapped, unmapped: true with its built position kept. A map whose
    source lies outside the root is refused, a malformed map costs only its own file's frames, and a
    dependency, a file outside the root or a Node internal frame is inApp: false. A symbolizer
    failure keeps the error with the agent's frames and counts it (collector.symbolization,
    collector.symbolizeFailed on the counts: line). New exports: createErrorFrameSymbolizer,
    DEFAULT_MAX_ERROR_MAP_BYTES, ErrorFrameSymbolizer, ErrorFrameSymbolizerOptions (analyzer),
    and types ErrorFrame, SymbolizeErrorFrames, ErrorSymbolization (collector).

  • captureError(error) (agent) reports an error your application handled: it writes the same
    error line as an uncaught exception, with origin handled and the traceId of the request in
    progress, so a framework's 500 is tied to the error behind it. It accepts any value (a non-Error
    is recorded by its type), never throws, does nothing while the agent is not running, and queues
    the line in the agent's non-blocking output instead of writing it synchronously. At most 10
    handled error lines are written per second; the rest are counted in the sample line's
    dropped.errors (present once above 0), which collector windows keep and the dashboard shows.
    The collector accepts origin handled. docs/API.md and the README give recipes for an Express
    error middleware, a Fastify onError hook and a Next.js onRequestError in instrumentation.ts;
    examples/express-app now reports its GET /error through an Express-shaped error middleware,
    and new examples/fastify-app and examples/nextjs-app cover the other two, without installing
    any framework.

  • Every window and span names the commit its process runs. The agent reads PHARGUS_COMMIT once at
    start, or else the first of VERCEL_GIT_COMMIT_SHA, RENDER_GIT_COMMIT,
    RAILWAY_GIT_COMMIT_SHA, HEROKU_BUILD_COMMIT and HEROKU_SLUG_COMMIT that is set, and writes it
    in one header line ({"type":"header","pid":…,"commit":"…"}) before any other line. A value that
    is not 7 to 40 hexadecimal characters is ignored, counted (commitIgnored) and warned about on
    stderr; the agent never runs git or reads .git, and with no variable set no header line is
    written. The collector attaches the commit to windows and spans (commit), the dashboard header
    shows the short sha or "commit unknown", and OTLP resources carry it as vcs.ref.head.revision.

  • The agent records uncaught exceptions and unhandled rejections. Each one becomes one NDJSON line
    with type: "error": class, code (only when it is letters, digits and _), origin
    (uncaught or rejection), up to 32 frames (file, line, column, function) parsed from
    the stack string, the traceId of the request in progress, pid and timestamp. It is written
    synchronously, so it reaches the output before the process exits. The agent listens on
    uncaughtExceptionMonitor only: whether the process dies, its exit code and its stderr do not
    change. The message is left out unless PHARGUS_ERROR_MESSAGES=1 (config key errorMessages).
    Collector windows carry an errors field (count and the first 10 errors) when they received
    any (each error with the run's commit), persisted windows keep it, and the dashboard lists them. New types: ErrorRecord,
    ErrorFrame, ErrorOrigin (agent), WindowError, WindowErrors (collector).

Fixed

  • A process that was stopped and resumed (SIGSTOP, a paused container, a suspended serverless
    instance) no longer reports the stop as event-loop delay, and an event-loop alert no longer fires
    on every resume. When the time since the agent's previous sample is longer than
    max(5 × PHARGUS_INTERVAL_MS, 1 s), the event loop spent more than half of it idle and the
    process used less CPU time than half of it, the sample carries `...
Read more

v0.3.0

Choose a tag to compare

@github-actions github-actions released this 24 Nov 16:53
e3bb941

Added

  • A file output now has a size bound: PHARGUS_OUTPUT_MAX_BYTES (config key outputMaxBytes,
    default 64 MiB, 0 = no bound). Before a line would take the file past it, the agent renames it
    to <file>.1, replacing an older one, and continues in a new file created with mode 0600, so
    at most twice the bound is on disk and no line is split. Rotation uses asynchronous file calls
    only; a failed rename disables the agent with one [phargus] agent disabled: ... line. Under
    --permission a file output now also needs --allow-fs-write=<file>.1 and
    --allow-fs-read=<file> (see docs/PERMISSIONS.md).
  • PHARGUS_SPAN_BUFFER (config key spanBuffer, 0 to 65536, default 1024) sets how many spans the
    agent keeps per sampling interval; the rest are counted in dropped.spans. 0 turns HTTP
    tracing off and keeps the samplers and the backpressure probe: nothing is patched or subscribed,
    no span line is written, and currentTraceId() returns undefined. The variable is read before
    anything is patched, like PHARGUS_ENABLED; an invalid value disables the agent with a message
    naming it. bench/overhead.mjs has a notrace variant (the agent with PHARGUS_SPAN_BUFFER=0).
  • phargus serve --alert '<metric><op><threshold>[:<windows>]' raises collector alerts from the
    command line, for example --alert 'eventLoop.p99>50ms:3' or --alert 'memory.rssLast>=512MiB'.
    The flag is repeatable, the rule id is its text, and the threshold takes ms/s for time
    metrics and MiB/GiB for memory metrics. Each rule prints one stderr line when it fires and
    one when it resolves, and the dashboard's Alerts panel shows them. A bad rule is a usage error
    (exit 2) that quotes it; an unknown metric lists the valid names.
  • Each dashboard card now shows the recent trend, not only the last value: the page keeps the last
    300 windows it received and draws an inline SVG sparkline of event loop p99, heap used and RSS,
    GC total pause, and backpressure total stall, labelled with the line's maximum. Sparkline redraws
    are coalesced to one per animation frame, and a reconnect refills the lines from the new replay.
  • The agent's drop counters now reach the user: each collector window carries
    dropped: { samples, spans } from its last sample (missing or malformed counts as 0; persisted
    windows without the field restore with zeros), the dashboard header shows "agent dropped N
    samples, M spans" when either is above 0 and the waterfall notes that older requests may be
    missing, and the counts: line of phargus serve adds agent.droppedSamples and
    agent.droppedSpans. OTLP metrics are unchanged.
  • Collector windows now keep where writes stalled: backpressure.hotspots holds the top 5 call
    sites by total stall, merged by site across the window's samples (at most 64 distinct sites
    tracked per window, sites cut to 256 characters). A sample with missing or malformed hotspots
    still counts. Persisted windows carry the field (older lines restore with an empty list), and
    the dashboard has a Backpressure section with the latest window's stalls and call sites. OTLP
    metrics are unchanged.
  • The dashboard says when its data is stale: each card shows the end time of the window on
    display, and after max(3 × window length, 5 s) without a new window the status reads
    stale: no data for N s (counting up, in the error style) until the next window arrives. A
    disconnected stream still shows reconnecting. docs/LIMITS.md §2 explains why the figures are
    one window behind.
  • phargus serve now passes the app's own output through: when reading stdin, every line that
    is not agent data (plain text and JSON log lines) is written to its stdout in input order,
    instead of disappearing. --no-passthrough turns it off; a file input never echoes. Output is
    bounded at 1 MiB waiting (further lines are dropped and counted as passthrough.dropped), and
    a closed stdout stops the passthrough with one stderr line. createNdjsonDecoder gets
    agentOnly: true, which skips non-agent JSON objects as foreign (a new counter and
    onSkipped reason with the raw line); the counts: line gains decoder.foreign and
    passthrough.dropped.
  • A request that closes before its response finishes (client disconnect, res.destroy(), a
    timeout) now leaves a span with aborted: true; the dashboard waterfall shows it as an error
    marked "aborted", and OTLP export sets its status to error.
  • A request that continues a W3C traceparent now keeps its parent-id: the span line carries it
    as parentSpanId (lowercased), and OTLP export sets the span's parentSpanId, so the span is
    no longer exported as a root. Spans of requests without a valid header have no parentSpanId.

Changed

  • The agent's sample line no longer carries heapSpaces (V8 heap space statistics): nothing in
    the collector, dashboard, OTLP export or CLI reads it, and it was about 1.6 KB of a 2 KB line. A
    line with no backpressure hotspots is now about 450 bytes. sampleHeapSpaces() is still
    exported with the same shape, and the collector still accepts lines from older agents that
    carry the field.
  • A window persistence failure (restore, append or compaction) no longer rejects
    collector.consume() or stops the pipeline: it is counted in collector.persistence.failed and
    reported as one PhargusPersistenceWarning per run of consecutive failures, and windows and
    alerts carry on. persist.maxBytes now caps the file: compaction keeps the newest windows that
    fit in half of it, so the file is rewritten rarely. Compaction writes <file>.compact.tmp, so
    grant --allow-fs-write for that path too (docs/PERMISSIONS.md).
  • The collector no longer adds samples from several processes on one stream (a node:cluster
    app, forked children) into one window: each consume() run follows the first sample pid it
    sees, skips samples from other processes as the new IgnoredReason other-process (counted in
    collector.ignored, passed to onIgnored), and emits one process warning saying how many
    other processes it skipped. Samples without a pid and all spans are kept as before.
  • One bounded drop-oldest queue (src/agent/bounded-queue.ts) now serves the agent exporter, the
    collector's ring buffers and persistence queue, the dashboard's SSE client and the OTLP batch
    queue, replacing four separate implementations. It grows to its capacity on demand, so a large
    bound costs nothing until used. createRingBuffer keeps its type and behaviour.
  • summarizeHeapSnapshot, diffHeapSnapshots and symbolizeStackFrames no longer re-check the
    shape of their worker's reply; the inputs are still checked before any worker runs. The pool
    option is meant for a pool from createHeapSnapshotPool() or createSymbolizationPool(): a pool
    running some other worker now gets that worker's reply back as is.
  • An OTLP batch that cannot be encoded now fails as a whole: it counts as one failed batch and all
    its items in failedItems, reported once through onError. The exporters no longer re-encode
    item by item to send the rest, since the collector already rejects malformed spans. The metrics
    and trace exporters now share one implementation; their options, counters and types are
    unchanged.
  • WindowStore.append() (from createWindowStore) no longer queues overlapping calls: call it
    again only once the previous call settled. The collector's persistence queue already appends one
    window at a time. release() and close() close the file once a pending write finishes. The
    collector now validates windowMs and the alert rules once, in createCollector, instead of on
    every consume().
  • The agent's prototype patches (write on Writable, Duplex and OutgoingMessage, emit on
    the HTTP and HTTPS Server) are installed once and never removed. When the agent disables
    itself they stay in place and are inert: they call the original with the same this and
    arguments and return its result, so a wrapper another library installed on top keeps working.
    The globalThis registries that let an ESM and a CJS copy share one set of wrappers, the
    identity-guarded restore and the peeling of dead wrapper layers are gone: only the copy that
    starts the agent patches, and the start-once flag is the agent's only globalThis entry.
  • Tests: the integration suites share one harness, test/support.ts, and npm test builds
    dist/ once per run in a Vitest global setup when it is older than src/. The cross-process
    build lock each suite carried is gone. Test files, test names and assertions are unchanged.

Removed

  • Breaking: createSinks, SinkConfig and SinkInput are gone from
    @pharn-dev/phargus/collector, and the collector's sinks option takes ready sinks only, built
    with createStdoutSink, createFileSink or createWebhookSink. A configuration object in
    sinks now throws a TypeError from createCollector that names the factory to use. Pass
    onError to the factory for a sink's delivery failures; onSinkError still sees a send() that
    rejects or a close() that fails. Before and after:

    // before
    createCollector({ windowMs, capacity, sinks: [{ type: 'webhook', url }] });
    // after
    createCollector({ windowMs, capacity, sinks: [createWebhookSink({ url })] });
  • Breaking: the deprecated dashboard login link /?token=<token> is gone, along with its
    PHARGUS_DEP_TOKEN_QUERY warning. A ?token= query is no longer a credential: GET /?token=…
    answers 401 and sets no cookie. Open /login#token=<token> in a browser, or send
    Authorization: Bearer <token>.

  • Breaking: @pharn-dev/phargus/agent no longer exports the agent's own wiring, configuration
    and permission internals. Importing the subpath starts the agent, so these were never safe to use
    next to it (a second controller doubles the observers; `createNdjsonExport...

Read more

v0.2.1

Choose a tag to compare

@github-actions github-actions released this 08 Nov 20:10
74be187

Fixed

  • The backpressure probe no longer double-counts a stall on http.ServerResponse and
    http.ClientRequest. On newer Node releases the message flushes to its underlying socket after
    write() returns, outside the synchronous window the probe's wrapper suppresses, so the probe
    started a second, separate stall for that socket even though it was the same write already
    tracked as a stall on the message. createBackpressureProbe now recognizes a socket covered by
    an open stall on its _httpMessage and skips observing it, so one slow write is reported once.

v0.2.0

Choose a tag to compare

@github-actions github-actions released this 19 Oct 07:28
08d736f

Security

  • Behavior change: symbolizeStackFrames now confines reads to the working directory when roots
    is left out. Frames whose built file or source map lies outside the working directory are no
    longer read; they come back unchanged unless you pass roots naming the directories to read
    from, or roots: null for the old unconfined behavior.
  • Dashboard login no longer puts the token in a request line. Open /login#token=<token>: the
    token is in the URL fragment, which the browser never sends; the public login page removes it
    from the address bar and history, then posts it as JSON to the new POST /session (4096-byte
    cap, JSON only, constant-time compare), which answers 204 with the same HttpOnly,
    SameSite=Strict session cookie, or 401 with none. phargus serve and the dashboard script
    now point at this link. /?token=<token> still works but is deprecated and will be removed in a
    later release; the first use emits a PHARGUS_DEP_TOKEN_QUERY deprecation warning.

Added

  • PHARGUS_CONFIG pins the agent's config file. When set, the agent loads exactly that .json
    or .js file (a relative path resolves against the working directory) and does not look for
    phargus.config.json or phargus.config.js there. An empty value, a missing or unreadable
    file, something that is not a regular file, or any other extension rejects with a
    PhargusConfigError naming PHARGUS_CONFIG, and never falls back to the working-directory
    lookup. docs/THREAT-MODEL.md gains row I1 for the config file as code-execution surface.

  • phargus serve, a command-line way to get the dashboard without writing a collector. The
    package now has a bin, so node --import @pharn-dev/phargus/agent app.mjs | npx phargus serve
    reads the agent's NDJSON from stdin (or -), replays a capture file given as an argument,
    aggregates it into windows and serves the dashboard. Flags: --port (default 7070), --host
    (default 127.0.0.1), --token, --window-ms (default 1000) and --max-line-bytes, plus
    --help and --version. PHARGUS_TOKEN supplies the token, and a non-loopback --host
    without one is refused with exit code 2 before anything binds. Diagnostics go to stderr only:
    the dashboard URL, an input-ended line and a counts: line (decoder.invalid,
    decoder.oversized, collector.ignored, dashboard.droppedEvents). The server keeps running
    after the input ends. SIGINT and SIGTERM close the server and the collector and exit 0; a stuck
    shutdown is forced out with exit code 1 after 5 seconds. Exit codes: 0 success, 1 runtime error
    (unreadable file, port in use), 2 usage error. Errors print without a stack unless
    PHARGUS_DEBUG is set. The CLI is ESM-only and is not an exports subpath.
    @pharn-dev/phargus/dashboard now also exports isLoopbackHost. npm run check:exports,
    check:package and check:install verify the bin.

  • phargus serve --allowed-host <host>, repeatable, passed to the dashboard's allowedHosts.
    It lets a browser reach a server bound with --host 0.0.0.0 (for example in a container) by
    IP or hostname instead of getting 421. A bare name matches on any port; host:port matches
    exactly. An empty value, or one with whitespace or /, is a usage error (exit code 2). It does
    not lift the token requirement for a non-loopback --host.

  • Webhook alert sinks take an optional headers option, for example
    { authorization: 'Bearer …' }, sent with every request (review finding F23). It works on
    createWebhookSink and on a { type: 'webhook' } sink config. Headers are copied and checked
    when the sink is created: a name must be an HTTP token, a value must be a string with no control
    characters (tab aside) and nothing above U+00FF, and the same name twice in different case is
    rejected. content-type is reserved for the sink's own application/json, so supplying it is a
    TypeError rather than a silent override. __proto__ is rejected too, because Node's fetch
    drops it. Errors name the header, never its value.

  • OTLP metrics export (@pharn-dev/phargus/otel) now carries every window field (review finding
    F22). New gauges phargus.gc.pause.max and phargus.backpressure.stall.max (ns); new delta
    monotonic sums phargus.gc.pause.total and phargus.backpressure.stall.total (ns),
    phargus.backpressure.events ({event}), phargus.window.samples and
    phargus.window.late_samples ({sample}, from the window's count and late). The metrics
    resource now carries service.instance.id, host.name and process.pid beside
    service.name, so several instances no longer merge into one series. service.instance.id
    defaults to a random UUID generated once per process; the new serviceInstanceId option on
    createOtlpMetricsExporter and toOtlpMetrics overrides it, and an empty or non-string value
    throws a TypeError. The trace exporter is unchanged.

  • docs/API.md, a reference of every supported export per subpath. npm run check:exports now
    also compares each subpath's runtime export names with an exact expected list, through import
    and require, and fails on a name added or missing.

Fixed

  • Lower memory cost of HTTP tracing under load. The tracer's span buffer kept each of its 1024
    most recent spans as an object plus four strings, and under load each lived long enough to be
    promoted by V8 and die in the old generation (about 3× the agent-off promotion rate on a
    promise-heavy server, and about 25 MiB more RSS after a minute). Spans are now stored as bytes
    in preallocated slots, which take about 280 KiB for the default 1024 spans. Promotion and
    steady-state RSS now match the agent-off run. What is buffered, dropped and exported is
    unchanged.
  • Lower per-request CPU cost of HTTP tracing. Trace and span ids are now cut from a 4 KiB buffer
    of CSPRNG bytes refilled as it runs out, instead of one randomBytes() call (and Buffer) per
    id; a CPU profile of the overhead benchmark put those calls at about 16% of the busy time of a
    traced server. Ids keep their format (lowercase hex, never all zeros) and no byte is used twice.
  • The dashboard no longer reports a normal SSE client disconnect as a server error. A write to a
    connection the client had already closed (EPIPE) is now treated like ECONNRESET: the client
    is cleaned up and onError (or the process warning) is not called. Other errors on an SSE
    response or socket are still reported, and cleanup stays idempotent.
  • summarizeHeapSnapshot and diffHeapSnapshots (@pharn-dev/phargus/analyzer) no longer time
    out on large snapshots within a raised maxSnapshotBytes (review finding F27). The task timeout
    is now max(30 s, size / 20 MB/s), summed over both files for a diff, computed by the new
    heapSnapshotTimeoutMs(bytes) export. It applies when no timeoutMs is passed and the pool is
    the one the call makes or one from createHeapSnapshotPool() without taskTimeoutMs. An
    explicit timeoutMs always wins, and a pool made with taskTimeoutMs, createWorkerPool or
    anything else keeps its own timeout. At the default 256 MiB cap the timeout stays 30 s.
  • Collector persistence no longer backpressures consume() (review finding F25). A slow disk used
    to hold every window up behind the append, all the way back to the source. Windows now go
    through a bounded queue and are appended one at a time, in emission order, off the pipeline.
    persist.maxQueueSize sets how many wait (default 1024); it must be a positive safe integer,
    or createCollector throws a RangeError. When the queue is full the oldest window is dropped.
    collector.persistence.dropped counts those drops and collector.persistence.failed counts
    windows whose append failed (both integers). A failed append still rejects consume() with the
    append error, now without waiting for the source to end. close() and the end of consume()
    wait for the queue to drain, with no time limit, so a disk that never completes an append
    stalls close(). close() stops accepting windows before it drains, so a consume() still
    running cannot hold it open; a window that arrives after it is counted in failed.
  • OTLP exporters (@pharn-dev/phargus/otel) no longer lose spans and windows under load (review
    finding F2). They used to send one request per exported span or window, with one request in
    flight, and silently dropped the newest batch once 64 were queued. They now batch: pending
    items go out in one request when maxBatchSize (default 512) items are pending or after
    flushIntervalMs (default 1000 ms), one request at a time. At most maxQueueSize (default 2048) items are held; when full, the OLDEST pending items are dropped, counted and reported
    through onError as aggregated "dropped" reports. New counters droppedItems, exportedItems
    and failedItems sit beside droppedBatches and failedBatches. The flush timer is
    unref()ed and armed only while items are pending. A record that cannot be encoded fails only
    itself. Behaviour change: one export call is no longer one request, and the first send waits up
    to flushIntervalMs unless a full batch is pending; call close() or flush() before exit.
    queueCapacity is deprecated: still accepted and validated, but it no longer bounds anything
    (the queue holds items, not batches); use maxQueueSize.
  • Dashboard: a client that connects to /events now receives the collector's whole history
    (every buffered alert, window and span) instead of losing part of it to the live-event drop
    queue; with full buffers it previously got no alerts and a truncated window history. The replay
    is written in one call outside that queue, alerts first, then windows, then spans.
    maxBufferedEvents and droppedEvents now cover live events only.
  • Dashboard: a request whose Host is not allowed still gets 421, but now with a short
    text/plain body...
Read more

v0.1.0

Choose a tag to compare

@PrzemekGalarowicz PrzemekGalarowicz released this 12 Oct 12:53
819a795

First release of Phargus (@pharn-dev/phargus).

Added

  • Release preparation workflow that validates a tarball without publishing, with explicit opt-in for later GitHub Release publishing.
  • Installed-package checks for ESM/CJS imports and types, analyzer workers, plugin sandbox, and the agent → collector → dashboard SSE flow.
  • Single npm package with subpath exports, built as both ESM and CommonJS.
  • Open-source baseline: README.md, SECURITY.md, CODE_OF_CONDUCT.md, docs/THREAT-MODEL.md, docs/LIMITS.md, issue and pull request templates.
  • CI: format, lint, typecheck, test, build, action-pin checks, CodeQL and gitleaks.
  • Manual release process with npm Trusted Publishing and provenance.
  • Agent: event loop delay and memory samplers driven by a sampler controller.
  • Agent: NDJSON export stream with bounded, drop-oldest backpressure, to stdout or a file.
  • Agent: configuration from PHARGUS_* environment variables and phargus.config.{js,json}.
  • Agent: GC sampler (count and pause times by kind) from PerformanceObserver.
  • Agent: stream backpressure probe that reports stalled writes by call site.
  • Agent: require('@pharn-dev/phargus/agent') / import '@pharn-dev/phargus/agent' (or --require/--import) starts the agent once per process.
  • Agent: automatic trace id per incoming node:http/node:https request through AsyncLocalStorage, honouring an incoming W3C traceparent; currentTraceId().
  • Agent: V8 heap space statistics in every sample and on-demand heap snapshots (takeHeapSnapshot).
  • Agent: on-demand allocation sampling through the inspector (sampleAllocations).
  • Agent: a parser for node --trace-deopt output (createDeoptParser). It does not capture the output itself.
  • Agent: runs under the Node permission model; a denied grant disables only that feature with a typed PhargusPermissionError; isPermissionModelEnabled() and checkPermission().
  • Agent: HTTP spans exported as NDJSON lines next to samples.
  • Collector (@pharn-dev/phargus/collector): fixed time windows with integer math and ring buffers of recent windows, alerts and spans.
  • Collector: window-based alerts with per-metric thresholds.
  • Collector: alert sinks for stdout, a file and a webhook (Node core fetch).
  • Collector: opt-in persistence of recent windows to an append-only file, restored on start.
  • Dashboard (@pharn-dev/phargus/dashboard): SSE server with token gating for non-loopback binds.
  • Dashboard: vanilla-JS live page with event loop, memory, GC, alerts and a trace waterfall of recent requests.
  • Analyzer (@pharn-dev/phargus/analyzer): Worker Thread pool with heap-snapshot summaries and diffs.
  • Analyzer: source-map stack-trace symbolization on the worker pool.
  • Plugin runner (@pharn-dev/phargus/plugin-runner): user rules in an isolated-vm sandbox in a child process, with a memory limit and a timeout.
  • Plugin runner: built-in rules (event loop lag, GC pause share, heap growth) and loadRulesDirectory.
  • OpenTelemetry (@pharn-dev/phargus/otel): opt-in OTLP/HTTP JSON export of windows as metrics and spans as traces.
  • Examples: examples/express-app (agent in the app, collector and dashboard in a second process) and examples/worker-pool.
  • Agent: every sample line carries cumulative dropped: { samples, spans } loss counters.
  • Agent: createDeoptParser({ maxEvents, maxLineLength }) and droppedEvents().
  • Agent: createSamplerController(onSample, { onError }); new PhargusSamplerWarning and PhargusBackpressureWarning process warnings.
  • Dashboard: allowedHosts option for names the dashboard is reached by (reverse proxy, container port mapping).
  • Collector and OpenTelemetry: closeTimeoutMs option on the webhook sink and the OTLP exporters; WindowStore.close().
  • Analyzer: maxSnapshotBytes option (default 256 MiB) and HeapSnapshotTooLargeError (ERR_HEAP_SNAPSHOT_TOO_LARGE); DEFAULT_RESOURCE_LIMITS, DEFAULT_MAX_SNAPSHOT_BYTES.
  • Analyzer: symbolizer roots option (reads confined by realpath) and maxFileBytes (default 64 MiB); DEFAULT_MAX_SOURCE_FILE_BYTES.
  • Plugin runner: maxFindings (default 10 000) and maxResultBytes (default 1 MiB) options.
  • bench/overhead.mjs (agent-on versus agent-off benchmark), bench/soak.mjs (leak checks under load) and a nightly workflow that runs both.
  • CI: npm run check:package in the Build job checks the tarball contents and that engines.node matches .nvmrc.

Changed

  • Renamed the project and npm package to Phargus (@pharn-dev/phargus). Imports and preloads now use @pharn-dev/phargus/<subpath>; configuration uses PHARGUS_* environment variables and phargus.config.{js,json}. Existing integrations must update those names.
  • Renamed public errors and warnings to Phargus*, error codes to PHARGUS_*, built-in rule IDs and OpenTelemetry metric names to phargus/... and phargus.*, and the dashboard session cookie to phargus_token (existing dashboard sessions must sign in again).
  • engines.node is now >=22.18.0, and .nvmrc pins 22.18.0; required CI jobs run on that floor.
  • The package no longer ships declaration maps or the analyzer test fixture; .js.map files embed their sources.
  • Agent: an unknown PHARGUS_* variable prints one warning on stderr and is ignored, instead of disabling the agent.
  • Agent: samples and spans are queued in separate lanes, each bounded by queueBound; sample lines are written first.
  • Agent: the backpressure probe also covers Duplex, Transform, PassThrough, net.Socket, tls.TLSSocket, http.ServerResponse and http.ClientRequest.
  • Agent: an ESM and a CJS copy of the agent share one set of prototype wrappers.
  • Agent: traceparent with an all-zero parent id starts a new trace; versions other than 00 are parsed with the 00 layout.
  • Dashboard: requests whose Host is not allowed get 421; a cross-origin Origin on /events or a non-GET request gets 403.
  • Dashboard: ?token= is accepted only on GET / and exchanged for an HttpOnly, SameSite=Strict cookie; assets and /events take the cookie or Authorization: Bearer.
  • Dashboard: malformed-request warnings are rate-limited to one report plus one summary per 10 s; client resets are not reported.
  • Collector and OpenTelemetry: close() waits at most closeTimeoutMs, then drops queued batches and aborts in-flight requests, counting both.
  • Collector: collector.close() closes the sinks first and latches the window store.
  • Analyzer: every pool worker runs with resourceLimits (default 512 MiB old, 64 MiB young generation).
  • Analyzer: the heap-snapshot worker streams the file; snapshots must list snapshot, nodes and strings in V8's order and have at most 262 144 distinct object names.
  • Analyzer: workers no longer inherit entry-point flags such as --input-type, -e or --inspect.
  • Plugin runner: the sandbox child receives the host's --permission, --experimental-permission and --allow-* flags.

Fixed

  • Agent: requests that arrive while the agent configuration loads are traced.
  • Agent: spans no longer evict metric samples from the output queue under load.
  • Agent: disabling the backpressure probe or tracing never leaves a throwing write or emit behind and never removes a wrapper another library installed later.
  • Agent: the stream write wrappers keep the original arity (write.length === 3).
  • Agent: a throwing onSample callback no longer becomes an uncaught exception.
  • Agent: the deopt parser no longer keeps every event forever.
  • Analyzer: an oversized heap snapshot can no longer abort the host process with a fatal out-of-memory error.
  • Analyzer: a host started with --input-type=module -e can start analyzer workers.
  • Collector: append() after collector.close() no longer reopens the persistence file.
  • Dashboard: a stalled SSE client no longer retains dropped events.

Security

  • Dashboard: Host/Origin allowlist against DNS rebinding.
  • Dashboard: the token no longer appears in page, asset or SSE URLs; the session cookie holds an HMAC of the token, not the token. /events and error responses send nosniff, a default-src 'none' CSP and Referrer-Policy: no-referrer.
  • Collector and OpenTelemetry: webhook and OTLP requests never follow redirects (a 3xx is a failed delivery) and read at most 64 KiB of a response body.
  • Files the agent, the window store and the file alert sink create are mode 0600.
  • Analyzer: symbolizer parse errors no longer quote file content.
  • Plugin runner: rule results are capped in the child and validated on the host; rule error messages are cut to 4 096 characters.