diff --git a/.changeset/node-storage-tracker.md b/.changeset/node-storage-tracker.md new file mode 100644 index 00000000..da1e0076 --- /dev/null +++ b/.changeset/node-storage-tracker.md @@ -0,0 +1,8 @@ +--- +'@bugsee/node': minor +'@bugsee/bun': minor +'@bugsee/deno': minor +'@bugsee/trackers': minor +--- + +The opt-in `captureDiskSpace` traces (`disk_mem_free`, `disk_mem_total`) now come from a per-process `StorageTracker` in the `@bugsee/trackers/node` entry, which takes over the statfs read and its poll from `@bugsee/node`. Trace names, integer-MB wire values, the 5 s cadence and the opt-in behaviour are unchanged: the tracker polls only while the producer is subscribed, reports a failing read once per failure streak, and omits an unreadable or unsane reading instead of reporting a zero. The tracker is shared per data directory: launches over the same directory share one (its `onError` and scheduler are latest-launch-wins), launches over different directories each keep polling their own directory and reporting to their own `onError`. `@bugsee/node` (and so `@bugsee/bun` and `@bugsee/deno`, which re-export it) also exports `storageTrackerFor`, `resetStorageTracker` and the `StorageTracker` type. diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md index 5bc10f56..5a17dbb1 100644 --- a/docs/PROGRESS.md +++ b/docs/PROGRESS.md @@ -413,7 +413,8 @@ solid), in slices: - **TR6 (DONE, `feat/storage-tracker`):** domain **`StorageTracker`** (`packages/trackers/src/browser/storage-tracker.ts`), singleton per window via `createTrackerRegistry` (`storageTrackerFor(env, onError?)`, `resetStorageTracker`; keyed window -> navigator -> env object, `rebind` as PowerTracker). Wraps `navigator.storage.estimate()` + `persisted()`; ONE stage `storageEstimate` `{usageBytes?, quotaBytes?, persisted?}`. This is an ORIGIN quota ESTIMATE (browsers fuzz/pad it), NOT device free space. No change event, so it polls sparsely: on activation, on `visibilitychange` -> visible, then a slow timer (default 5 min via an injectable scheduler; ticks while the page is hidden are skipped). A field that is non-finite/negative/non-number is omitted (never 0); `persisted` only when boolean; an estimate with no usable field emits nothing. A rejected/throwing `estimate()`/`persisted()` is reported via `onError` and costs only its own field (host getters through `hostRead`); launch is never failed. **Retention rule (tested):** the LAST estimate survives the last unsubscribe (`current()` answers at once; a failed poll never erases it); timer and visibility listener do not (released, re-armed on the next subscriber, which also polls afresh). A single epoch counter is bumped by every poll/stop/reset, so a stale in-flight promise (after stop/reset, or superseded by a newer poll) is inert. `rebind` keeps every defined seam (undefined never clobbers) and applies it from the NEXT activation; a tracker that is attached keeps the navigator/document/scheduler it armed (only `onError` changes at once). Visibility-triggered polls are throttled to one per 60 s (`VISIBILITY_MIN_GAP_MS`, injectable `now`); the slow timer is not. Poll failures are reported ONCE per failure streak (reset by a poll without failures, and by `reset()`), not on every tick. A PARTIAL poll (one of `estimate()`/`persisted()` failed) merges: the failed call's retained fields are kept, answered fields replace, and the estimate's age advances only when usage/quota were refreshed. `currentFresh()` returns the retained estimate only while younger than 2x the poll interval (`current()` still returns it regardless). `StorageProducer` (browser `trace-producers.ts`, built after the `sensors:false` gate like the other sensor producers, so a `systemMetricsSampler` replaces it) emits the NEW JS-specific trace `storage_estimate` `{usage, quota}` in integer MB (`bytesToMegabytes`, floored; a missing key is omitted, `persisted` is not a trace) - NOT the Android `disk_mem_*` group. It is held/de-duplicated (`emitIfChanged`) because the poll period (5 min) far exceeds the default 60 s recording window; a non-held value would almost never appear in a report. `StorageProducer.onStart` seeds only from `currentFresh()` (never a snapshot older than 2x the interval). **OWNER DECISION PENDING:** a held polled value cannot be retracted, so after failed polls the last known estimate keeps being re-recorded every `refreshMs`. Alternatives: plain `emit` (the value would rarely land in a 60 s window) or a provider retract/release mechanism (same open question as the TR4 time traces). Usage under 1 MiB floors to 0 MB (an honest floor, not a measurement of zero). Shared by the WebView launch via the browser producers. Launch-level test proves launch goes through `storageTrackerFor` (the window's singleton holds the estimate). - **TR7 (DONE, `feat/environment-tracker`):** domain **`EnvironmentTracker`** (`packages/trackers/src/browser/environment-tracker.ts`), singleton per window via `createTrackerRegistry` (`environmentTrackerFor(env, onError?)`, `resetEnvironmentTracker`; keyed window -> navigator -> env object; `rebind` merges seams, never drops a defined one; a RUNNING tracker whose window/navigator/document/scheduler/interval changed detaches with the OLD seams, swaps in place, then re-attaches; `detectPrivateMode` turned on while running probes at once, turned off drops the result and any in-flight probe). Five stages: `language` `{language?, languages?, previous}` (`navigator.language(s)` + `languagechange`), `timezone` `{timeZone?, utcOffsetMinutes?, previous}` (no browser event, so re-read on a slow injectable timer, default 60 s with hidden-page ticks skipped, and on visibility -> visible; a DST shift is an offset change), `hints` `{cookiesEnabled?, secureContext?, crossOriginIsolated?, serviceWorkerControlled?, automation?, doNotTrack?, globalPrivacyControl?}`, `permissions` `{camera?, microphone?, geolocation?, notifications?, 'idle-detection'?: 'granted'|'denied'|'prompt'}` and `privateMode` `{private: 'yes'|'no'|'unknown', method?}`. `language`/`timezone` are CHANGE-ONLY (the first reading is a silent baseline held in `current()`, because they back `*_changed` events); `hints`/`permissions` are SNAPSHOT stages (first reading + every change); `privateMode` emits when its answer first arrives and when it changes. **Never prompts:** only `navigator.permissions.query()` is called (never requestPermission/getUserMedia/...), only the state STRING is kept, a PermissionStatus `change` refreshes it; a name the browser rejects with TypeError is omitted silently (Firefox does not know `camera`), other rejections are reported once per failure streak. **Private mode** is a HEURISTIC, never a certainty: one method `storage-quota` (`estimate().quota` under 120 MiB -> `yes`, at/over 1 GiB -> `no`, between or unreadable -> `unknown`; Chromium gives incognito a small fixed quota, Safari fuzzes). Omit-never-fabricate everywhere (empty/non-string language, NaN offset, non-boolean hints, unusable permission states are omitted; unknown DNT values omitted). Every host read goes through `hostRead` (a hostile getter costs only its field and is reported), a throwing `onError` never escapes. **Retention rule (tested):** the last language/time zone/hints/permissions/private-mode readings survive the last unsubscribe (and the change-only stages compare a restart against them); DOM listeners (languagechange, visibilitychange, PermissionStatus change), the timer and async work in flight do not (epoch tokens make a stale query/probe inert). **Events (`events.system`, `createBrowserSystemEventsSource`; the WebView launch shares the same source):** `language_changed` `{language?, languages?, previousLanguage?}`, `timezone_changed` `{timezone?, utcOffsetMinutes?, previousTimezone?, previousUtcOffsetMinutes?}`, `private_mode_detected` `{method?}` (ONLY for a `yes`; `no`/`unknown` never produce an event). Event names are free-form in `SystemEvent` (no registry/schema list exists to extend). **Launch option `captureEnvironmentHints`** (canonical `com.bugsee.option.capture.environment-hints`, browser launch only, default TRUE (opt-out), fail-closed boolean: anything but a boolean is OFF and reported) -> tracker `detectPrivateMode`; the WebView launch never enables it. **OWNER DECISION (2026-10-20, binding): private/incognito detection is OPT-OUT, ON by default** (the launch option keeps its name `captureEnvironmentHints`, default TRUE, `false` opts out, an invalid value is OFF and reported); still a tri-state heuristic (`yes`/`no`/`unknown`, method `storage-quota`), never a certainty. The decision covers private mode only, not other sensitive signals. The WebView launch still passes `detectPrivateMode: false` (no launch option there; a WebView's storage quota is not a private-window signal). **Not done / scope notes:** no `displayMode` stage (the UiTracker owns display-mode; `display_mode_changed` will be derived from it later); `hints` and `permissions` are tracker-level only, they have no wire consumer (the environment envelope schema is closed and has no field for them, so language/timezone were NOT added to `environment` either: `platform.locale`/`utc_offset` are still read once at launch by `buildBrowserEnvironment`, and the new events carry the later changes); **hints and permissions are NOT read by default (PR #84 review):** tracker env flags `observeHints` / `queryPermissions` (default false; a change while running re-attaches, turning one off drops its reading and, for permissions, the status listeners and in-flight queries); the browser system-events source passes both `false` explicitly (never inherited from the window's shared tracker), so a launch issues no `permissions.query()` and reads no hints until a real consumer sets them. Launch tests prove launch goes through `environmentTrackerFor` (the window's singleton holds the readings; mutating the source to `new EnvironmentTracker` fails them) and that private mode is ON by default and off with `captureEnvironmentHints: false`; the WebView launch has the same singleton test. **Review round 2:** persistent host-read failures of language/timezone/hints/visibility are reported once per failure streak (a clean run or `reset()` ends it); emitted stage payloads are copies, so a subscriber cannot mutate retained readings; the WebView launch now passes `document` + `scheduler` to the environment source; `resetEnvironmentTracker` is NOT re-exported from `@bugsee/browser` (reach teardown via `environmentTrackerFor(env).reset()`). **Round 3:** a host read that THROWS keeps that field's retained value (language, languages, time zone id, offset, each hint), so a transient failure never yields a fake `language_changed`/`timezone_changed`; `reset()` now drops all subscribers (`removeAllListeners`, as ApplicationTracker does) so the tracker re-activates for the next subscriber; a throwing `PermissionStatus.state` getter is reported once per streak. **Round 4:** per-permission-name streaks; a throwing state read, or a name whose re-query is rejected with a non-TypeError, keeps that name's retained state (a TypeError still omits it). **Round 5:** the browser system-events source subscribes to the tracker with ONE `onAny` (the activation read can emit a change made while the SDK was stopped, so per-stage subscriptions lost the later stages: a zone change alongside a language change vanished); the WebView launch passes `detectPrivateMode: false` explicitly (never inherits ON from an earlier launch on the window); stage payloads copy `previous` as well (a kept field shares its array). **PR review:** `privateMode` is no longer re-emitted on every activation: it emits when the answer first arrives and when it changes, a retained yes/no is not re-probed on a restart or a seam-moving rebind (an `unknown` is retried), and turning detection off then on re-detects; the browser events source always passes `detectPrivateMode` explicitly (omitted = false, never inherited); an answered-but-unusable permission state clears the stale entry (a failed/throwing read still retains it); private-probe getter failures (storage/estimate/quota) are reported once per streak; it stays a heuristic (constrained storage can false-positive). **Per-session delivery:** the tracker outlives sessions and never re-probes a retained yes/no, so the browser events source reads `current().privateMode` right after subscribing and re-emits `private_mode_detected` once for a retained `yes` (never for `no`/`unknown`, and never when this source opted out; the sink-side `detectPrivateMode` guard also covers the retained read). - **TR5 (implemented on `feat/process-tracker`, PR #83; multi-agent review rounds still in progress, one owner decision open — see "Known limit" below):** domain **`ProcessTracker`** (`packages/trackers/src/browser/process-tracker.ts`), singleton per window via `createTrackerRegistry` (`processTrackerFor(env, onError?)`, `resetProcessTracker`; keyed window -> performance -> env object, `rebind` merge-not-drop: a seam change on a RUNNING tracker first detaches every armed stage with the seams it was armed with, then swaps and restarts). It ABSORBS and replaces the per-signal `MemoryTracker` and `MainThreadLagTracker` (files + tests deleted; `MemoryProducer`/`MainThreadLagProducer` now subscribe to it; trace names and wire shapes unchanged). Five stages, each armed ONLY while it has listeners (via the `listenerCount(name)` / `onListenersChanged()` hooks `MultiKeyEmitterBase` already has on `main` from TR2; this PR does not touch the emitter; `start()`/`stop()` do nothing here): `heap` `{used, limit}` (`performance.memory`, polled; a figure that is not a finite non-negative number omits the reading), `mainThreadLag` `{lagMs}` (TIMER DRIFT, algorithm and visible-only gating unchanged: block >= 1 s always shows, shorter that crosses no due tick reads 0, reported once, fresh baseline each visible start), `idle` `{idleMs}` (NEW, ONE `requestIdleCallback` probe per sampling tick, never a loop and at most one in flight, visible pages only, `timeRemaining()` clamped to <= 50 ms; a tick whose callback never runs yields NO sample, never 0; omitted without rIC, e.g. Safari), `userIdle` `{userState: 'active'|'idle', screenState?: 'locked'|'unlocked'}` (NEW, Idle Detection API), `uptime` `{uptimeMs}` (`performance.now()`, omitted without a clock; no trace consumes it yet). **Idle Detection permission rule (binding): the SDK NEVER prompts.** `IdleDetector.requestPermission()` is never called; the detector starts ONLY when `navigator.permissions.query({name:'idle-detection'})` ALREADY reports `granted` (an engine that does not know the name rejects = stage inert, silent). The permission is re-queried on every activation and watched through its `change` event (granted later -> starts; revoked -> aborts and drops the tracker's retained state). Threshold floored at the spec's 60 s; stop aborts via `AbortController`; every async continuation is guarded by its run. **Retention rule (tested):** the last `userIdle` state survives the last unsubscribe (`currentUserIdle()`; `currentUserIdleFresh()`, which `UserIdleProducer` seeds from, answers only once the ARMED stage's detector has PUBLISHED in this run (permission re-confirmed and its `start()` settled; no age bound, a live detector reports changes only) and is undefined while the async permission re-query or `start()` is pending, or after a refusal/revoke; with NO armed stage it serves the state only while younger than 2 detector thresholds, via a new injectable `now` seam defaulting to `Date.now`, mirroring TR6's `currentFresh()`. A revoke while no stage is armed is therefore only noticed by the next activation's re-query (the plain `currentUserIdle()` read keeps the snapshot until then), but it can never seed a held trace); heap is read live; idle/lag/uptime keep nothing (a stale baseline would be a lie); timers, lifecycle subscription, pending probe and detector are released. New JS-specific traces (`BrowserTraceEnv` gains `requestIdleCallback`/`cancelIdleCallback`/`IdleDetector`/`AbortController`, bound/taken from the injected window by `browserTraceEnvFrom`): `main_thread_idle_ms` (ms, polled/not held; built under the same lifecycle gate as lag/fps) and `user_idle_state` (a STRING like `app_state`: `active` | `idle` | `locked`, where a locked screen wins over `userState`; held, de-duplicated; no trace at all unless the permission was already granted). **`user_idle_state` is OPT-IN (review P2; the maintainer's decision, PENDING OWNER CONFIRMATION): the host page's `idle-detection` grant shows only that the page was given the permission, not consent to record and upload idle/locked state. So `createBrowserSystemTraceProducers` builds `UserIdleProducer` only for `BrowserTraceEnv.captureUserIdle === true`, fed by the new browser + WebView launch option `captureUserIdle` (default false, strict boolean: any other value stays off and is reported; local key `com.bugsee.option.browser.capture-user-idle`, exported as `CAPTURE_USER_IDLE_OPTION_KEY`). Even when on, the tracker starts a detector only if the permission ALREADY reports `granted` (the SDK still never prompts). Without the opt-in the permission is not even queried. This applies ONLY to `user_idle_state`; private-mode detection is opt-out by a separate owner decision.** The viewer has no definition for either name yet (generic value block, design §13.3). **Known limit (OWNER DECISION PENDING — no retract mechanism invented):** `user_idle_state` is a HELD trace and the tracker emits nothing when the permission is revoked, so a producer that already published a value keeps having it re-recorded every `refreshMs` until the producer stops (the revoke only drops the tracker's retained copy and so stops NEW seeds; the seed is gated as above). Resolving it needs a decision on a retract/clear signal for held traces (same family as TR6's held `storage_estimate`). Other hardening from review: a hostile `performance.now` getter is reported exactly once in total (the factory reads silently, the tracker reports; only a SUCCESSFUL clock read is memoised per env, a failed one is retried on the next activation); `ProcessTracker.reset()` now drops every listener (like `ApplicationTracker`), so a later listener change cannot re-arm a stage for a gone subscriber; `browserTraceEnvFrom` now hands back stable bound closures per (window, function), so a no-op relaunch no longer restarts armed stages; a non-finite lag baseline omits that tick's `main_thread_lag_ms` instead of sending NaN; the gated teardown always closes the run. Launch-level test proves browser launch goes through `processTrackerFor` (the window's singleton can read the heap through launch's seams); the WebView launch shares the producers. `sensors:false` (a `systemMetricsSampler`) still builds only the battery producer. -- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is a later slice):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Ten **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `availableMemory` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) there is NO CPU start value any more: before, the producer published a microsecond-window noise reading at start (`processPct` 7-43%, never a true share), now the tracker keeps its internal counters but the CPU producer has an empty `baseline()` and `current('cpu')` is undefined until the first tick (as for gc/event-loop-lag/utilization); an unusable core count (`os.cpus()` empty) now omits the cpu sample instead of emitting Infinity/NaN; (6) **seams merge, never drop:** the tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's (it can replace a seam, never shed one), and merely BUILDING a producer set rebinds the shared tracker (including the Bun/Deno default sets built before `...options` in their `launch.ts`); tests must use a private `key` or `resetProcessTracker()` (added to the afterEach of the node, bun, deno and elysia launch tests). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. +- **TR8 part 1 (implemented on `feat/node-process-tracker`; Process only, Storage/disk is part 2 below):** the node/bun/deno **`ProcessTracker`** (`packages/trackers/src/node/process-tracker.ts`, `@bugsee/trackers/node`) ABSORBS and REPLACES `@bugsee/node`'s per-signal `ProcessStatsTracker` (files + tests deleted from `packages/node/src/trackers/`); `gc-observer`, `guarded-event-loop` and `runtime-readers` moved (with their tests) to `packages/trackers/src/node/` unchanged apart from `EventLoopSource` now living beside the histogram source. Singleton per process via the registry (`processTrackerFor(env, onError?)`, key `env.key` else the `process` object; `resetProcessTracker(key?)`); `rebind` merges (defined seams replace, undefined never clobber; an UNCHANGED relaunch restarts nothing; a changed seam tears every armed stage down with the OLD seams, the timer is cleared on the scheduler that armed it, then re-arms on the new ones; latest `onError` wins). Ten **per-stage-activated** stages (one shared unref'd timer exists only while some stage has a listener; each stage's machinery only while it is wanted): `memory`, `systemMemory`, `cpu` `{userDelta, systemDelta, processPct}`, `eventLoop` `{meanMs, maxMs, p99Ms}`, `utilization` `{utilization}`, `gc` `{count, pauseMs, maxPauseMs}`, `v8Heap`, `memoryLimit` `{bytes}`, `availableMemory` `{bytes}`, `uptime` `{seconds}`. Trace names and wire values are unchanged. Honesty rules are unchanged and still tracker-owned: a stage that cannot answer EMITS NOTHING (ELU zeros on Bun/Deno, an unsampled histogram, a blind/refusing GC observer, untrue heap/limit/available readings), and the runtime-identity GATES (`measuresEventLoopDelay`/`measuresV8Heap`/`measuresAvailableMemory`/`measuresGc`) are now tracker env flags that the platform composition roots (`@bugsee/{deno,bun}` via `createNodeSystemTraceProducers`) pass through; an injected source/reader wins over its gate. **Retention rule (stated and tested):** only the resolved seams and the "this runtime refused" memory inside the guarded sources survive the last unsubscribe; the CPU baseline, ELU baseline, histogram, GC interval and the last windowed sample all start FRESH on the next subscription. `current(stage)` reads stateless stages LIVE (guarded, copies) and answers the last emitted sample of a windowed stage (`cpu` is seeded with a zero-length window when it arms, so a producer has a baseline). Hardening: reporter indirection that swallows a throwing `onError`, generation-guarded timer callbacks (a timer whose clear failed never emits), each stage read isolated (one throwing reader drops only itself; a failed CPU read never advances the baseline), a failing source start leaves its stage unarmed (never half-armed, retried on the next listener change/rebind), a timer that cannot be armed unwinds the stages armed for it, one failing stop never strands another, emitted payloads are copies. `@bugsee/node`'s `trace-producers.ts` is now composition only (ten producers, each subscribed to ONE stage; `NodeTraceProducerDeps` = tracker env + `onError`), and `@bugsee/node` re-exports `processTrackerFor`/`resetProcessTracker`/`ProcessTracker` (and drops the `ProcessStatsTracker`/`ProcessStats` exports). **Behaviour notes:** (1) the tracker is one per PROCESS now, so a second producer set / relaunch shares it and its seams are rebound (tests that inject fakes must pass a private `key` or call `resetProcessTracker()`); (2) per-stage activation means the GC observer and the delay histogram exist only while their producer is subscribed (before, they ran whenever any producer was); (3) the ELU baseline is taken when its stage arms (before: when the producers were built), so the first sample no longer spans an idle gap; (4) the activation CPU/baseline read and the poll are per stage, so one failing reader no longer fails the whole poll (before: an `uptime` failure dropped the whole row); (5) there is NO CPU start value any more: before, the producer published a microsecond-window noise reading at start (`processPct` 7-43%, never a true share), now the tracker keeps its internal counters but the CPU producer has an empty `baseline()` and `current('cpu')` is undefined until the first tick (as for gc/event-loop-lag/utilization); an unusable core count (`os.cpus()` empty) now omits the cpu sample instead of emitting Infinity/NaN; (6) **seams merge, never drop:** the tracker outlives launches, so a later launch that omits `scheduler`/`onError`/a reader KEEPS the previous launch's (it can replace a seam, never shed one), and merely BUILDING a producer set rebinds the shared tracker (including the Bun/Deno default sets built before `...options` in their `launch.ts`); tests must use a private `key` or `resetProcessTracker()` (added to the afterEach of the node, bun, deno and elysia launch tests). **Tooling:** `@bugsee/trackers` gained `@types/node` (devDependency) and `tsconfig.json` now carries `types: ["node"]` for `src/node`; `tsconfig.portable.json` re-typechecks the portable root + browser entries WITHOUT node types (`pnpm typecheck` runs both) so a node global cannot leak into code shipped to browsers. `@bugsee/node` gained the `@bugsee/trackers` workspace dependency. Launch tests prove the default producers go through the registry accessor (mutating the producer factory to `new ProcessTracker` fails them) and that the Bun/Deno gates reach the shared tracker end to end. +- **TR8 part 2 (implemented on `feat/node-storage-tracker`; Storage/disk):** the node/bun/deno **`StorageTracker`** (`packages/trackers/src/node/storage-tracker.ts`, `@bugsee/trackers/node`) ABSORBS the statfs polling of `@bugsee/node`'s `disk-space-producer.ts`, which is now composition only (one `StorageTracker` stage `disk` -> `disk_mem_free`/`disk_mem_total`; the old timer/streak/generation machinery and its tests were deleted; the producer tests were rewritten over the tracker). Singleton per VOLUME IDENTITY (`storageTrackerFor(env, onError?)`; key = the interned RESOLVED data dir, so launches over the same dir share one tracker and launches over different dirs get different ones; an explicit `env.key` overrides (tests); no data dir -> the shared inert `process`-keyed tracker; `resetStorageTracker(key?: object | dir)` drops one, no argument drops all). ONE stage, `disk` `{freeBytes, totalBytes}` (bytes; the producer converts to integer binary MB with `bytesToMegabytes`, free then total, `hold:false`, so a failing statfs leaves a gap). Activation is by listener: the first listener reads the data dir's volume at once and arms an unref'd 5 s timer (injectable scheduler/`intervalMs`); no listener, no data dir, or `statfs: null`/no `fs.promises.statfs` (Node < 18.15, as the old producer handled it) means no timer and no read. Reads never overlap (in-flight latch), every read and timer callback is guarded by the generation that armed it (a stop, a path change or a seam change abandons it: it can neither emit nor report), failures are reported ONCE per failure streak (a success, an unsane answer, a new run or a new path starts a new one), an unsane answer (non-positive block size/total, negative or non-finite free, overflowing product, non-numbers) is omitted without an error and never zeroed (a full disk is a true 0 free). `rebind` merges seams within one key (defined replaces, undefined never clobbers; `statfs: null` is a defined seam): `onError`/`scheduler`/`statfs`/`intervalMs` are latest-launch-wins per key, while the data dir is part of the key, so a running launch can never be redirected to (or have its failures reported to) another launch's dir/`onError`; a CHANGED seam while a listener is attached tears the poll down on the scheduler that armed it and starts again at once (a changed path is re-read immediately and the old path's reading and failure streak do not leak); an unchanged relaunch restarts nothing; idle rebinds only store. Merely BUILDING the producer rebinds the shared tracker. **Retention rule (stated and tested):** only the merged seams survive the last unsubscribe; the last reading does not (`current()` is undefined with no listener, and is dropped on a failed/unsane read and on a path change); payloads and `current()` are copies. Hardening: reporter indirection that swallows a throwing `onError`, a timer that cannot be armed is reported and leaves the tracker inert, a throwing `clearInterval` is reported. The disk producer is NOT built when the legacy `systemMetricsSampler` replaces the producer list (it would never start, and building it touches the shared tracker). Launch tests wrap `storageTrackerFor` and prove the opt-in launch goes through it (mutating the producer to `new StorageTracker` fails) and that no tracker is requested when the opt-in is off or there is no data dir. `@bugsee/node` also re-exports `storageTrackerFor`/`resetStorageTracker`/`StorageTracker`. **Behaviour notes:** (1) the tracker is one per DATA DIR, so a second launch over the same dir shares it (and hands it its `onError`/seams) while a launch over another dir has its own (tests that inject `diskStatfs` must pass a private `key` or call `resetStorageTracker()`; added to the node launch test afterEach); (2) within one dir, seams merge, so a later launch without `diskStatfs`/`scheduler` keeps an earlier launch's; (3) wire behaviour is unchanged (each producer polls its own dir and reports to its own `onError`, as the pre-tracker code did); a relaunch over the same dir with a changed seam re-reads at once. An earlier revision keyed the singleton on the `process` object and let a later launch's data dir replace a running launch's: fixed in review. - **ST0′ (DONE, `feat/trace-producers`):** `traces.system` is now producers over shared trackers. `@bugsee/capture` has `TraceProducer`/`TraceProducerBase`; the traces provider is a producer container (per-producer start/stop isolation, last-value refresh so a rolling window never loses a rarely-changing diff --git a/packages/node/src/disk-space-producer.test.ts b/packages/node/src/disk-space-producer.test.ts index 08b6f849..2f00230b 100644 --- a/packages/node/src/disk-space-producer.test.ts +++ b/packages/node/src/disk-space-producer.test.ts @@ -1,358 +1,180 @@ -import type { Scheduler } from '@bugsee/core'; -import { describe, expect, it, vi } from 'vitest'; -import { createDiskSpaceProducer, type StatFs } from './disk-space-producer'; - -function fakeScheduler() { - let cb: (() => void) | undefined; - const live = new Set(); - let n = 0; - const scheduler: Scheduler = { - setInterval: (c) => { - cb = c; - n += 1; - const h = { id: n }; - live.add(h); - return h; - }, - clearInterval: (h) => { - expect(live.has(h)).toBe(true); - live.delete(h); - }, - }; - return { scheduler, tick: () => cb?.(), live: () => live.size }; -} +import { resetStorageTracker, type StatFs } from '@bugsee/trackers/node'; +import { afterEach, describe, expect, it } from 'vitest'; +import { createDiskSpaceProducer } from './disk-space-producer'; + +const keys: object[] = []; +afterEach(() => { + for (const k of keys.splice(0)) resetStorageTracker(k); + resetStorageTracker(); +}); -type Sample = { bsize: number; bavail: number; blocks: number }; -const mkStat = (sample: () => Sample | Error): { statfs: StatFs; paths: string[] } => { - const paths: string[] = []; - return { - paths, - statfs: async (path) => { - paths.push(path); - const s = sample(); - if (s instanceof Error) throw s; - return s; - }, - }; -}; const flush = () => new Promise((r) => setImmediate(r)); -function run( - sample: () => Sample | Error, - over: { dataDir?: string; statfs?: StatFs | null } = {}, -) { - const fs = fakeScheduler(); - const stat = mkStat(sample); - const calls: Array<[string, unknown, { hold?: boolean } | undefined]> = []; - const errors: unknown[] = []; +function setup(statfs: StatFs, over: { intervalMs?: number } = {}) { + const key = {}; + keys.push(key); + const handles: unknown[] = []; + let tick: (() => void) | undefined; const producer = createDiskSpaceProducer({ - dataDir: over.dataDir ?? '/data', - ...(over.statfs === null ? {} : { statfs: over.statfs ?? stat.statfs }), - scheduler: fs.scheduler, - onError: (e) => errors.push(e), + key, + dataDir: '/var/bugsee', + statfs, + scheduler: { + setInterval: (cb) => { + tick = cb; + handles.push(cb); + return handles.length; + }, + clearInterval: () => void handles.pop(), + }, + ...over, }); + const calls: Array<[string, unknown, unknown?]> = []; const sink = { - emit: (n: string, v: unknown, _d?: number, o?: { hold?: boolean }) => - void calls.push([n, v, o]), + emit: (n: string, v: unknown, _d?: number, o?: unknown) => void calls.push([n, v, o]), }; - return { producer, sink, calls, errors, fs, stat }; + return { producer, sink, calls, key, handles, tick: () => tick?.() }; } -const names = (calls: Array<[string, unknown, unknown]>) => calls.map(([n, v]) => [n, v] as const); - -describe('createDiskSpaceProducer', () => { - it('attaches nothing until start()', () => { - const r = run(() => ({ bsize: 4096, bavail: 1, blocks: 2 })); - expect(r.fs.live()).toBe(0); - expect(r.stat.paths).toEqual([]); - }); - it('reads the dataDir volume at start and emits binary integer MB: free = bsize*bavail, total = bsize*blocks', async () => { - const r = run(() => ({ bsize: 4096, bavail: 300 * 256 + 100, blocks: 1000 * 256 + 5 }), { - dataDir: '/var/bugsee', +describe('createDiskSpaceProducer (composition over the StorageTracker)', () => { + it('attaches nothing until start(), then maps the tracker stage to integer-MB traces (free then total)', async () => { + const paths: string[] = []; + const s = setup(async (p) => { + paths.push(p); + return { bsize: 4096, bavail: 300 * 256 + 100, blocks: 1000 * 256 + 5 }; }); - r.producer.start(r.sink); + expect(paths).toEqual([]); + expect(s.handles).toHaveLength(0); + s.producer.start(s.sink); await flush(); - expect(r.stat.paths).toEqual(['/var/bugsee']); - expect(names(r.calls)).toEqual([ + expect(paths).toEqual(['/var/bugsee']); + expect(s.calls.map(([n, v]) => [n, v])).toEqual([ ['disk_mem_free', 300], ['disk_mem_total', 1000], ]); }); - it('is POLLED, not held: every read emits, and a read that later fails leaves a gap instead of a frozen value', async () => { + it('is POLLED, not held: every poll emits with hold:false', async () => { let free = 10 * 256; - const r = run(() => ({ bsize: 4096, bavail: free, blocks: 100 * 256 })); - r.producer.start(r.sink); + const s = setup(async () => ({ bsize: 4096, bavail: free, blocks: 100 * 256 })); + s.producer.start(s.sink); await flush(); free = 9 * 256; - r.fs.tick(); + s.tick(); await flush(); - expect(names(r.calls)).toEqual([ + expect(s.calls.map(([n, v]) => [n, v])).toEqual([ ['disk_mem_free', 10], ['disk_mem_total', 100], ['disk_mem_free', 9], ['disk_mem_total', 100], ]); - // hold:false = the provider never re-records it, so a failing statfs cannot leave a stale value in the window - expect(r.calls.every(([, , o]) => o?.hold === false)).toBe(true); + expect(s.calls.every(([, , o]) => (o as { hold?: boolean })?.hold === false)).toBe(true); }); - it('a full disk is a true 0 MB free, not an omission', async () => { - const r = run(() => ({ bsize: 4096, bavail: 0, blocks: 256 * 10 })); - r.producer.start(r.sink); + it('a full disk is a true 0 MB free; an unreadable volume emits nothing (gap, never a stale or zero value)', async () => { + let next: 'full' | 'fail' = 'full'; + const s = setup(async () => { + if (next === 'fail') throw new Error('EIO'); + return { bsize: 4096, bavail: 0, blocks: 256 * 10 }; + }); + s.producer.start(s.sink); await flush(); - expect(names(r.calls)).toEqual([ + expect(s.calls.map(([n, v]) => [n, v])).toEqual([ ['disk_mem_free', 0], ['disk_mem_total', 10], ]); - }); - - it('omits both traces when the reading is not sane (never a fabricated 0)', async () => { - for (const bad of [ - { bsize: 0, bavail: 5, blocks: 5 }, - { bsize: 4096, bavail: Number.NaN, blocks: 5 }, - { bsize: 4096, bavail: -1, blocks: 5 }, - { bsize: 4096, bavail: 5, blocks: 0 }, - { bsize: 4096, bavail: 5, blocks: Number.POSITIVE_INFINITY }, - { bsize: Number.NaN, bavail: 5, blocks: 5 }, - { bsize: Number.POSITIVE_INFINITY, bavail: 5, blocks: 5 }, - { bsize: 4096, bavail: Number.POSITIVE_INFINITY, blocks: 5 }, - ]) { - const r = run(() => bad); - r.producer.start(r.sink); - await flush(); - expect(r.calls, JSON.stringify(bad)).toEqual([]); - expect(r.errors).toEqual([]); - } - }); - - it('a failing statfs is reported and omits only that reading; the next tick recovers', async () => { - let fail = true; - const r = run(() => (fail ? new Error('EIO') : { bsize: 4096, bavail: 256, blocks: 512 })); - r.producer.start(r.sink); - await flush(); - expect(r.calls).toEqual([]); - expect((r.errors[0] as Error).message).toBe('EIO'); - fail = false; - r.fs.tick(); - await flush(); - expect(names(r.calls)).toEqual([ - ['disk_mem_free', 1], - ['disk_mem_total', 2], - ]); - }); - - it('reports a failure streak once, and again after a recovery (no flood every 5 s)', async () => { - let fail = true; - const r = run(() => (fail ? new Error('ENOENT') : { bsize: 4096, bavail: 256, blocks: 512 })); - r.producer.start(r.sink); - await flush(); - for (let i = 0; i < 3; i++) { - r.fs.tick(); - await flush(); - } - expect(r.errors).toHaveLength(1); - fail = false; - r.fs.tick(); - await flush(); - fail = true; - r.fs.tick(); - await flush(); - expect(r.errors).toHaveLength(2); - r.producer.stop(); // a new session starts a new streak - r.producer.start(r.sink); - await flush(); - expect(r.errors).toHaveLength(3); - }); - - it('a read abandoned by stop() reports nothing when it fails afterwards (no restart needed)', async () => { - let reject: (() => void) | undefined; - const slow: StatFs = () => - new Promise((_resolve, rej) => { - reject = () => rej(new Error('late')); + next = 'fail'; + s.tick(); + await flush(); + expect(s.calls).toHaveLength(2); + }); + + it('stop() unsubscribes (the tracker releases its timer); a restart reads and emits again', async () => { + const s = setup(async () => ({ bsize: 4096, bavail: 256, blocks: 512 })); + s.producer.start(s.sink); + await flush(); + expect(s.handles).toHaveLength(1); + s.producer.stop(); + expect(s.handles).toHaveLength(0); + s.producer.start(s.sink); + await flush(); + expect(s.calls).toHaveLength(4); + }); + + it('stop() before start() is harmless', () => { + const s = setup(async () => ({ bsize: 1, bavail: 1, blocks: 1 })); + expect(() => s.producer.stop()).not.toThrow(); + }); + + it('two producers over two dirs: each keeps polling its own dir and reporting to its own onError', async () => { + const mk = (dir: string) => { + const paths: string[] = []; + const errors: unknown[] = []; + let tick: (() => void) | undefined; + const producer = createDiskSpaceProducer({ + dataDir: dir, + statfs: async (p) => { + paths.push(p); + throw new Error(`failed ${dir}`); + }, + scheduler: { + setInterval: (cb) => { + tick = cb; + return 1; + }, + clearInterval: () => {}, + }, + onError: (e) => errors.push(e), }); - const r = run(() => ({ bsize: 1, bavail: 1, blocks: 1 }), { statfs: slow }); - r.producer.start(r.sink); - r.producer.stop(); - reject?.(); - await flush(); - expect(r.errors).toEqual([]); - }); - - it('a synchronously throwing statfs is reported too, and onError is optional', async () => { - const throwing: StatFs = () => { - throw new Error('sync'); + return { producer, paths, errors, tick: () => tick?.() }; }; - const r = run(() => ({ bsize: 1, bavail: 1, blocks: 1 }), { statfs: throwing }); - r.producer.start(r.sink); + const a = mk('/disk/a'); + const b = mk('/disk/b'); // built AFTER a started: must not redirect a + a.producer.start({ emit() {} }); + b.producer.start({ emit() {} }); await flush(); - expect((r.errors[0] as Error).message).toBe('sync'); - - const quiet = createDiskSpaceProducer({ - dataDir: '/d', - statfs: throwing, - scheduler: fakeScheduler().scheduler, - }); - expect(() => quiet.start(r.sink)).not.toThrow(); + a.tick(); + b.tick(); await flush(); + expect(a.paths).toEqual(['/disk/a', '/disk/a']); + expect(b.paths).toEqual(['/disk/b', '/disk/b']); + expect(a.errors.map((e) => (e as Error).message)).toEqual(['failed /disk/a']); + expect(b.errors.map((e) => (e as Error).message)).toEqual(['failed /disk/b']); + a.producer.stop(); + b.producer.stop(); }); - it('never overlaps reads: a tick while one is in flight is skipped', async () => { - let release: (() => void) | undefined; + it('two producers over the SAME dir share one tracker (one poll)', async () => { let calls = 0; - const slow: StatFs = (path) => { - calls += 1; - return new Promise((resolve) => { - release = () => resolve({ bsize: 4096, bavail: 256, blocks: 512 }); - void path; - }); - }; - const r = run(() => ({ bsize: 1, bavail: 1, blocks: 1 }), { statfs: slow }); - r.producer.start(r.sink); - r.fs.tick(); - r.fs.tick(); - expect(calls).toBe(1); - release?.(); - await flush(); - r.fs.tick(); - expect(calls).toBe(2); - }); - - it('a read that finishes after stop() emits nothing', async () => { - let release: (() => void) | undefined; - const slow: StatFs = () => - new Promise((resolve) => { - release = () => resolve({ bsize: 4096, bavail: 256, blocks: 512 }); - }); - const r = run(() => ({ bsize: 1, bavail: 1, blocks: 1 }), { statfs: slow }); - r.producer.start(r.sink); - r.producer.stop(); - release?.(); - await flush(); - expect(r.calls).toEqual([]); - }); - - it('stop() releases the timer; a restart reads again and re-emits (fresh dedupe state)', async () => { - const r = run(() => ({ bsize: 4096, bavail: 256, blocks: 512 })); - r.producer.start(r.sink); - await flush(); - expect(r.fs.live()).toBe(1); - r.producer.stop(); - expect(r.fs.live()).toBe(0); - r.producer.start(r.sink); - await flush(); - expect(r.calls).toHaveLength(4); - }); - - it('a read from before a stop never lands after a restart (value or error), and the restart reads afresh', async () => { - const resolvers: Array<{ ok: () => void; fail: () => void }> = []; - const sizes = [300, 7]; - let calls = 0; - const slow: StatFs = () => - new Promise((resolve, reject) => { - const size = sizes[calls] ?? 1; + const deps = { + dataDir: '/disk/same', + statfs: async () => { calls += 1; - resolvers.push({ - ok: () => resolve({ bsize: 1024 * 1024, bavail: size, blocks: 1000 }), - fail: () => reject(new Error('stale')), - }); - }); - const r = run(() => ({ bsize: 1, bavail: 1, blocks: 1 }), { statfs: slow }); - r.producer.start(r.sink); - r.producer.stop(); - r.producer.start(r.sink); - expect(calls).toBe(2); // the restart is not blocked by the dead read - resolvers[0]?.ok(); // stale value - await flush(); - expect(r.calls).toEqual([]); - resolvers[1]?.ok(); - await flush(); - expect(names(r.calls)).toEqual([ - ['disk_mem_free', 7], - ['disk_mem_total', 1000], - ]); - // the error path obeys the same generation rule - r.producer.stop(); - r.producer.start(r.sink); // read #3, then dies with the next stop - r.producer.stop(); - r.producer.start(r.sink); - resolvers[2]?.fail(); - await flush(); - expect(r.errors).toEqual([]); - }); - - it('polls every 5 s by default and honors intervalMs', () => { - const seen: number[] = []; - const sched: Scheduler = { - setInterval: (_cb, ms) => { - seen.push(ms); - return 1; + return { bsize: 1, bavail: 1, blocks: 1 }; }, - clearInterval: () => {}, + scheduler: { setInterval: () => 1, clearInterval: () => {} }, }; - const stat: StatFs = async () => ({ bsize: 1, bavail: 1, blocks: 1 }); - createDiskSpaceProducer({ dataDir: '/d', statfs: stat, scheduler: sched }).start({ emit() {} }); - createDiskSpaceProducer({ - dataDir: '/d', - statfs: stat, - scheduler: sched, - intervalMs: 123, - }).start({ - emit() {}, - }); - expect(seen).toEqual([5000, 123]); - }); - - it("the default timer is unref'd (never keeps the process alive) and is cleared on stop", () => { - const real = globalThis.setInterval; - const realClear = globalThis.clearInterval; - const handle = { unref: vi.fn() }; - const cleared: unknown[] = []; - const intervals: unknown[] = []; - globalThis.setInterval = ((_cb: unknown, ms: unknown) => { - intervals.push(ms); - return handle; - }) as never; - globalThis.clearInterval = ((h: unknown) => void cleared.push(h)) as never; - try { - const p = createDiskSpaceProducer({ - dataDir: '/d', - statfs: async () => ({ bsize: 1, bavail: 1, blocks: 1 }), - }); - p.start({ emit() {} }); - expect(handle.unref).toHaveBeenCalledTimes(1); - expect(intervals).toEqual([5000]); - p.stop(); - expect(cleared).toEqual([handle]); - } finally { - globalThis.setInterval = real; - globalThis.clearInterval = realClear; - } - }); - - it('stop() before start() is harmless', async () => { - const r = run(() => ({ bsize: 4096, bavail: 256, blocks: 512 })); - expect(() => r.producer.stop()).not.toThrow(); - }); - - it('a runtime without statfs is a no-op: nothing read, nothing emitted, no timer', async () => { - const fs = fakeScheduler(); - const calls: unknown[] = []; - const p = createDiskSpaceProducer({ dataDir: '/d', statfs: null, scheduler: fs.scheduler }); - p.start({ emit: (...a) => void calls.push(a) }); + const p1 = createDiskSpaceProducer(deps); + const p2 = createDiskSpaceProducer(deps); + p1.start({ emit() {} }); + p2.start({ emit() {} }); await flush(); - expect(calls).toEqual([]); - expect(fs.live()).toBe(0); + expect(calls).toBe(1); + p1.stop(); + p2.stop(); }); - it('reads the real filesystem by default (the dataDir volume)', async () => { + it('reads the real filesystem by default (the data dir volume)', async () => { + const key = {}; + keys.push(key); const calls: Array<[string, unknown]> = []; const p = createDiskSpaceProducer({ + key, dataDir: process.cwd(), - scheduler: fakeScheduler().scheduler, + scheduler: { setInterval: () => 1, clearInterval: () => {} }, }); p.start({ emit: (n, v) => void calls.push([n, v]) }); - await new Promise((r) => setTimeout(r, 50)); + for (let i = 0; i < 100 && calls.length === 0; i++) await new Promise((r) => setTimeout(r, 10)); p.stop(); const total = calls.find(([n]) => n === 'disk_mem_total')?.[1]; const free = calls.find(([n]) => n === 'disk_mem_free')?.[1]; diff --git a/packages/node/src/disk-space-producer.ts b/packages/node/src/disk-space-producer.ts index c6093761..a35403c6 100644 --- a/packages/node/src/disk-space-producer.ts +++ b/packages/node/src/disk-space-producer.ts @@ -1,117 +1,52 @@ -import * as fsp from 'node:fs/promises'; import { TraceProducerBase } from '@bugsee/capture'; -import type { Scheduler } from '@bugsee/core'; import { bytesToMegabytes } from '@bugsee/protocol'; +import { + type DiskReading, + type StorageTracker, + type StorageTrackerEnv, + storageTrackerFor, +} from '@bugsee/trackers/node'; // `disk_mem_free` / `disk_mem_total` (Android parity, binary integer MB like the environment envelope) for the // filesystem the SDK's data directory lives on — NOT `/` or the cwd: it is that volume's space. Opt-in and only -// created when there IS a data directory, so an in-memory launch never reports a disk it does not use. Polled -// every few seconds off the event loop (`fs.promises.statfs`). Emitted every poll and NOT held: a held value -// would be re-recorded by the provider for the rest of the session after statfs starts failing (the data dir -// removed, a dead mount), reporting a disk reading that is no longer true. +// created when there IS a data directory, so an in-memory launch never reports a disk it does not use. +// +// COMPOSITION only: the statfs read, its poll timer, failure-streak reporting and the omit-never-zero rule belong to +// the per-process StorageTracker (`@bugsee/trackers/node`); this producer subscribes to its `disk` stage and maps it +// to the two trace names. Emitted every poll and NOT held (`emit`, hold:false): a held value would be re-recorded by +// the provider for the rest of the session after statfs starts failing (the data dir removed, a dead mount), +// reporting a disk reading that is no longer true. -export interface StatFsResult { - bsize: number; - bavail: number; - blocks: number; -} -export type StatFs = (path: string) => Promise; +export type { StatFs } from '@bugsee/trackers/node'; -export interface DiskSpaceDeps { +export interface DiskSpaceDeps extends Omit { /** The directory whose volume is measured (the launch's effective data dir). */ dataDir: string; - /** Test seam. `null` = the runtime has no statfs (nothing is read). Default: `fs.promises.statfs` when present. */ - statfs?: StatFs | null; - scheduler?: Scheduler; - /** Android reads disk every 5 s. */ - intervalMs?: number; onError?: (error: unknown) => void; } -// Unref'd so the producer never keeps a process alive. -const defaultScheduler: Scheduler = { - setInterval: (cb, ms) => { - const h = setInterval(cb, ms); - (h as { unref?: () => void }).unref?.(); - return h; - }, - clearInterval: (h) => clearInterval(h as ReturnType), -}; - -const isCount = (n: number): boolean => Number.isFinite(n) && n >= 0; -const isPositive = (n: number): boolean => Number.isFinite(n) && n > 0; - class DiskSpaceProducer extends TraceProducerBase { readonly name = 'disk-space'; - readonly #deps: DiskSpaceDeps; - readonly #statfs: StatFs | undefined; - #timer: unknown = null; - #inFlight = false; - #failing = false; - #generation = 0; - - constructor(deps: DiskSpaceDeps) { + #off: (() => void) | undefined; + constructor(private readonly tracker: StorageTracker) { super(); - this.#deps = deps; - // Namespace import: a Node without `statfs` (< 18.15) must degrade to "no traces", not fail to load. - const real = (fsp as { statfs?: StatFs }).statfs; - this.#statfs = deps.statfs === undefined ? real : (deps.statfs ?? undefined); } - + // Subscribing arms the tracker's stage (an immediate read, then its own timer): no baseline to emit here. protected onStart(): void { - if (this.#statfs === undefined) return; - this.#generation += 1; - this.#read(this.#generation); - const generation = this.#generation; - this.#timer = (this.#deps.scheduler ?? defaultScheduler).setInterval( - () => this.#read(generation), - this.#deps.intervalMs ?? 5000, - ); + this.#off = this.tracker.on('disk', (d) => this.publish(d)); } - protected override onStop(): void { - // A read still in flight is abandoned: a new generation means it can neither report nor emit when it - // settles, and clearing the latch lets the next start() read. - this.#generation += 1; - this.#inFlight = false; - this.#failing = false; - if (this.#timer !== null) (this.#deps.scheduler ?? defaultScheduler).clearInterval(this.#timer); - } - - #read(generation: number): void { - if (this.#inFlight || this.#statfs === undefined) return; - this.#inFlight = true; - let pending: Promise; - try { - pending = this.#statfs(this.#deps.dataDir); - } catch (error) { - pending = Promise.reject(error); - } - pending.then( - (s) => { - if (generation !== this.#generation) return; - this.#inFlight = false; - this.#failing = false; - this.#publish(s); - }, - (error: unknown) => { - if (generation !== this.#generation) return; - this.#inFlight = false; - // One report per failure streak: a removed data dir fails every 5 s and must not flood onError. - if (!this.#failing) this.#deps.onError?.(error); - this.#failing = true; - }, - ); + this.#off?.(); + this.#off = undefined; } - - // Omit, never zero: an unsane reading emits nothing. `bavail` may legitimately be 0 (a full disk). - #publish(s: StatFsResult): void { - if (!isPositive(s.bsize) || !isCount(s.bavail) || !isPositive(s.blocks)) return; - this.emit('disk_mem_free', bytesToMegabytes(s.bsize * s.bavail)); - this.emit('disk_mem_total', bytesToMegabytes(s.bsize * s.blocks)); + private publish(d: DiskReading): void { + this.emit('disk_mem_free', bytesToMegabytes(d.freeBytes)); + this.emit('disk_mem_total', bytesToMegabytes(d.totalBytes)); } } export function createDiskSpaceProducer(deps: DiskSpaceDeps): TraceProducerBase { - return new DiskSpaceProducer(deps); + const { onError, ...env } = deps; + // The per-process singleton: building the producer hands it THIS launch's data dir and seams (latest launch wins). + return new DiskSpaceProducer(storageTrackerFor(env, onError)); } diff --git a/packages/node/src/index.test.ts b/packages/node/src/index.test.ts index 7b6e2908..d23585c9 100644 --- a/packages/node/src/index.test.ts +++ b/packages/node/src/index.test.ts @@ -64,10 +64,12 @@ const EXPECTED_EXPORTS = [ 'openServerRequest', 'processTrackerFor', 'resetProcessTracker', + 'resetStorageTracker', 'realSystemProbe', 'runServerRequest', 'sanitizeHardwareGpu', 'startServerSpan', + 'storageTrackerFor', 'wrapFetchHandler', ] as const; diff --git a/packages/node/src/index.ts b/packages/node/src/index.ts index 8b0cf09b..0b563ce6 100644 --- a/packages/node/src/index.ts +++ b/packages/node/src/index.ts @@ -29,6 +29,9 @@ export { type ProcessTracker, processTrackerFor, resetProcessTracker, + resetStorageTracker, + type StorageTracker, + storageTrackerFor, } from '@bugsee/trackers/node'; // The request-scoped active-span store for bare-`@bugsee/node` consumers wiring APM by // hand. One store per context source: the stash key is process-global (realm convergence), so two diff --git a/packages/node/src/launch.test.ts b/packages/node/src/launch.test.ts index 4a74eadc..64a1316d 100644 --- a/packages/node/src/launch.test.ts +++ b/packages/node/src/launch.test.ts @@ -58,7 +58,12 @@ import { type RequestJson, Severity, } from '@bugsee/protocol'; -import { processTrackerFor, resetProcessTracker } from '@bugsee/trackers/node'; +import { + processTrackerFor, + resetProcessTracker, + resetStorageTracker, + storageTrackerFor, +} from '@bugsee/trackers/node'; import { strFromU8, unzipSync } from '@bugsee/util'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { hashAppToken } from './data-location'; @@ -121,6 +126,13 @@ function fakeProcess(onExit?: (code?: number) => void) { }; } +// Wraps (never replaces) the registry accessor so a launch-level test can prove the opt-in disk producer is built +// through it. Behaviour is untouched: the spy forwards to the real function. +vi.mock('@bugsee/trackers/node', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, storageTrackerFor: vi.fn(actual.storageTrackerFor) }; +}); + const probe: SystemProbe = { platformType: () => 'node', runtimeVersion: () => '20.1.2', @@ -178,6 +190,7 @@ afterEach(async () => { // Stop every launched client so the console interceptor unpatches the global console. await Promise.all(clients.splice(0).map((c) => c.stop())); resetProcessTracker(); // the per-process ProcessTracker singleton must not carry one test's seams into the next + resetStorageTracker(); // ...nor the StorageTracker's data dir / statfs seam vi.restoreAllMocks(); // Reset the process Carrier so each test builds fresh interceptor singletons (default global path). delete (globalThis as { __BUGSEE__?: unknown }).__BUGSEE__; @@ -1632,6 +1645,76 @@ describe('launch — system trace producers', () => { await client.stop(50); }); + it("goes through the per-process StorageTracker registry accessor when on (one shared tracker, this launch's data dir)", async () => { + const dir = mkdtempSync(join(tmpdir(), 'bugsee-disk-')); + const fs = fakeScheduler(); + vi.mocked(storageTrackerFor).mockClear(); + const paths: string[] = []; + const onError = () => {}; + launchTracked( + 'tok', + baseOptions({ + dataDir: dir, + captureStore: memStore(), + systemMetricsSampler: undefined, + captureDiskSpace: true, + scheduler: fs.scheduler, + diskStatfs: async (path) => { + paths.push(path); + return { bsize: 1024 * 1024, bavail: 5, blocks: 9 }; + }, + onError, + }), + ); + const calls = vi.mocked(storageTrackerFor).mock.calls; + expect(calls).toHaveLength(1); + expect(calls[0]?.[0]).toMatchObject({ dataDir: dir, scheduler: fs.scheduler }); + expect(calls[0]?.[1]).toBe(onError); + // the launch's producer is subscribed to THE process singleton: its poll is armed (5 s, the launch's scheduler) + expect(fs.calls.some((c) => c.ms === 5000)).toBe(true); + expect(paths).toEqual([dir]); + await new Promise((r) => setTimeout(r, 0)); + expect(storageTrackerFor({ dataDir: dir }).current()).toEqual({ + freeBytes: 5 * 1024 * 1024, + totalBytes: 9 * 1024 * 1024, + }); + }); + + it('creates no StorageTracker when the opt-in is off or there is no data dir', () => { + vi.mocked(storageTrackerFor).mockClear(); + launchTracked( + 'tok', + baseOptions({ + dataDir: mkdtempSync(join(tmpdir(), 'bugsee-disk-')), + captureStore: memStore(), + systemMetricsSampler: undefined, + }), + ); + launchTracked( + 'tok', + baseOptions({ + captureStore: memStore(), + capturedDataStore: 'memory', + systemMetricsSampler: undefined, + captureDiskSpace: true, + }), + ); + expect(storageTrackerFor).not.toHaveBeenCalled(); + }); + + it('does not build the disk producer (nor touch the shared tracker) when systemMetricsSampler replaces the producer list', () => { + vi.mocked(storageTrackerFor).mockClear(); + launchTracked( + 'tok', + baseOptions({ + dataDir: mkdtempSync(join(tmpdir(), 'bugsee-disk-')), + captureStore: memStore(), + captureDiskSpace: true, // baseOptions carries a systemMetricsSampler + }), + ); + expect(storageTrackerFor).not.toHaveBeenCalled(); + }); + it('measures the effective data dir (never / or the cwd), through the statfs seam', async () => { const dir = mkdtempSync(join(tmpdir(), 'bugsee-disk-')); const store = memStore(); diff --git a/packages/node/src/launch.ts b/packages/node/src/launch.ts index 27a03862..4eefa93b 100644 --- a/packages/node/src/launch.ts +++ b/packages/node/src/launch.ts @@ -948,9 +948,13 @@ function buildLaunch(appToken: string, options: BugseeLaunchOptions = {}): Launc }); // Opt-in disk space: the volume the SDK's data dir lives on, so only when there IS one (an in-memory or // degraded launch has none, and never falls back to `/` or the cwd). Appended to caller-supplied producers - // too: the option is an explicit request, and Bun/Deno build their own producer list. + // too: the option is an explicit request, and Bun/Deno build their own producer list. NOT built when the legacy + // `systemMetricsSampler` replaces the producer list: it would never be started, and merely building it touches + // the shared per-volume tracker. const traceProducers = - resolved.isEnabled(NodeTraceOption.CaptureDiskSpace) && effectiveDataDir !== undefined + options.systemMetricsSampler === undefined && + resolved.isEnabled(NodeTraceOption.CaptureDiskSpace) && + effectiveDataDir !== undefined ? [ ...baseTraceProducers, createDiskSpaceProducer({ diff --git a/packages/trackers/README.md b/packages/trackers/README.md index 6f2f33ad..891094a1 100644 --- a/packages/trackers/README.md +++ b/packages/trackers/README.md @@ -26,6 +26,8 @@ The `./browser` entry exports the `ApplicationTracker` (`applicationTrackerFor`, The `./node` entry is shared by Node, Bun and Deno and exports the process `ProcessTracker` (`processTrackerFor`, `resetProcessTracker`; a per-process singleton, keyed on the `process` object by default). Its ten stages (`memory`, `systemMemory`, `cpu`, `eventLoop`, `utilization`, `gc`, `v8Heap`, `memoryLimit`, `availableMemory`, `uptime`) are each armed only while they have listeners, behind one shared sampling timer. A stage the runtime cannot honestly measure emits nothing rather than zero (event-loop utilization on Bun/Deno is dropped by its own tell, idle and active both zero; the event-loop delay histogram on Deno, the GC observer on Bun/Deno, the V8 heap on Bun and available memory on Bun/Deno are gated by the `measures*` flags the platform packages pass in). The CPU stage has no start value: it reports from the first tick. Seams merge and are never dropped: a later launch that omits `scheduler` or `onError` keeps the previous launch's, and building a producer set already rebinds the shared tracker, so tests that inject fakes need a private `key` or `resetProcessTracker()`. It also exports the guarded runtime sources it is built from (`createGuardedEventLoopSource`, `createGuardedElu`, `createGcSource`, `createV8HeapReader`, `createMemoryLimitReader`, `createAvailableMemoryReader`). +The `./node` entry also exports the disk `StorageTracker` (`storageTrackerFor`, `resetStorageTracker`; one singleton per resolved data directory, so launches over the same directory share a tracker and launches over different directories never affect each other; a launch without a data directory gets the shared inert `process`-keyed tracker, and an explicit `key` overrides, for tests) behind the opt-in `disk_mem_free` / `disk_mem_total` traces. Its one stage, `disk` (`{freeBytes, totalBytes}`), reads the volume of the launch's data directory with `fs.promises.statfs` (not `/` or the working directory) at once when a listener arrives and then on its own unref'd 5 s timer, and does nothing while no one listens, when there is no data directory, or when the runtime has no `statfs`. An unreadable or unsane reading emits nothing (a full disk is a true 0 free), and failures are reported once per failure streak. Within one directory's tracker, `onError`, `scheduler` and `statfs` are latest-launch-wins, an omitted seam keeps the earlier one, and a changed seam is applied (and re-read) immediately. Only the merged seams survive the last unsubscribe; the last reading does not. + ## Links - Repository: https://github.com/bugsee/bugsee-javascript/tree/main/packages/trackers diff --git a/packages/trackers/package.json b/packages/trackers/package.json index 222c0ab5..1d8637d0 100644 --- a/packages/trackers/package.json +++ b/packages/trackers/package.json @@ -7,7 +7,7 @@ "url": "git+https://github.com/bugsee/bugsee-javascript.git", "directory": "packages/trackers" }, - "description": "Domain-tracker foundation: multi-key emitter, InterceptorBase and the per-window tracker registry, with a ./browser entry (ApplicationTracker, ConnectivityTracker, PowerTracker, ProcessTracker, StorageTracker, UiTracker, EnvironmentTracker, hostRead), a ./node entry shared by Node, Bun and Deno (ProcessTracker and its guarded runtime sources) and a reserved ./electron platform entry", + "description": "Domain-tracker foundation: multi-key emitter, InterceptorBase and the per-window tracker registry, with a ./browser entry (ApplicationTracker, ConnectivityTracker, PowerTracker, ProcessTracker, StorageTracker, UiTracker, EnvironmentTracker, hostRead), a ./node entry shared by Node, Bun and Deno (ProcessTracker, StorageTracker and their guarded runtime sources) and a reserved ./electron platform entry", "type": "module", "main": "./src/index.ts", "types": "./src/index.ts", diff --git a/packages/trackers/src/node/index.test.ts b/packages/trackers/src/node/index.test.ts index 925fe5c4..c303ed27 100644 --- a/packages/trackers/src/node/index.test.ts +++ b/packages/trackers/src/node/index.test.ts @@ -6,6 +6,7 @@ describe('@bugsee/trackers/node public surface', () => { it('exports the node tracker values', () => { expect(Object.keys(nodeEntry).sort()).toEqual([ 'ProcessTracker', + 'StorageTracker', 'createAvailableMemoryReader', 'createGcSource', 'createGuardedElu', @@ -16,6 +17,8 @@ describe('@bugsee/trackers/node public surface', () => { 'processTrackerFor', 'realPerfHooks', 'resetProcessTracker', + 'resetStorageTracker', + 'storageTrackerFor', ]); }); }); diff --git a/packages/trackers/src/node/index.ts b/packages/trackers/src/node/index.ts index 522cb183..9f4f8d34 100644 --- a/packages/trackers/src/node/index.ts +++ b/packages/trackers/src/node/index.ts @@ -34,3 +34,15 @@ export { createV8HeapReader, type V8HeapStats, } from './runtime-readers'; +export { + type DiskReading, + resetStorageTracker, + type StatFs, + type StatFsResult, + type StorageEnv, + type StorageEvents, + type StorageTimers, + StorageTracker, + type StorageTrackerEnv, + storageTrackerFor, +} from './storage-tracker'; diff --git a/packages/trackers/src/node/storage-tracker.test.ts b/packages/trackers/src/node/storage-tracker.test.ts new file mode 100644 index 00000000..6fddf7ce --- /dev/null +++ b/packages/trackers/src/node/storage-tracker.test.ts @@ -0,0 +1,805 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + type DiskReading, + resetStorageTracker, + type StatFs, + type StatFsResult, + type StorageEnv, + StorageTracker, + storageTrackerFor, +} from './index'; + +// clearInterval must be handed exactly a live handle setInterval returned (never undefined/null/twice). +function fakeScheduler() { + const callbacks: (() => void)[] = []; + const periods: number[] = []; + const live = new Set(); + const scheduler = { + setInterval: (cb: () => void, ms: number) => { + callbacks.push(cb); + periods.push(ms); + const handle = { id: callbacks.length }; + live.add(handle); + return handle; + }, + clearInterval: (h: unknown) => { + expect(live.has(h), 'clearInterval was not given a live handle').toBe(true); + live.delete(h); + }, + }; + return { + scheduler, + tick: () => callbacks.at(-1)?.(), + callbackAt: (i: number) => callbacks[i], + sets: () => callbacks.length, + periods, + live: () => live.size, + }; +} + +const MB = 1024 * 1024; +const flush = () => new Promise((r) => setImmediate(r)); +type Outcome = StatFsResult | Error; +const stat = (sample: () => Outcome) => { + const paths: string[] = []; + const statfs: StatFs = async (path) => { + paths.push(path); + const s = sample(); + if (s instanceof Error) throw s; + return s; + }; + return { statfs, paths }; +}; + +function mk(sample: () => Outcome, over: StorageEnv = {}, onError?: (e: unknown) => void) { + const fs = fakeScheduler(); + const st = stat(sample); + const tracker = new StorageTracker( + { dataDir: '/data', statfs: st.statfs, scheduler: fs.scheduler, ...over }, + onError, + ); + const seen: DiskReading[] = []; + const subscribe = () => tracker.on('disk', (r) => void seen.push(r)); + return { tracker, fs, st, seen, subscribe }; +} +const ok = (bavail = 300, blocks = 1000): StatFsResult => ({ bsize: MB, bavail, blocks }); + +describe('StorageTracker (node)', () => { + it('does nothing until a listener arrives: no timer, no read', () => { + const r = mk(() => ok()); + expect(r.fs.sets()).toBe(0); + expect(r.st.paths).toEqual([]); + expect(r.tracker.current()).toBeUndefined(); + }); + + it('reads the data dir volume on the first listener and emits bytes: free = bsize*bavail, total = bsize*blocks', async () => { + const r = mk(() => ({ bsize: 4096, bavail: 10, blocks: 25 }), { dataDir: '/var/bugsee' }); + r.subscribe(); + await flush(); + expect(r.st.paths).toEqual(['/var/bugsee']); + expect(r.seen).toEqual([{ freeBytes: 40960, totalBytes: 102400 }]); + expect(r.tracker.current()).toEqual({ freeBytes: 40960, totalBytes: 102400 }); + }); + + it('polls on its own timer (5 s by default, intervalMs honoured) and emits every poll', async () => { + let free = 10; + const r = mk(() => ok(free, 100)); + r.subscribe(); + await flush(); + expect(r.fs.periods).toEqual([5000]); + free = 9; + r.fs.tick(); + await flush(); + expect(r.seen.map((s) => s.freeBytes)).toEqual([10 * MB, 9 * MB]); + const custom = mk(() => ok(), { intervalMs: 123 }); + custom.subscribe(); + expect(custom.fs.periods).toEqual([123]); + }); + + it('a second listener shares the poll; the timer is released only with the LAST listener', async () => { + const r = mk(() => ok()); + const off1 = r.subscribe(); + const off2 = r.subscribe(); + await flush(); + expect(r.fs.sets()).toBe(1); + expect(r.st.paths).toHaveLength(1); + off1(); + expect(r.fs.live()).toBe(1); + off2(); + expect(r.fs.live()).toBe(0); + }); + + it('a full disk is a true 0 free, not an omission', async () => { + const r = mk(() => ok(0, 10)); + r.subscribe(); + await flush(); + expect(r.seen).toEqual([{ freeBytes: 0, totalBytes: 10 * MB }]); + }); + + it('omits an unsane reading (never a fabricated 0) without reporting an error', async () => { + for (const bad of [ + { bsize: 0, bavail: 5, blocks: 5 }, + { bsize: 4096, bavail: Number.NaN, blocks: 5 }, + { bsize: 4096, bavail: -1, blocks: 5 }, + { bsize: 4096, bavail: 5, blocks: 0 }, + { bsize: 4096, bavail: 5, blocks: Number.POSITIVE_INFINITY }, + { bsize: Number.NaN, bavail: 5, blocks: 5 }, + { bsize: Number.POSITIVE_INFINITY, bavail: 5, blocks: 5 }, + { bsize: 4096, bavail: Number.POSITIVE_INFINITY, blocks: 5 }, + { bsize: '4096', bavail: 5, blocks: 5 }, + { bsize: 1e308, bavail: 1e308, blocks: 5 }, // product overflows + { bsize: 1e308, bavail: 1, blocks: 1e308 }, + {}, + null, + undefined, + ]) { + const errors: unknown[] = []; + const r = mk( + () => bad as unknown as StatFsResult, + {}, + (e) => errors.push(e), + ); + r.subscribe(); + await flush(); + expect(r.seen, JSON.stringify(bad)).toEqual([]); + expect(r.tracker.current()).toBeUndefined(); + expect(errors).toEqual([]); + } + }); + + it('a non-number block count is rejected (never coerced)', async () => { + const r = mk(() => ({ bsize: MB, bavail: 5, blocks: true }) as unknown as StatFsResult); + r.subscribe(); + await flush(); + expect(r.seen).toEqual([]); + }); + + it('an overflowing reading after a good one clears the retained reading', async () => { + let next: Outcome = ok(5, 9); + const r = mk(() => next); + r.subscribe(); + await flush(); + expect(r.tracker.current()).toBeDefined(); + next = { bsize: 1e308, bavail: 1e308, blocks: 5 }; + r.fs.tick(); + await flush(); + expect(r.tracker.current()).toBeUndefined(); + }); + + it('after the last unsubscribe a changed seam stores only: no read and no live timer', async () => { + const r = mk(() => ok(), { dataDir: '/a' }); + const off = r.subscribe(); + await flush(); + off(); + const reads = r.st.paths.length; + r.tracker.rebind({ dataDir: '/b' }); + await flush(); + expect(r.st.paths).toHaveLength(reads); + expect(r.fs.live()).toBe(0); + r.subscribe(); + await flush(); + expect(r.st.paths.at(-1)).toBe('/b'); + }); + + it('a failing statfs is reported and omits only that reading; the next poll recovers', async () => { + let fail = true; + const errors: unknown[] = []; + const r = mk( + () => (fail ? new Error('EIO') : ok(1, 2)), + {}, + (e) => errors.push(e), + ); + r.subscribe(); + await flush(); + expect(r.seen).toEqual([]); + expect((errors[0] as Error).message).toBe('EIO'); + fail = false; + r.fs.tick(); + await flush(); + expect(r.seen).toEqual([{ freeBytes: MB, totalBytes: 2 * MB }]); + }); + + it('reports a failure streak once, and again after a recovery or a new run (no flood every 5 s)', async () => { + let fail = true; + const errors: unknown[] = []; + const r = mk( + () => (fail ? new Error('ENOENT') : ok()), + {}, + (e) => errors.push(e), + ); + const off = r.subscribe(); + await flush(); + for (let i = 0; i < 3; i++) { + r.fs.tick(); + await flush(); + } + expect(errors).toHaveLength(1); + fail = false; + r.fs.tick(); + await flush(); + fail = true; + r.fs.tick(); + await flush(); + expect(errors).toHaveLength(2); + off(); // a new run starts a new streak + r.subscribe(); + await flush(); + expect(errors).toHaveLength(3); + }); + + it('an unsane reading ends a failure streak like any answered read', async () => { + let next: Outcome = new Error('x'); + const errors: unknown[] = []; + const r = mk( + () => next, + {}, + (e) => errors.push(e), + ); + r.subscribe(); + await flush(); + next = { bsize: 0, bavail: 0, blocks: 0 }; + r.fs.tick(); + await flush(); + next = new Error('y'); + r.fs.tick(); + await flush(); + expect(errors).toHaveLength(2); + }); + + it('a failed or unsane read drops the retained reading (a gap, never a stale number)', async () => { + let next: Outcome = ok(5, 9); + const r = mk( + () => next, + {}, + () => {}, + ); + r.subscribe(); + await flush(); + expect(r.tracker.current()?.freeBytes).toBe(5 * MB); + next = new Error('gone'); + r.fs.tick(); + await flush(); + expect(r.tracker.current()).toBeUndefined(); + next = ok(6, 9); + r.fs.tick(); + await flush(); + expect(r.tracker.current()?.freeBytes).toBe(6 * MB); + next = { bsize: 0, bavail: 0, blocks: 0 }; + r.fs.tick(); + await flush(); + expect(r.tracker.current()).toBeUndefined(); + }); + + it('emitted payloads and current() are copies: a subscriber cannot corrupt the retained reading', async () => { + const r = mk(() => ok()); + r.tracker.on('disk', (d) => { + d.freeBytes = -5; + }); + r.subscribe(); + await flush(); + (r.tracker.current() as DiskReading).freeBytes = -1; + expect(r.tracker.current()?.freeBytes).toBe(300 * MB); + }); + + it('a synchronously throwing or non-promise statfs is handled (reported / awaited)', async () => { + const errors: unknown[] = []; + const throwing = mk( + () => ok(), + { + statfs: () => { + throw new Error('sync'); + }, + }, + (e) => errors.push(e), + ); + throwing.subscribe(); + await flush(); + expect((errors[0] as Error).message).toBe('sync'); + const plain = mk(() => ok(), { statfs: (() => ok(2, 4)) as unknown as StatFs }); + plain.subscribe(); + await flush(); + expect(plain.seen).toEqual([{ freeBytes: 2 * MB, totalBytes: 4 * MB }]); + }); + + it('onError is optional and a throwing reporter never escapes', async () => { + const quiet = mk(() => new Error('e')); + expect(() => quiet.subscribe()).not.toThrow(); + await flush(); + const loud = mk( + () => new Error('e'), + {}, + () => { + throw new Error('reporter'); + }, + ); + loud.subscribe(); + await flush(); + loud.fs.tick(); + await flush(); + // a throwing LISTENER is isolated by the emitter and reported through the same guarded reporter + const l = mk( + () => ok(), + {}, + () => { + throw new Error('reporter'); + }, + ); + l.tracker.on('disk', () => { + throw new Error('listener'); + }); + await flush(); + }); + + it('never overlaps reads: a tick while one is in flight is skipped', async () => { + let release: (() => void) | undefined; + let calls = 0; + const slow: StatFs = () => { + calls += 1; + return new Promise((resolve) => { + release = () => resolve(ok()); + }); + }; + const r = mk(() => ok(), { statfs: slow }); + r.subscribe(); + r.fs.tick(); + r.fs.tick(); + expect(calls).toBe(1); + release?.(); + await flush(); + r.fs.tick(); + expect(calls).toBe(2); + }); + + it('a read in flight when the last listener leaves can neither emit nor report when it settles', async () => { + const pending: Array<{ ok: () => void; fail: () => void }> = []; + const slow: StatFs = () => + new Promise((resolve, reject) => { + pending.push({ ok: () => resolve(ok()), fail: () => reject(new Error('late')) }); + }); + const errors: unknown[] = []; + const r = mk( + () => ok(), + { statfs: slow }, + (e) => errors.push(e), + ); + const off = r.subscribe(); + off(); + const off2 = r.subscribe(); // the restart is not blocked by the dead read + expect(pending).toHaveLength(2); + pending[0]?.ok(); + await flush(); + expect(r.seen).toEqual([]); + off2(); + pending[1]?.fail(); + await flush(); + expect(errors).toEqual([]); + expect(r.seen).toEqual([]); + }); + + it('a timer callback from an earlier run (its clear failed) never reads', async () => { + const r = mk(() => ok()); + const off = r.subscribe(); + await flush(); + off(); + const reads = r.st.paths.length; + r.fs.callbackAt(0)?.(); + await flush(); + expect(r.st.paths).toHaveLength(reads); + r.subscribe(); + await flush(); + r.fs.callbackAt(0)?.(); // still the OLD generation after a re-arm + await flush(); + expect(r.st.paths).toHaveLength(reads + 1); + }); + + it('retention: only the seams survive the last unsubscribe; the reading does not, and a re-subscribe re-reads', async () => { + let free = 5; + const r = mk(() => ok(free, 9), { dataDir: '/kept' }); + const off = r.subscribe(); + await flush(); + expect(r.tracker.current()?.freeBytes).toBe(5 * MB); + off(); + expect(r.tracker.current()).toBeUndefined(); + free = 4; + r.subscribe(); + await flush(); + expect(r.st.paths).toEqual(['/kept', '/kept']); + expect(r.seen.map((s) => s.freeBytes)).toEqual([5 * MB, 4 * MB]); + }); + + it('is inert without a data dir: no timer, no read, no error; a later rebind with one starts it', async () => { + const fs = fakeScheduler(); + const st = stat(() => ok()); + const errors: unknown[] = []; + const t = new StorageTracker({ statfs: st.statfs, scheduler: fs.scheduler }, (e) => + errors.push(e), + ); + const seen: DiskReading[] = []; + t.on('disk', (r) => void seen.push(r)); + await flush(); + expect(fs.sets()).toBe(0); + expect(st.paths).toEqual([]); + t.rebind({ dataDir: '/late' }); + await flush(); + expect(st.paths).toEqual(['/late']); + expect(fs.live()).toBe(1); + expect(seen).toHaveLength(1); + expect(errors).toEqual([]); + }); + + it('a runtime without statfs (null) is inert: nothing read, no timer; rebind(undefined) never sheds the seam', async () => { + const fs = fakeScheduler(); + const t = new StorageTracker({ dataDir: '/d', statfs: null, scheduler: fs.scheduler }); + const seen: DiskReading[] = []; + t.on('disk', (r) => void seen.push(r)); + await flush(); + expect(fs.sets()).toBe(0); + expect(seen).toEqual([]); + t.rebind({ scheduler: fs.scheduler }); + expect(fs.sets()).toBe(0); // unchanged: still null + }); + + it('reads the real filesystem by default (the data dir volume)', async () => { + const fs = fakeScheduler(); + const t = new StorageTracker({ dataDir: process.cwd(), scheduler: fs.scheduler }); + const seen: DiskReading[] = []; + const off = t.on('disk', (r) => void seen.push(r)); + for (let i = 0; i < 100 && seen.length === 0; i++) await new Promise((r) => setTimeout(r, 10)); + off(); + expect(seen).toHaveLength(1); + const { freeBytes, totalBytes } = seen[0] as DiskReading; + expect(Number.isInteger(totalBytes) && totalBytes > 0).toBe(true); + expect(freeBytes <= totalBytes).toBe(true); + }); + + it("the default timer is unref'd, uses the default period and is cleared on the last unsubscribe", () => { + const real = globalThis.setInterval; + const realClear = globalThis.clearInterval; + const handle = { unref: vi.fn() }; + const cleared: unknown[] = []; + const periods: unknown[] = []; + globalThis.setInterval = ((_cb: unknown, ms: unknown) => { + periods.push(ms); + return handle; + }) as never; + globalThis.clearInterval = ((h: unknown) => void cleared.push(h)) as never; + try { + const t = new StorageTracker({ dataDir: '/d', statfs: async () => ok() }); + const off = t.on('disk', () => {}); + expect(handle.unref).toHaveBeenCalledTimes(1); + expect(periods).toEqual([5000]); + off(); + expect(cleared).toEqual([handle]); + } finally { + globalThis.setInterval = real; + globalThis.clearInterval = realClear; + } + }); + + it('a handle without unref is tolerated by the default timer', () => { + const real = globalThis.setInterval; + const realClear = globalThis.clearInterval; + globalThis.setInterval = (() => 7) as never; + globalThis.clearInterval = (() => {}) as never; + try { + const t = new StorageTracker({ dataDir: '/d', statfs: async () => ok() }); + expect(() => t.on('disk', () => {})()).not.toThrow(); + } finally { + globalThis.setInterval = real; + globalThis.clearInterval = realClear; + } + }); + + describe('failures to arm or release', () => { + it('a timer that cannot be armed is reported and leaves the tracker inert (no read), retried on the next activation', async () => { + let throwOnce = true; + const errors: unknown[] = []; + const fs = fakeScheduler(); + const st = stat(() => ok()); + const t = new StorageTracker( + { + dataDir: '/d', + statfs: st.statfs, + scheduler: { + setInterval: (cb, ms) => { + if (throwOnce) { + throwOnce = false; + throw new Error('no timer'); + } + return fs.scheduler.setInterval(cb, ms); + }, + clearInterval: fs.scheduler.clearInterval, + }, + }, + (e) => errors.push(e), + ); + const seen: DiskReading[] = []; + const off = t.on('disk', (r) => void seen.push(r)); + await flush(); + expect((errors[0] as Error).message).toBe('no timer'); + expect(st.paths).toEqual([]); + off(); + t.on('disk', (r) => void seen.push(r)); + await flush(); + expect(seen).toHaveLength(1); + }); + + it('a clearInterval that throws is reported and does not stop the teardown', async () => { + const errors: unknown[] = []; + const t = new StorageTracker( + { + dataDir: '/d', + statfs: async () => ok(), + scheduler: { + setInterval: () => 1, + clearInterval: () => { + throw new Error('clear failed'); + }, + }, + }, + (e) => errors.push(e), + ); + const off = t.on('disk', () => {}); + off(); + expect((errors[0] as Error).message).toBe('clear failed'); + // the next activation still works + t.on('disk', () => {}); + }); + }); + + describe('rebind (latest launch wins, merge never drop)', () => { + it('a changed data dir while listening re-reads IMMEDIATELY on the new path and restarts the timer', async () => { + const r = mk(() => ok(), { dataDir: '/a' }); + r.subscribe(); + await flush(); + r.tracker.rebind({ dataDir: '/b' }); + await flush(); + expect(r.st.paths).toEqual(['/a', '/b']); + expect(r.fs.sets()).toBe(2); + expect(r.fs.live()).toBe(1); // the old timer was cleared + expect(r.seen).toHaveLength(2); + }); + + it('a retained reading and failure streak of the old path do not leak into the new one', async () => { + let next: Outcome = ok(5, 9); + const errors: unknown[] = []; + const r = mk( + () => next, + { dataDir: '/a' }, + (e) => errors.push(e), + ); + r.subscribe(); + await flush(); + next = new Error('a gone'); + r.fs.tick(); + await flush(); + expect(errors).toHaveLength(1); + r.tracker.rebind({ dataDir: '/b' }); // still failing on the new path: a NEW streak is reported + await flush(); + expect(errors).toHaveLength(2); + next = ok(7, 9); + r.tracker.rebind({ dataDir: '/c' }); + expect(r.tracker.current()).toBeUndefined(); // cleared until the new read lands + await flush(); + expect(r.tracker.current()?.freeBytes).toBe(7 * MB); + }); + + it('a read of the OLD path in flight at the rebind is ignored when it settles', async () => { + const pending: Array<(r: StatFsResult) => void> = []; + const slow: StatFs = () => new Promise((resolve) => void pending.push(resolve)); + const r = mk(() => ok(), { statfs: slow, dataDir: '/a' }); + r.subscribe(); + r.tracker.rebind({ dataDir: '/b' }); + expect(pending).toHaveLength(2); + pending[0]?.(ok(1, 1)); + await flush(); + expect(r.seen).toEqual([]); + pending[1]?.(ok(2, 2)); + await flush(); + expect(r.seen).toEqual([{ freeBytes: 2 * MB, totalBytes: 2 * MB }]); + }); + + it('an UNCHANGED relaunch restarts nothing; an omitted seam keeps the earlier one', async () => { + const r = mk(() => ok(), { dataDir: '/a', intervalMs: 77 }); + r.subscribe(); + await flush(); + r.tracker.rebind({}); + r.tracker.rebind({ dataDir: '/a', intervalMs: 77, scheduler: r.fs.scheduler }); + expect(r.fs.sets()).toBe(1); + expect(r.st.paths).toEqual(['/a']); + r.tracker.rebind({ dataDir: '/b' }); + await flush(); + expect(r.fs.periods).toEqual([77, 77]); // interval kept across the data dir swap + }); + + it('a new scheduler: the old timer is cleared on the OLD scheduler and re-armed on the new one', async () => { + const r = mk(() => ok()); + r.subscribe(); + await flush(); + const next = fakeScheduler(); + r.tracker.rebind({ scheduler: next.scheduler }); + expect(r.fs.live()).toBe(0); + expect(next.live()).toBe(1); + await flush(); + next.tick(); + await flush(); + expect(r.seen).toHaveLength(3); + }); + + it('a new statfs seam is used at once; null switches the read off', async () => { + const r = mk(() => ok(1, 2)); + r.subscribe(); + await flush(); + const other = stat(() => ok(3, 4)); + r.tracker.rebind({ statfs: other.statfs }); + await flush(); + expect(other.paths).toEqual(['/data']); + expect(r.seen.at(-1)).toEqual({ freeBytes: 3 * MB, totalBytes: 4 * MB }); + r.tracker.rebind({ statfs: null }); + expect(r.fs.live()).toBe(0); + }); + + it('while idle, seams are only stored: nothing is read until a listener arrives, then it uses the latest', async () => { + const r = mk(() => ok()); + r.tracker.rebind({ dataDir: '/later' }); + expect(r.st.paths).toEqual([]); + r.subscribe(); + await flush(); + expect(r.st.paths).toEqual(['/later']); + }); + + it('the latest onError wins; undefined keeps it', async () => { + const first = vi.fn(); + const second = vi.fn(); + const r = mk(() => new Error('x'), {}, first); + r.tracker.rebind({}, second); + r.tracker.rebind({}, undefined); + r.subscribe(); + await flush(); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + }); + }); + + it('reset() drops every listener, releases the timer and ignores anything in flight', async () => { + const r = mk(() => ok()); + r.subscribe(); + r.tracker.reset(); + expect(r.fs.live()).toBe(0); + await flush(); + expect(r.seen).toEqual([]); + }); +}); + +describe('storageTrackerFor (singleton per data dir)', () => { + const done: string[] = []; + afterEach(() => { + resetStorageTracker(); + done.length = 0; + }); + + it('two launches over DIFFERENT dirs get different trackers: each keeps polling its own dir and reporting to its own onError', async () => { + const fsA = fakeScheduler(); + const fsB = fakeScheduler(); + const a = stat(() => new Error('a failed')); + const b = stat(() => new Error('b failed')); + const errA: unknown[] = []; + const errB: unknown[] = []; + const ta = storageTrackerFor( + { dataDir: '/one', statfs: a.statfs, scheduler: fsA.scheduler }, + (e) => errA.push(e), + ); + ta.on('disk', () => {}); + await flush(); + const tb = storageTrackerFor( + { dataDir: '/two', statfs: b.statfs, scheduler: fsB.scheduler }, + (e) => errB.push(e), + ); + tb.on('disk', () => {}); + await flush(); + expect(tb).not.toBe(ta); + fsA.tick(); + fsB.tick(); + await flush(); + expect(a.paths).toEqual(['/one', '/one']); + expect(b.paths).toEqual(['/two', '/two']); + // each streak reported once, to its own launch + expect(errA.map((e) => (e as Error).message)).toEqual(['a failed']); + expect(errB.map((e) => (e as Error).message)).toEqual(['b failed']); + expect(fsA.live()).toBe(1); + expect(fsB.live()).toBe(1); + }); + + it('two launches over the SAME dir share one tracker; the latest seams win and omitted ones are kept', async () => { + const fs = fakeScheduler(); + const a = stat(() => new Error('boom')); + const first = vi.fn(); + const second = vi.fn(); + const t1 = storageTrackerFor( + { dataDir: '/same', statfs: a.statfs, scheduler: fs.scheduler }, + first, + ); + const t2 = storageTrackerFor({ dataDir: '/same/' }, second); // an equivalent spelling is the same volume identity + expect(t2).toBe(t1); + t2.on('disk', () => {}); + await flush(); + expect(a.paths).toEqual(['/same']); + expect(first).not.toHaveBeenCalled(); + expect(second).toHaveBeenCalledTimes(1); + }); + + it('an explicit key overrides the data-dir identity; resetStorageTracker(key) drops just it', async () => { + const key = {}; + const fs = fakeScheduler(); + const t = storageTrackerFor({ + key, + dataDir: '/x', + statfs: stat(() => ok()).statfs, + scheduler: fs.scheduler, + }); + expect(storageTrackerFor({ dataDir: '/x' })).not.toBe(t); + expect(storageTrackerFor({ key })).toBe(t); + t.on('disk', () => {}); + expect(fs.live()).toBe(1); + resetStorageTracker(key); + expect(fs.live()).toBe(0); + expect(storageTrackerFor({ key })).not.toBe(t); + resetStorageTracker(key); + }); + + it('a launch without a data dir gets the shared inert process-keyed tracker', async () => { + const fs = fakeScheduler(); + const st = stat(() => ok()); + const t = storageTrackerFor({ statfs: st.statfs, scheduler: fs.scheduler }); + expect(storageTrackerFor()).toBe(t); + t.on('disk', () => {}); + await flush(); + expect(st.paths).toEqual([]); + expect(fs.sets()).toBe(0); + }); + + it('resetStorageTracker(dir) drops that dir only; resetStorageTracker() drops every dir tracker and the process one', async () => { + const fs1 = fakeScheduler(); + const fs2 = fakeScheduler(); + const t1 = storageTrackerFor({ + dataDir: '/r1', + statfs: stat(() => ok()).statfs, + scheduler: fs1.scheduler, + }); + const t2 = storageTrackerFor({ + dataDir: '/r2', + statfs: stat(() => ok()).statfs, + scheduler: fs2.scheduler, + }); + const p = storageTrackerFor(); + t1.on('disk', () => {}); + t2.on('disk', () => {}); + resetStorageTracker('/r1'); + expect(fs1.live()).toBe(0); + expect(fs2.live()).toBe(1); + expect(storageTrackerFor({ dataDir: '/r1' })).not.toBe(t1); + expect(storageTrackerFor({ dataDir: '/r2' })).toBe(t2); + resetStorageTracker('/never-launched'); // no-op + const rel = fakeScheduler(); + const tr = storageTrackerFor({ + dataDir: 'relative/dir', + statfs: stat(() => ok()).statfs, + scheduler: rel.scheduler, + }); + tr.on('disk', () => {}); + resetStorageTracker('relative/dir'); // the same resolved identity as the launch spelling + expect(rel.live()).toBe(0); + resetStorageTracker(); + expect(fs2.live()).toBe(0); + expect(storageTrackerFor({ dataDir: '/r2' })).not.toBe(t2); + expect(storageTrackerFor()).not.toBe(p); + }); + + it('different explicit keys never share state', () => { + const k1 = {}; + const k2 = {}; + expect(storageTrackerFor({ key: k1 })).not.toBe(storageTrackerFor({ key: k2 })); + resetStorageTracker(k1); + resetStorageTracker(k2); + }); +}); diff --git a/packages/trackers/src/node/storage-tracker.ts b/packages/trackers/src/node/storage-tracker.ts new file mode 100644 index 00000000..6350c378 --- /dev/null +++ b/packages/trackers/src/node/storage-tracker.ts @@ -0,0 +1,329 @@ +import * as fsp from 'node:fs/promises'; +import { resolve } from 'node:path'; +import nodeProcess from 'node:process'; +import { InterceptorBase } from '../interceptor-base'; +import { createTrackerRegistry } from '../tracker-registry'; + +// Node/Bun/Deno STORAGE tracker (domain tracker, design §15.2; Android reference: BugseeTrackerStorage). It owns the +// disk-space read for ONE directory's volume (the launch's effective data dir, NOT `/` or the cwd) through +// `fs.promises.statfs`, and polls it sparsely off the event loop. One stage: +// +// disk -> { freeBytes, totalBytes } free = bsize * bavail (what an unprivileged process can use), total = bsize * blocks +// +// PER-LISTENER ACTIVATION. Nothing runs at construction. While the stage has a listener the tracker reads the volume +// at once and then on its own unref'd timer (default 5 s, Android parity); with no listener there is no timer and no +// read. A tracker with no data dir, or a runtime without `statfs` (`statfs: null`, or Node < 18.15), stays inert. +// +// ABSENCE IS NEVER ZERO. A read that fails, or answers numbers that are not sane (non-positive block size or total, +// negative/non-finite free), emits nothing. `freeBytes` may be a true 0 (a full disk). FAILURES are reported once +// per failure streak (a removed data dir fails on every poll and must not flood `onError`); a success starts a new +// streak. +// +// SINGLETON per VOLUME IDENTITY (see `storageTrackerFor`): the key is the resolved data dir, so two launches over +// the same directory share one tracker and two launches over different directories get DIFFERENT trackers (a running +// launch can never be redirected to another launch's directory, nor have its failures reported to another launch's +// `onError`). A launch without a data dir gets the inert `process`-keyed tracker; an explicit `key` overrides (tests). +// Within one key, SEAMS MERGE, NEVER DROP: a later launch that omits `onError`/`scheduler`/`statfs` KEEPS the previous +// launch's (it can replace one, never shed one), and the LATEST launch's wins. A change to any seam while a listener +// is attached tears the poll down (the timer is cleared on the scheduler that armed it) and starts it again at once on +// the merged seams; an unchanged relaunch restarts nothing. Tests that inject fakes must use a private `key` or call +// `resetStorageTracker()`. +// +// RETENTION rule — what survives the last unsubscribe: ONLY the merged seams. The last reading does not survive +// (`current()` is undefined with no listener attached): free space is a live number and a retained one would be a lie +// by the next subscriber. It is also dropped on a failed/unsane read and on a path change. Every read and timer +// callback is guarded by the generation that armed it, so a read still in flight when the tracker stops, or when the +// path/seams change, can neither report nor emit when it settles, and a timer whose clear failed never reads. + +export interface StatFsResult { + bsize: number; + bavail: number; + blocks: number; +} +export type StatFs = (path: string) => Promise; + +export interface DiskReading { + freeBytes: number; + totalBytes: number; +} +export interface StorageEvents { + disk: DiskReading; +} + +export interface StorageTimers { + setInterval(callback: () => void, ms: number): unknown; + clearInterval(handle: unknown): void; +} + +/** What the tracker needs from a launch. Every member is optional; an absent one keeps the earlier launch's. */ +export interface StorageEnv { + /** The directory whose volume is measured. Without one the tracker is inert. */ + dataDir?: string; + /** Test seam. `null` = the runtime has no statfs (nothing is read). Default: `fs.promises.statfs` when present. */ + statfs?: StatFs | null; + /** Drives the poll; default the global timers, unref'd so the tracker never holds a process alive. */ + scheduler?: StorageTimers; + /** Poll period in ms (default 5000; Android reads disk every 5 s). */ + intervalMs?: number; +} + +const DEFAULT_INTERVAL_MS = 5000; + +const defaultScheduler: StorageTimers = { + setInterval: (cb, ms) => { + const h = setInterval(cb, ms); + (h as { unref?: () => void }).unref?.(); + return h; + }, + clearInterval: (h) => clearInterval(h as ReturnType), +}; + +const SEAM_KEYS = [ + 'dataDir', + 'statfs', + 'scheduler', + 'intervalMs', +] as const satisfies readonly (keyof StorageEnv)[]; + +const isCount = (n: unknown): n is number => typeof n === 'number' && Number.isFinite(n) && n >= 0; +const isPositive = (n: unknown): n is number => + typeof n === 'number' && Number.isFinite(n) && n > 0; + +export class StorageTracker extends InterceptorBase { + readonly name = 'node-storage'; + #env: StorageEnv; + #active = false; + #timer: { handle: unknown; scheduler: StorageTimers } | null = null; + #inFlight = false; + #failing = false; + /** Bumped by every teardown/restart: a read or timer callback of an older run never reports or emits. */ + #gen = 0; + #last: DiskReading | undefined; + // Mutable indirection: the SHARED tracker outlives launches, so the reporter is always the latest launch's. + readonly #report: { fn: ((error: unknown) => void) | undefined }; + + constructor(env: StorageEnv = {}, onError?: (error: unknown) => void) { + const report = { fn: onError }; + // A throwing reporter must not escape into the emitter's dispatch (which runs inside the host's timers). + super((error) => { + try { + report.fn?.(error); + } catch { + /* the reporter itself failed */ + } + }); + this.#report = report; + this.#env = env; + } + + /** + * Hand the latest launch's seams to this shared tracker. A defined `onError` replaces the reporter (undefined keeps + * it). Every defined seam REPLACES ours (`statfs: null` is defined: it switches the read off); an undefined one never + * clobbers an earlier one. When a seam actually changed and a listener is attached, the poll is torn down with the + * seams it was armed with and started again at once on the merged ones (a new path is read immediately). + */ + rebind(env: StorageEnv, onError?: (error: unknown) => void): void { + if (onError !== undefined) this.#report.fn = onError; + const merged: Record = {}; + let changed = false; + for (const key of SEAM_KEYS) { + const given = (env as Record)[key]; + const kept = (this.#env as Record)[key]; + const next = given !== undefined ? given : kept; + if (next !== undefined) merged[key] = next; + if (next !== kept) changed = true; + } + if (!changed) return; + if (this.#active) this.#end(); // OLD seams + this.#env = merged as StorageEnv; + if (this.#active) this.#begin(); + } + + /** The last reading of the current run; undefined with no listener, before the first read, and after a failed read. */ + current(): DiskReading | undefined { + return this.#last === undefined ? undefined : { ...this.#last }; + } + + /** Test/teardown: drop EVERY listener (which releases the timer and ignores anything in flight). */ + reset(): void { + this.removeAllListeners(); + } + + protected onActivate(): void { + this.#active = true; + this.#begin(); + } + + protected override onDeactivate(): void { + this.#active = false; + this.#end(); + } + + #onError(error: unknown): void { + try { + this.#report.fn?.(error); + } catch { + /* the reporter itself failed */ + } + } + + #statfs(): StatFs | undefined { + const seam = this.#env.statfs; + if (seam !== undefined) return seam ?? undefined; + // Namespace import: a Node without `statfs` (< 18.15) must degrade to "no reading", not fail to load. + return (fsp as { statfs?: StatFs }).statfs; + } + + /** Arms the timer and reads once, against the CURRENT seams. Inert without a data dir or a statfs. */ + #begin(): void { + if (this.#env.dataDir === undefined || this.#statfs() === undefined) return; + const scheduler = this.#env.scheduler ?? defaultScheduler; + const gen = ++this.#gen; + try { + const handle = scheduler.setInterval(() => { + if (gen === this.#gen) this.#read(gen); + }, this.#env.intervalMs ?? DEFAULT_INTERVAL_MS); + this.#timer = { handle, scheduler }; + } catch (error) { + this.#onError(error); // nothing would ever poll again: stay inert (retried on the next activation/rebind) + return; + } + this.#read(gen); + } + + /** Releases the timer (on the scheduler that armed it) and abandons any read in flight. */ + #end(): void { + this.#gen += 1; + this.#inFlight = false; + this.#failing = false; + this.#last = undefined; + const timer = this.#timer; + this.#timer = null; + if (timer === null) return; + try { + timer.scheduler.clearInterval(timer.handle); + } catch (error) { + this.#onError(error); + } + } + + #read(gen: number): void { + const statfs = this.#statfs(); + const dataDir = this.#env.dataDir; + if (this.#inFlight || statfs === undefined || dataDir === undefined) return; + this.#inFlight = true; + let pending: Promise; + try { + pending = Promise.resolve(statfs(dataDir)); + } catch (error) { + pending = Promise.reject(error); + } + pending.then( + (s) => { + if (gen !== this.#gen) return; + this.#inFlight = false; + this.#failing = false; + this.#publish(s); + }, + (error: unknown) => { + if (gen !== this.#gen) return; + this.#inFlight = false; + this.#last = undefined; // an unreadable volume is a gap, never the previous number + // One report per failure streak: a removed data dir fails on every poll. + if (!this.#failing) this.#onError(error); + this.#failing = true; + }, + ); + } + + // Omit, never zero: an unsane reading emits nothing. `bavail` may legitimately be 0 (a full disk). + #publish(s: StatFsResult): void { + const { bsize, bavail, blocks } = (s ?? {}) as Partial>; + if (!isPositive(bsize) || !isCount(bavail) || !isPositive(blocks)) { + this.#last = undefined; + return; + } + const freeBytes = bsize * bavail; + const totalBytes = bsize * blocks; + if (!isCount(freeBytes) || !isPositive(totalBytes)) { + this.#last = undefined; // the product overflowed + return; + } + this.#last = { freeBytes, totalBytes }; + this.emit('disk', { ...this.#last }); + } +} + +const registry = createTrackerRegistry(); + +/** A {@link StorageEnv} plus an explicit object to key the singleton on (overrides the data-dir identity; for tests). */ +export interface StorageTrackerEnv extends StorageEnv { + key?: object; +} + +function seamsOf(env: StorageTrackerEnv): StorageEnv { + const seams: Record = {}; + for (const key of SEAM_KEYS) { + const value = env[key]; + if (value !== undefined) seams[key] = value; + } + // The same normalised spelling the key uses: `/d` and `/d/` are one volume, so an equivalent relaunch is unchanged. + if (env.dataDir !== undefined) seams.dataDir = resolve(env.dataDir); + return seams as StorageEnv; +} + +// One interned key object per resolved data dir (the registry is a WeakMap over objects). The map holds one small +// object per distinct directory ever launched with; `resetStorageTracker` drops them. +const dirKeys = new Map(); + +function keyOf(env: StorageTrackerEnv): object { + if (env.key !== undefined) return env.key; + if (env.dataDir === undefined) return nodeProcess; + const dir = resolve(env.dataDir); + let key = dirKeys.get(dir); + if (key === undefined) { + key = {}; + dirKeys.set(dir, key); + } + return key; +} + +/** + * The singleton StorageTracker for the env's volume identity (the resolved `dataDir`; an explicit `key` overrides; + * no data dir means the shared inert `process`-keyed tracker). Every call (a relaunch on the same directory included) + * hands the shared tracker the latest launch's `onError` and seams (see {@link StorageTracker.rebind}); nothing else of + * the env is kept. + */ +export function storageTrackerFor( + env: StorageTrackerEnv = {}, + onError?: (error: unknown) => void, +): StorageTracker { + const seams = seamsOf(env); + return registry.for( + keyOf(env), + () => new StorageTracker(seams, onError), + (tracker) => tracker.rebind(seams, onError), + ); +} + +/** + * Test/teardown: drop trackers (resetting them, so timers are released and in-flight reads ignored). With an object + * key: that key's tracker. With a string: the tracker of that data dir. With nothing: EVERY tracker (all data dirs and + * the `process`-keyed one). + */ +export function resetStorageTracker(key?: object | string): void { + if (typeof key === 'string') { + const dir = resolve(key); + const interned = dirKeys.get(dir); + dirKeys.delete(dir); + if (interned !== undefined) registry.reset(interned); + return; + } + if (key !== undefined) { + registry.reset(key); + return; + } + for (const interned of dirKeys.values()) registry.reset(interned); + dirKeys.clear(); + registry.reset(nodeProcess); +}