@dudousxd/nestjs-telescope
Version:
Laravel Telescope-style observability console for NestJS — core: watchers, recorder, correlation, SQLite store, headless API.
122 lines • 6.14 kB
JavaScript
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
// packages/core/src/metrics/stats.service.ts
import { Inject, Injectable, Optional } from '@nestjs/common';
import { TELESCOPE_STORAGE } from '../nest/telescope.options.js';
import { estimatePercentileFromHistogram } from '../rollup/estimate-percentile.js';
import { emptyHistogram, floorToBucket, isRollupStore, mergeHistograms, } from '../rollup/rollup-store.js';
import { collectEntriesInWindow } from './collect-window.js';
import { summarizeStats } from './stats.js';
const DEFAULT_BUCKETS = 60;
const MAX_BUCKETS = 500;
const DEFAULT_SLOW_MS = 100;
/** Computes per-type analytics (latency percentiles, family/cache/status
* breakdowns, throughput) by aggregating stored entries over a window.
* Reads the store on demand and delegates the maths to {@link summarizeStats}. */
let StatsService = class StatsService {
storage;
pageSize;
scanCap;
slowMs;
defaultBuckets;
constructor(storage, options) {
this.storage = storage;
this.pageSize = options?.pageSize;
this.scanCap = options?.scanCap;
this.slowMs = options?.slowMs ?? DEFAULT_SLOW_MS;
this.defaultBuckets = options?.defaultBuckets ?? DEFAULT_BUCKETS;
}
async getStats(query) {
if (!Number.isFinite(query.windowMs) || query.windowMs <= 0) {
throw new RangeError(`windowMs must be a positive, finite number (got ${query.windowMs}).`);
}
const buckets = Math.min(MAX_BUCKETS, Math.max(1, Math.floor(query.buckets ?? this.defaultBuckets)));
const windowEnd = new Date();
const windowStart = new Date(windowEnd.getTime() - query.windowMs);
const baseQuery = {
after: windowStart,
type: query.type,
};
const { entries, truncated } = await collectEntriesInWindow(this.storage, baseQuery, {
...(this.pageSize !== undefined ? { pageSize: this.pageSize } : {}),
...(this.scanCap !== undefined ? { scanCap: this.scanCap } : {}),
});
// Fast path for the latency percentiles ONLY: when the store supports
// rollups, estimate p50/p95/p99 from the pre-aggregated latency histogram
// (O(buckets)) instead of sorting every raw durationMs (O(rows)). Everything
// else summarizeStats does — count/max/slow, family/cache/status/exception
// breakdowns, throughput — still derives from the raw scan. When the store
// is NOT a RollupStore, the override is omitted and percentiles fall back to
// the raw-scan computation unchanged.
const latencyPercentiles = isRollupStore(this.storage)
? await this.estimatePercentiles(this.storage, query.type, windowStart, windowEnd)
: undefined;
return summarizeStats({
entries,
type: query.type,
windowStart,
windowEnd,
windowMs: query.windowMs,
buckets,
slowMs: this.slowMs,
truncated,
...(latencyPercentiles !== undefined ? { latencyPercentiles } : {}),
});
}
/**
* Queries the 1-minute latency-histogram rollups for `type` over the window,
* merges them element-wise, and estimates p50/p95/p99. Returns `undefined`
* when no histogram samples exist (total 0), so the latency block's shape and
* the "no durations ⇒ no latency" behavior match the raw path.
*/
async estimatePercentiles(store, type, windowStart, windowEnd) {
const fromBucket = floorToBucket(windowStart.getTime());
const toBucket = floorToBucket(windowEnd.getTime());
const rollups = await store.queryRollups([type], fromBucket, toBucket);
const merged = emptyHistogram();
let mergedMax = 0;
for (const rollup of rollups) {
mergeHistogramInto(merged, rollup.histogram);
mergedMax = Math.max(mergedMax, rollup.max);
}
let total = 0;
for (const count of merged)
total += count;
if (total === 0)
return undefined;
// The histogram estimate returns a bucket's UPPER boundary, which can exceed
// the true maximum (e.g. one sample of 410ms lands in the <=500ms bucket and
// estimates 500). Clamp to the rollup's exact `max` so a percentile is never
// reported above the observed maximum — `p99 > max` reads as a bug to users.
return {
p50: Math.min(estimatePercentileFromHistogram(merged, 0.5), mergedMax),
p95: Math.min(estimatePercentileFromHistogram(merged, 0.95), mergedMax),
p99: Math.min(estimatePercentileFromHistogram(merged, 0.99), mergedMax),
};
}
};
StatsService = __decorate([
Injectable(),
__param(0, Inject(TELESCOPE_STORAGE)),
__param(1, Optional()),
__metadata("design:paramtypes", [Object, Object])
], StatsService);
export { StatsService };
/** Folds `addend` into `target` in place via the canonical element-wise merge. */
function mergeHistogramInto(target, addend) {
const merged = mergeHistograms(target, addend);
for (let index = 0; index < merged.length; index += 1) {
target[index] = merged[index] ?? 0;
}
}
//# sourceMappingURL=stats.service.js.map