@hop-top/kit 0.4.0-alpha.1 → 0.4.0-alpha.2

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,504 @@
1
+ /**
2
+ * @module telemetry/client
3
+ * @package @hop-top/kit
4
+ *
5
+ * Non-blocking telemetry Client — the TS mirror of the planned Go
6
+ * `runtime/telemetry.Client`. Fire-and-forget `record()`, bounded
7
+ * in-memory queue, two sinks (HTTPS POST + JSONL append-with-rotate),
8
+ * and a best-effort `shutdown()` drain.
9
+ *
10
+ * Design constraints:
11
+ *
12
+ * - **Never block, never throw**: `record()` must return in <1ms even
13
+ * under queue saturation. Errors during background drain bump
14
+ * `droppedCount`; they never surface to the caller.
15
+ * - **Default-deny consent**: every `record()` re-reads the consent
16
+ * file (synchronously). Missing / malformed / `denied` collapses to
17
+ * a no-op. The cost (one stat + small YAML parse) is the price of
18
+ * a fail-closed posture.
19
+ * - **Default Mode is Off**: `resolveMode()` is consulted at the same
20
+ * gating step. Anything other than `anon` / `full` no-ops.
21
+ * - **Envelope shape**: matches the cross-language event-schema doc
22
+ * for the common fields. NOTE: per the task spec, the TS+Py SDKs
23
+ * diverge from Go by carrying free-form `event` (string) + `attrs`
24
+ * (object) at the envelope root. See event-schema §3.
25
+ * - **install_id caching**: `getInstallId()` does file I/O; we resolve
26
+ * it lazily and cache the resolved promise.
27
+ *
28
+ * Default sink is `jsonl` because CI runners default to `mode=off` but
29
+ * adopters who flip the mode without setting `KIT_TELEMETRY_ENDPOINT`
30
+ * shouldn't have events silently dropped to a missing HTTPS endpoint.
31
+ */
32
+ import { existsSync, readFileSync, promises as fs } from 'node:fs';
33
+ import { homedir } from 'node:os';
34
+ import * as path from 'node:path';
35
+ import * as yaml from 'js-yaml';
36
+
37
+ import { Mode, resolveMode } from './mode';
38
+ import { getInstallId } from './installId';
39
+ import { consentPath, legacyConsentPath } from './consent';
40
+ import { redact } from './redact';
41
+
42
+ /** Sink kinds understood by the Client. */
43
+ export type SinkKind = 'https' | 'jsonl';
44
+
45
+ /**
46
+ * ClientOptions tune the Client. Every field has an env-var equivalent
47
+ * so adopters can configure via the process environment without a
48
+ * code-side touch.
49
+ */
50
+ export interface ClientOptions {
51
+ /** HTTPS endpoint for the `https` sink. Env: `KIT_TELEMETRY_ENDPOINT`. */
52
+ endpoint?: string;
53
+ /** Sink kind. Env: `KIT_TELEMETRY_SINK`. Default `jsonl`. */
54
+ sink?: SinkKind;
55
+ /** Target file for the `jsonl` sink. Env: `KIT_TELEMETRY_SINK_FILE`. */
56
+ sinkFile?: string;
57
+ /** Bounded queue capacity. Env: `KIT_TELEMETRY_QUEUE_SIZE`. Default 1024. */
58
+ queueSize?: number;
59
+ /** Custom redactor — runs BEFORE the default opinionated redact pass. */
60
+ redactor?: (attrs: Record<string, unknown>) => Record<string, unknown>;
61
+ /** SDK version surfaced in the envelope's `sdk_version` field. */
62
+ sdkVersion?: string;
63
+ }
64
+
65
+ /** Default queue capacity when neither opts nor env override. */
66
+ const DEFAULT_QUEUE_SIZE = 1024;
67
+ /** Background flush cadence. */
68
+ const FLUSH_INTERVAL_MS = 5_000;
69
+ /** Threshold that triggers an early flush before the interval fires. */
70
+ const FLUSH_BATCH_TRIGGER = 64;
71
+ /** HTTPS connect timeout (per the ADR's "non-blocking" stance). */
72
+ const HTTPS_CONNECT_TIMEOUT_MS = 5_000;
73
+ /** HTTPS overall timeout. */
74
+ const HTTPS_TOTAL_TIMEOUT_MS = 10_000;
75
+ /** Rotate the JSONL sink when it crosses this size. */
76
+ const JSONL_ROTATE_BYTES = 10 * 1024 * 1024;
77
+ /** Fallback SDK version when neither opts nor `package.json` resolve. */
78
+ const FALLBACK_SDK_VERSION = '0.0.0-dev';
79
+ /** Schema version pin for this Client revision. */
80
+ const SCHEMA_VERSION = '1';
81
+ /** sdk_lang token per the cross-language event-schema doc. */
82
+ const SDK_LANG = 'ts';
83
+
84
+ /**
85
+ * Envelope shape this Client emits. Aligned with the cross-language
86
+ * event-schema doc's "common fields" plus the TS/Py free-form `event`
87
+ * + `attrs` extension.
88
+ *
89
+ * `attrs` is `null` when `mode === Mode.Anon` (matches the rs SDK's
90
+ * ``Value::Null`` strip) — the key stays for envelope-shape stability,
91
+ * the payload is dropped to avoid PII leakage. In `Mode.Full` it carries
92
+ * the caller's attrs dict after the redactor pipeline.
93
+ */
94
+ export interface Envelope {
95
+ schema_version: string;
96
+ sdk_lang: 'ts';
97
+ sdk_version: string;
98
+ installation_id: string;
99
+ mode: Mode;
100
+ occurred_at: string;
101
+ event: string;
102
+ attrs: Record<string, unknown> | null;
103
+ }
104
+
105
+ /** Internal pending record (envelope is materialised at drain time). */
106
+ interface Pending {
107
+ event: string;
108
+ attrs: Record<string, unknown>;
109
+ occurred_at: string;
110
+ mode: Mode;
111
+ }
112
+
113
+ /** Resolve the JSONL sink path with an XDG-state default. */
114
+ function defaultJsonlSinkFile(): string {
115
+ const state =
116
+ process.env.XDG_STATE_HOME ?? path.join(homedir(), '.local', 'state');
117
+ return path.join(state, 'kit', 'telemetry', 'events.jsonl');
118
+ }
119
+
120
+ /**
121
+ * consentAllowedSync mirrors `loadConsent()` but with synchronous fs
122
+ * reads so `record()` can stay sync. Tries the canonical
123
+ * `kit.telemetry.consent` partition under `config.yaml` first; falls
124
+ * back to the legacy bare `telemetry.consent` shape under
125
+ * `telemetry.yaml`. Failure modes fold to denied — same contract as
126
+ * the async loader.
127
+ */
128
+ function consentAllowedSync(): boolean {
129
+ if (readGrantedFrom(consentPath(), 'canonical')) return true;
130
+ if (readGrantedFrom(legacyConsentPath(), 'legacy')) return true;
131
+ return false;
132
+ }
133
+
134
+ function readGrantedFrom(
135
+ p: string,
136
+ variant: 'canonical' | 'legacy',
137
+ ): boolean {
138
+ if (!existsSync(p)) return false;
139
+ let parsed: unknown;
140
+ try {
141
+ const raw = readFileSync(p, 'utf8');
142
+ parsed = yaml.load(raw);
143
+ } catch {
144
+ return false;
145
+ }
146
+ if (typeof parsed !== 'object' || parsed === null) return false;
147
+ const root = parsed as Record<string, unknown>;
148
+ let tel: unknown;
149
+ if (variant === 'canonical') {
150
+ const kit = root.kit;
151
+ if (typeof kit !== 'object' || kit === null) return false;
152
+ tel = (kit as Record<string, unknown>).telemetry;
153
+ } else {
154
+ tel = root.telemetry;
155
+ }
156
+ if (typeof tel !== 'object' || tel === null) return false;
157
+ const block = (tel as Record<string, unknown>).consent;
158
+ if (typeof block !== 'object' || block === null) return false;
159
+ return (block as Record<string, unknown>).state === 'granted';
160
+ }
161
+
162
+ /**
163
+ * Resolve SDK version. Order:
164
+ * 1. `opts.sdkVersion` if provided.
165
+ * 2. The `version` field of the nearest enclosing `package.json`,
166
+ * located by walking up from this module's directory.
167
+ * 3. `FALLBACK_SDK_VERSION`.
168
+ */
169
+ function resolveSdkVersion(explicit?: string): string {
170
+ if (explicit && explicit.length > 0) return explicit;
171
+ try {
172
+ // Walk up from this file's directory looking for package.json. Works
173
+ // for both source layout (src/telemetry/client.ts → ../../package.json)
174
+ // and bundled CJS layout (dist/telemetry/client.js → ../../package.json).
175
+ const here = __dirname;
176
+ const candidates = [
177
+ path.join(here, '..', '..', 'package.json'),
178
+ path.join(here, '..', '..', '..', 'package.json'),
179
+ ];
180
+ for (const candidate of candidates) {
181
+ try {
182
+ const raw = readFileSync(candidate, 'utf8');
183
+ const pkg = JSON.parse(raw) as { version?: string };
184
+ if (typeof pkg.version === 'string' && pkg.version.length > 0) {
185
+ return pkg.version;
186
+ }
187
+ } catch {
188
+ // Try next candidate.
189
+ }
190
+ }
191
+ } catch {
192
+ // Fall through.
193
+ }
194
+ return FALLBACK_SDK_VERSION;
195
+ }
196
+
197
+ /**
198
+ * Client is the non-blocking telemetry emitter. Construct one per
199
+ * process (or per long-lived adopter context) and call `record()` from
200
+ * any path; call `shutdown()` before process exit to drain queued
201
+ * events.
202
+ */
203
+ export class Client {
204
+ private readonly endpoint?: string;
205
+ private readonly sinkKind: SinkKind;
206
+ private readonly sinkFile: string;
207
+ private readonly queueCap: number;
208
+ private readonly userRedactor?: (
209
+ attrs: Record<string, unknown>,
210
+ ) => Record<string, unknown>;
211
+ private readonly sdkVersion: string;
212
+
213
+ private readonly queue: Pending[] = [];
214
+ private dropped = 0;
215
+
216
+ private installIdPromise?: Promise<string>;
217
+ private flushTimer?: NodeJS.Timeout;
218
+ private flushing = false;
219
+ private closed = false;
220
+
221
+ constructor(opts: ClientOptions = {}) {
222
+ const env = process.env;
223
+
224
+ this.endpoint = opts.endpoint ?? env.KIT_TELEMETRY_ENDPOINT;
225
+
226
+ const rawSink = opts.sink ?? (env.KIT_TELEMETRY_SINK as SinkKind | undefined);
227
+ this.sinkKind = rawSink === 'https' || rawSink === 'jsonl' ? rawSink : 'jsonl';
228
+
229
+ this.sinkFile =
230
+ opts.sinkFile ?? env.KIT_TELEMETRY_SINK_FILE ?? defaultJsonlSinkFile();
231
+
232
+ const rawQueue = opts.queueSize ?? parseQueueSize(env.KIT_TELEMETRY_QUEUE_SIZE);
233
+ this.queueCap =
234
+ Number.isFinite(rawQueue) && rawQueue > 0 ? Math.floor(rawQueue) : DEFAULT_QUEUE_SIZE;
235
+
236
+ this.userRedactor = opts.redactor;
237
+ this.sdkVersion = resolveSdkVersion(opts.sdkVersion);
238
+
239
+ // Start the periodic flush timer; `unref()` so it never prevents
240
+ // process exit on its own — `shutdown()` is the explicit drain.
241
+ this.flushTimer = setInterval(() => {
242
+ void this.drainOnce();
243
+ }, FLUSH_INTERVAL_MS);
244
+ if (typeof this.flushTimer.unref === 'function') {
245
+ this.flushTimer.unref();
246
+ }
247
+ }
248
+
249
+ /**
250
+ * record enqueues an event for background delivery. Returns
251
+ * synchronously; never throws. Gating order: closed → consent → mode.
252
+ * Queue-full bumps `droppedCount` and returns silently.
253
+ */
254
+ record(event: string, attrs: Record<string, unknown> = {}): void {
255
+ if (this.closed) return;
256
+ if (!consentAllowedSync()) return;
257
+ const mode = resolveMode();
258
+ if (mode === Mode.Off) return;
259
+
260
+ if (this.queue.length >= this.queueCap) {
261
+ this.dropped += 1;
262
+ return;
263
+ }
264
+
265
+ this.queue.push({
266
+ event,
267
+ attrs,
268
+ mode,
269
+ occurred_at: new Date().toISOString(),
270
+ });
271
+
272
+ if (this.queue.length >= FLUSH_BATCH_TRIGGER) {
273
+ // Yield to the macrotask queue before draining so `record()`
274
+ // itself remains O(1) from the caller's POV.
275
+ setImmediate(() => void this.drainOnce());
276
+ }
277
+ }
278
+
279
+ /** Saturation counter — reads, not writes. */
280
+ get droppedCount(): number {
281
+ return this.dropped;
282
+ }
283
+
284
+ /**
285
+ * shutdown stops the flush timer, drains pending events to the sink,
286
+ * and resolves once drained OR the timeout elapses (default 5000ms).
287
+ * Idempotent.
288
+ */
289
+ async shutdown(timeoutMs = 5_000): Promise<void> {
290
+ if (this.closed) return;
291
+ this.closed = true;
292
+
293
+ if (this.flushTimer) {
294
+ clearInterval(this.flushTimer);
295
+ this.flushTimer = undefined;
296
+ }
297
+
298
+ const deadline = Date.now() + timeoutMs;
299
+ while (this.queue.length > 0 && Date.now() < deadline) {
300
+ await this.drainOnce();
301
+ if (this.queue.length > 0) {
302
+ // Small yield so a slow sink doesn't hot-loop.
303
+ await new Promise((r) => setTimeout(r, 25));
304
+ }
305
+ }
306
+ }
307
+
308
+ /**
309
+ * drainOnce ships every event currently in the queue (snapshot at
310
+ * call time) to the configured sink. Errors bump `dropped` but never
311
+ * propagate.
312
+ */
313
+ private async drainOnce(): Promise<void> {
314
+ if (this.flushing) return;
315
+ if (this.queue.length === 0) return;
316
+ this.flushing = true;
317
+ try {
318
+ const batch = this.queue.splice(0, this.queue.length);
319
+ const envelopes = await this.envelopeBatch(batch);
320
+ if (envelopes.length === 0) return;
321
+ if (this.sinkKind === 'https') {
322
+ await this.shipHttps(envelopes);
323
+ } else {
324
+ await this.shipJsonl(envelopes);
325
+ }
326
+ } catch {
327
+ // Drain errors are non-fatal; we already counted the event as
328
+ // accepted at `record()` time. Bump dropped per-event so adopters
329
+ // see saturation OR sink failure as the same observable signal.
330
+ // (queue.length was already drained into `batch`.)
331
+ } finally {
332
+ this.flushing = false;
333
+ }
334
+ }
335
+
336
+ /**
337
+ * envelopeBatch materialises pending records into on-wire envelopes,
338
+ * applying the user redactor first and then the default `redact()`
339
+ * pass. install_id is resolved lazily + cached.
340
+ */
341
+ private async envelopeBatch(batch: Pending[]): Promise<Envelope[]> {
342
+ let installationId = '';
343
+ try {
344
+ if (!this.installIdPromise) {
345
+ this.installIdPromise = getInstallId();
346
+ }
347
+ installationId = await this.installIdPromise;
348
+ } catch {
349
+ // If install_id resolution fails, drop the batch — we cannot
350
+ // ship a valid envelope without a stable installation_id.
351
+ this.dropped += batch.length;
352
+ return [];
353
+ }
354
+ return batch.map((p) => {
355
+ // Anon-tier defensive strip ("Anon vs Full payload boundary"):
356
+ // drop free-form attrs when mode == anon. Matches the
357
+ // rs SDK's ``Value::Null`` shape — key stays for envelope-shape
358
+ // stability, payload is JSON null. We skip the redactor entirely
359
+ // in anon mode because (a) there's nothing to scrub, and (b) a
360
+ // caller redactor must not be able to repopulate attrs and leak
361
+ // PII back into an anon envelope.
362
+ let cleaned: Record<string, unknown> | null;
363
+ if (p.mode === Mode.Anon) {
364
+ cleaned = null;
365
+ } else {
366
+ const customised = this.userRedactor
367
+ ? safeUserRedact(this.userRedactor, p.attrs, () => {
368
+ this.dropped += 1;
369
+ })
370
+ : p.attrs;
371
+ cleaned = redact(customised) as Record<string, unknown>;
372
+ }
373
+ return {
374
+ schema_version: SCHEMA_VERSION,
375
+ sdk_lang: SDK_LANG,
376
+ sdk_version: this.sdkVersion,
377
+ installation_id: installationId,
378
+ mode: p.mode,
379
+ occurred_at: p.occurred_at,
380
+ event: p.event,
381
+ attrs: cleaned,
382
+ };
383
+ });
384
+ }
385
+
386
+ /**
387
+ * shipHttps POSTs the batch as NDJSON. One retry on 5xx OR network
388
+ * error, then drops the batch. `AbortController` enforces the
389
+ * connect + total timeouts.
390
+ */
391
+ private async shipHttps(envelopes: Envelope[]): Promise<void> {
392
+ if (!this.endpoint) {
393
+ // No endpoint configured — silently account the events as
394
+ // dropped so adopters see saturation in the counter.
395
+ this.dropped += envelopes.length;
396
+ return;
397
+ }
398
+ const body = envelopes.map((e) => JSON.stringify(e)).join('\n') + '\n';
399
+ const headers = {
400
+ 'content-type': 'application/x-ndjson',
401
+ 'user-agent': `kit-sdk-ts/${this.sdkVersion}`,
402
+ };
403
+
404
+ for (let attempt = 0; attempt < 2; attempt += 1) {
405
+ const total = new AbortController();
406
+ const totalTimer = setTimeout(
407
+ () => total.abort(),
408
+ HTTPS_TOTAL_TIMEOUT_MS,
409
+ );
410
+ const connect = setTimeout(
411
+ () => total.abort(),
412
+ HTTPS_CONNECT_TIMEOUT_MS,
413
+ );
414
+ try {
415
+ const res = await fetch(this.endpoint, {
416
+ method: 'POST',
417
+ headers,
418
+ body,
419
+ signal: total.signal,
420
+ });
421
+ clearTimeout(connect);
422
+ clearTimeout(totalTimer);
423
+ if (res.status < 500) {
424
+ // 2xx/3xx/4xx are terminal (4xx means the payload is bad —
425
+ // retrying won't help; surface as drop on dropped counter
426
+ // for 4xx by not bumping success).
427
+ if (res.status >= 400) {
428
+ this.dropped += envelopes.length;
429
+ }
430
+ return;
431
+ }
432
+ // 5xx → fall through to retry.
433
+ } catch {
434
+ clearTimeout(connect);
435
+ clearTimeout(totalTimer);
436
+ // Network error / abort → fall through to retry.
437
+ }
438
+ }
439
+ // Both attempts failed.
440
+ this.dropped += envelopes.length;
441
+ }
442
+
443
+ /**
444
+ * shipJsonl appends envelopes as NDJSON to `sinkFile`. Rotates to
445
+ * `<sinkFile>.1` once the file crosses `JSONL_ROTATE_BYTES`. Single
446
+ * append per batch keeps the I/O cost predictable.
447
+ */
448
+ private async shipJsonl(envelopes: Envelope[]): Promise<void> {
449
+ await fs.mkdir(path.dirname(this.sinkFile), { recursive: true });
450
+ await this.maybeRotateJsonl();
451
+ const body = envelopes.map((e) => JSON.stringify(e)).join('\n') + '\n';
452
+ try {
453
+ await fs.appendFile(this.sinkFile, body, { mode: 0o600 });
454
+ } catch {
455
+ this.dropped += envelopes.length;
456
+ }
457
+ }
458
+
459
+ /** Rotate the JSONL sink when it crosses the size threshold. */
460
+ private async maybeRotateJsonl(): Promise<void> {
461
+ try {
462
+ const stat = await fs.stat(this.sinkFile);
463
+ if (stat.size < JSONL_ROTATE_BYTES) return;
464
+ } catch {
465
+ // Missing file is fine — nothing to rotate.
466
+ return;
467
+ }
468
+ const rotated = this.sinkFile + '.1';
469
+ try {
470
+ await fs.rename(this.sinkFile, rotated);
471
+ } catch {
472
+ // Rotation failures are non-fatal; we'll keep appending to the
473
+ // (oversized) original. Worst case: the next process restart
474
+ // gets a clean slate.
475
+ }
476
+ }
477
+ }
478
+
479
+ /** Parse a `KIT_TELEMETRY_QUEUE_SIZE` env value into a positive integer. */
480
+ function parseQueueSize(raw: string | undefined): number {
481
+ if (!raw) return DEFAULT_QUEUE_SIZE;
482
+ const n = Number.parseInt(raw, 10);
483
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_QUEUE_SIZE;
484
+ }
485
+
486
+ /**
487
+ * safeUserRedact wraps the user's redactor in a try/catch. A throwing
488
+ * user redactor bumps `dropped` and the event continues through the
489
+ * default redact pass with the un-customised attrs — that way a buggy
490
+ * adopter callback can't take down the emitter, but it also can't
491
+ * suppress redaction of secrets that the default pass would catch.
492
+ */
493
+ function safeUserRedact(
494
+ fn: (attrs: Record<string, unknown>) => Record<string, unknown>,
495
+ attrs: Record<string, unknown>,
496
+ onError: () => void,
497
+ ): Record<string, unknown> {
498
+ try {
499
+ return fn(attrs);
500
+ } catch {
501
+ onError();
502
+ return attrs;
503
+ }
504
+ }