polartrace 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.HostMetricsMonitor = void 0;
37
+ const os = __importStar(require("os"));
38
+ const fs = __importStar(require("fs"));
39
+ const perf_hooks_1 = require("perf_hooks");
40
+ const NS_PER_MS = 1000000;
41
+ const safePercentile = (histogram, percentile) => {
42
+ try {
43
+ return histogram.percentile(percentile) / NS_PER_MS;
44
+ }
45
+ catch {
46
+ return 0;
47
+ }
48
+ };
49
+ const readCgroupFile = (path) => {
50
+ try {
51
+ return fs.readFileSync(path, "utf-8").trim();
52
+ }
53
+ catch {
54
+ return null;
55
+ }
56
+ };
57
+ const readContainerMetrics = () => {
58
+ if (process.platform !== "linux")
59
+ return undefined;
60
+ const memMax = readCgroupFile("/sys/fs/cgroup/memory.max");
61
+ const memCurrent = readCgroupFile("/sys/fs/cgroup/memory.current");
62
+ const cpuMax = readCgroupFile("/sys/fs/cgroup/cpu.max");
63
+ if (memMax === null && memCurrent === null && cpuMax === null) {
64
+ return undefined;
65
+ }
66
+ const memoryLimitBytes = memMax === null || memMax === "max" ? null : Number.parseInt(memMax, 10);
67
+ const memoryUsageBytes = memCurrent === null ? null : Number.parseInt(memCurrent, 10);
68
+ let cpuLimitCores = null;
69
+ if (cpuMax) {
70
+ const [quotaStr, periodStr] = cpuMax.split(/\s+/);
71
+ if (quotaStr && quotaStr !== "max" && periodStr) {
72
+ const quota = Number.parseInt(quotaStr, 10);
73
+ const period = Number.parseInt(periodStr, 10);
74
+ if (!Number.isNaN(quota) && !Number.isNaN(period) && period > 0) {
75
+ cpuLimitCores = quota / period;
76
+ }
77
+ }
78
+ }
79
+ return {
80
+ memoryLimitBytes: memoryLimitBytes !== null && Number.isFinite(memoryLimitBytes)
81
+ ? memoryLimitBytes
82
+ : null,
83
+ memoryUsageBytes: memoryUsageBytes !== null && Number.isFinite(memoryUsageBytes)
84
+ ? memoryUsageBytes
85
+ : null,
86
+ cpuLimitCores,
87
+ };
88
+ };
89
+ class HostMetricsMonitor {
90
+ constructor(config) {
91
+ this.prevCpu = { user: 0, system: 0 };
92
+ this.prevWallMs = 0;
93
+ this.initialized = false;
94
+ this.config = {
95
+ sampleIntervalMs: 10000,
96
+ eventLoopResolutionMs: 20,
97
+ ...config,
98
+ };
99
+ }
100
+ initialize() {
101
+ if (this.initialized)
102
+ return;
103
+ try {
104
+ this.histogram = (0, perf_hooks_1.monitorEventLoopDelay)({
105
+ resolution: this.config.eventLoopResolutionMs,
106
+ });
107
+ this.histogram.enable();
108
+ this.prevCpu = process.cpuUsage();
109
+ this.prevWallMs = Date.now();
110
+ this.timer = setInterval(() => {
111
+ try {
112
+ this.sample();
113
+ }
114
+ catch (err) {
115
+ this.config.onError?.(err instanceof Error ? err : new Error(String(err)));
116
+ }
117
+ }, this.config.sampleIntervalMs);
118
+ this.timer.unref?.();
119
+ this.initialized = true;
120
+ }
121
+ catch (err) {
122
+ this.config.onError?.(err instanceof Error ? err : new Error(String(err)));
123
+ }
124
+ }
125
+ destroy() {
126
+ if (this.timer) {
127
+ clearInterval(this.timer);
128
+ this.timer = undefined;
129
+ }
130
+ if (this.histogram) {
131
+ this.histogram.disable();
132
+ this.histogram = undefined;
133
+ }
134
+ this.initialized = false;
135
+ }
136
+ sample() {
137
+ const nowMs = Date.now();
138
+ const cpu = process.cpuUsage();
139
+ const wallDeltaMs = Math.max(1, nowMs - this.prevWallMs);
140
+ const userDeltaMicros = cpu.user - this.prevCpu.user;
141
+ const systemDeltaMicros = cpu.system - this.prevCpu.system;
142
+ const cpuPercent = ((userDeltaMicros + systemDeltaMicros) / (wallDeltaMs * 1000)) * 100;
143
+ this.prevCpu = cpu;
144
+ this.prevWallMs = nowMs;
145
+ const mem = process.memoryUsage();
146
+ const histogram = this.histogram;
147
+ const eventLoop = histogram
148
+ ? {
149
+ meanMs: histogram.mean / NS_PER_MS,
150
+ p50Ms: safePercentile(histogram, 50),
151
+ p95Ms: safePercentile(histogram, 95),
152
+ p99Ms: safePercentile(histogram, 99),
153
+ maxMs: histogram.max / NS_PER_MS,
154
+ }
155
+ : { meanMs: 0, p50Ms: 0, p95Ms: 0, p99Ms: 0, maxMs: 0 };
156
+ histogram?.reset();
157
+ const loadAvg = os.loadavg();
158
+ const sample = {
159
+ timestamp: nowMs,
160
+ process: {
161
+ pid: process.pid,
162
+ cpuPercent: Number.isFinite(cpuPercent) ? cpuPercent : 0,
163
+ cpuUserMicros: cpu.user,
164
+ cpuSystemMicros: cpu.system,
165
+ rssBytes: mem.rss,
166
+ heapUsedBytes: mem.heapUsed,
167
+ heapTotalBytes: mem.heapTotal,
168
+ externalBytes: mem.external,
169
+ arrayBuffersBytes: mem.arrayBuffers ?? 0,
170
+ uptimeSeconds: process.uptime(),
171
+ },
172
+ eventLoop,
173
+ host: {
174
+ hostname: os.hostname(),
175
+ platform: process.platform,
176
+ cpuCount: os.cpus().length,
177
+ loadAvg1: loadAvg[0] ?? 0,
178
+ loadAvg5: loadAvg[1] ?? 0,
179
+ loadAvg15: loadAvg[2] ?? 0,
180
+ freeMemBytes: os.freemem(),
181
+ totalMemBytes: os.totalmem(),
182
+ uptimeSeconds: os.uptime(),
183
+ container: readContainerMetrics(),
184
+ },
185
+ };
186
+ this.config.onSample(sample);
187
+ }
188
+ }
189
+ exports.HostMetricsMonitor = HostMetricsMonitor;
@@ -0,0 +1,3 @@
1
+ type ModuleHandler = (exports: any) => any | void;
2
+ export declare function onModuleLoad(packageName: string, handler: ModuleHandler): void;
3
+ export {};
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.onModuleLoad = onModuleLoad;
7
+ const module_1 = __importDefault(require("module"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const handlers = new Map();
10
+ const entryCache = new Map();
11
+ let installed = false;
12
+ function packageEntryFor(request) {
13
+ if (!path_1.default.isAbsolute(request)) {
14
+ return request.startsWith(".") ? undefined : request;
15
+ }
16
+ if (entryCache.has(request))
17
+ return entryCache.get(request);
18
+ let result;
19
+ const marker = `${path_1.default.sep}node_modules${path_1.default.sep}`;
20
+ const idx = request.lastIndexOf(marker);
21
+ if (idx !== -1) {
22
+ const segments = request.slice(idx + marker.length).split(path_1.default.sep);
23
+ const name = segments[0]?.startsWith("@")
24
+ ? `${segments[0]}/${segments[1]}`
25
+ : segments[0];
26
+ if (name && handlers.has(name)) {
27
+ try {
28
+ const root = request.slice(0, idx + marker.length) + name;
29
+ if (require.resolve(root) === request)
30
+ result = name;
31
+ }
32
+ catch {
33
+ }
34
+ }
35
+ }
36
+ entryCache.set(request, result);
37
+ return result;
38
+ }
39
+ function onModuleLoad(packageName, handler) {
40
+ const existing = handlers.get(packageName);
41
+ if (existing) {
42
+ existing.push(handler);
43
+ }
44
+ else {
45
+ handlers.set(packageName, [handler]);
46
+ }
47
+ entryCache.clear();
48
+ install();
49
+ }
50
+ function install() {
51
+ if (installed)
52
+ return;
53
+ installed = true;
54
+ const ModuleAny = module_1.default;
55
+ const originalLoad = ModuleAny._load;
56
+ ModuleAny._load = function (request) {
57
+ const exports = originalLoad.apply(this, arguments);
58
+ let name;
59
+ try {
60
+ name = packageEntryFor(request);
61
+ }
62
+ catch {
63
+ return exports;
64
+ }
65
+ if (!name)
66
+ return exports;
67
+ const list = handlers.get(name);
68
+ if (!list)
69
+ return exports;
70
+ let current = exports;
71
+ for (const handler of list) {
72
+ try {
73
+ const replacement = handler(current);
74
+ if (replacement !== undefined)
75
+ current = replacement;
76
+ }
77
+ catch {
78
+ }
79
+ }
80
+ return current;
81
+ };
82
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const ts_loader_1 = require("./ts-loader");
4
+ (0, ts_loader_1.registerTypeScriptLoaderIfNeeded)();
5
+ const instrumentation_manager_1 = require("./instrumentations/instrumentation-manager");
6
+ const mongo_instrumentation_1 = require("./instrumentations/mongo.instrumentation");
7
+ const redis_instrumentation_1 = require("./instrumentations/redis.instrumentation");
8
+ const postgres_instrumentation_1 = require("./instrumentations/postgres.instrumentation");
9
+ const manager = instrumentation_manager_1.InstrumentationManager.getInstance();
10
+ manager.register(new mongo_instrumentation_1.MongoInstrumentation(() => { }));
11
+ manager.register(new redis_instrumentation_1.RedisInstrumentation(() => { }));
12
+ manager.register(new postgres_instrumentation_1.PostgresInstrumentation(() => { }));
13
+ manager.enableAll();
14
+ globalThis.__POLARTRACE_MONGO_INSTRUMENTATION_ENABLED__ = true;
15
+ globalThis.__POLARTRACE_REDIS_INSTRUMENTATION_ENABLED__ = true;
16
+ globalThis.__POLARTRACE_POSTGRES_INSTRUMENTATION_ENABLED__ = true;
@@ -0,0 +1 @@
1
+ export { TraceMonitor, TraceSpan, TraceMonitorConfig } from './trace-monitor';
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TraceMonitor = void 0;
4
+ var trace_monitor_1 = require("./trace-monitor");
5
+ Object.defineProperty(exports, "TraceMonitor", { enumerable: true, get: function () { return trace_monitor_1.TraceMonitor; } });
@@ -0,0 +1,42 @@
1
+ export interface TraceSpan {
2
+ traceId: string;
3
+ spanId: string;
4
+ parentSpanId?: string;
5
+ name: string;
6
+ kind: string;
7
+ startTime: number;
8
+ endTime: number;
9
+ duration: number;
10
+ status: {
11
+ code: string;
12
+ message?: string;
13
+ };
14
+ attributes: Record<string, any>;
15
+ events?: Array<{
16
+ name: string;
17
+ timestamp: number;
18
+ attributes?: Record<string, any>;
19
+ }>;
20
+ links?: Array<{
21
+ traceId: string;
22
+ spanId: string;
23
+ }>;
24
+ resource?: Record<string, any>;
25
+ }
26
+ export interface TraceMonitorConfig {
27
+ serviceName: string;
28
+ serviceVersion?: string;
29
+ onSpan: (span: TraceSpan) => void;
30
+ excludeAgentSpans?: boolean;
31
+ agentEndpoints?: string[];
32
+ sharedSpanIdMap?: Map<string, string>;
33
+ }
34
+ export declare class TraceMonitor {
35
+ private config;
36
+ private sdk?;
37
+ private isInitialized;
38
+ constructor(config: TraceMonitorConfig);
39
+ get initialized(): boolean;
40
+ initialize(): Promise<void>;
41
+ destroy(): void;
42
+ }