Repository navigation
Expand file tree
/
Copy pathtelemetry.rs
More file actions
1842 lines (1699 loc) · 65.2 KB
/
Copy pathtelemetry.rs
File metadata and controls
1842 lines (1699 loc) · 65.2 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
use std::collections::HashMap;
use once_cell::sync::Lazy;
use uuid::Uuid;
use crate::api::client::ApiRoute;
use crate::constants::USER_AGENT;
use crate::utils::env_compat::{is_offline_env, proxy_url_from_env};
use crate::utils::fs::home_dir;
use crate::vex::time::unix_to_ymdhms;
// ---------------------------------------------------------------------------
// Session ID — generated once per process invocation
// ---------------------------------------------------------------------------
/// Unique session ID for the current CLI invocation.
/// Shared across all telemetry events in a single run.
static SESSION_ID: Lazy<String> = Lazy::new(|| Uuid::new_v4().to_string());
/// Package version — sourced from the crate's `Cargo.toml` at build time so
/// it always tracks the real release (matching `USER_AGENT` in `constants.rs`
/// and the `vex` tooling string). A hardcoded literal here silently drifts
/// from the published version.
const PACKAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
/// Telemetry event types for the patch lifecycle.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PatchTelemetryEventType {
// Write-side: apply / remove / rollback
PatchApplied,
PatchApplyFailed,
PatchRemoved,
PatchRemoveFailed,
PatchRolledBack,
PatchRollbackFailed,
// Read-side: scan / get (get is internally "fetch")
PatchScanned,
PatchScanFailed,
PatchFetched,
PatchFetchFailed,
// Write-side: vendor
PatchVendored,
PatchVendorFailed,
// Inspection / housekeeping
PatchListed,
PatchRepaired,
PatchRepairFailed,
// OpenVEX attestation (added in #81)
VexGenerated,
VexFailed,
// Self-update (`socket-patch --update`)
CliUpdated,
CliUpdateFailed,
}
impl PatchTelemetryEventType {
/// Every variant, for the backend-contract test.
#[cfg(test)]
const ALL: [Self; 19] = [
Self::PatchApplied,
Self::PatchApplyFailed,
Self::PatchRemoved,
Self::PatchRemoveFailed,
Self::PatchRolledBack,
Self::PatchRollbackFailed,
Self::PatchScanned,
Self::PatchScanFailed,
Self::PatchFetched,
Self::PatchFetchFailed,
Self::PatchVendored,
Self::PatchVendorFailed,
Self::PatchListed,
Self::PatchRepaired,
Self::PatchRepairFailed,
Self::VexGenerated,
Self::VexFailed,
Self::CliUpdated,
Self::CliUpdateFailed,
];
/// Return the wire-format string for this event type.
fn as_str(&self) -> &'static str {
match self {
Self::PatchApplied => "patch_applied",
Self::PatchApplyFailed => "patch_apply_failed",
Self::PatchRemoved => "patch_removed",
Self::PatchVendored => "patch_vendored",
Self::PatchVendorFailed => "patch_vendor_failed",
Self::PatchRemoveFailed => "patch_remove_failed",
Self::PatchRolledBack => "patch_rolled_back",
Self::PatchRollbackFailed => "patch_rollback_failed",
Self::PatchScanned => "patch_scanned",
Self::PatchScanFailed => "patch_scan_failed",
Self::PatchFetched => "patch_fetched",
Self::PatchFetchFailed => "patch_fetch_failed",
Self::PatchListed => "patch_listed",
Self::PatchRepaired => "patch_repaired",
Self::PatchRepairFailed => "patch_repair_failed",
Self::VexGenerated => "vex_generated",
Self::VexFailed => "vex_failed",
Self::CliUpdated => "cli_updated",
Self::CliUpdateFailed => "cli_update_failed",
}
}
}
/// Telemetry context describing the execution environment.
#[derive(Debug, Clone, serde::Serialize)]
struct PatchTelemetryContext {
version: String,
platform: String,
arch: String,
command: String,
}
/// Error details for telemetry events.
#[derive(Debug, Clone, serde::Serialize)]
struct PatchTelemetryError {
#[serde(rename = "type")]
error_type: String,
message: Option<String>,
}
/// Telemetry event structure for patch operations.
#[derive(Debug, Clone, serde::Serialize)]
struct PatchTelemetryEvent {
event_sender_created_at: String,
event_type: String,
context: PatchTelemetryContext,
session_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<HashMap<String, serde_json::Value>>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<PatchTelemetryError>,
}
// ---------------------------------------------------------------------------
// Environment checks
// ---------------------------------------------------------------------------
/// Check if telemetry is disabled via environment variables.
///
/// Telemetry is disabled when:
/// - `SOCKET_TELEMETRY_DISABLED` is `"1"` or `"true"`
/// - `VITEST` is `"true"`. Load-bearing downstream dependency, not a relic:
/// socket-cli's vitest integration suite
/// (`packages/cli/test/integration/cli/cmd-patch*.test.mts`) spawns this
/// binary with its inherited environment and sets no
/// `SOCKET_TELEMETRY_DISABLED`, so this gate is the only thing keeping
/// those runs from POSTing telemetry to the public proxy.
/// - `SOCKET_OFFLINE` is `"1"` or `"true"` (airgap mode — the telemetry
/// endpoint is a network call, so honoring `--offline`/`SOCKET_OFFLINE`
/// here keeps every command compliant with the strict-airgap contract)
///
/// Note that the CLI also exposes a `--no-telemetry` flag; when that flag
/// is set the CLI dispatcher sets `SOCKET_TELEMETRY_DISABLED=1` for the
/// duration of the process so this check stays the single source of truth.
pub fn is_telemetry_disabled() -> bool {
let env_value = std::env::var("SOCKET_TELEMETRY_DISABLED").unwrap_or_default();
let disabled_via_env = matches!(env_value.as_str(), "1" | "true");
let vitest = std::env::var("VITEST").unwrap_or_default() == "true";
disabled_via_env || vitest || is_offline_env()
}
/// Log debug messages when debug mode is enabled.
fn debug_log(message: &str) {
crate::utils::env_compat::debug_log("telemetry", message);
}
// ---------------------------------------------------------------------------
// Build event
// ---------------------------------------------------------------------------
/// Build the telemetry context for the current environment.
fn build_telemetry_context(command: &str) -> PatchTelemetryContext {
PatchTelemetryContext {
version: PACKAGE_VERSION.to_string(),
platform: std::env::consts::OS.to_string(),
arch: std::env::consts::ARCH.to_string(),
command: command.to_string(),
}
}
/// Sanitize an error message for telemetry.
///
/// Every URL in it is redacted ([`crate::utils::redact::redact_urls_in`]:
/// userinfo, grant tokens, signed query values), and the user's home
/// directory path is replaced with `~` to avoid leaking sensitive file
/// system information.
pub fn sanitize_error_message(message: &str) -> String {
let message = crate::utils::redact::redact_urls_in(message);
let message = message.as_ref();
let Some(home) = home_dir() else {
return message.to_string();
};
let home = home.to_string_lossy();
// `home_dir()` is `None` with no (absolute) home set, so a set-but-empty
// HOME never reaches here — replacing `""` would splice `~` between
// every byte. Trailing separators are trimmed so a `HOME=/home/user/` redaction keeps
// the separator (`~/.cache`, not `~.cache`); a home that trims to nothing
// (`HOME=/`, common for unmapped-UID containers) is a filesystem root with
// no user-identifying prefix to redact — replacing it would splice `~`
// between every path segment in the message.
let home = home.trim_end_matches(['/', '\\']);
if home.is_empty() {
return message.to_string();
}
message.replace(home, "~")
}
/// Build a telemetry event. `error` is an `(error_type, message)` pair; the
/// message is home-dir-sanitized before it leaves the process.
fn build_telemetry_event(
event_type: PatchTelemetryEventType,
command: &str,
metadata: Option<HashMap<String, serde_json::Value>>,
error: Option<(String, String)>,
) -> PatchTelemetryEvent {
PatchTelemetryEvent {
event_sender_created_at: chrono_now_iso(),
event_type: event_type.as_str().to_string(),
context: build_telemetry_context(command),
session_id: SESSION_ID.clone(),
metadata,
error: error.map(|(error_type, message)| PatchTelemetryError {
error_type,
message: Some(sanitize_error_message(&message)),
}),
}
}
/// Get the current time as an ISO 8601 string with millisecond precision,
/// e.g. `2024-01-15T10:30:45.123Z`. The civil-date arithmetic is shared with
/// `vex::time` (`unix_to_ymdhms`); only the `.mmm` suffix differs from the
/// RFC 3339 string vex emits.
fn chrono_now_iso() -> String {
let duration = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default();
let (year, month, day, hours, minutes, seconds) = unix_to_ymdhms(duration.as_secs());
let millis = duration.subsec_millis();
format!("{year:04}-{month:02}-{day:02}T{hours:02}:{minutes:02}:{seconds:02}.{millis:03}Z")
}
// ---------------------------------------------------------------------------
// Send event
// ---------------------------------------------------------------------------
/// Where a run's telemetry events go, and the bearer they carry: the org
/// API's `/v0/orgs/<slug>/telemetry` with the token, or the public proxy's
/// `/patch/telemetry` anonymously.
///
/// A command that built an [`ApiClient`](crate::api::client::ApiClient)
/// takes this from it ([`Self::for_client`]), so its telemetry follows the
/// run's one [`ApiRoute`] — the same host and org as every API call. Only a
/// command that never builds a client (`list`) uses
/// [`Self::from_credentials`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TelemetryAuth {
url: String,
/// The bearer token to attach (org endpoint only).
bearer: Option<String>,
}
impl TelemetryAuth {
/// The client's route: its org endpoint with its token, or the proxy
/// endpoint on its (proxy) base URL.
pub fn for_client(client: &crate::api::client::ApiClient) -> Self {
let base = client.api_url().trim_end_matches('/');
match client.route() {
ApiRoute::Org { slug } => Self {
url: format!("{base}/v0/orgs/{slug}/telemetry"),
bearer: client.api_token().cloned(),
},
ApiRoute::Proxy => Self::proxy_at(base),
}
}
/// The route for a command without a client, with no network: the org
/// endpoint only when BOTH a non-empty token and a non-empty org slug
/// are given (the API base from env → socket-cli config → default, as
/// client construction resolves it), else the proxy from the
/// environment. An empty string is treated as absent: a `Some("")` slug
/// would otherwise build a malformed `/v0/orgs//telemetry` URL and a
/// `Some("")` token an empty `Bearer ` header.
pub fn from_credentials(api_token: Option<&str>, org_slug: Option<&str>) -> Self {
let token = api_token.filter(|t| !t.is_empty());
let slug = org_slug.filter(|s| !s.is_empty());
match (token, slug) {
(Some(token), Some(slug)) => {
let api_url = crate::utils::socket_cli_config::resolve_api_base_url();
// Trim trailing slashes like `ApiClient::new` does, so a base
// URL of `https://host/` doesn't produce a `//v0/...` path.
let api_url = api_url.trim_end_matches('/');
Self {
url: format!("{api_url}/v0/orgs/{slug}/telemetry"),
bearer: Some(token.to_string()),
}
}
_ => Self::proxy_at(&proxy_url_from_env()),
}
}
fn proxy_at(base: &str) -> Self {
Self {
url: format!("{}/patch/telemetry", base.trim_end_matches('/')),
bearer: None,
}
}
/// The endpoint events are POSTed to.
pub fn url(&self) -> &str {
&self.url
}
/// Whether events carry the bearer (org endpoint).
pub fn is_authenticated(&self) -> bool {
self.bearer.is_some()
}
}
/// A telemetry event with its destination resolved, ready to POST. Built
/// synchronously where the event fires (timestamp, env and config reads,
/// the "Sending telemetry" debug line), so sending it inline or from a
/// background task posts the very same request.
struct PreparedSend {
event: PatchTelemetryEvent,
url: String,
/// The bearer token to attach (authenticated endpoint only).
bearer: Option<String>,
}
/// Address `event` per `auth`.
fn prepare_send(event: PatchTelemetryEvent, auth: &TelemetryAuth) -> PreparedSend {
debug_log(&format!("Sending telemetry to {}", auth.url));
PreparedSend {
event,
url: auth.url.clone(),
bearer: auth.bearer.clone(),
}
}
/// Send a telemetry event to the API.
///
/// This is fire-and-forget: errors are logged in debug mode but never
/// propagated. Uses `reqwest` with a 5-second request timeout and a
/// 2-second connect timeout: a command awaits every send before it exits
/// (inline, or via [`PendingTelemetry::flush`]), so a network that
/// blackholes the endpoint (dropped SYNs, no RST) must give up on the
/// handshake quickly rather than stall even a read-only `scan --json` for
/// the full request budget.
async fn send_telemetry_event(prepared: PreparedSend) {
let PreparedSend { event, url, bearer } = prepared;
let client = match crate::utils::http::client_builder()
.connect_timeout(std::time::Duration::from_secs(2))
.timeout(std::time::Duration::from_secs(5))
.build()
{
Ok(c) => c,
Err(e) => {
debug_log(&format!("Failed to build HTTP client: {e}"));
return;
}
};
let mut request = client
.post(&url)
.header("Content-Type", "application/json")
.header("User-Agent", USER_AGENT);
if let Some(token) = bearer {
request = request.header("Authorization", format!("Bearer {token}"));
}
match request.json(&event).send().await {
Ok(response) => {
let status = response.status();
if status.is_success() {
debug_log("Telemetry sent successfully");
} else {
debug_log(&format!("Telemetry request returned status {status}"));
}
}
Err(e) => {
debug_log(&format!("Telemetry request failed: {e}"));
}
}
}
/// Telemetry sends a command started off its critical path. Each send is
/// spawned where its event fires (the event is built right there, so its
/// body and timestamp are what an inline send would have posted) and the
/// command awaits [`Self::flush`] before its first stdout write after that
/// point — the send overlaps only the work in between, and is delivered (or
/// given up on within the same 2 s connect / 5 s request budget) before
/// any output that could raise SIGPIPE, and before any prompt a Ctrl-C
/// could interrupt, exactly as an inline send was.
///
/// One `--debug`-only difference is inherent to the overlap and accepted:
/// the "Sending telemetry to …" line still prints where the event fires,
/// but its "Telemetry sent successfully" twin now prints where the send
/// finishes (by [`Self::flush`] at the latest), so the two are no longer
/// adjacent — whatever the run did in between sits between them. Each
/// line is still one atomic `eprintln!`, and no other stream is affected.
#[derive(Debug, Default)]
pub struct PendingTelemetry {
sends: Vec<tokio::task::JoinHandle<()>>,
}
impl PendingTelemetry {
pub fn new() -> Self {
Self::default()
}
/// Await every send started so far, in start order. Idempotent: a
/// second flush with nothing started since returns at once.
pub async fn flush(&mut self) {
for send in std::mem::take(&mut self.sends) {
// A send never panics on its own; a JoinError here can only be
// a runtime shutting down, which leaves nothing to deliver.
let _ = send.await;
}
}
fn spawn(&mut self, prepared: PreparedSend) {
self.sends
.push(tokio::spawn(send_telemetry_event(prepared)));
}
/// [`Self::spawn`] a prepared event, or do nothing when telemetry is
/// disabled (`prepare` returned `None`).
fn spawn_prepared(&mut self, prepared: Option<PreparedSend>) {
if let Some(prepared) = prepared {
self.spawn(prepared);
}
}
}
// ---------------------------------------------------------------------------
// Per-event tracker wrappers (the public API)
//
// Each takes the run's `TelemetryAuth` (see `TelemetryAuth::for_client`).
// ---------------------------------------------------------------------------
/// Build the event the tracker wrappers below send, or `None` when
/// telemetry is disabled via environment variables. `metadata` is a
/// `serde_json::json!({...})` object; non-object / empty values are dropped
/// to avoid `.unwrap()` noise at every call site.
fn prepare(
event_type: PatchTelemetryEventType,
command: &'static str,
metadata: serde_json::Value,
error: Option<impl std::fmt::Display>,
auth: &TelemetryAuth,
) -> Option<PreparedSend> {
if is_telemetry_disabled() {
debug_log("Telemetry is disabled, skipping event");
return None;
}
let metadata = match metadata {
serde_json::Value::Object(map) if !map.is_empty() => Some(map.into_iter().collect()),
_ => None,
};
let error = error.map(|e| ("Error".to_string(), e.to_string()));
let event = build_telemetry_event(event_type, command, metadata, error);
Some(prepare_send(event, auth))
}
/// Shared fire-and-forget helper for the per-event tracker wrappers below.
///
/// Never returns errors: telemetry failures are logged in debug mode but
/// do not affect CLI operation. Returns immediately when telemetry is
/// disabled via environment variables.
async fn fire(
event_type: PatchTelemetryEventType,
command: &'static str,
metadata: serde_json::Value,
error: Option<impl std::fmt::Display>,
auth: &TelemetryAuth,
) {
fire_prepared(prepare(event_type, command, metadata, error, auth)).await;
}
/// Send a prepared event inline, or return at once when telemetry is
/// disabled (`prepare` returned `None`).
async fn fire_prepared(prepared: Option<PreparedSend>) {
if let Some(prepared) = prepared {
send_telemetry_event(prepared).await;
}
}
/// Track a successful in-place (agent mode) patch application.
pub async fn track_patch_applied(patches_count: usize, dry_run: bool, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::PatchApplied,
"apply",
serde_json::json!({
"patches_count": patches_count,
"dry_run": dry_run,
"mode": "agent",
}),
None::<&str>,
auth,
)
.await;
}
/// Track a failed patch application.
///
/// Accepts any `Display` type for the error (works with `&str`, `String`,
/// `anyhow::Error`, `std::io::Error`, etc.).
pub async fn track_patch_apply_failed(
error: impl std::fmt::Display,
dry_run: bool,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::PatchApplyFailed,
"apply",
serde_json::json!({ "dry_run": dry_run, "mode": "agent" }),
Some(error),
auth,
)
.await;
}
/// Track a hosted-mode run (`scan`/`get --mode hosted`) that pinned
/// patched dependencies to Socket's hosted patch server. Sent as
/// `patch_applied` with `mode: "hosted"`: the lockfile pin is how hosted
/// mode applies a patch, and the backend's adoption views count
/// `patch_applied`. `files_count` is the number of lockfiles/manifests
/// rewritten.
pub async fn track_patch_hosted(
command: &'static str,
patches_count: usize,
files_count: usize,
dry_run: bool,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::PatchApplied,
command,
serde_json::json!({
"patches_count": patches_count,
"files_count": files_count,
"dry_run": dry_run,
"mode": "hosted",
}),
None::<&str>,
auth,
)
.await;
}
/// Track a failed hosted-mode run (see [`track_patch_hosted`]).
pub async fn track_patch_hosted_failed(
command: &'static str,
error: impl std::fmt::Display,
dry_run: bool,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::PatchApplyFailed,
command,
serde_json::json!({ "dry_run": dry_run, "mode": "hosted" }),
Some(error),
auth,
)
.await;
}
/// Track a successful vendor run (count = packages vendored).
pub async fn track_patch_vendored(vendored_count: u32, dry_run: bool, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::PatchVendored,
"vendor",
serde_json::json!({ "patches_count": vendored_count, "dry_run": dry_run }),
None::<&str>,
auth,
)
.await;
}
/// Track a failed vendor run.
pub async fn track_patch_vendor_failed(
error: impl std::fmt::Display,
dry_run: bool,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::PatchVendorFailed,
"vendor",
serde_json::json!({ "dry_run": dry_run }),
Some(error),
auth,
)
.await;
}
/// Track a successful patch removal.
pub async fn track_patch_removed(removed_count: usize, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::PatchRemoved,
"remove",
serde_json::json!({ "removed_count": removed_count }),
None::<&str>,
auth,
)
.await;
}
/// Track a failed patch removal. Accepts any `Display` type for the error.
pub async fn track_patch_remove_failed(error: impl std::fmt::Display, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::PatchRemoveFailed,
"remove",
serde_json::Value::Null,
Some(error),
auth,
)
.await;
}
/// Track a successful patch rollback.
pub async fn track_patch_rolled_back(rolled_back_count: usize, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::PatchRolledBack,
"rollback",
serde_json::json!({ "rolled_back_count": rolled_back_count }),
None::<&str>,
auth,
)
.await;
}
/// Track a failed patch rollback. Accepts any `Display` type for the error.
pub async fn track_patch_rollback_failed(error: impl std::fmt::Display, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::PatchRollbackFailed,
"rollback",
serde_json::Value::Null,
Some(error),
auth,
)
.await;
}
// ---------------------------------------------------------------------------
// Read-side trackers: scan + get
// ---------------------------------------------------------------------------
/// The whole `patch_scanned` event — type, command and metadata (per-tier
/// patch counts, whether the call was downgraded to the public proxy
/// after an auth-endpoint 401/403, the mode the run was asked for —
/// `hosted` / `vendored` / `agent`, or `report` with none — and the modes
/// the project is already wired for, from its hosted lockfile pins, vendor
/// ledger and agent manifest). Both wrappers below build their event here,
/// so the inline and background paths can never drift apart.
#[allow(clippy::too_many_arguments)]
fn prepare_patch_scanned(
packages_scanned: usize,
free_patches: usize,
paid_patches: usize,
can_access_paid: bool,
ecosystems: &[String],
fallback_to_proxy: bool,
mode: &str,
project_modes: &[&str],
auth: &TelemetryAuth,
) -> Option<PreparedSend> {
prepare(
PatchTelemetryEventType::PatchScanned,
"scan",
serde_json::json!({
"packages_scanned": packages_scanned,
"free_patches": free_patches,
"paid_patches": paid_patches,
"can_access_paid": can_access_paid,
"ecosystems": ecosystems,
"fallback_to_proxy": fallback_to_proxy,
"mode": mode,
"project_modes": project_modes,
}),
None::<&str>,
auth,
)
}
/// Track a successful `scan`. Reports per-tier patch counts and whether
/// the call was downgraded to the public proxy after an auth-endpoint
/// 401/403 (`fallback_to_proxy`).
///
/// The argument count intentionally mirrors the metadata fields the
/// dashboard needs — grouping them into a struct would force callers
/// to build a config object for a single fire-and-forget call, which
/// is worse ergonomics for a tracker.
///
/// The CLI's `scan` sends this event through [`spawn_patch_scanned`]; the
/// inline tracker stays as this published crate's public API, alongside
/// the inline tracker every other event has. Both build the event with
/// [`prepare_patch_scanned`], so neither can describe it differently.
#[allow(clippy::too_many_arguments)]
pub async fn track_patch_scanned(
packages_scanned: usize,
free_patches: usize,
paid_patches: usize,
can_access_paid: bool,
ecosystems: &[String],
fallback_to_proxy: bool,
mode: &str,
project_modes: &[&str],
auth: &TelemetryAuth,
) {
fire_prepared(prepare_patch_scanned(
packages_scanned,
free_patches,
paid_patches,
can_access_paid,
ecosystems,
fallback_to_proxy,
mode,
project_modes,
auth,
))
.await;
}
/// [`track_patch_scanned`], sent in the background: the event is built
/// now and its send joins `pending`, which the command flushes before it
/// returns.
#[allow(clippy::too_many_arguments)]
pub fn spawn_patch_scanned(
pending: &mut PendingTelemetry,
packages_scanned: usize,
free_patches: usize,
paid_patches: usize,
can_access_paid: bool,
ecosystems: &[String],
fallback_to_proxy: bool,
mode: &str,
project_modes: &[&str],
auth: &TelemetryAuth,
) {
pending.spawn_prepared(prepare_patch_scanned(
packages_scanned,
free_patches,
paid_patches,
can_access_paid,
ecosystems,
fallback_to_proxy,
mode,
project_modes,
auth,
));
}
/// The whole `patch_scan_failed` event (see [`prepare_patch_scanned`]).
fn prepare_patch_scan_failed(
error: impl std::fmt::Display,
fallback_to_proxy: bool,
auth: &TelemetryAuth,
) -> Option<PreparedSend> {
prepare(
PatchTelemetryEventType::PatchScanFailed,
"scan",
serde_json::json!({ "fallback_to_proxy": fallback_to_proxy }),
Some(error),
auth,
)
}
/// Track a failed `scan`. The CLI sends it through
/// [`spawn_patch_scan_failed`]; kept as public API like
/// [`track_patch_scanned`].
pub async fn track_patch_scan_failed(
error: impl std::fmt::Display,
fallback_to_proxy: bool,
auth: &TelemetryAuth,
) {
fire_prepared(prepare_patch_scan_failed(error, fallback_to_proxy, auth)).await;
}
/// [`track_patch_scan_failed`], sent in the background (see
/// [`spawn_patch_scanned`]).
pub fn spawn_patch_scan_failed(
pending: &mut PendingTelemetry,
error: impl std::fmt::Display,
fallback_to_proxy: bool,
auth: &TelemetryAuth,
) {
pending.spawn_prepared(prepare_patch_scan_failed(error, fallback_to_proxy, auth));
}
/// Track a successful `get`. Reports patch identity and whether the call
/// was downgraded to the public proxy after an auth-endpoint 401/403.
/// `download_mode` is always `"file"`: v5 fetches patch content only as
/// per-file blobs, and the field stays so the event schema is unchanged.
pub async fn track_patch_fetched(
uuid: &str,
tier: &str,
ecosystem: &str,
fallback_to_proxy: bool,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::PatchFetched,
"get",
serde_json::json!({
"uuid": uuid,
"tier": tier,
"ecosystem": ecosystem,
"download_mode": "file",
"fallback_to_proxy": fallback_to_proxy,
}),
None::<&str>,
auth,
)
.await;
}
/// The `uuid` a `patch_fetch_failed` event reports: `identifier` when it
/// is a patch uuid, else empty. `get` passes whatever the user asked for
/// (a CVE, a GHSA, a purl, a private package name), and only a uuid
/// belongs in that field.
fn fetch_failed_uuid(identifier: &str) -> &str {
if crate::patch::path_safety::is_canonical_uuid(&identifier.to_ascii_lowercase()) {
identifier
} else {
""
}
}
/// Track a failed `get`. `uuid` may be empty when the failure occurred
/// before the patch was resolved (e.g. lookup miss); anything that is not
/// a uuid is reported as empty.
pub async fn track_patch_fetch_failed(
uuid: &str,
error: impl std::fmt::Display,
fallback_to_proxy: bool,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::PatchFetchFailed,
"get",
serde_json::json!({
"uuid": fetch_failed_uuid(uuid),
"fallback_to_proxy": fallback_to_proxy
}),
Some(error),
auth,
)
.await;
}
// ---------------------------------------------------------------------------
// Inspection / housekeeping trackers: list / repair
// ---------------------------------------------------------------------------
/// Track a successful `list`. Reports the number of patches surfaced.
pub async fn track_patch_listed(patches_count: usize, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::PatchListed,
"list",
serde_json::json!({ "patches_count": patches_count }),
None::<&str>,
auth,
)
.await;
}
/// Track a successful `repair`. Reports blob deltas and bytes freed.
pub async fn track_patch_repaired(
blobs_added: usize,
blobs_removed: usize,
bytes_freed: u64,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::PatchRepaired,
"repair",
serde_json::json!({
"blobs_added": blobs_added,
"blobs_removed": blobs_removed,
"bytes_freed": bytes_freed,
}),
None::<&str>,
auth,
)
.await;
}
/// Track a failed `repair`.
pub async fn track_patch_repair_failed(error: impl std::fmt::Display, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::PatchRepairFailed,
"repair",
serde_json::Value::Null,
Some(error),
auth,
)
.await;
}
// ---------------------------------------------------------------------------
// OpenVEX trackers
// ---------------------------------------------------------------------------
/// Track a successful `vex` generation. `format` is e.g. `"openvex-0.2.0"`;
/// `output_kind` describes where the document went (`"stdout"`, `"file"`).
pub async fn track_vex_generated(
advisories_count: usize,
format: &str,
output_kind: &str,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::VexGenerated,
"vex",
serde_json::json!({
"advisories_count": advisories_count,
"format": format,
"output_kind": output_kind,
}),
None::<&str>,
auth,
)
.await;
}
/// Track a failed `vex` generation.
pub async fn track_vex_failed(error: impl std::fmt::Display, auth: &TelemetryAuth) {
fire(
PatchTelemetryEventType::VexFailed,
"vex",
serde_json::Value::Null,
Some(error),
auth,
)
.await;
}
// ---------------------------------------------------------------------------
// Self-update trackers
// ---------------------------------------------------------------------------
/// Track a successful self-update (`socket-patch --update`). The event's
/// `context.version` is the running (pre-update) build; `to_version` is
/// what was installed. `channel` is the detected install channel
/// (`standalone`, or the package manager a `--force` overrode).
pub async fn track_cli_updated(
to_version: &str,
channel: &str,
pinned: bool,
forced: bool,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::CliUpdated,
"update",
serde_json::json!({
"from_version": PACKAGE_VERSION,
"to_version": to_version,
"channel": channel,
"pinned": pinned,
"forced": forced,
}),
None::<&str>,
auth,
)
.await;
}
/// Track a failed self-update. `error_code` is the machine code the
/// `--json` envelope carries (e.g. `managed_install`, `check_failed`).
pub async fn track_cli_update_failed(
error_code: &str,
error: impl std::fmt::Display,
auth: &TelemetryAuth,
) {
fire(
PatchTelemetryEventType::CliUpdateFailed,
"update",
serde_json::json!({ "error_code": error_code }),
Some(error),
auth,
)
.await;
}
#[cfg(test)]
mod tests {
use super::*;
/// A prepared event posted to `server`'s `/telemetry` route.