-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtelemetry.ts
More file actions
1121 lines (1026 loc) · 36.3 KB
/
telemetry.ts
File metadata and controls
1121 lines (1026 loc) · 36.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Telemetry for Sentry CLI
*
* Tracks anonymous usage data to improve the CLI:
* - Command execution (which commands run, success/failure)
* - Error tracking (unhandled exceptions)
* - Performance (command duration)
*
* No PII is collected. Opt-out via SENTRY_CLI_NO_TELEMETRY=1 environment variable.
*/
import { chmodSync, statSync } from "node:fs";
// biome-ignore lint/performance/noNamespaceImport: Sentry SDK recommends namespace import
import * as Sentry from "@sentry/node-core/light";
import {
CLI_VERSION,
getConfiguredSentryUrl,
SENTRY_CLI_DSN,
} from "./constants.js";
import { isReadonlyError, tryRepairAndRetry } from "./db/schema.js";
import { getEnv } from "./env.js";
import { ApiError, AuthError } from "./errors.js";
import { attachSentryReporter } from "./logger.js";
import { getSentryBaseUrl, isSentrySaasUrl } from "./sentry-urls.js";
import { getRealUsername } from "./utils.js";
export type { Span } from "@sentry/core";
/** Re-imported locally because Span is exported via re-export */
type Span = Sentry.Span;
/**
* Initialize telemetry context with user and instance information.
* Called after Sentry is initialized to set user context and instance tags.
*/
async function initTelemetryContext(): Promise<void> {
try {
// Dynamic imports to avoid circular dependencies and for ES module compatibility
const { getUserInfo } = await import("./db/user.js");
const { getInstanceId } = await import("./db/instance.js");
const user = getUserInfo();
const instanceId = getInstanceId();
if (user) {
Sentry.setUser({ id: user.userId, email: user.email });
}
if (instanceId) {
Sentry.setTag("instance_id", instanceId);
}
} catch (error) {
// Context initialization is not critical - continue without it
// But capture the error for debugging
Sentry.captureException(error);
}
}
/**
* Mark the active session as crashed.
*
* Checks both current scope and isolation scope since processSessionIntegration
* stores the session on the isolation scope. Called when a command error
* propagates through withTelemetry — the SDK auto-marks crashes for truly
* uncaught exceptions (mechanism.handled === false), but command errors need
* explicit marking.
*
* @internal Exported for testing
*/
export function markSessionCrashed(): void {
const session =
Sentry.getCurrentScope().getSession() ??
Sentry.getIsolationScope().getSession();
if (session) {
session.status = "crashed";
}
}
/**
* Wrap CLI execution with telemetry tracking.
*
* Creates a Sentry span for the command execution and captures exceptions.
* Session lifecycle is managed by the SDK's processSessionIntegration
* (started during Sentry.init) and a beforeExit handler (registered in
* initSentry) that ends healthy sessions and flushes events. This ensures
* sessions are reliably tracked even for unhandled rejections and other
* paths that bypass this function's try/catch.
*
* Telemetry can be disabled via SENTRY_CLI_NO_TELEMETRY=1 env var.
*
* @param callback - The CLI execution function to wrap, receives the span for naming
* @returns The result of the callback
*/
export async function withTelemetry<T>(
callback: (span: Span | undefined) => T | Promise<T>,
options?: { libraryMode?: boolean }
): Promise<T> {
const enabled = getEnv().SENTRY_CLI_NO_TELEMETRY !== "1";
const client = initSentry(enabled, options);
if (!client?.getOptions().enabled) {
return callback(undefined);
}
// Initialize user and instance context
await initTelemetryContext();
// Flush deferred completion telemetry (queued during __complete fast-path).
// Best-effort: never block CLI execution for telemetry emission.
try {
const { drainCompletionTelemetry } = await import(
"./db/completion-telemetry.js"
);
for (const entry of drainCompletionTelemetry()) {
Sentry.metrics.distribution("completion.duration_ms", entry.durationMs, {
attributes: { command_path: entry.commandPath },
});
}
} catch {
// Queue flush is non-essential
}
try {
return await Sentry.startSpanManual(
{ name: "cli.command", op: "cli.command", forceTransaction: true },
async (span) => {
try {
return await callback(span);
} catch (e) {
// Record 4xx API errors as span attributes instead of exceptions.
// These are user errors (wrong ID, no access) not CLI bugs, but
// recording on the span lets us detect volume spikes in Discover.
if (isClientApiError(e)) {
recordApiErrorOnSpan(span, e as ApiError);
}
throw e;
} finally {
span.end();
}
}
);
} catch (e) {
const isExpectedAuthState =
e instanceof AuthError &&
(e.reason === "not_authenticated" || e.reason === "expired");
// 4xx API errors are user errors (wrong ID, no access), not CLI bugs.
// They're recorded as span attributes above for volume-spike detection.
if (!(isExpectedAuthState || isClientApiError(e))) {
Sentry.captureException(e);
markSessionCrashed();
}
throw e;
}
}
/**
* Create a beforeExit handler that ends healthy sessions and flushes events.
*
* The SDK's processSessionIntegration only ends non-OK sessions (crashed/errored).
* This handler complements it by ending OK sessions (clean exit → 'exited')
* and flushing pending events. Includes a re-entry guard since flush is async
* and causes beforeExit to re-fire when complete.
*
* @param client - The Sentry client to flush
* @returns A handler function for process.on("beforeExit")
*
* @internal Exported for testing
*/
export function createBeforeExitHandler(
client: Sentry.LightNodeClient
): () => void {
let isFlushing = false;
return () => {
if (isFlushing) {
return;
}
isFlushing = true;
const session = Sentry.getIsolationScope().getSession();
if (session?.status === "ok") {
Sentry.endSession();
}
// Flush pending events before exit. Convert PromiseLike to Promise
// for proper error handling. The async work causes beforeExit to
// re-fire when complete, which the isFlushing guard handles.
Promise.resolve(client.flush(3000)).catch(() => {
// Ignore flush errors — telemetry should never block CLI exit
});
};
}
/**
* Check if a Sentry event represents an EPIPE error.
*
* EPIPE (errno -32) occurs when writing to a pipe whose reading end has been
* closed. This is normal Unix behavior when CLI output is piped through
* commands like `head`, `less`, or `grep -m1`. These errors are not bugs
* and should be silently dropped from telemetry.
*
* Detects both Bun-style ("EPIPE: broken pipe, write") and Node.js-style
* ("write EPIPE") error messages, plus the structured `node_system_error` context.
*
* @internal Exported for testing
*/
export function isEpipeError(event: Sentry.ErrorEvent): boolean {
// Check exception message for EPIPE
const exceptions = event.exception?.values;
if (exceptions) {
for (const ex of exceptions) {
if (ex.value?.includes("EPIPE")) {
return true;
}
}
}
// Check Node.js system error context (set by the SDK for system errors)
const systemError = event.contexts?.node_system_error as
| { code?: string }
| undefined;
if (systemError?.code === "EPIPE") {
return true;
}
return false;
}
/**
* Check if an error is a client-side (4xx) API error.
*
* 4xx errors are user errors — wrong issue IDs, no access, invalid input —
* not CLI bugs. These should be recorded as span attributes for volume-spike
* detection in Discover, but should NOT be captured as Sentry exceptions.
*
* @internal Exported for testing
*/
export function isClientApiError(error: unknown): boolean {
return error instanceof ApiError && error.status >= 400 && error.status < 500;
}
/**
* Record a client API error as span attributes for Discover queryability.
*
* Sets `api_error.status`, `api_error.message`, and optionally `api_error.detail`
* on the span. Must be called before `span.end()`.
*
* @internal Exported for testing
*/
export function recordApiErrorOnSpan(span: Span, error: ApiError): void {
span.setAttribute("api_error.status", error.status);
span.setAttribute("api_error.message", error.message);
if (error.detail) {
span.setAttribute("api_error.detail", error.detail);
}
}
/**
* Integrations to exclude for CLI.
* These add overhead without benefit for short-lived CLI processes.
*/
const EXCLUDED_INTEGRATIONS = new Set([
"Console", // Captures console output - too noisy for CLI
"ContextLines", // Reads source files - we rely on uploaded sourcemaps instead
"LocalVariables", // Captures local variables - adds significant overhead
"Modules", // Lists all loaded modules - unnecessary for CLI telemetry
]);
/**
* Integrations to exclude in library mode.
*
* Extends {@link EXCLUDED_INTEGRATIONS} with integrations that register
* global process listeners, monkey-patch builtins, or monitor child
* processes — all of which would pollute the host application's runtime.
*/
const LIBRARY_EXCLUDED_INTEGRATIONS = new Set([
...EXCLUDED_INTEGRATIONS,
"OnUncaughtException", // process.on('uncaughtException')
"OnUnhandledRejection", // process.on('unhandledRejection')
"ProcessSession", // process.on('beforeExit') — anonymous handler, no cleanup
"Http", // diagnostics_channel + trace headers
"NodeFetch", // diagnostics_channel + trace headers
"FunctionToString", // wraps Function.prototype.toString
"ChildProcess", // monitors child processes
"NodeContext", // reads OS info
]);
/**
* Check whether `util.getSystemErrorMap` exists at setup time.
* Bun does not implement this Node.js API, which the SDK's NodeSystemError
* integration uses in its `processEvent` hook. When missing, the hook crashes
* during event processing instead of sending the error report (CLI-K1).
*
* Checked once at module load so the integration filter is a simple boolean.
*/
const hasGetSystemErrorMap = (() => {
try {
// Dynamic require to avoid bundler issues — the check only matters at runtime
const util = require("node:util") as Record<string, unknown>;
return typeof util.getSystemErrorMap === "function";
} catch {
return false;
}
})();
/** Current beforeExit handler, tracked so it can be replaced on re-init */
let currentBeforeExitHandler: (() => void) | null = null;
/** Match all SaaS regional URLs (us.sentry.io, de.sentry.io, o1234.ingest.us.sentry.io, etc.) */
const SENTRY_SAAS_SUBDOMAIN_RE = /^https:\/\/[^/]*\.sentry\.io(\/|$)/;
/** Match the bare sentry.io domain itself */
const SENTRY_SAAS_ROOT_RE = /^https:\/\/sentry\.io(\/|$)/;
/**
* Build trace propagation targets for Sentry API URLs.
*
* Matches:
* - SaaS: *.sentry.io (all regional URLs like us.sentry.io, de.sentry.io)
* - SaaS: sentry.io itself
* - Self-hosted: the configured SENTRY_HOST/SENTRY_URL if non-SaaS
*
* @internal Exported for testing
*/
export function getSentryTracePropagationTargets(): (string | RegExp)[] {
const targets: (string | RegExp)[] = [
SENTRY_SAAS_SUBDOMAIN_RE,
SENTRY_SAAS_ROOT_RE,
];
// Also match self-hosted Sentry instances
const customUrl = getConfiguredSentryUrl();
if (customUrl && !isSentrySaasUrl(customUrl)) {
targets.push(customUrl);
}
return targets;
}
/**
* Initialize Sentry for telemetry.
*
* @param enabled - Whether telemetry is enabled
* @param options - Optional configuration
* @param options.libraryMode - When true, strips all global-polluting
* integrations (process listeners, HTTP trace headers, Function.prototype
* patches) and disables logs/client reports to avoid timers and beforeExit
* handlers. The caller is responsible for calling `client.flush()` manually.
* @returns The Sentry client, or undefined if initialization failed
*
* @internal Exported for testing
*/
export function initSentry(
enabled: boolean,
options?: { libraryMode?: boolean }
): Sentry.LightNodeClient | undefined {
const libraryMode = options?.libraryMode ?? false;
const environment = getEnv().NODE_ENV ?? "development";
// Close the previous client to clean up its internal timers and beforeExit
// handlers (client report flusher interval, log flush listener). Without
// this, re-initializing the SDK (e.g., in tests) leaks setInterval handles
// that keep the event loop alive and prevent the process from exiting.
// close(0) removes listeners synchronously; we don't need to await the flush.
Sentry.getClient()?.close(0);
const client = Sentry.init({
dsn: SENTRY_CLI_DSN,
enabled,
// Keep default integrations but filter out ones that add overhead without benefit.
// Important: Don't use defaultIntegrations: false as it may break debug ID support.
// NodeSystemError is excluded on runtimes missing util.getSystemErrorMap (Bun) — CLI-K1.
// Library mode uses the extended exclusion set to avoid polluting the host process.
integrations: (defaults) => {
const excluded = libraryMode
? LIBRARY_EXCLUDED_INTEGRATIONS
: EXCLUDED_INTEGRATIONS;
return defaults.filter(
(integration) =>
!excluded.has(integration.name) &&
(integration.name !== "NodeSystemError" || hasGetSystemErrorMap)
);
},
environment,
// Enable Sentry structured logs for non-exception telemetry (e.g., unexpected input warnings).
// Disabled when telemetry is off or in library mode — the SDK registers
// beforeExit handlers for log flushing that keep the event loop alive.
enableLogs: enabled && !libraryMode,
// Disable client reports when telemetry is off or in library mode — the SDK
// registers a setInterval + beforeExit handler that keep the event loop alive.
...((libraryMode || !enabled) && { sendClientReports: false }),
// Sample all events for CLI telemetry (low volume)
tracesSampleRate: 1,
sampleRate: 1,
release: CLI_VERSION,
// Propagate traces to Sentry API for distributed tracing
tracePropagationTargets: getSentryTracePropagationTargets(),
beforeSendTransaction: (event) => {
// Remove server_name which may contain hostname (PII)
event.server_name = undefined;
return event;
},
beforeSend: (event) => {
// Remove server_name which may contain hostname (PII)
event.server_name = undefined;
// EPIPE errors are expected when stdout is piped and the consumer closes
// early (e.g., `sentry issue list | head`). Not actionable — drop them.
if (isEpipeError(event)) {
return null;
}
return event;
},
});
// Always remove our own previous handler on re-init.
if (currentBeforeExitHandler) {
process.removeListener("beforeExit", currentBeforeExitHandler);
currentBeforeExitHandler = null;
}
if (client?.getOptions().enabled) {
const isBun = typeof process.versions.bun !== "undefined";
const runtime = isBun ? "bun" : "node";
// LightNodeClient hardcodes runtime to { name: 'node' }. Override it so
// events carry the correct runtime when running as a compiled Bun binary.
const opts = client.getOptions();
opts.runtime = {
name: runtime,
version: isBun ? process.versions.bun : process.version,
};
// Tag whether running as bun binary or node (npm package).
// Kept alongside the SDK's promoted 'runtime' tag for explicit signaling
// and backward compatibility with existing dashboards/alerts.
Sentry.setTag("cli.runtime", runtime);
// Tag whether targeting self-hosted Sentry (not SaaS)
Sentry.setTag("is_self_hosted", !isSentrySaasUrl(getSentryBaseUrl()));
// Tag whether running in an interactive terminal or agent/CI environment
Sentry.setTag("is_tty", !!process.stdout.isTTY);
// Wire up consola → Sentry log forwarding now that the client is active
attachSentryReporter();
// End healthy sessions and flush events when the event loop drains.
// The SDK's processSessionIntegration starts a session during init and
// registers its own beforeExit handler that ends non-OK (crashed/errored)
// sessions. We complement it by ending OK sessions (clean exit → 'exited')
// and flushing pending events. This covers unhandled rejections and other
// paths that bypass withTelemetry's try/catch.
// Ref: https://nodejs.org/api/process.html#event-beforeexit
//
// Skipped in library mode — the host owns the process lifecycle.
// The library entry point calls client.flush() manually after completion.
//
if (!libraryMode) {
currentBeforeExitHandler = createBeforeExitHandler(client);
process.on("beforeExit", currentBeforeExitHandler);
}
}
return client;
}
/**
* Set the command name on the telemetry span.
*
* Called by stricli's forCommand context builder with the resolved
* command path (e.g., "auth.login", "issue.list").
*
* @param span - The span to update (from withTelemetry callback)
* @param command - The command name (dot-separated path)
*/
export function setCommandSpanName(
span: Span | undefined,
command: string
): void {
if (span) {
Sentry.updateSpanName(span, command);
}
// Also set as tag for easier filtering in Sentry UI
Sentry.setTag("command", command);
}
/**
* Set organization and project context as tags.
*
* Call this from commands after resolving the target org/project
* to enable filtering by org/project in Sentry.
* Accepts arrays to support multi-project commands.
*
* @param orgs - Organization slugs
* @param projects - Project slugs
*/
export function setOrgProjectContext(orgs: string[], projects: string[]): void {
if (orgs.length > 0) {
Sentry.setTag("sentry.org", orgs.join(","));
}
if (projects.length > 0) {
Sentry.setTag("sentry.project", projects.join(","));
}
}
/**
* Flag names whose values must never be sent to telemetry.
* Values for these flags are replaced with "[REDACTED]" regardless of content.
*/
const SENSITIVE_FLAGS = new Set(["token"]);
/**
* Set command flags as telemetry tags.
*
* Converts flag names from camelCase to kebab-case and sets them as tags
* with the `flag.` prefix (e.g., `flag.no-modify-path`).
*
* Only sets tags for flags with non-default/meaningful values:
* - Boolean flags: only when true
* - String/number flags: only when defined and non-empty
* - Array flags: only when non-empty
*
* Sensitive flags (e.g., `--token`) have their values replaced with
* "[REDACTED]" to prevent secrets from reaching telemetry.
*
* Call this at the start of command func() to instrument flag usage.
*
* @param flags - The parsed flags object from Stricli
*
* @example
* ```ts
* async func(this: SentryContext, flags: MyFlags): Promise<void> {
* setFlagContext(flags);
* // ... command implementation
* }
* ```
*/
export function setFlagContext(flags: Record<string, unknown>): void {
for (const [key, value] of Object.entries(flags)) {
// Skip undefined/null values
if (value === undefined || value === null) {
continue;
}
// Skip false booleans (default state)
if (value === false) {
continue;
}
// Skip empty strings
if (value === "") {
continue;
}
// Skip empty arrays
if (Array.isArray(value) && value.length === 0) {
continue;
}
// Convert camelCase to kebab-case for consistency with CLI flag names
const kebabKey = key.replace(/([A-Z])/g, "-$1").toLowerCase();
// Redact sensitive flag values (e.g., API tokens) — never send secrets to telemetry
if (SENSITIVE_FLAGS.has(kebabKey)) {
Sentry.setTag(`flag.${kebabKey}`, "[REDACTED]");
continue;
}
// Set the tag with flag. prefix
// For booleans, just set "true"; for other types, convert to string
const tagValue =
typeof value === "boolean" ? "true" : String(value).slice(0, 200); // Truncate long values
Sentry.setTag(`flag.${kebabKey}`, tagValue);
}
}
/**
* Set positional arguments as Sentry context.
*
* Stores positional arguments in a structured context for debugging.
* Unlike tags, context is not indexed but provides richer data.
*
* @param args - The positional arguments passed to the command
*/
export function setArgsContext(args: readonly unknown[]): void {
if (args.length === 0) {
return;
}
Sentry.setContext("args", {
values: args.map((arg) =>
typeof arg === "string" ? arg : JSON.stringify(arg)
),
count: args.length,
});
}
/**
* Wrap an operation with a Sentry span for tracing.
*
* Creates a child span under the current active span to track
* operation duration and status. Automatically sets span status
* to OK on success or Error on failure.
*
* Use this generic helper for custom operations, or use the specialized
* helpers (withHttpSpan, withDbSpan, withFsSpan, withSerializeSpan) for
* common operation types.
*
* @param name - Span name (e.g., "scanDirectory", "findProjectRoot")
* @param op - Operation type (e.g., "dsn.scan", "file.read")
* @param fn - Function to execute within the span
* @param attributes - Optional span attributes for additional context
* @returns The result of the function
*/
export function withTracing<T>(
name: string,
op: string,
fn: () => T | Promise<T>,
attributes?: Record<string, string | number | boolean>
): Promise<T> {
return Sentry.startSpan(
{ name, op, attributes, onlyIfParent: true },
async (span) => {
try {
const result = await fn();
span.setStatus({ code: 1 }); // OK
return result;
} catch (error) {
span.setStatus({ code: 2 }); // Error
throw error;
}
}
);
}
/**
* Wrap an operation with a Sentry span, passing the span to the callback.
*
* Like `withTracing`, but passes the span to the callback for cases where
* you need to set attributes or record metrics during execution.
* Automatically sets span status to OK on success or Error on failure,
* unless the callback has already set a status.
*
* @param name - Span name (e.g., "scanDirectory", "findProjectRoot")
* @param op - Operation type (e.g., "dsn.scan", "file.read")
* @param fn - Function to execute, receives the span as argument
* @param attributes - Optional initial span attributes
* @returns The result of the function
*
* @example
* ```ts
* const result = await withTracingSpan(
* "scanDirectory",
* "dsn.scan",
* async (span) => {
* const files = await collectFiles();
* span.setAttribute("files.count", files.length);
* return processFiles(files);
* },
* { "scan.dir": cwd }
* );
* ```
*/
export function withTracingSpan<T>(
name: string,
op: string,
fn: (span: Span) => T | Promise<T>,
attributes?: Record<string, string | number | boolean>
): Promise<T> {
return Sentry.startSpan(
{ name, op, attributes, onlyIfParent: true },
async (span) => {
// Track if callback sets status, so we don't override it
let statusWasSet = false;
const originalSetStatus = span.setStatus.bind(span);
span.setStatus = (...args) => {
statusWasSet = true;
return originalSetStatus(...args);
};
try {
const result = await fn(span);
if (!statusWasSet) {
span.setStatus({ code: 1 }); // OK
}
return result;
} catch (error) {
if (!statusWasSet) {
span.setStatus({ code: 2 }); // Error
}
throw error;
}
}
);
}
/**
* Wrap an HTTP request with a span for tracing.
*
* Creates a child span under the current active span to track
* HTTP request duration and status.
*
* @param method - HTTP method (GET, POST, etc.)
* @param url - Request URL or path
* @param fn - The async function that performs the HTTP request
* @returns The result of the function
*/
export function withHttpSpan<T>(
method: string,
url: string,
fn: () => Promise<T>
): Promise<T> {
return withTracing(`${method} ${url}`, "http.client", fn, {
"http.request.method": method,
"url.path": url,
});
}
/**
* Wrap a database operation with a span for tracing.
*
* Creates a child span under the current active span to track
* database operation duration. This is a synchronous wrapper that
* preserves the sync nature of the callback.
*
* Use this for grouping logical operations (e.g., "clearAuth" which runs
* multiple queries). Individual SQL queries are automatically traced when
* using a database wrapped with `createTracedDatabase`.
*
* @param operation - Name of the operation (e.g., "getAuthToken", "setDefaults")
* @param fn - The function that performs the database operation
* @returns The result of the function
*/
export function withDbSpan<T>(operation: string, fn: () => T): T {
return Sentry.startSpan(
{
name: operation,
op: "db.operation",
attributes: { "db.system": "sqlite" },
onlyIfParent: true,
},
fn
);
}
/** Intentional no-op used as a self-replacement target for one-shot functions. */
// biome-ignore lint/suspicious/noEmptyBlockStatements: intentional noop
const noop = (): void => {};
/** Resolves the database path, falling back to a default if the import fails. */
function resolveDbPath(): string {
try {
const { getDbPath } = require("./db/index.js") as {
getDbPath: () => string;
};
return getDbPath();
} catch {
return "~/.sentry/cli.db";
}
}
/**
* Print a one-time warning to stderr when the local database is read-only.
* Replaces itself with a noop after the first call so subsequent invocations
* are free. Assigned via `let` so the binding can be swapped.
*
* Uses lazy require for db/index.js to avoid a circular dependency
* (db/index.ts imports createTracedDatabase from this module).
*/
let warnReadonlyDatabaseOnce = (): void => {
warnReadonlyDatabaseOnce = noop;
const dbPath = resolveDbPath();
process.stderr.write(
`\nWarning: Sentry CLI local database is read-only. Caching and preferences won't persist.\n` +
` Path: ${dbPath}\n` +
" Fix: sentry cli fix\n\n"
);
};
/** Whether we already attempted a permission repair this process. */
let repairAttempted = false;
/**
* Attempt to repair database file permissions so future commands can write.
*
* SQLite caches the readonly state at connection open time, so even after a
* successful chmod the *current* connection remains readonly. This function
* repairs permissions for the NEXT command and prints a differentiated message.
* If the repair fails (e.g., file owned by another user) we fall through to
* {@link warnReadonlyDatabaseOnce} which tells the user to run `sentry cli fix`.
*
* Replaces itself with a noop after the first call via the `repairAttempted`
* guard so we only try once per process.
*/
/**
* Chmod a path, ignoring ENOENT (file doesn't exist yet).
* Re-throws any other error so permission failures aren't silently masked.
*/
function chmodIfExists(filePath: string, mode: number): void {
try {
chmodSync(filePath, mode);
} catch (error: unknown) {
if (
error instanceof Error &&
(error as NodeJS.ErrnoException).code === "ENOENT"
) {
return;
}
throw error;
}
}
/**
* Check whether the file at `filePath` is owned by root (uid 0).
* Returns false if the file doesn't exist, can't be stat'd, or if running on
* Windows where `fs.stat().uid` always returns 0 regardless of ownership.
*/
function isOwnedByRoot(filePath: string): boolean {
// Windows fs.stat() always reports uid 0 — skip the check entirely.
if (process.platform === "win32") {
return false;
}
try {
return statSync(filePath).uid === 0;
} catch {
return false;
}
}
function tryRepairReadonly(): boolean {
if (repairAttempted) {
return false;
}
repairAttempted = true;
const dbPath = resolveDbPath();
const { dirname } = require("node:path") as {
dirname: (p: string) => string;
};
const configDir = dirname(dbPath);
// If the config dir or DB file is root-owned, chmod won't help.
// Emit an actionable message telling the user to run sudo chown.
if (isOwnedByRoot(configDir) || isOwnedByRoot(dbPath)) {
const username = getRealUsername();
// Disable the generic warning — we're emitting a better one here.
warnReadonlyDatabaseOnce = noop;
process.stderr.write(
"\nWarning: Sentry CLI config directory is owned by root.\n" +
` Path: ${configDir}\n` +
` Fix: sudo chown -R ${username} "${configDir}"\n` +
" Or: sudo sentry cli fix\n\n"
);
return false;
}
try {
// Repair config directory (needs rwx for WAL/SHM creation)
chmodSync(configDir, 0o700);
// Repair database file and journal files
chmodSync(dbPath, 0o600);
chmodIfExists(`${dbPath}-wal`, 0o600);
chmodIfExists(`${dbPath}-shm`, 0o600);
// Disable the fallback warning — repair succeeded
warnReadonlyDatabaseOnce = noop;
process.stderr.write(
"\nNote: Database permissions were auto-repaired. Caching will resume on next command.\n\n"
);
return true;
} catch {
// chmod failed — fall through so warnReadonlyDatabaseOnce fires
return false;
}
}
/**
* Reset all readonly-related state (for testing).
* @internal
*/
export function resetReadonlyWarning(): void {
repairAttempted = false;
warnReadonlyDatabaseOnce = (): void => {
warnReadonlyDatabaseOnce = noop;
const dbPath = resolveDbPath();
process.stderr.write(
`\nWarning: Sentry CLI local database is read-only. Caching and preferences won't persist.\n` +
` Path: ${dbPath}\n` +
" Fix: sentry cli fix\n\n"
);
};
}
/** Methods on SQLite Statement that execute queries and should be traced */
const TRACED_STATEMENT_METHODS = ["get", "run", "all", "values"] as const;
/**
* Handle a readonly database error by attempting auto-repair and returning a
* type-appropriate no-op value. Returns `undefined` for run/get (void / no-row)
* and `[]` for all/values (empty result set).
*
* First tries to repair file permissions via {@link tryRepairReadonly}. If that
* fails (or was already attempted), falls back to a one-shot warning directing
* the user to `sentry cli fix`.
*/
function handleReadonlyError(method: string | symbol): unknown {
if (!tryRepairReadonly()) {
warnReadonlyDatabaseOnce();
}
if (method === "all" || method === "values") {
return [];
}
return;
}
/**
* Wrap a SQLite Statement to automatically trace query execution.
*
* Intercepts get/run/all/values methods and wraps them with Sentry spans
* that include the SQL query as both the span name and db.statement attribute.
*
* @param stmt - The SQLite Statement to wrap
* @param sql - The SQL query string (parameterized)
* @returns A proxied Statement with automatic tracing
*
* @internal Used by createTracedDatabase
*/
function createTracedStatement<T>(stmt: T, sql: string): T {
return new Proxy(stmt as object, {
get(target, prop) {
const value = Reflect.get(target, prop);
// Non-function properties pass through directly
if (typeof value !== "function") {
return value;
}
// Non-traced methods get bound to preserve 'this' context for native methods
if (
!TRACED_STATEMENT_METHODS.includes(
prop as (typeof TRACED_STATEMENT_METHODS)[number]
)
) {
return value.bind(target);
}
// Traced methods get wrapped with Sentry span and auto-repair
return (...args: unknown[]) =>
Sentry.startSpan(
{
name: sql,
op: "db",
attributes: {
"db.system": "sqlite",
"db.statement": sql,
},
onlyIfParent: true,
},
() => {
const execute = () =>
(value as (...a: unknown[]) => unknown).apply(target, args);
try {
return execute();
} catch (error) {
// Attempt auto-repair for schema errors
const repairResult = tryRepairAndRetry(execute, error);
if (repairResult.attempted) {
return repairResult.result;
}
// Handle readonly database gracefully: warn once, skip the write.
// The CLI still works — reads succeed, only caching/persistence is lost.
if (isReadonlyError(error)) {
return handleReadonlyError(prop);
}
// Re-throw if repair didn't help or wasn't applicable
throw error;
}
}
);
},
}) as T;
}
/** Minimal interface for a database with a query method */
type QueryableDatabase = { query: (sql: string) => unknown };
/**
* Wrap a SQLite Database to automatically trace all queries.
*
* Intercepts the query() method and wraps returned Statements with
* createTracedStatement, which traces get/run/all/values calls.