diff --git a/README.md b/README.md index d2a39c4c1..89d6b7f8a 100644 --- a/README.md +++ b/README.md @@ -108,11 +108,14 @@ to Socket as a small JSON event. An event holds the event name (for example `patch_applied` or `patch_scan_failed`), the subcommand, the CLI version, the operating system and CPU architecture, a timestamp, a random ID generated for that one run, and a few counters and flags for the command (such as patches -applied, packages scanned, ecosystems found, the patch mode, `dry_run`). `get` -adds the patch UUID. A failure adds the error message, with URL credentials -redacted and your home directory replaced by `~`. Apart from what an error -message quotes, events hold no package names, file paths, file contents, or -dependency lists. +applied, packages scanned, ecosystems found, the patch mode, `dry_run`). An +event about specific patches (downloading, applying, vendoring, removing, or +rolling them back) names each by its patch UUID, with its ecosystem, mode, and +outcome; a patch UUID tells Socket which package version the patch is for. A +failure adds an error code and the error message, with URL credentials redacted +and your home directory replaced by `~`. Apart from those patch UUIDs and what +an error message quotes, events hold no package names, file paths, file +contents, or dependency lists. Events go to `api.socket.dev` with your API token when a token and organization are configured, otherwise anonymously to `patches-api.socket.dev`. They are sent diff --git a/crates/socket-patch-cli/CLI_CONTRACT.md b/crates/socket-patch-cli/CLI_CONTRACT.md index 08b9aeab2..db3e22c49 100644 --- a/crates/socket-patch-cli/CLI_CONTRACT.md +++ b/crates/socket-patch-cli/CLI_CONTRACT.md @@ -2021,9 +2021,13 @@ State lives at `$XDG_CACHE_HOME`|`~/.cache` (Unix/macOS) or `%LOCALAPPDATA%` (Wi ## Telemetry -Telemetry is **on by default**. Each command reports its outcome as one JSON event per row of the table below (a `scan` or `get` that also applies sends two). +Telemetry is **on by default**. Each command reports its outcome as one JSON event per row of the table below (a `scan` or `get` that also downloads and applies sends up to three; a `scan` over several project directories reports each). -**What is sent.** `{event_sender_created_at, event_type, context: {version, platform, arch, command}, session_id, metadata?, error?: {type, message}}`; no `event_kind`, so the backend stores it as a required event. `context` is the client version, `std::env::consts::OS` / `ARCH` and the subcommand. `session_id` is a random UUID generated per process and never stored, so it links the events of one run and nothing else. `metadata` holds only the per-event fields in the table. `error.message` (failure events) has every URL redacted (userinfo, grant tokens, signed query values) and the home directory replaced by `~`; it can otherwise quote a package name or a path. The request carries `User-Agent: SocketPatchCLI/` and, on the org route, `Authorization: Bearer `. Nothing else is sent: no package list, no file contents, no machine identifier. +**What is sent.** `{event_sender_created_at, event_type, context: {version, platform, arch, command, channel?}, session_id, metadata?, error?: {type, message}}`; no `event_kind`, so the backend stores it as a required event. `context` is the client version, `std::env::consts::OS` / `ARCH`, the subcommand, and `channel`: the install channel of the running binary (`npm`, `cargo`, `homebrew`, `pypi`, `launcher_cache`, or `standalone` for any location none of those owns; the same detection `--update` uses, from the binary's canonical path, read from environment variables alone and resolved before `--update` swaps the binary), omitted when that path cannot be read. `session_id` is a random UUID generated per process and never stored, so it links the events of one run and nothing else. `metadata` holds only the per-event fields in the table. `error.message` (failure events) has every URL redacted (userinfo, grant tokens, signed query values), the home directory replaced by `~`, and is cut to 1,000 characters; it can otherwise quote a package name or a path. The request carries `User-Agent: SocketPatchCLI/` and, on the org route, `Authorization: Bearer `. Nothing else is sent: no package name, no file contents, no machine identifier. The patches an event names are named by patch UUID (see below), which identifies a patched package version to Socket. + +**Patches.** An event about specific patches (the rows marked *patches*) adds to `metadata`: `patches`, at most 50 `{uuid, ecosystem, mode, outcome, code?}` entries, one per patch and mode, failed ones first (`mode`: `agent` / `hosted` / `vendored`; `outcome`: `applied`, `downloaded`, `rolled_back`, `removed`, `rebuilt`, `verified` (a dry run), `skipped`, `failed`; `code` is the event's `errorCode`, on `skipped` and `failed` only); `patches_truncated: true` when the cap dropped entries; `outcomes`, the count of patches per outcome over the whole run; and `ecosystems` / `modes`, their distinct values. They are derived from the run's `--json` events, so the two cannot disagree: several events for one patch (one per installed copy) fold into the one that says most (a failure over a change, a change over a preview, a preview over a skip). A run that named no patch adds none of these. The event body stays under 9,000 bytes (the server's dashboards cannot read one past 10,000 characters): an event that would not fit gives up the tail of its error message, down to 200 characters, and then entries off the end of its patch list. + +**Failures.** Every failure event carries `error_code`: the code the run's `--json` envelope reports as its `error.code` (`patch_not_found`, `rollback_failed`, `vendor_revert_kept`, …), so a mistyped target is distinguishable from a patch that failed. It is the same with and without `--json`. A run whose envelope has failed events and no top-level error reports `apply_failed`, `vendor_failed`, `hosted_failed` or `repair_failed`. Two kinds of run report nothing, in every command: one that exits 2 on a usage error, and one that could not take the apply lock. **Where.** `POST /v0/orgs//telemetry` with the bearer when the run has a token and an org, else anonymously `POST /patch/telemetry` (`--api-url` / `--proxy-url` and their env vars move both). The route is the run's API client's when the run built one, so telemetry follows the same host and org as its API calls. A run that built no client (see [API client construction](#api-client-construction)) takes the route from the configured credentials alone (flag → env → socket-cli config, no network): a token with no configured org then reports anonymously, because the org is never looked up only to address an event. @@ -2044,14 +2048,16 @@ Every `event_type` must be in the Socket API's patch event map, or it is stored | Command | Success | Failure | Metadata | |---|---|---|---| -| `scan` | `patch_scanned` | `patch_scan_failed` | `packages_scanned`, `free_patches`, `paid_patches`, `can_access_paid`, `ecosystems` (found by the crawl), `fallback_to_proxy`, `mode` (requested: `hosted` / `vendored` / `agent`, or `report` with none), `project_modes` (already wired: `hosted` lockfile pins, `vendored` ledger, `agent` manifest) | -| `scan`/`get --mode hosted` (non-empty selection) | `patch_applied` | `patch_apply_failed` | `mode: "hosted"`, `patches_count` (pins confirmed), `files_count` (files rewritten), `dry_run` | -| `apply` (and the nested apply of `scan`/`get --mode agent`) | `patch_applied` | `patch_apply_failed` | `mode: "agent"`, `patches_count`, `dry_run` | -| `vendor` / `scan`/`get --mode vendored` | `patch_vendored` | `patch_vendor_failed` | `patches_count`, `dry_run` | -| `get` | `patch_fetched` | `patch_fetch_failed` | `uuid`, `tier`, `ecosystem`, `download_mode`, `fallback_to_proxy` | -| `remove` / `rollback` | `patch_removed` / `patch_rolled_back` | `patch_remove_failed` / `patch_rollback_failed` | `removed_count` / `rolled_back_count` | -| `list` / `repair` | `patch_listed` / `patch_repaired` | — / `patch_repair_failed` | `patches_count` / `blobs_added`, `blobs_removed`, `bytes_freed` | -| `vex` | `vex_generated` | `vex_failed` | `advisories_count`, `format`, `output_kind` | +| `scan` (one per project directory) | `patch_scanned` | `patch_scan_failed` | `packages_scanned`, `free_patches`, `paid_patches`, `can_access_paid`, `ecosystems` (found by the crawl), `packages_by_ecosystem` / `patches_by_ecosystem` (ecosystem → count), `fallback_to_proxy`, `mode` (requested: `hosted` / `vendored` / `agent`, or `report` with none), `project_modes` (already wired: `hosted` lockfile pins, `vendored` ledger, `agent` manifest), `dry_run`. Failure: `error_code`, `fallback_to_proxy`, `mode` | +| `scan`/`get --mode hosted` (non-empty selection) | `patch_applied` | `patch_apply_failed` | `mode: "hosted"`, `patches_count` (pins confirmed), `files_count` (files rewritten), `dry_run`, *patches* | +| `apply` (and the nested apply of `scan`/`get --mode agent`, reported under `scan` / `get`) | `patch_applied` | `patch_apply_failed` | `mode: "agent"`, `patches_count` (packages patched; on a failure, what the run did apply), `dry_run`, *patches* | +| `scan --mode agent`, `get ` in agent mode (a run that reached a patch) | `patch_fetched` | — | `mode: "agent"`, `patches_count` (records downloaded), `download_mode`, *patches* (`downloaded`, `skipped` / `already_in_manifest`, `failed`) | +| `vendor` / `scan`/`get --mode vendored` (reported under the command run) | `patch_vendored` | `patch_vendor_failed` | `mode: "vendored"`, `patches_count`, `dry_run`, *patches* | +| `get ` | `patch_fetched` | `patch_fetch_failed` | `uuid`, `tier`, `ecosystem`, `mode`, `patches_count: 1`, `download_mode`, `fallback_to_proxy`, *patches*. Failure: `uuid` (when one was asked for), `error_code` (`not_found`, `paid_required`, `patch_fetch_failed`), `fallback_to_proxy` | +| `remove`, `vendor --revert` (never on `--dry-run`; one event per run) | `patch_removed` | `patch_remove_failed` | `removed_count` (patches taken out), *patches* | +| `rollback` | `patch_rolled_back` | `patch_rollback_failed` | `rolled_back_count` (packages restored, as `summary.rolledBack`), `dry_run`, `targeted` (targets were named), *patches* | +| `list` / `repair` | `patch_listed` / `patch_repaired` | — / `patch_repair_failed` | `patches_count` / `blobs_added`, `blobs_removed`, `bytes_freed`. Failure: `error_code` | +| `vex` | `vex_generated` | `vex_failed` | `advisories_count`, `format`, `output_kind`. Failure: `error_code` | | `--update` (an install, not a no-op or `--dry-run`) | `cli_updated` | `cli_update_failed` | `from_version`, `to_version`, `channel`, `pinned`, `forced` / `error_code` (the envelope's) | ## Environment variables diff --git a/crates/socket-patch-cli/src/commands/agent_download.rs b/crates/socket-patch-cli/src/commands/agent_download.rs index 3986f0014..070ae24d5 100644 --- a/crates/socket-patch-cli/src/commands/agent_download.rs +++ b/crates/socket-patch-cli/src/commands/agent_download.rs @@ -1593,6 +1593,18 @@ pub(crate) struct DetachedDownload { } impl DetachedDownload { + /// The patches the phase could not download, as the run's telemetry + /// names them: the vendor step never sees these (it works from the + /// records that did download), so its event adds them. + pub(crate) fn failed_outcomes(&self) -> Vec { + crate::telemetry_outcomes::patch_outcomes_of( + self.events + .iter() + .filter(|event| event.action == EventAction::Failed), + socket_patch_core::telemetry::MODE_VENDORED, + ) + } + /// Fold the phase's events and warnings into `env` (records via /// [`Envelope::record`], so `summary` and `status` follow) and hand back /// the exit code and the records. @@ -1826,6 +1838,33 @@ pub(crate) fn nested_apply_args_from_params( nested_apply_args(&common, manifest_path, params.quiet()) } +/// The patches an agent-mode download pass reached, as its telemetry +/// names them: a patch fetched in place of an older one is `downloaded` +/// like any other. +fn fetched_outcomes(events: &[PatchEvent]) -> Vec { + let events: Vec = events + .iter() + .map(|event| PatchEvent { + action: match event.action { + EventAction::Updated => EventAction::Downloaded, + action => action, + }, + ..event.clone() + }) + .collect(); + crate::telemetry_outcomes::patch_outcomes_of(&events, socket_patch_core::telemetry::MODE_AGENT) +} + +/// The command an engine run's telemetry reports: the one whose envelope +/// it fills. `scan` and `get` are the engine's two callers; both pass +/// their own envelope, printed or not. +pub(crate) fn telemetry_command(env: &Envelope) -> &'static str { + match env.command { + EnvelopeCommand::Scan => "scan", + _ => "get", + } +} + /// Run the nested `apply` step with `common` (see [`nested_apply_args`]) /// on the caller's `client`, under the apply `lock` the caller took for /// its manifest write — one lock window for download → manifest write → @@ -1839,6 +1878,7 @@ pub(crate) fn nested_apply_args_from_params( /// opt-in on the top-level command only, never on this internal /// invocation. pub(crate) async fn run_nested_apply( + command: &'static str, common: GlobalArgs, json: bool, report_user_patch_skips: bool, @@ -1856,6 +1896,7 @@ pub(crate) async fn run_nested_apply( nested: Some(super::apply::NestedApply { caller_json: json, report_user_patch_skips, + command, }), }; // The nested apply runs on the host's client: seeded, never rebuilt. @@ -2228,6 +2269,14 @@ pub async fn download_and_apply_patches_into( // single-uuid flow's summary in `save_and_apply_patch`; their sum gates // the apply step. let downloaded = batch.fetched.len(); + // Telemetry: the patch records this run fetched. `get ` reports + // its own fetch; every other agent-mode download comes through here. + socket_patch_core::telemetry::track_patches_fetched( + telemetry_command(env), + &fetched_outcomes(&batch.events), + &socket_patch_core::telemetry::TelemetryAuth::for_client(run.api_client), + ) + .await; let mut updated = 0usize; let mut new_blobs: Vec = Vec::new(); // `(purl, uuid)` of every selected patch now recorded: the fetched ones @@ -2331,6 +2380,7 @@ pub async fn download_and_apply_patches_into( crate::hot_patch::mark_apply_started(); apply_report = Some( run_nested_apply( + telemetry_command(env), nested_apply_args_from_params(params, run, &manifest_path), params.json, !params.user_patch_skips_reported, diff --git a/crates/socket-patch-cli/src/commands/apply.rs b/crates/socket-patch-cli/src/commands/apply.rs index 5e92c9fd2..7942e2234 100644 --- a/crates/socket-patch-cli/src/commands/apply.rs +++ b/crates/socket-patch-cli/src/commands/apply.rs @@ -186,6 +186,9 @@ pub struct NestedApply { /// (`get`) checked only its own selection. `scan` already reported /// every protected installed package, so it passes `false`. pub report_user_patch_skips: bool, + /// The command the user ran (`scan`, `get`): what the nested run's + /// telemetry reports as its command. + pub command: &'static str, } impl ApplyArgs { @@ -1610,6 +1613,12 @@ pub(crate) async fn run_locked( // Packages the project patched itself sit this run out (warned); every // other record still applies. The read-only `--check` verifies them all. + // Each record's patch, for telemetry: results name the package only. + let patch_uuids: HashMap = manifest + .patches + .iter() + .map(|(purl, record)| (purl.clone(), record.uuid.clone())) + .collect(); let mut manifest = manifest; let (user_patch_warnings, user_patch_skips) = if args.check { Default::default() @@ -2133,12 +2142,23 @@ pub(crate) async fn run_locked( } // Track telemetry + let reported = reported_patches(&results, &caveats, args.common.dry_run, &patch_uuids); if success { - track_patch_applied(patched_count, args.common.dry_run, &telemetry()).await; + track_patch_applied( + telemetry_command(&args), + patched_count, + args.common.dry_run, + &reported, + &telemetry(), + ) + .await; } else { track_patch_apply_failed( + telemetry_command(&args), + "apply_failed", "One or more patches failed to apply", args.common.dry_run, + &reported, &telemetry(), ) .await; @@ -2218,6 +2238,34 @@ pub(crate) async fn run_locked( } } +/// The command an apply run's telemetry reports: `apply`, or the `scan` / +/// `get` whose agent mode ran it. +fn telemetry_command(args: &ApplyArgs) -> &'static str { + args.nested.map_or("apply", |nested| nested.command) +} + +/// The patches an apply run acted on, as its telemetry names them: the +/// run's per-package events ([`GemCaveats::event_of`], what `--json` +/// prints), each under the patch its manifest record names. +/// +/// A plain fn, so the events it builds stay off the async frame of `run`. +fn reported_patches( + results: &[ApplyResult], + caveats: &GemCaveats, + dry_run: bool, + patch_uuids: &HashMap, +) -> Vec { + let events: Vec = results + .iter() + .map(|result| caveats.event_of(result, dry_run)) + .collect(); + crate::telemetry_outcomes::patch_outcomes( + &events, + socket_patch_core::telemetry::MODE_AGENT, + crate::telemetry_outcomes::uuid_lookup(patch_uuids), + ) +} + /// The one apply-failure exit: `apply_failed` telemetry, then the error /// envelope (`--json`) or an `Error:` line that prints even under /// `--silent` ("errors only", never "nothing" — exit 1 with no message @@ -2232,7 +2280,15 @@ async fn report_apply_failure( skipped: &[PatchEvent], telemetry: &TelemetryAuth, ) -> i32 { - track_patch_apply_failed(error, args.common.dry_run, telemetry).await; + track_patch_apply_failed( + telemetry_command(args), + &err.code, + error, + args.common.dry_run, + &[], + telemetry, + ) + .await; if args.common.json { let mut env = Envelope::new(Command::Apply); env.dry_run = args.common.dry_run; diff --git a/crates/socket-patch-cli/src/commands/get.rs b/crates/socket-patch-cli/src/commands/get.rs index 0dbbd5efb..574217ff9 100644 --- a/crates/socket-patch-cli/src/commands/get.rs +++ b/crates/socket-patch-cli/src/commands/get.rs @@ -51,17 +51,6 @@ use crate::json_envelope::{ }; use crate::ui::{print_json, select_one, SelectError}; -/// Best-effort ecosystem extractor for a `pkg:/...` PURL. Used as -/// the telemetry `ecosystem` field. Returns an empty string when the -/// PURL is malformed — telemetry events should never block on input -/// validation. -fn ecosystem_from_purl(purl: &str) -> String { - purl.strip_prefix("pkg:") - .and_then(|rest| rest.split('/').next()) - .unwrap_or("") - .to_string() -} - /// A fresh `get` envelope for this run (`dryRun` from the flags). fn new_envelope(common: &GlobalArgs) -> Envelope { let mut env = Envelope::new(JsonCommand::Get); @@ -128,7 +117,14 @@ async fn report_fetch_failure( common: &GlobalArgs, ) -> i32 { let msg = error.to_string(); - track_patch_fetch_failed(identifier, &msg, fallback_to_proxy, telemetry).await; + track_patch_fetch_failed( + identifier, + "patch_fetch_failed", + &msg, + fallback_to_proxy, + telemetry, + ) + .await; report_error(common, "patch_fetch_failed", msg) } @@ -1329,7 +1325,8 @@ pub async fn run(args: GetArgs) -> i32 { track_patch_fetched( &patch.uuid, &patch.tier, - &ecosystem_from_purl(&patch.purl), + &crate::telemetry_outcomes::ecosystem_of(&patch.purl), + mode.cli_name(), fallback_to_proxy, &telemetry, ) @@ -1408,6 +1405,7 @@ pub async fn run(args: GetArgs) -> i32 { track_patch_fetch_failed( &args.identifier, "not_found", + "not_found", fallback_to_proxy, &telemetry, ) @@ -1880,7 +1878,14 @@ async fn report_paid_required_uuid( telemetry: &TelemetryAuth, org_warnings: &[(String, String)], ) -> i32 { - track_patch_fetch_failed(patch_id, "paid_required", fallback_to_proxy, telemetry).await; + track_patch_fetch_failed( + patch_id, + "paid_required", + "paid_required", + fallback_to_proxy, + telemetry, + ) + .await; if args.common.json { let mut env = new_envelope(&args.common); env.status = Status::PaidRequired; @@ -2213,6 +2218,7 @@ async fn save_and_apply_patch( // result in one line (`Applied 1 patch.`). apply_report = Some( run_nested_apply( + "get", nested_apply_args(&args.common, &manifest_path, quiet), args.common.json, true, @@ -2467,8 +2473,16 @@ async fn run_get_vendored( // Same failure telemetry as the vendor-step Err arm below: this // run exits 1 without vendoring anything. socket_patch_core::telemetry::track_patch_vendor_failed( + "get", + code, detail, args.common.dry_run, + &crate::telemetry_outcomes::uniform_outcomes( + [(patch.purl.as_str(), patch.uuid.as_str())], + socket_patch_core::telemetry::MODE_VENDORED, + socket_patch_core::telemetry::OUTCOME_FAILED, + Some(code), + ), telemetry, ) .await; @@ -2507,6 +2521,7 @@ async fn run_get_vendored( )) .await }; + let download_failures = download.failed_outcomes(); let (dl_code, _, records) = download.into_envelope(&mut env); // The vendor step (scan's, verbatim): apply lock, in-memory staging @@ -2515,6 +2530,7 @@ async fn run_get_vendored( // and over this run's client, then the run's telemetry. A per-patch // download failure does not skip it (scan parity). match super::scan::boxed_vendor_step(super::scan::VendorStep { + command: "get", common: &args.common, records, client: api_client.clone(), @@ -2522,6 +2538,7 @@ async fn run_get_vendored( report_empty: true, prior: None, download_errors: dl_code != 0, + download_failures, telemetry_auth: telemetry, closing_lines: None, }) diff --git a/crates/socket-patch-cli/src/commands/remove.rs b/crates/socket-patch-cli/src/commands/remove.rs index 496f6f578..ad840952e 100644 --- a/crates/socket-patch-cli/src/commands/remove.rs +++ b/crates/socket-patch-cli/src/commands/remove.rs @@ -7,7 +7,10 @@ use socket_patch_core::manifest::cleanup_blobs::{ use socket_patch_core::manifest::operations::{manifest_exists, read_manifest, write_manifest}; use socket_patch_core::manifest::schema::PatchManifest; use socket_patch_core::patch::redirect::upstream::HostedPin; -use socket_patch_core::telemetry::{track_patch_remove_failed, track_patch_removed, TelemetryAuth}; +use socket_patch_core::telemetry::{ + track_patch_remove_failed, track_patch_removed, PatchOutcome, TelemetryAuth, MODE_AGENT, + MODE_HOSTED, MODE_VENDORED, OUTCOME_FAILED, +}; use socket_patch_core::utils::purl_key::PurlKey; use socket_patch_core::utils::target::Target; use socket_patch_core::vendor::{ @@ -314,6 +317,150 @@ pub struct RemoveArgs { pub preserve_state: bool, } +/// Telemetry for a removal that did not happen. `code` is the run's +/// `--json` error code (what tells a mistyped identifier from a patch +/// that would not come off) and `patches` the patches it could not +/// remove, when it got as far as resolving them. A `--dry-run` reports +/// nothing, like its success. +async fn track_failed( + args: &RemoveArgs, + code: &str, + error: impl std::fmt::Display, + patches: &[PatchOutcome], + telemetry: &TelemetryAuth, +) { + if !args.common.dry_run { + track_patch_remove_failed("remove", code, error, patches, telemetry).await; + } +} + +/// The `mode: "vendored"` / `"hosted"` tag of a patch event. +fn mode_details(mode: &str) -> serde_json::Value { + serde_json::json!({ "mode": mode }) +} + +/// The vendored leg as per-patch events for telemetry: each entry the +/// revert took out of the lockfiles (reverted, or unwired under +/// `--preserve-state`) is `removed`, each it had to keep is `failed` +/// (`vendor_revert_kept`). `entries` are the matched ledger entries, read +/// before the revert, for their patch UUIDs. +fn vendor_leg_events(leg: &RemoveVendorLeg, entries: &[(String, VendorEntry)]) -> Vec { + let uuid_of = |key: &str| { + entries + .iter() + .find(|(k, _)| k == key) + .map(|(_, entry)| entry.uuid.clone()) + }; + let unwired = leg.reverted.iter().chain( + leg.skipped + .iter() + .filter(|event| event.error_code.as_deref() == Some("vendor_state_preserved")), + ); + let kept = leg.kept.iter().filter_map(|key| { + Some( + PatchEvent::new(PatchAction::Failed, key.clone()) + .with_uuid(uuid_of(key)?) + .with_error("vendor_revert_kept", "vendored state kept") + .with_details(mode_details(MODE_VENDORED)), + ) + }); + let removed = unwired.filter_map(|event| { + let key = event.purl.as_deref()?; + Some( + PatchEvent::new(PatchAction::Removed, key) + .with_uuid(uuid_of(key)?) + .with_details(mode_details(MODE_VENDORED)), + ) + }); + kept.chain(removed).collect() +} + +/// The vendored entries a revert kept, as telemetry names them. +fn kept_outcomes(kept: &[String], entries: &[(String, VendorEntry)]) -> Vec { + crate::telemetry_outcomes::uniform_outcomes( + entries + .iter() + .filter(|(key, _)| kept.contains(key)) + .map(|(key, entry)| (key.as_str(), entry.uuid.as_str())), + MODE_VENDORED, + OUTCOME_FAILED, + Some("vendor_revert_kept"), + ) +} + +/// Hosted pins as telemetry names them: `removed` for the ones the leg +/// restored (`restored`, by purl), `failed` (`hosted_revert_failed`) for +/// the rest. A leg that stopped on one pin may have restored others, and +/// a patch that was taken out is not one that would not come off. +fn hosted_pin_outcomes(pins: &[HostedPin], restored: &[String]) -> Vec { + let (done, failed): (Vec<&HostedPin>, Vec<&HostedPin>) = + pins.iter().partition(|pin| restored.contains(&pin.purl)); + let named = |pins: Vec<&HostedPin>, outcome, code| { + crate::telemetry_outcomes::uniform_outcomes( + pins.into_iter() + .map(|pin| (pin.purl.as_str(), pin.uuid.as_str())), + MODE_HOSTED, + outcome, + code, + ) + }; + crate::telemetry_outcomes::with_more( + named(failed, OUTCOME_FAILED, Some("hosted_revert_failed")), + &named(done, "removed", None), + ) +} + +/// What a manifest-backed removal did, for [`removal_outcomes`]. +struct RemovalReport<'a> { + manifest: &'a PatchManifest, + /// The manifest records the run took out. + taken_out: &'a [String], + /// The matched vendor ledger entries, read before the revert. + vendored: &'a [(String, VendorEntry)], + vendor_leg: &'a RemoveVendorLeg, + /// The hosted leg's events, one per restored pin. + hosted_restored: &'a [PatchEvent], + hosted_pins: &'a [HostedPin], +} + +/// The patches a manifest-backed removal acted on, as its telemetry names +/// them: the vendored leg's ([`vendor_leg_events`]), each manifest record +/// taken out (in vendored mode when the ledger covers it, else agent), +/// and each hosted pin restored. +fn removal_outcomes(report: &RemovalReport<'_>) -> Vec { + let mut events = vendor_leg_events(report.vendor_leg, report.vendored); + for purl in report.taken_out { + let Some(record) = report.manifest.patches.get(purl) else { + continue; + }; + let event = + PatchEvent::new(PatchAction::Removed, purl.clone()).with_uuid(record.uuid.clone()); + let vendor_owned = report + .vendored + .iter() + .any(|(key, entry)| entry.covers_purl(key, purl)); + events.push(if vendor_owned { + event.with_details(mode_details(MODE_VENDORED)) + } else { + event + }); + } + for purl in report + .hosted_restored + .iter() + .filter_map(|event| event.purl.as_deref()) + { + if let Some(pin) = report.hosted_pins.iter().find(|pin| pin.purl == purl) { + events.push( + PatchEvent::new(PatchAction::Removed, purl) + .with_uuid(pin.uuid.clone()) + .with_details(mode_details(MODE_HOSTED)), + ); + } + } + crate::telemetry_outcomes::patch_outcomes_of(&events, MODE_AGENT) +} + pub async fn run(args: RemoveArgs) -> i32 { apply_env_toggles(&args.common); // The shared target grammar: a UUID, a purl (versioned or not) or an @@ -367,6 +514,7 @@ pub async fn run(args: RemoveArgs) -> i32 { Ok(present) => !present, Err(e) => { let err = crate::json_envelope::manifest_load_error(&manifest_path, &e); + track_failed(&args, &err.code, &err.message, &[], &telemetry).await; emit_error_envelope( args.common.json, args.common.dry_run, @@ -393,6 +541,7 @@ pub async fn run(args: RemoveArgs) -> i32 { // Contested hosted wiring is still hosted state: name it // instead of reporting a bare project. if let Some(refusal) = hosted_inventory.contested_refusal() { + track_failed(&args, "hosted_wiring_contested", &refusal, &[], &telemetry).await; emit_error_envelope( args.common.json, args.common.dry_run, @@ -422,6 +571,8 @@ pub async fn run(args: RemoveArgs) -> i32 { } else { Default::default() }; + let not_found = format!("Manifest not found at {}", manifest_path.display()); + track_failed(&args, "manifest_not_found", ¬_found, &[], &telemetry).await; // `--json` keeps its `manifest_not_found` message; a person is // told what that means for the command they ran. if args.common.json { @@ -429,7 +580,7 @@ pub async fn run(args: RemoveArgs) -> i32 { true, args.common.dry_run, "manifest_not_found", - format!("Manifest not found at {}", manifest_path.display()), + not_found, below.warnings(), ); } else { @@ -475,16 +626,19 @@ pub async fn run(args: RemoveArgs) -> i32 { Ok(Some(m)) => m, Ok(None) => { // Present at the existence check above, gone by the read. + let msg = format!("Manifest not found at {}", manifest_path.display()); + track_failed(&args, "manifest_not_found", &msg, &[], &telemetry).await; emit_error_envelope( args.common.json, args.common.dry_run, "manifest_not_found", - format!("Manifest not found at {}", manifest_path.display()), + msg, ); return 1; } Err(e) => { let err = crate::json_envelope::manifest_load_error(&manifest_path, &e); + track_failed(&args, &err.code, &err.message, &[], &telemetry).await; emit_error_envelope( args.common.json, args.common.dry_run, @@ -531,6 +685,7 @@ pub async fn run(args: RemoveArgs) -> i32 { match target.settle(candidates) { Ok(settled) => settled, Err(msg) => { + track_failed(&args, "ambiguous_target", &msg, &[], &telemetry).await; emit_error_envelope( args.common.json, args.common.dry_run, @@ -551,6 +706,18 @@ pub async fn run(args: RemoveArgs) -> i32 { .collect(); matching.sort_by(|a, b| a.0.cmp(b.0)); let matched_keys: Vec = matching.iter().map(|(purl, _)| (*purl).clone()).collect(); + // The matched records, for the event of a run that fails before it + // can say what became of each: all of them `outcome`, under `code`. + let matched_patches = |outcome: &'static str, code: &str| { + crate::telemetry_outcomes::uniform_outcomes( + matching + .iter() + .map(|(purl, record)| (purl.as_str(), record.uuid.as_str())), + MODE_AGENT, + outcome, + Some(code), + ) + }; if matching.is_empty() { // Ledger-only entries (vendored mode keeps no manifest record) — @@ -588,7 +755,7 @@ pub async fn run(args: RemoveArgs) -> i32 { } let msg = format!("No patch found matching identifier: {}", args.identifier); - track_patch_remove_failed(&msg, &telemetry).await; + track_failed(&args, "not_found", &msg, &[], &telemetry).await; if args.common.json { let mut env = Envelope::new(Command::Remove); env.dry_run = args.common.dry_run; @@ -622,7 +789,14 @@ pub async fn run(args: RemoveArgs) -> i32 { manifest without restoring files.", kind.detail(&key) ); - track_patch_remove_failed(&msg, &telemetry).await; + track_failed( + &args, + kind.code(), + &msg, + &matched_patches(OUTCOME_FAILED, kind.code()), + &telemetry, + ) + .await; emit_error_envelope(args.common.json, args.common.dry_run, kind.code(), msg); return 1; } @@ -781,8 +955,28 @@ pub async fn run(args: RemoveArgs) -> i32 { } rollback_warnings = outcome.warnings; if !outcome.success { - track_patch_remove_failed("Rollback failed during patch removal", &telemetry) - .await; + // The patches whose files could not be restored. + let failed = crate::telemetry_outcomes::uniform_outcomes( + outcome + .results + .iter() + .filter(|r| !r.success) + .filter_map(|r| { + let record = manifest.patches.get(&r.package_key)?; + Some((r.package_key.as_str(), record.uuid.as_str())) + }), + MODE_AGENT, + OUTCOME_FAILED, + Some("rollback_failed"), + ); + track_failed( + &args, + "rollback_failed", + "Rollback failed during patch removal", + &failed, + &telemetry, + ) + .await; // The nested rollback reports per-package failures // inline only under --silent; say why here otherwise. if loud { @@ -857,7 +1051,14 @@ pub async fn run(args: RemoveArgs) -> i32 { } } Err(e) => { - track_patch_remove_failed(&e, &telemetry).await; + track_failed( + &args, + "rollback_failed", + &e, + &matched_patches(OUTCOME_FAILED, "rollback_failed"), + &telemetry, + ) + .await; let remedy = "Use --skip-rollback to remove from manifest without restoring files."; if args.common.json { // The pinned envelope message keeps its historical prefix. @@ -893,11 +1094,20 @@ pub async fn run(args: RemoveArgs) -> i32 { let mut vendor_state = match vendor_state_result { Ok(s) => s, Err(e) => { + let msg = format!("cannot read .socket/vendor/state.json: {e}"); + track_failed( + &args, + "vendor_state_unreadable", + &msg, + &matched_patches(OUTCOME_FAILED, "vendor_state_unreadable"), + &telemetry, + ) + .await; emit_error_envelope( args.common.json, args.common.dry_run, "vendor_state_unreadable", - format!("cannot read .socket/vendor/state.json: {e}"), + msg, ); return 1; } @@ -955,7 +1165,15 @@ pub async fn run(args: RemoveArgs) -> i32 { hosted_leg_warnings.extend(leg.warnings.iter().cloned()); leg } - Err(err) => { + Err((err, restored)) => { + track_failed( + &args, + "hosted_revert_failed", + &err, + &hosted_pin_outcomes(&hosted_matches, &restored), + &telemetry, + ) + .await; emit_hosted_unwind_error(&args.common, err, true); return 1; } @@ -1010,7 +1228,14 @@ pub async fn run(args: RemoveArgs) -> i32 { // not happen. NOT not_found; partialFailure keeps `summary.removed` // honest at 0. let msg = all_kept_message(&args.identifier, &vendor_leg.kept_causes); - track_patch_remove_failed(&msg, &telemetry).await; + track_failed( + &args, + "vendor_revert_kept", + &msg, + &kept_outcomes(&vendor_leg.kept, &vendored_matches), + &telemetry, + ) + .await; if args.common.json { let mut env = Envelope::new(Command::Remove); env.dry_run = args.common.dry_run; @@ -1033,7 +1258,14 @@ pub async fn run(args: RemoveArgs) -> i32 { if !args.common.dry_run && !removed.is_empty() { if let Err(e) = write_manifest(&manifest_path, &updated_manifest).await { let msg = e.to_string(); - track_patch_remove_failed(&msg, &telemetry).await; + track_failed( + &args, + "remove_failed", + &msg, + &matched_patches(OUTCOME_FAILED, "remove_failed"), + &telemetry, + ) + .await; emit_error_envelope(args.common.json, args.common.dry_run, "remove_failed", msg); return 1; } @@ -1041,6 +1273,22 @@ pub async fn run(args: RemoveArgs) -> i32 { sweep_target_orphans(&args, &vendor_state, &target, &mut vendor_leg).await; printed_progress |= loud && vendor_leg.printed; + // What telemetry says this run took out. Under `--preserve-state` no + // record is dropped, and the patches it took out of the tree are the + // matched ones. + let reported_patches = removal_outcomes(&RemovalReport { + manifest: &manifest, + taken_out: if args.preserve_state { + &matched_keys + } else { + &removed + }, + vendored: &vendored_matches, + vendor_leg: &vendor_leg, + hosted_restored: &hosted_reverted_events, + hosted_pins: &hosted_pins, + }); + if loud { if printed_progress { println!(); @@ -1307,7 +1555,13 @@ pub async fn run(args: RemoveArgs) -> i32 { } if !args.common.dry_run { - track_patch_removed(removed.len(), &telemetry).await; + track_patch_removed( + "remove", + PatchOutcome::count(&reported_patches, "removed"), + &reported_patches, + &telemetry, + ) + .await; } kept_exit_code(&args.common, &vendor_leg.kept_causes, "manifest record") } @@ -1408,6 +1662,11 @@ async fn revert_vendored_matches( keep_artifact: args.preserve_state, }; let mut leg = RemoveVendorLeg::default(); + // The entries' patches, read before the revert drops them. + let uuids: Vec<(String, String)> = keys + .iter() + .filter_map(|key| Some((key.clone(), state.entries.get(key)?.uuid.clone()))) + .collect(); // Stops at the first hard failure: remove aborts there, leaving the // remaining matches (and the manifest) untouched. let backend = VendoredBackend::new(&args.common, None); @@ -1439,8 +1698,23 @@ async fn revert_vendored_matches( match step { VendorRevertStep::Missing => {} VendorRevertStep::Failed(why) => { - track_patch_remove_failed("vendor revert failed during patch removal", telemetry) - .await; + let failed = crate::telemetry_outcomes::uniform_outcomes( + uuids + .iter() + .filter(|(k, _)| *k == key) + .map(|(k, uuid)| (k.as_str(), uuid.as_str())), + MODE_VENDORED, + OUTCOME_FAILED, + Some("vendor_revert_failed"), + ); + track_failed( + args, + "vendor_revert_failed", + "vendor revert failed during patch removal", + &failed, + telemetry, + ) + .await; emit_error_envelope( args.common.json, args.common.dry_run, @@ -1534,6 +1808,16 @@ async fn revert_vendored_matches( println!("{line}"); } } + let failed = crate::telemetry_outcomes::uniform_outcomes( + uuids + .iter() + .filter(|(k, _)| *k == key) + .map(|(k, uuid)| (k.as_str(), uuid.as_str())), + MODE_VENDORED, + OUTCOME_FAILED, + Some("vendor_state_write_failed"), + ); + track_failed(args, "vendor_state_write_failed", &e, &failed, telemetry).await; emit_error_envelope( args.common.json, args.common.dry_run, @@ -1610,18 +1894,19 @@ async fn sweep_target_orphans( /// Restore the hosted pins in `hosted_matches` to their upstream registry /// entries. Nothing is written unless every pin resolved (the restore is /// all-or-nothing per pin, and a refused pin fails the remove). The error -/// is the first refusal (or write failure), naming the pin and its remedy. +/// is the first refusal (or write failure), naming the pin and its remedy, +/// with the pins the stopped leg did restore. async fn unwind_hosted( common: &GlobalArgs, hosted_matches: &[HostedPin], api_client: &RunApiClient, -) -> Result { +) -> Result)> { let leg = run_hosted_leg(common, hosted_matches, api_client).await; // Printed as soon as the leg returns, so a human run that then fails // still says what it did to the files. print_run_warnings(common, &leg.warnings); if let Some((_, why)) = leg.failed.first().cloned() { - return Err(why); + return Err((why, leg.reverted)); } if let Some(warning) = super::rollback::retire_legacy_redirect_ledger(common).await { print_run_warnings(common, std::slice::from_ref(&warning)); @@ -1690,15 +1975,17 @@ async fn remove_hosted_only( ) -> i32 { let loud = !args.common.json && !args.common.silent; if args.skip_rollback { + let msg = format!( + "{} matches only hosted lockfile pins; removing one means restoring its \ + upstream registry entry, which --skip-rollback prevents", + args.identifier + ); + track_failed(args, "hosted_state_retained", &msg, &[], telemetry).await; emit_error_envelope( args.common.json, args.common.dry_run, "hosted_state_retained", - format!( - "{} matches only hosted lockfile pins; removing one means restoring its \ - upstream registry entry, which --skip-rollback prevents", - args.identifier - ), + msg, ); return 1; } @@ -1741,8 +2028,15 @@ async fn remove_hosted_only( let leg = match unwind_hosted(&args.common, &hosted_matches, api_client).await { Ok(leg) => leg, - Err(err) => { - track_patch_remove_failed("hosted redirect revert failed", telemetry).await; + Err((err, restored)) => { + track_failed( + args, + "hosted_revert_failed", + "hosted redirect revert failed", + &hosted_pin_outcomes(&hosted_matches, &restored), + telemetry, + ) + .await; emit_hosted_unwind_error(&args.common, err, false); return 1; } @@ -1769,7 +2063,18 @@ async fn remove_hosted_only( crate::ui::print_json(&env.to_value()); } if !args.common.dry_run { - track_patch_removed(leg.reverted.len(), telemetry).await; + let restored: Vec = hosted_matches + .iter() + .filter(|pin| leg.reverted.contains(&pin.purl)) + .cloned() + .collect(); + track_patch_removed( + "remove", + leg.reverted.len(), + &hosted_pin_outcomes(&restored, &leg.reverted), + telemetry, + ) + .await; } 0 } @@ -1795,15 +2100,17 @@ async fn remove_ledger_only( ) -> i32 { let loud = !args.common.json && !args.common.silent; if args.skip_rollback { + let msg = format!( + "{} matches only vendored patches with no manifest record; removing one \ + means reverting its vendoring, which --skip-rollback prevents", + args.identifier + ); + track_failed(args, "vendor_state_retained", &msg, &[], telemetry).await; emit_error_envelope( args.common.json, args.common.dry_run, "vendor_state_retained", - format!( - "{} matches only vendored patches with no manifest record; removing one \ - means reverting its vendoring, which --skip-rollback prevents", - args.identifier - ), + msg, ); return 1; } @@ -1860,6 +2167,10 @@ async fn remove_ledger_only( Err(code) => return code, }; sweep_target_orphans(args, &state, target, &mut leg).await; + let reported_patches = crate::telemetry_outcomes::patch_outcomes_of( + &vendor_leg_events(&leg, &matches), + MODE_VENDORED, + ); let mut env = Envelope::new(Command::Remove); env.dry_run = args.common.dry_run; @@ -1892,16 +2203,38 @@ async fn remove_ledger_only( env.mark_partial_failure(); if leg.kept.len() == keys.len() { let msg = all_kept_message(&args.identifier, &leg.kept_causes); - track_patch_remove_failed(&msg, telemetry).await; env.error = Some(EnvelopeError::new("vendor_revert_kept", msg)); } } + // One event per run: a removal that took nothing out is the failure + // alone, not a failure and a removal of zero. Sent before the + // envelope prints, so a consumer that closes stdout on it cannot drop + // the event. + match &env.error { + Some(error) => { + track_failed( + args, + &error.code, + &error.message, + &reported_patches, + telemetry, + ) + .await; + } + None if !args.common.dry_run => { + track_patch_removed( + "remove", + PatchOutcome::count(&reported_patches, "removed"), + &reported_patches, + telemetry, + ) + .await; + } + None => {} + } if args.common.json { crate::ui::print_json(&env.to_value()); } - if !args.common.dry_run { - track_patch_removed(leg.reverted_count, telemetry).await; - } kept_exit_code(&args.common, &leg.kept_causes, "ledger record") } @@ -1911,6 +2244,43 @@ mod tests { use socket_patch_core::manifest::schema::PatchRecord; use std::collections::HashMap; + /// A hosted leg that stopped on one pin may have restored others. The + /// failure event counts only the refused pin as failed: the restored + /// one was taken out. + #[test] + fn a_stopped_hosted_leg_reports_what_it_restored_as_removed() { + const RESTORED: &str = "11111111-1111-4111-8111-111111111111"; + const REFUSED: &str = "22222222-2222-4222-8222-222222222222"; + let pin = |purl: &str, uuid: &str| HostedPin { + purl: purl.to_string(), + uuid: uuid.to_string(), + files: vec!["package-lock.json".to_string()], + }; + let pins = [ + pin("pkg:npm/a@1.0.0", RESTORED), + pin("pkg:npm/b@1.0.0", REFUSED), + ]; + + let outcomes = hosted_pin_outcomes(&pins, &["pkg:npm/a@1.0.0".to_string()]); + let named: Vec<(&str, &str, Option<&str>)> = outcomes + .iter() + .map(|o| (o.uuid.as_str(), o.outcome, o.code.as_deref())) + .collect(); + assert_eq!( + named, + [ + (REFUSED, OUTCOME_FAILED, Some("hosted_revert_failed")), + (RESTORED, "removed", None), + ] + ); + assert!(outcomes.iter().all(|o| o.mode == MODE_HOSTED)); + + // Nothing restored (a failed write): every pin failed. + let outcomes = hosted_pin_outcomes(&pins, &[]); + assert!(outcomes.iter().all(|o| o.outcome == OUTCOME_FAILED)); + assert_eq!(outcomes.len(), 2); + } + fn make_record(uuid: &str) -> PatchRecord { PatchRecord { uuid: uuid.to_string(), diff --git a/crates/socket-patch-cli/src/commands/repair.rs b/crates/socket-patch-cli/src/commands/repair.rs index 610a70dfb..b6712a9e9 100644 --- a/crates/socket-patch-cli/src/commands/repair.rs +++ b/crates/socket-patch-cli/src/commands/repair.rs @@ -65,8 +65,12 @@ pub async fn run(args: RepairArgs) -> i32 { Ok(present) => present, Err(e) => { let err = crate::json_envelope::manifest_load_error(&manifest_path, &e); - track_patch_repair_failed(&err.message, &TelemetryAuth::from_credentials(None, None)) - .await; + track_patch_repair_failed( + &err.code, + &err.message, + &TelemetryAuth::from_credentials(None, None), + ) + .await; if args.common.json { let env = error_envelope( Command::Repair, @@ -229,8 +233,19 @@ pub async fn run(args: RepairArgs) -> i32 { env.warnings.extend(ignored); let had_failure = matches!(env.status, Status::PartialFailure | Status::Error); if had_failure { - track_patch_repair_failed("One or more artifacts failed to download", &telemetry) - .await; + // The envelope's own error code when it has one; a run + // with failed events and no top-level error is + // `repair_failed`. + let code = env + .error + .as_ref() + .map_or("repair_failed", |e| e.code.as_str()); + track_patch_repair_failed( + code, + "One or more artifacts failed to download", + &telemetry, + ) + .await; } else { track_patch_repaired( counts.downloaded, @@ -246,7 +261,7 @@ pub async fn run(args: RepairArgs) -> i32 { i32::from(had_failure) } Err(e) => { - track_patch_repair_failed(&e.message, &telemetry).await; + track_patch_repair_failed(&e.code, &e.message, &telemetry).await; if args.common.json { let mut env = error_envelope(Command::Repair, args.common.dry_run, &e.code, &e.message); diff --git a/crates/socket-patch-cli/src/commands/rollback.rs b/crates/socket-patch-cli/src/commands/rollback.rs index 8cfc33c5f..4cbed5e85 100644 --- a/crates/socket-patch-cli/src/commands/rollback.rs +++ b/crates/socket-patch-cli/src/commands/rollback.rs @@ -12,7 +12,9 @@ use socket_patch_core::patch::rollback::{ cannot_rollback_error, rollback_package_patch, verify_file_rollback, RollbackResult, VerifyRollbackResult, VerifyRollbackStatus, }; -use socket_patch_core::telemetry::{track_patch_rollback_failed, track_patch_rolled_back}; +use socket_patch_core::telemetry::{ + track_patch_rollback_failed, track_patch_rolled_back, RollbackRun, TelemetryAuth, MODE_AGENT, +}; use socket_patch_core::utils::purl::strip_purl_qualifiers; use socket_patch_core::utils::purl_key::PurlKey; use socket_patch_core::utils::target::{is_path_shaped, Target, TargetKind}; @@ -1589,6 +1591,46 @@ impl BelowNotes { /// the patched project directories below it. const PROJECTS_NOT_ROLLED_BACK: &str = "projects_not_rolled_back"; +/// What a rollback event says about the run itself. +fn rollback_run(args: &RollbackArgs, rolled_back_count: usize) -> RollbackRun { + RollbackRun { + rolled_back_count, + dry_run: args.common.dry_run, + targeted: !args.targets.is_empty(), + } +} + +/// Telemetry for a rollback that ended before it reached a patch: a +/// manifest it could not read, a target that matched nothing. `code` is +/// the run's `--json` error code, which is what tells a mistyped target +/// from a patch that would not come off. +async fn track_unstarted( + args: &RollbackArgs, + code: &str, + error: impl std::fmt::Display, + telemetry: &TelemetryAuth, +) { + track_patch_rollback_failed(code, error, rollback_run(args, 0), &[], telemetry).await; +} + +/// The patches a rollback's events name, as its telemetry reports them. +/// The manifest cleanup's `removed` events are left out: they say a record +/// was dropped, and the patch's own event already says what happened to +/// the package. +fn reported_rollback_patches(env: &Envelope) -> Vec { + crate::telemetry_outcomes::patch_outcomes_of( + env.events.iter().filter(|event| { + !event + .details + .as_ref() + .and_then(|details| details.get("manifest")) + .and_then(serde_json::Value::as_bool) + .unwrap_or(false) + }), + MODE_AGENT, + ) +} + pub async fn run(args: RollbackArgs) -> i32 { use crate::commands::projects_below::{self, Depth, Work}; apply_env_toggles(&args.common); @@ -1830,8 +1872,8 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { let manifest_missing = match manifest_exists(&manifest_path).await { Ok(present) => !present, Err(e) => { - track_patch_rollback_failed(&e.to_string(), &telemetry).await; let err = crate::json_envelope::manifest_load_error(&manifest_path, &e); + track_unstarted(&args, &err.code, e.to_string(), &telemetry).await; emit_rollback_error( args.common.json, args.common.dry_run, @@ -1996,7 +2038,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { Ok(None) => { // Deleted between the existence probe and the read. let msg = format!("Manifest not found at {}", manifest_path.display()); - track_patch_rollback_failed(&msg, &telemetry).await; + track_unstarted(&args, "manifest_not_found", &msg, &telemetry).await; emit_rollback_error( args.common.json, args.common.dry_run, @@ -2007,7 +2049,13 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { } Err(e) => { let msg = e.to_string(); - track_patch_rollback_failed(&msg, &telemetry).await; + track_unstarted( + &args, + crate::json_envelope::manifest_load_error_code(&e), + &msg, + &telemetry, + ) + .await; if args.common.json { let err = crate::json_envelope::manifest_load_error(&manifest_path, &e); println!( @@ -2083,7 +2131,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { if let Ok(state) = &vendor_state_result { if let Some(detail) = unledgered_vendor_wiring(&args.common, &ledger_root, state).await { - track_patch_rollback_failed(&detail, &telemetry).await; + track_unstarted(&args, "vendor_ledger_missing", &detail, &telemetry).await; emit_rollback_error( args.common.json, args.common.dry_run, @@ -2133,7 +2181,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { let id = match settled { Ok(settled) => settled, Err(msg) => { - track_patch_rollback_failed(&msg, &telemetry).await; + track_unstarted(&args, "ambiguous_target", &msg, &telemetry).await; emit_rollback_error( args.common.json, args.common.dry_run, @@ -2155,7 +2203,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { format!(" (to target a directory instead, use ./{id} or {id}/**)") }; let msg = format!("No patch found matching identifier: {id}{hint}"); - track_patch_rollback_failed(&msg, &telemetry).await; + track_unstarted(&args, "patch_not_found", &msg, &telemetry).await; if args.common.json { let mut env = error_envelope( args.common.dry_run, @@ -2229,7 +2277,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { identifier or an unscoped rollback)", unmatched.1 ); - track_patch_rollback_failed(&msg, &telemetry).await; + track_unstarted(&args, "path_glob_no_match", &msg, &telemetry).await; emit_rollback_error( args.common.json, args.common.dry_run, @@ -2786,6 +2834,34 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { )); } + // Telemetry names the patches the `--json` envelope's events + // name, so the two cannot disagree: the same report, built + // without the run-level extras no event of it carries. + let reported_patches = + reported_rollback_patches(&build_rollback_envelope(&RollbackReport { + dry_run: args.common.dry_run, + success, + manifest: &manifest, + results: &results, + not_installed: ¬_installed, + unsupported_skips: &unsupported_skips, + invalid_keys: &invalid_keys, + project_owned: if project_state { + &[] + } else { + &vendored_excluded + }, + vendored: &vendored_leg, + vendor_entries: &vendor_entries, + hosted: &hosted_leg, + hosted_pins: &hosted_pins, + contested: contested.as_deref(), + removed: &removed, + gc: None, + warnings: &[], + paths: path_scope.raw(), + })); + if args.common.json { // The GC was requested (not `--preserve-state`) but could not // run: `gc` stays absent and this warning says why. @@ -2999,10 +3075,18 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { } } + let run = rollback_run(&args, rolled_back_total); if success { - track_patch_rolled_back(rolled_back_total, &telemetry).await; + track_patch_rolled_back(run, &reported_patches, &telemetry).await; } else { - track_patch_rollback_failed("One or more rollbacks failed", &telemetry).await; + track_patch_rollback_failed( + "rollback_failed", + "One or more rollbacks failed", + run, + &reported_patches, + &telemetry, + ) + .await; } if success { @@ -3012,7 +3096,7 @@ async fn run_project(args: RollbackArgs, below: BelowNotes) -> i32 { } } Err(e) => { - track_patch_rollback_failed(&e, &telemetry).await; + track_unstarted(&args, "rollback_failed", &e, &telemetry).await; if args.common.json { println!( "{}", diff --git a/crates/socket-patch-cli/src/commands/scan/hosted.rs b/crates/socket-patch-cli/src/commands/scan/hosted.rs index 703050063..94f5682a6 100644 --- a/crates/socket-patch-cli/src/commands/scan/hosted.rs +++ b/crates/socket-patch-cli/src/commands/scan/hosted.rs @@ -91,6 +91,20 @@ pub(super) fn record_hosted_events( skipped: &[socket_patch_core::hosted::engine::SkippedPatch], dry_run: bool, ) { + for event in hosted_events(confirmed, unconfirmed, skipped, dry_run) { + env.record(event); + } +} + +/// A hosted run's per-patch outcomes as events, tagged `mode: "hosted"` +/// (see [`record_hosted_events`]): what the envelope records and what the +/// run's telemetry names. +fn hosted_events( + confirmed: &[(String, String)], + unconfirmed: &[(String, String)], + skipped: &[socket_patch_core::hosted::engine::SkippedPatch], + dry_run: bool, +) -> Vec { let pinned = if dry_run { PatchAction::Verified } else { @@ -116,9 +130,10 @@ pub(super) fn record_hosted_events( })) .collect(); events.sort_by(|a, b| (&a.purl, &a.uuid).cmp(&(&b.purl, &b.uuid))); - for event in events { - env.record(tag_mode(event, Some("hosted"))); - } + events + .into_iter() + .map(|event| tag_mode(event, Some("hosted"))) + .collect() } /// A `{code, detail}` warning object (the shape the stale-install probes @@ -131,7 +146,8 @@ fn run_warning_of(w: &serde_json::Value) -> RunWarning { } /// An engine refusal (nothing was written): `Error (): ` on -/// stderr plus the `--json` error envelope carrying the code, exit 1. +/// stderr plus the error envelope carrying the code (printed under +/// `--json`; its code is also the failure event's), exit 1. fn refuse( common: &crate::args::GlobalArgs, scan_result: Option, @@ -139,14 +155,12 @@ fn refuse( json_error: &mut Option, ) -> i32 { eprintln!("Error ({}): {}", refusal.code, refusal.message); - if common.json { - *json_error = Some(json_error_envelope( - common, - scan_result, - &refusal.code, - &refusal.message, - )); - } + *json_error = Some(json_error_envelope( + common, + scan_result, + &refusal.code, + &refusal.message, + )); 1 } @@ -169,14 +183,12 @@ fn acquire_hosted_lock( "{}", crate::commands::lock_cli::format_lock_error(&socket_dir, &err, timeout) ); - if common.json { - *json_error = Some(json_error_envelope( - common, - scan_result.take(), - code, - &message, - )); - } + *json_error = Some(json_error_envelope( + common, + scan_result.take(), + code, + &message, + )); Err(1) } } @@ -1059,17 +1071,35 @@ pub(crate) async fn run_redirect_selected( ) .await; if code != 0 && !telemetry.sent && !selected.is_empty() { + // Nothing was pinned: every selected patch is one the run failed + // on, under the code its error envelope carries. + let error_code = telemetry + .json_error + .as_ref() + .and_then(|envelope| envelope.error.as_ref()) + .map_or("hosted_failed", |error| error.code.as_str()); + let failed = crate::telemetry_outcomes::uniform_outcomes( + selected + .iter() + .map(|(purl, uuid)| (purl.as_str(), uuid.as_str())), + socket_patch_core::telemetry::MODE_HOSTED, + socket_patch_core::telemetry::OUTCOME_FAILED, + Some(error_code), + ); socket_patch_core::telemetry::track_patch_hosted_failed( command, + error_code, "hosted redirect failed", common.dry_run, + &failed, &telemetry.auth, ) .await; } - // The `--json` error envelope prints only after the failure event went - // out, so a consumer that closes stdout on it cannot drop the event. - if let Some(envelope) = telemetry.json_error.take() { + // The error envelope prints (under `--json`) only after the failure + // event went out, so a consumer that closes stdout on it cannot drop + // the event. + if let Some(envelope) = telemetry.json_error.take().filter(|_| common.json) { emit_scan(&envelope); } code @@ -1081,8 +1111,9 @@ struct HostedTelemetry { command: &'static str, auth: socket_patch_core::telemetry::TelemetryAuth, sent: bool, - /// A `--json` error envelope a failure path built, printed by - /// [`run_redirect_selected`] after the failure event is sent. + /// The error envelope a failure path built: [`run_redirect_selected`] + /// takes the failure event's code from it and, under `--json`, prints + /// it after that event is sent. json_error: Option, } @@ -1171,14 +1202,12 @@ async fn run_redirect_selected_untracked( "{} (nothing was changed; re-run to retry)", format_error_line(&message) ); - if common.json { - telemetry.json_error = Some(json_error_envelope( - common, - scan_result.take(), - "reference_resolve_failed", - &message, - )); - } + telemetry.json_error = Some(json_error_envelope( + common, + scan_result.take(), + "reference_resolve_failed", + &message, + )); return 1; } }; @@ -1876,14 +1905,12 @@ async fn run_redirect_selected_untracked( .await { eprintln!("{}", format_error_line(&message)); - if common.json { - telemetry.json_error = Some(json_error_envelope( - common, - scan_result.take(), - "lockfile_write_failed", - &message, - )); - } + telemetry.json_error = Some(json_error_envelope( + common, + scan_result.take(), + "lockfile_write_failed", + &message, + )); return 1; } @@ -2237,6 +2264,10 @@ async fn run_redirect_selected_untracked( confirmed.len(), done.rewritten.len(), common.dry_run, + &crate::telemetry_outcomes::patch_outcomes_of( + &hosted_events(&confirmed, &unconfirmed, &skipped, common.dry_run), + socket_patch_core::telemetry::MODE_HOSTED, + ), &telemetry.auth, ) .await; diff --git a/crates/socket-patch-cli/src/commands/scan/mod.rs b/crates/socket-patch-cli/src/commands/scan/mod.rs index 746e3f31f..630d65862 100644 --- a/crates/socket-patch-cli/src/commands/scan/mod.rs +++ b/crates/socket-patch-cli/src/commands/scan/mod.rs @@ -19,14 +19,16 @@ use socket_patch_core::crawlers::ruby_crawler::{ use socket_patch_core::crawlers::Ecosystem; use socket_patch_core::ledgers::merge_ledger_records_for_updates; use socket_patch_core::manifest::schema::PatchManifest; -use socket_patch_core::telemetry::{track_patch_scan_failed, track_patch_scanned, TelemetryAuth}; +use socket_patch_core::telemetry::{ + track_patch_scan_failed, track_patch_scanned, ScanReport, TelemetryAuth, +}; use socket_patch_core::utils::concurrent::{api_concurrency_for, ordered_concurrent}; use socket_patch_core::utils::purl::{canonical_purl, normalize_purl}; use socket_patch_core::utils::purl_key::{canonical_base_purl, PurlKey}; use socket_patch_core::vendor::lock_inventory::unsupported_layout_warnings; use socket_patch_core::vendor::{purl_keys_cover, VendorState}; use socket_patch_core::vex::discover::{LedgerLiveness, WiringMode}; -use std::collections::{HashMap, HashSet}; +use std::collections::{BTreeMap, HashMap, HashSet}; use std::path::{Path, PathBuf}; use crate::args::{apply_env_toggles, GlobalArgs}; @@ -42,8 +44,7 @@ use crate::json_envelope::{ use crate::ui::{self, plural, print_json, StatusLine}; use crate::commands::agent_download::{ - download_and_apply_patches_into, download_and_apply_patches_with, DownloadParams, DownloadRun, - ALREADY_IN_MANIFEST, + download_and_apply_patches_into, DownloadParams, DownloadRun, ALREADY_IN_MANIFEST, }; use self::policy::{load_invocation_policy, InvocationPolicy, PolicyLoadError, ScanPolicy}; @@ -1601,15 +1602,21 @@ fn emit_scan_error(common: &GlobalArgs, error: EnvelopeError) { emit_scan(&env); } -/// The ecosystems `purls` span, by CLI name, sorted and deduplicated. -fn scanned_ecosystems(purls: &[String]) -> Vec { - purls - .iter() - .filter_map(|purl| Ecosystem::from_purl(purl)) - .map(|eco| eco.cli_name().to_string()) - .collect::>() - .into_iter() - .collect() +/// `(purl, n)` pairs summed per ecosystem, by CLI name: how many packages +/// (or patches) of each ecosystem a scan found. An ecosystem with nothing +/// has no entry; a purl of no known ecosystem is not counted. +fn count_by_ecosystem<'a>( + counts: impl Iterator, +) -> BTreeMap { + let mut by_ecosystem = BTreeMap::new(); + for (purl, n) in counts { + if let Some(ecosystem) = Ecosystem::from_purl(purl).filter(|_| n > 0) { + *by_ecosystem + .entry(ecosystem.cli_name().to_string()) + .or_default() += n; + } + } + by_ecosystem } pub async fn run(args: ScanArgs) -> i32 { @@ -2562,6 +2569,14 @@ async fn scan_project( let err = crate::json_envelope::manifest_load_error(&manifest_path, e); if apply { status.finish(); + track_patch_scan_failed( + &err.code, + &err.message, + false, + ScanMode::Agent.cli_name(), + &telemetry_auth, + ) + .await; if args.common.json { emit_scan_error(&args.common, err); } else { @@ -2937,14 +2952,17 @@ async fn scan_project( } // Telemetry: empty-scan still counts as a successful scan. track_patch_scanned( - 0, - 0, - 0, - false, - &[], - false, - requested_mode, - &project_modes, + ScanReport { + packages_by_ecosystem: &BTreeMap::new(), + patches_by_ecosystem: &BTreeMap::new(), + free_patches: 0, + paid_patches: 0, + can_access_paid: false, + fallback_to_proxy: false, + mode: requested_mode, + project_modes: &project_modes, + dry_run: args.common.dry_run, + }, &telemetry_auth, ) .await; @@ -3288,7 +3306,14 @@ async fn scan_project( if total_batches > 0 && batch_error_count == total_batches { status.finish(); let err = last_batch_error.unwrap_or_else(|| "all batches failed".to_string()); - track_patch_scan_failed(&err, fallback_to_proxy, &telemetry_auth).await; + track_patch_scan_failed( + API_BATCH_FAILED, + &err, + fallback_to_proxy, + requested_mode, + &telemetry_auth, + ) + .await; if args.common.json { let mut env = scan_envelope(&args.common); env.set_extra("scannedPackages", serde_json::json!(package_count)); @@ -3343,6 +3368,14 @@ async fn scan_project( .as_ref() .and_then(|sweep| sweep.half_restored().map(str::to_string)) { + track_patch_scan_failed( + "lockfile_write_failed", + &why, + fallback_to_proxy, + requested_mode, + &telemetry_auth, + ) + .await; if args.common.json { let mut env = scan_envelope(&args.common); env.set_extra("scannedPackages", serde_json::json!(package_count)); @@ -3381,14 +3414,21 @@ async fn scan_project( // ecosystems the crawl actually found (not the `--ecosystems` filter, // which is empty on a default run). track_patch_scanned( - package_count, - free_patches, - paid_patches, - can_access_paid_patches, - &scanned_ecosystems(&all_purls), - fallback_to_proxy, - requested_mode, - &project_modes, + ScanReport { + packages_by_ecosystem: &count_by_ecosystem(all_purls.iter().map(|purl| (purl, 1))), + patches_by_ecosystem: &count_by_ecosystem( + all_packages_with_patches + .iter() + .map(|pkg| (&pkg.purl, pkg.patches.len())), + ), + free_patches, + paid_patches, + can_access_paid: can_access_paid_patches, + fallback_to_proxy, + mode: requested_mode, + project_modes: &project_modes, + dry_run: args.common.dry_run, + }, &telemetry_auth, ) .await; @@ -4278,10 +4318,14 @@ async fn scan_project( // record and the nested apply re-applies them (a no-op on disk // when the installed copy is still patched). let to_download: Vec<_> = selected.iter().chain(&already_recorded).cloned().collect(); - let (code, outcome) = download_and_apply_patches_with( + // Into a scan envelope (never printed here): the engine reports + // its telemetry under the command whose envelope it fills. + let mut outcome = scan_envelope(&args.common); + let code = download_and_apply_patches_into( &to_download, ¶ms, &download_run(&args, &api_client), + &mut outcome, ) .await; // Under the apply's result line: one row per package it left diff --git a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs index ca7f3e900..c9f3f71cd 100644 --- a/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs +++ b/crates/socket-patch-cli/src/commands/scan/vendor_flow.rs @@ -476,6 +476,9 @@ pub(crate) fn merge_vendor_envelope(env: &mut Envelope, venv: Envelope) { /// blob `seed` that phase fetched (so the stager fetches no view twice), /// the run's API client, and the run outcome so far for telemetry. pub(crate) struct VendorStep<'a> { + /// The command the user ran (`scan`, `get`): what the step's telemetry + /// reports as its command. + pub(crate) command: &'static str, pub(crate) common: &'a GlobalArgs, pub(crate) records: HashMap, pub(crate) client: ApiClient, @@ -491,6 +494,10 @@ pub(crate) struct VendorStep<'a> { /// The download phase failed or refused some patch: the run exits 1 /// and its telemetry must not report a clean vendoring. pub(crate) download_errors: bool, + /// The patches the download phase could not get + /// (`DetachedDownload::failed_outcomes`), for the step's telemetry to + /// name beside the ones it vendored. + pub(crate) download_failures: Vec, pub(crate) telemetry_auth: &'a TelemetryAuth, /// Lines for the human close to print under its summary line (see /// [`VendoredBackend::with_closing_lines`]). @@ -516,6 +523,7 @@ pub(crate) struct VendorStep<'a> { /// `success`. async fn run_vendor_step(step: VendorStep<'_>) -> VendorStepResult { let VendorStep { + command, common, records, client, @@ -523,9 +531,16 @@ async fn run_vendor_step(step: VendorStep<'_>) -> VendorStepResult { report_empty, prior, download_errors, + download_failures, telemetry_auth, closing_lines, } = step; + // The records' patches, for the telemetry of a run whose events name + // packages only. + let uuids: HashMap = records + .iter() + .map(|(purl, record)| (purl.clone(), record.uuid.clone())) + .collect(); let outcome = vendor_under_lock( common, records, @@ -542,15 +557,39 @@ async fn run_vendor_step(step: VendorStep<'_>) -> VendorStepResult { // successful vendoring of zero patches. Ok((vendor_errors, venv)) => { track_outcomes_for_vendor( + command, download_errors || *vendor_errors, venv, common.dry_run, + &uuids, + &download_failures, telemetry_auth, ) .await } - Err((_, message, _)) => { - track_patch_vendor_failed(message, common.dry_run, telemetry_auth).await + // Nothing was vendored: every downloaded patch is one the step + // failed on, beside the ones that never downloaded. + Err((code, message, _)) => { + let failed = crate::telemetry_outcomes::with_more( + crate::telemetry_outcomes::uniform_outcomes( + uuids + .iter() + .map(|(purl, uuid)| (purl.as_str(), uuid.as_str())), + socket_patch_core::telemetry::MODE_VENDORED, + socket_patch_core::telemetry::OUTCOME_FAILED, + Some(code), + ), + &download_failures, + ); + track_patch_vendor_failed( + command, + code, + message, + common.dry_run, + &failed, + telemetry_auth, + ) + .await } } outcome.map(|(vendor_errors, venv)| (download_errors || vendor_errors, venv)) @@ -860,14 +899,15 @@ async fn run_vendor_json_path( let params = download_params( args, /*save_only=*/ true, /*json=*/ true, /*silent=*/ true, ); - let (dl_code, _, records) = - boxed_download_patch_records(&selected, ¶ms, api_client, HashMap::new(), prior) - .await - .into_envelope(env); + let download = + boxed_download_patch_records(&selected, ¶ms, api_client, HashMap::new(), prior).await; + let download_failures = download.failed_outcomes(); + let (dl_code, _, records) = download.into_envelope(env); // 2) The vendor engine, under the same lock as apply/vendor (a no-op // that creates nothing when there is nothing to vendor). let vendor_code = match boxed_vendor_step(VendorStep { + command: "scan", common: &args.common, records, client: api_client.clone(), @@ -875,6 +915,7 @@ async fn run_vendor_json_path( report_empty: true, prior, download_errors: dl_code != 0, + download_failures, telemetry_auth, closing_lines: None, }) @@ -962,6 +1003,7 @@ async fn run_vendor_interactive_path( // the rows under the summary line. let download = boxed_download_patch_records(selected, params, api_client, prefetched, prior).await; + let download_failures = download.failed_outcomes(); let (dl_code, records) = (download.code, download.records); // Patches the download phase could not get (it reported each one). let download_failed = download.failed as u64; @@ -990,6 +1032,7 @@ async fn run_vendor_interactive_path( rows }; let code = match boxed_vendor_step(VendorStep { + command: "scan", common: &args.common, records, client: api_client.clone(), @@ -997,6 +1040,7 @@ async fn run_vendor_interactive_path( report_empty: false, prior, download_errors: dl_code != 0, + download_failures, telemetry_auth, closing_lines: Some(&closing_lines), }) diff --git a/crates/socket-patch-cli/src/commands/update.rs b/crates/socket-patch-cli/src/commands/update.rs index 37df27f47..6b0bf7725 100644 --- a/crates/socket-patch-cli/src/commands/update.rs +++ b/crates/socket-patch-cli/src/commands/update.rs @@ -8,7 +8,9 @@ //! machinery lives in `socket_patch_core::update`. use clap::Args; -use socket_patch_core::telemetry::{track_cli_update_failed, track_cli_updated}; +use socket_patch_core::telemetry::{ + prime_install_channel, track_cli_update_failed, track_cli_updated, +}; use socket_patch_core::update::{ self as core_update, asset_name_for_target, channel_label_for, current_version, detect_channel, fetch_latest_version, is_newer, upgrade_hint_for, ChannelEnv, InstallChannel, UpdateEndpoints, @@ -190,6 +192,10 @@ pub async fn run(args: UpdateArgs) -> i32 { }; let channel_env = ChannelEnv::from_env(); let channel = detect_channel(&install_path, &channel_env); + // Before anything replaces this binary: the event this run reports + // names the channel of the binary that ran, and once the swap has + // happened that binary's path no longer resolves on Linux. + prime_install_channel(); let hint = upgrade_hint_for(channel, &install_path, &channel_env); if channel != InstallChannel::Standalone { if args.force { diff --git a/crates/socket-patch-cli/src/commands/vendor.rs b/crates/socket-patch-cli/src/commands/vendor.rs index 19560cf8c..c85b55838 100644 --- a/crates/socket-patch-cli/src/commands/vendor.rs +++ b/crates/socket-patch-cli/src/commands/vendor.rs @@ -30,7 +30,7 @@ use socket_patch_core::manifest::schema::{PatchManifest, PatchRecord}; use socket_patch_core::patch::apply::{verify_file_patch, PatchSources}; use socket_patch_core::patch::redirect::upstream::HostedPin; use socket_patch_core::telemetry::{ - track_patch_vendor_failed, track_patch_vendored, TelemetryAuth, + track_patch_vendor_failed, track_patch_vendored, TelemetryAuth, MODE_VENDORED, }; use socket_patch_core::utils::concurrent::ordered_concurrent; use socket_patch_core::utils::group_commit::{CommittedFile, GroupCommit}; @@ -1246,8 +1246,10 @@ pub async fn run(args: VendorArgs) -> i32 { } } + // The patches of the ledger entries a `--revert` starts from. + let mut reverted_uuids: HashMap = HashMap::new(); let mut exit = match &vendor_service { - None => run_revert(&args, &mut env).await, + None => run_revert(&args, &mut env, &mut reverted_uuids).await, Some((service, _)) => run_vendor(&args, &manifest_path, &mut env, service).await, }; @@ -1302,16 +1304,40 @@ pub async fn run(args: VendorArgs) -> i32 { env.warnings .extend(crate::commands::sync_bazelignore(&args.common, true).await); + // The patches this run's event names are read while the lock is still + // held. Once it is released another run on the same project can rewrite + // the ledger and the manifest, and this run's event would be credited to + // that run's patches. + let uuids = match &vendor_service { + Some(_) => recorded_patch_uuids(&args.common, &manifest_path).await, + None => HashMap::new(), + }; + // Everything below is output and telemetry, so release the lock before // the telemetry round-trip. drop(lock); - if args.common.json { - println!("{}", env.to_pretty_json()); + // Sent before the envelope prints, like `remove` and the hosted flow: a + // consumer that closes stdout on the envelope cannot drop the event. + match &vendor_service { + Some((_, telemetry)) => { + track_outcomes_for_vendor( + "vendor", + exit != 0, + &env, + args.common.dry_run, + &uuids, + &[], + telemetry, + ) + .await; + } + // `--revert` takes every vendored patch out: a removal. + None => track_revert(&args, exit, &env, &reverted_uuids).await, } - if let Some((_, telemetry)) = &vendor_service { - track_outcomes_for_vendor(exit != 0, &env, args.common.dry_run, telemetry).await; + if args.common.json { + println!("{}", env.to_pretty_json()); } exit @@ -1957,6 +1983,8 @@ async fn run_eject( commit_recovery: Option, ) -> i32 { let common = &args.common; + // The pins' patches, for the run's telemetry. + let eject_uuids = pin_uuids(&pins); // A ledger git would not commit refuses before anything is fetched or // restored, so the project stays hosted (#1638). let purls: Vec = pins.iter().map(|pin| pin.purl.clone()).collect(); @@ -2059,7 +2087,16 @@ async fn run_eject( if common.json { println!("{}", env.to_pretty_json()); } - track_outcomes_for_vendor(true, &env, common.dry_run, &telemetry).await; + track_outcomes_for_vendor( + "vendor", + true, + &env, + common.dry_run, + &eject_uuids, + &[], + &telemetry, + ) + .await; return 1; } @@ -2166,7 +2203,16 @@ async fn run_eject( if common.json { println!("{}", env.to_pretty_json()); } - track_outcomes_for_vendor(true, &env, common.dry_run, &telemetry).await; + track_outcomes_for_vendor( + "vendor", + true, + &env, + common.dry_run, + &eject_uuids, + &[], + &telemetry, + ) + .await; return 1; } @@ -2213,7 +2259,7 @@ async fn run_eject( if common.json { println!("{}", env.to_pretty_json()); } - track_outcomes_for_vendor(false, &env, true, &telemetry).await; + track_outcomes_for_vendor("vendor", false, &env, true, &eject_uuids, &[], &telemetry).await; return 0; } @@ -2524,7 +2570,16 @@ async fn run_eject( if common.json { println!("{}", env.to_pretty_json()); } - track_outcomes_for_vendor(exit != 0, &env, common.dry_run, &telemetry).await; + track_outcomes_for_vendor( + "vendor", + exit != 0, + &env, + common.dry_run, + &eject_uuids, + &[], + &telemetry, + ) + .await; exit } @@ -2554,21 +2609,138 @@ fn no_manifest_message(tracked_entries: usize) -> String { } } +/// Telemetry for `vendor --revert`: each entry it took out is a patch +/// removed (in vendored mode), as `remove` reports one. A run that could +/// take none out is the failure; a `--dry-run` reports nothing, like +/// `remove`'s. +async fn track_revert( + args: &VendorArgs, + exit: i32, + env: &Envelope, + uuids: &HashMap, +) { + if args.common.dry_run { + return; + } + let patches = vendor_outcomes(env, uuids); + let removed = socket_patch_core::telemetry::PatchOutcome::count(&patches, "removed"); + let telemetry = args.common.telemetry_auth(); + if exit != 0 && removed == 0 { + let (code, message) = env.error.as_ref().map_or( + ("vendor_revert_failed", "vendor --revert failed"), + |error| (error.code.as_str(), error.message.as_str()), + ); + socket_patch_core::telemetry::track_patch_remove_failed( + "vendor", code, message, &patches, &telemetry, + ) + .await; + } else if removed > 0 { + socket_patch_core::telemetry::track_patch_removed("vendor", removed, &patches, &telemetry) + .await; + } +} + +/// The patches a vendor run's events are about, as its telemetry names +/// them. The events name packages; `uuids` (purl → patch UUID) names +/// their patches. A swept orphan directory is left out: its event names +/// the package it once held, which would credit the sweep to the patch +/// the ledger records for that package now. +fn vendor_outcomes( + env: &Envelope, + uuids: &HashMap, +) -> Vec { + crate::telemetry_outcomes::patch_outcomes( + env.events + .iter() + .filter(|event| event.error_code.as_deref() != Some("vendor_orphan_removed")), + MODE_VENDORED, + crate::telemetry_outcomes::uuid_lookup(uuids), + ) +} + /// Telemetry for a vendor run's success/failure split, shared by -/// [`run`] and the scan-driven vendor step (`scan --mode vendored`). +/// [`run`] and the vendor step of `scan` / `get --mode vendored` +/// (`command` is the one the user ran). `uuids` names the patches of the +/// run's events ([`vendor_outcomes`]); `download_failures` are the +/// patches a download phase before the step could not get, which the +/// step's own events never name. pub(crate) async fn track_outcomes_for_vendor( + command: &'static str, has_errors: bool, env: &Envelope, dry_run: bool, + uuids: &HashMap, + download_failures: &[socket_patch_core::telemetry::PatchOutcome], telemetry: &TelemetryAuth, ) { + let patches = + crate::telemetry_outcomes::with_more(vendor_outcomes(env, uuids), download_failures); if has_errors { - track_patch_vendor_failed("vendor completed with failures", dry_run, telemetry).await; + let code = env + .error + .as_ref() + .map_or("vendor_failed", |e| e.code.as_str()); + track_patch_vendor_failed( + command, + code, + "vendor completed with failures", + dry_run, + &patches, + telemetry, + ) + .await; } else { - track_patch_vendored(env.summary.applied, dry_run, telemetry).await; + track_patch_vendored(command, env.summary.applied, dry_run, &patches, telemetry).await; } } +/// [`read_recorded_patch_uuids`] for a run's telemetry: nothing is read +/// when telemetry is off. +async fn recorded_patch_uuids( + common: &GlobalArgs, + manifest_path: &Path, +) -> HashMap { + if socket_patch_core::telemetry::is_telemetry_disabled() { + return HashMap::new(); + } + read_recorded_patch_uuids(&common.project_root(), manifest_path).await +} + +/// purl → patch UUID over what the project at `root` records: the vendor +/// ledger's entries, and over them the manifest's records. For the +/// telemetry of a `vendor` run, whose events name packages only. The +/// manifest wins: it is what the run vendors from, and the ledger may +/// still hold the patch a failed run was replacing. Only keys are +/// recorded, never an entry's base purl: a purl with no key of its own is +/// matched across qualifiers by the lookup, which refuses an ambiguous one. +async fn read_recorded_patch_uuids(root: &Path, manifest_path: &Path) -> HashMap { + let mut uuids = HashMap::new(); + if let Ok(state) = load_state(root).await { + uuids.extend( + state + .entries + .into_iter() + .map(|(key, entry)| (key, entry.uuid)), + ); + } + if let Ok(Some(manifest)) = read_manifest(manifest_path).await { + uuids.extend( + manifest + .patches + .into_iter() + .map(|(purl, record)| (purl, record.uuid)), + ); + } + uuids +} + +/// The patches of hosted pins, by purl. +fn pin_uuids(pins: &[HostedPin]) -> HashMap { + pins.iter() + .map(|pin| (pin.purl.clone(), pin.uuid.clone())) + .collect() +} + async fn run_vendor( args: &VendorArgs, manifest_path: &Path, @@ -4862,7 +5034,11 @@ pub(crate) async fn reconcile_dropped( (had_error, Ok(state)) } -async fn run_revert(args: &VendorArgs, env: &mut Envelope) -> i32 { +async fn run_revert( + args: &VendorArgs, + env: &mut Envelope, + uuids: &mut HashMap, +) -> i32 { let common = &args.common; let mut state = match load_state(&common.cwd).await { Ok(s) => s, @@ -4872,6 +5048,12 @@ async fn run_revert(args: &VendorArgs, env: &mut Envelope) -> i32 { return 1; } }; + uuids.extend( + state + .entries + .iter() + .map(|(key, entry)| (key.clone(), entry.uuid.clone())), + ); let mut has_errors = false; let mut recorded: Vec = state.entries.keys().cloned().collect(); @@ -6454,6 +6636,73 @@ mod gc_tests { } } + /// A `vendor` run's events are credited to the patch the manifest + /// records, not to the one the ledger still holds for the package: a + /// run that fails to replace a patch leaves the old one in the ledger. + #[tokio::test] + async fn telemetry_credits_the_manifests_patch_over_the_ledgers() { + const NEW_UUID: &str = "22222222-2222-4222-8222-222222222222"; + let tmp = tempfile::tempdir().unwrap(); + let root = tmp.path(); + let mut manifest = PatchManifest::new(); + manifest.patches.insert( + PURL.to_string(), + socket_patch_core::manifest::schema::PatchRecord { + uuid: NEW_UUID.to_string(), + exported_at: String::new(), + files: HashMap::new(), + vulnerabilities: HashMap::new(), + description: String::new(), + license: String::new(), + tier: String::new(), + }, + ); + let manifest_path = root.join(".socket/manifest.json"); + tokio::fs::create_dir_all(root.join(".socket")) + .await + .unwrap(); + write_manifest(&manifest_path, &manifest).await.unwrap(); + let mut state = VendorState::default(); + state.entries.insert(PURL.to_string(), entry(false)); + // A ledger-only entry keeps its own patch. + let other = "pkg:npm/other@1.0.0?artifact_id=x"; + state.entries.insert(other.to_string(), entry(true)); + save_state(root, &state).await.unwrap(); + + let uuids = read_recorded_patch_uuids(root, &manifest_path).await; + assert_eq!(uuids.get(PURL).map(String::as_str), Some(NEW_UUID)); + assert_eq!(uuids.get(other).map(String::as_str), Some(UUID)); + // Keys only: an entry's base purl is not a key of its own. + assert_eq!(uuids.len(), 2, "{uuids:?}"); + } + + /// A swept orphan directory names the package it once held. Its + /// `removed` event must not be credited to the patch the ledger + /// records for that package, which this run kept. + #[test] + fn a_swept_orphan_is_not_credited_to_the_ledgers_patch() { + let mut env = Envelope::new(Command::Vendor); + env.record( + PatchEvent::new(PatchAction::Skipped, PURL) + .with_reason("vendor_revert_kept", "the lockfile drifted"), + ); + env.record( + PatchEvent::new(PatchAction::Removed, PURL) + .with_reason("vendor_orphan_removed", "an unowned artifact directory"), + ); + let uuids: HashMap = [(PURL.to_string(), UUID.to_string())].into(); + + let outcomes = vendor_outcomes(&env, &uuids); + assert_eq!(outcomes.len(), 1, "{outcomes:?}"); + assert_eq!(outcomes[0].uuid, UUID); + assert_eq!(outcomes[0].outcome, "skipped"); + assert_eq!(outcomes[0].code.as_deref(), Some("vendor_revert_kept")); + assert_eq!( + socket_patch_core::telemetry::PatchOutcome::count(&outcomes, "removed"), + 0 + ); + } + /// Tempdir with: a manifest carrying PURL, a ledger with one entry, /// the artifact on disk, and a package-lock that resolves to it. async fn gc_fixture(detached: bool) -> (tempfile::TempDir, GlobalArgs, PathBuf) { diff --git a/crates/socket-patch-cli/src/lib.rs b/crates/socket-patch-cli/src/lib.rs index 7466821ad..92b3ccc95 100644 --- a/crates/socket-patch-cli/src/lib.rs +++ b/crates/socket-patch-cli/src/lib.rs @@ -73,6 +73,7 @@ pub mod interrupt; pub use socket_patch_core::hosted::memory as hosted_memory; pub mod json_envelope; pub mod path_scope; +pub(crate) mod telemetry_outcomes; pub mod ui; pub mod update_notifier; diff --git a/crates/socket-patch-cli/src/telemetry_outcomes.rs b/crates/socket-patch-cli/src/telemetry_outcomes.rs new file mode 100644 index 000000000..a892e7555 --- /dev/null +++ b/crates/socket-patch-cli/src/telemetry_outcomes.rs @@ -0,0 +1,430 @@ +//! What a run's telemetry says about each patch it acted on. +//! +//! Every command already describes its run as per-patch [`PatchEvent`]s +//! (the `--json` envelope's `events[]`). Telemetry reports the same +//! outcomes, reduced to what an event may carry: the patch UUID, the +//! ecosystem, the mode and what happened. Deriving the one from the other +//! keeps a run's telemetry and its `--json` output from disagreeing. + +use std::collections::HashMap; + +use socket_patch_core::telemetry::{ + PatchOutcome, MODE_AGENT, MODE_HOSTED, MODE_VENDORED, OUTCOME_FAILED, +}; + +use crate::json_envelope::{PatchAction, PatchEvent}; + +/// The ecosystem a purl names, as events spell it: the ecosystem's CLI +/// name (`npm`, `pypi`, … the names `scan` reports), or the purl's own +/// type for one this CLI has no ecosystem for. Empty for a key that is +/// not a purl. +pub(crate) fn ecosystem_of(purl: &str) -> String { + match socket_patch_core::crawlers::Ecosystem::from_purl(purl) { + Some(ecosystem) => ecosystem.cli_name().to_string(), + None => purl + .strip_prefix("pkg:") + .and_then(|rest| rest.split('/').next()) + .unwrap_or("") + .to_string(), + } +} + +/// `outcomes` with each of `more` it does not already name (by patch and +/// mode) added at the end. +pub(crate) fn with_more( + mut outcomes: Vec, + more: &[PatchOutcome], +) -> Vec { + for outcome in more { + if !outcomes + .iter() + .any(|have| have.uuid == outcome.uuid && have.mode == outcome.mode) + { + outcomes.push(outcome.clone()); + } + } + outcomes +} + +/// The telemetry word for an envelope action, and how much it says about +/// the patch (lower wins when one patch has several events): a failure +/// over a change, a change over a preview, a preview over a skip. `None` +/// for an action telemetry does not report. +fn outcome_of(action: PatchAction) -> Option<(&'static str, u8)> { + match action { + PatchAction::Failed => Some((OUTCOME_FAILED, 0)), + PatchAction::Applied | PatchAction::Updated => Some(("applied", 1)), + PatchAction::RolledBack => Some(("rolled_back", 1)), + PatchAction::Removed => Some(("removed", 1)), + PatchAction::Downloaded => Some(("downloaded", 1)), + PatchAction::Rebuilt => Some(("rebuilt", 1)), + PatchAction::Verified => Some(("verified", 2)), + PatchAction::Skipped => Some(("skipped", 3)), + PatchAction::Discovered => None, + } +} + +/// The mode an event is tagged with (`details.mode`), else `default`. +fn mode_of(event: &PatchEvent, default: &'static str) -> &'static str { + match event + .details + .as_ref() + .and_then(|details| details.get("mode")) + .and_then(|mode| mode.as_str()) + { + Some(MODE_HOSTED) => MODE_HOSTED, + Some(MODE_VENDORED) => MODE_VENDORED, + Some(MODE_AGENT) => MODE_AGENT, + _ => default, + } +} + +/// The patches `events` are about, one entry per patch and mode, in the +/// order the run first reached them. +/// +/// * An event names its patch by `uuid`, or by a purl `uuid_of` resolves +/// (apply's events carry the purl only). One that names neither is +/// about no single patch (an artifact sweep, a lockfile write) and is +/// left out. +/// * The mode is the event's `details.mode`, else `default_mode`. +/// * Several events for one patch (one per installed copy, or a download +/// and then an apply) fold into the one that says most: see +/// [`outcome_of`]. The `code` is that event's `errorCode`, and only a +/// failure or a skip has one. +pub(crate) fn patch_outcomes<'a>( + events: impl IntoIterator, + default_mode: &'static str, + uuid_of: impl Fn(&str) -> Option, +) -> Vec { + let mut outcomes: Vec<(PatchOutcome, u8)> = Vec::new(); + let mut index: HashMap<(String, &'static str), usize> = HashMap::new(); + for event in events { + let Some((outcome, rank)) = outcome_of(event.action) else { + continue; + }; + let purl = event.purl.as_deref(); + let Some(uuid) = event.uuid.clone().or_else(|| purl.and_then(&uuid_of)) else { + continue; + }; + let mode = mode_of(event, default_mode); + let code = matches!(event.action, PatchAction::Failed | PatchAction::Skipped) + .then(|| event.error_code.clone()) + .flatten(); + let entry = PatchOutcome { + uuid: uuid.clone(), + ecosystem: purl.map(ecosystem_of).unwrap_or_default(), + mode, + outcome, + code, + }; + match index.get(&(uuid.clone(), mode)) { + Some(&at) => { + if rank < outcomes[at].1 { + // Keep an ecosystem an earlier event of this patch knew. + let ecosystem = if entry.ecosystem.is_empty() { + std::mem::take(&mut outcomes[at].0.ecosystem) + } else { + entry.ecosystem.clone() + }; + outcomes[at] = (PatchOutcome { ecosystem, ..entry }, rank); + } else if outcomes[at].0.ecosystem.is_empty() { + outcomes[at].0.ecosystem = entry.ecosystem; + } + } + None => { + index.insert((uuid, mode), outcomes.len()); + outcomes.push((entry, rank)); + } + } + } + outcomes.into_iter().map(|(outcome, _)| outcome).collect() +} + +/// A purl → patch UUID lookup over `uuids`, for events that name the +/// package only. A purl with no entry of its own matches across its +/// qualifiers (`?artifact_id=…`, `?platform=…`), as long as every such +/// entry names the same patch: one event must not be credited to another +/// release's patch. +pub(crate) fn uuid_lookup(uuids: &HashMap) -> impl Fn(&str) -> Option + '_ { + use socket_patch_core::utils::purl::strip_purl_qualifiers; + move |purl| { + if let Some(uuid) = uuids.get(purl) { + return Some(uuid.clone()); + } + let base = strip_purl_qualifiers(purl); + let mut matches = uuids + .iter() + .filter(|(key, _)| strip_purl_qualifiers(key) == base) + .map(|(_, uuid)| uuid); + let first = matches.next()?; + matches.all(|uuid| uuid == first).then(|| first.clone()) + } +} + +/// [`patch_outcomes`] for events that all carry their own `uuid`. +pub(crate) fn patch_outcomes_of<'a>( + events: impl IntoIterator, + default_mode: &'static str, +) -> Vec { + patch_outcomes(events, default_mode, |_| None) +} + +/// One outcome for each `(purl, uuid)`, all in `mode`: for a run that +/// knows which patches it was about and that they all ended the same way +/// (a removal that failed before it reached any of them). +pub(crate) fn uniform_outcomes<'a>( + patches: impl IntoIterator, + mode: &'static str, + outcome: &'static str, + code: Option<&str>, +) -> Vec { + let mut seen = std::collections::HashSet::new(); + patches + .into_iter() + .filter(|(_, uuid)| seen.insert(*uuid)) + .map(|(purl, uuid)| PatchOutcome { + uuid: uuid.to_string(), + ecosystem: ecosystem_of(purl), + mode, + outcome, + code: code.map(str::to_string), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + const A: &str = "11111111-1111-4111-8111-111111111111"; + const B: &str = "22222222-2222-4222-8222-222222222222"; + + fn entry( + uuid: &str, + ecosystem: &str, + mode: &'static str, + outcome: &'static str, + code: Option<&str>, + ) -> PatchOutcome { + PatchOutcome { + uuid: uuid.to_string(), + ecosystem: ecosystem.to_string(), + mode, + outcome, + code: code.map(str::to_string), + } + } + + #[test] + fn an_event_is_named_by_its_uuid_or_by_its_resolved_purl() { + let events = [ + PatchEvent::new(PatchAction::Applied, "pkg:npm/a@1.0.0"), + PatchEvent::new(PatchAction::RolledBack, "pkg:pypi/b@2.0.0").with_uuid(B), + // No uuid and a purl nothing resolves: not a patch of this run. + PatchEvent::new(PatchAction::Applied, "pkg:npm/unknown@1.0.0"), + // About no single patch. + PatchEvent::artifact(PatchAction::Removed), + ]; + let outcomes = patch_outcomes(&events, MODE_AGENT, |purl| { + (purl == "pkg:npm/a@1.0.0").then(|| A.to_string()) + }); + assert_eq!( + outcomes, + [ + entry(A, "npm", MODE_AGENT, "applied", None), + entry(B, "pypi", MODE_AGENT, "rolled_back", None), + ] + ); + } + + #[test] + fn the_mode_is_the_events_own_when_it_has_one() { + let events = [ + PatchEvent::new(PatchAction::RolledBack, "pkg:npm/a@1.0.0") + .with_uuid(A) + .with_details(serde_json::json!({ "mode": "vendored" })), + PatchEvent::new(PatchAction::RolledBack, "pkg:npm/a@1.0.0") + .with_uuid(A) + .with_details(serde_json::json!({ "mode": "hosted" })), + PatchEvent::new(PatchAction::RolledBack, "pkg:npm/a@1.0.0") + .with_uuid(A) + .with_details(serde_json::json!({ "path": "node_modules/a" })), + ]; + let outcomes = patch_outcomes_of(&events, MODE_AGENT); + // One patch, three modes: three entries, each its own. + assert_eq!( + outcomes, + [ + entry(A, "npm", MODE_VENDORED, "rolled_back", None), + entry(A, "npm", MODE_HOSTED, "rolled_back", None), + entry(A, "npm", MODE_AGENT, "rolled_back", None), + ] + ); + } + + /// One patch installed in several places is one entry, and the event + /// that says most about it wins: a failed copy over the restored ones, + /// a restored copy over one that had nothing to do. + #[test] + fn the_events_of_one_patch_fold_into_the_one_that_says_most() { + let copy = |action| PatchEvent::new(action, "pkg:npm/a@1.0.0").with_uuid(A); + let events = [ + copy(PatchAction::Skipped).with_reason("already_original", "nothing to restore"), + copy(PatchAction::RolledBack), + copy(PatchAction::RolledBack), + PatchEvent::new(PatchAction::Verified, "pkg:npm/b@1.0.0").with_uuid(B), + PatchEvent::new(PatchAction::Failed, "pkg:npm/b@1.0.0") + .with_uuid(B) + .with_error("hash_mismatch", "the file changed"), + PatchEvent::new(PatchAction::RolledBack, "pkg:npm/b@1.0.0").with_uuid(B), + ]; + assert_eq!( + patch_outcomes_of(&events, MODE_AGENT), + [ + entry(A, "npm", MODE_AGENT, "rolled_back", None), + entry(B, "npm", MODE_AGENT, OUTCOME_FAILED, Some("hash_mismatch")), + ] + ); + } + + #[test] + fn a_skip_keeps_its_code_and_a_change_has_none() { + let events = [ + PatchEvent::new(PatchAction::Skipped, "pkg:gem/a@1.0.0") + .with_uuid(A) + .with_reason("package_not_installed", "no installed copy"), + // A change that carries a code (an advisory) reports none. + PatchEvent::new(PatchAction::Applied, "pkg:gem/b@1.0.0") + .with_uuid(B) + .with_reason("gem_extension_not_rebuilt", "rebuild it"), + ]; + assert_eq!( + patch_outcomes_of(&events, MODE_AGENT), + [ + entry( + A, + "gem", + MODE_AGENT, + "skipped", + Some("package_not_installed") + ), + entry(B, "gem", MODE_AGENT, "applied", None), + ] + ); + } + + #[test] + fn discovered_events_are_not_outcomes() { + let events = [PatchEvent::new(PatchAction::Discovered, "pkg:npm/a@1.0.0").with_uuid(A)]; + assert!(patch_outcomes_of(&events, MODE_AGENT).is_empty()); + } + + #[test] + fn uniform_outcomes_name_each_patch_once() { + let outcomes = uniform_outcomes( + [ + ("pkg:pypi/a@1.0.0?artifact_id=x", A), + ("pkg:pypi/a@1.0.0?artifact_id=y", A), + ("pkg:cargo/b@1.0.0", B), + ], + MODE_AGENT, + OUTCOME_FAILED, + Some("rollback_failed"), + ); + assert_eq!( + outcomes, + [ + entry( + A, + "pypi", + MODE_AGENT, + OUTCOME_FAILED, + Some("rollback_failed") + ), + entry( + B, + "cargo", + MODE_AGENT, + OUTCOME_FAILED, + Some("rollback_failed") + ), + ] + ); + } + + #[test] + fn a_purl_is_looked_up_across_its_qualifiers_when_that_is_unambiguous() { + let uuids: HashMap = [ + ("pkg:npm/a@1.0.0", A), + ("pkg:pypi/b@1.0.0?artifact_id=wheel", B), + ("pkg:gem/c@1.0.0?platform=x86_64-linux", A), + ("pkg:gem/c@1.0.0?platform=arm64-darwin", B), + ] + .into_iter() + .map(|(purl, uuid)| (purl.to_string(), uuid.to_string())) + .collect(); + let lookup = uuid_lookup(&uuids); + assert_eq!(lookup("pkg:npm/a@1.0.0").as_deref(), Some(A)); + // The base purl of one qualified record, and another qualifier of it. + assert_eq!(lookup("pkg:pypi/b@1.0.0").as_deref(), Some(B)); + assert_eq!( + lookup("pkg:pypi/b@1.0.0?artifact_id=sdist").as_deref(), + Some(B) + ); + // Two releases with different patches: the base purl names neither. + assert_eq!(lookup("pkg:gem/c@1.0.0"), None); + assert_eq!( + lookup("pkg:gem/c@1.0.0?platform=arm64-darwin").as_deref(), + Some(B) + ); + assert_eq!(lookup("pkg:npm/unknown@1.0.0"), None); + } + + /// Events spell an ecosystem the way `scan` reports it, so the two + /// join: the CLI name, which is not always the purl's type. + #[test] + fn the_ecosystem_is_the_cli_name() { + use socket_patch_core::crawlers::Ecosystem; + assert_eq!(ecosystem_of("pkg:golang/example.com/m@v1.0.0"), "golang"); + for purl in [ + "pkg:npm/a@1.0.0", + "pkg:jsr/@std/path@1.0.0", + "pkg:gem/a@1.0.0", + ] { + let ecosystem = Ecosystem::from_purl(purl).expect("a known ecosystem"); + assert_eq!(ecosystem_of(purl), ecosystem.cli_name(), "{purl}"); + } + // No ecosystem of this CLI: the purl's own type. Not a purl: none. + assert_eq!(ecosystem_of("pkg:hex/phoenix@1.7.0"), "hex"); + assert_eq!(ecosystem_of("not-a-purl"), ""); + } + + #[test] + fn with_more_adds_only_the_patches_not_already_named() { + let have = vec![entry(A, "npm", MODE_VENDORED, "applied", None)]; + let more = [ + // Already named in this mode: the outcome on record stands. + entry(A, "npm", MODE_VENDORED, OUTCOME_FAILED, Some("x")), + entry( + B, + "npm", + MODE_VENDORED, + OUTCOME_FAILED, + Some("download_failed"), + ), + ]; + assert_eq!( + with_more(have, &more), + [ + entry(A, "npm", MODE_VENDORED, "applied", None), + entry( + B, + "npm", + MODE_VENDORED, + OUTCOME_FAILED, + Some("download_failed") + ), + ] + ); + } +} diff --git a/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs b/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs index 34ec214dd..f2b04fbaa 100644 --- a/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs +++ b/crates/socket-patch-cli/tests/cli/telemetry_e2e.rs @@ -56,6 +56,23 @@ fn run_cmd( ) } +/// [`run_cmd`] without `--json`: the output a person gets. +fn run_human( + cwd: &Path, + api_url: &str, + subcommand: &str, + extra_args: &[&str], +) -> (i32, String, String) { + let out = build_cmd_as(cwd, api_url, subcommand, false, extra_args, &[]) + .output() + .expect("run socket-patch"); + ( + out.status.code().unwrap_or(-1), + String::from_utf8_lossy(&out.stdout).to_string(), + String::from_utf8_lossy(&out.stderr).to_string(), + ) +} + /// The [`run_cmd`] invocation, unstarted (for tests that wire its stdio). fn build_cmd( cwd: &Path, @@ -64,16 +81,30 @@ fn build_cmd( extra_args: &[&str], extra_env: &[(&str, &str)], ) -> Command { - let mut args = vec![ - subcommand, - "--json", + build_cmd_as(cwd, api_url, subcommand, true, extra_args, extra_env) +} + +/// [`build_cmd`], with `--json` or without. +fn build_cmd_as( + cwd: &Path, + api_url: &str, + subcommand: &str, + json: bool, + extra_args: &[&str], + extra_env: &[(&str, &str)], +) -> Command { + let mut args = vec![subcommand]; + if json { + args.push("--json"); + } + args.extend_from_slice(&[ "--api-url", api_url, "--api-token", "fake-token-for-test", "--org", ORG_SLUG, - ]; + ]); args.extend_from_slice(extra_args); // The binary binds a wide `SOCKET_*` env surface; an ambient value // silently changes what these tests exercise — SOCKET_ECOSYSTEMS=cargo @@ -359,6 +390,33 @@ async fn get_emits_patch_fetched_telemetry_on_uuid_lookup_success() { ); } +/// A `get` for a patch that does not exist reports the failure with the +/// code its `--json` output carries, like every other failure event. +#[tokio::test] +async fn get_of_an_unknown_patch_reports_not_found() { + const UUID: &str = "12345678-1234-4123-8123-123456789abc"; + // No view endpoint is mounted: the lookup is a 404. + let mock = setup_mock( + serde_json::json!({ "packages": [], "canAccessPaidPatches": false }), + None, + ) + .await; + let tmp = tempfile::tempdir().expect("tempdir"); + write_root_package_json(tmp.path()); + + let (_code, stdout, stderr) = run_cmd(tmp.path(), &mock.uri(), "get", &["--id", UUID], &[]); + let bodies = telemetry_bodies(&mock).await; + assert_eq!( + bodies.len(), + 1, + "stdout:\n{stdout}\nstderr:\n{stderr}\n{bodies:#?}" + ); + let failed = &bodies[0]; + assert_eq!(failed["event_type"], "patch_fetch_failed"); + assert_eq!(failed["metadata"]["error_code"], "not_found"); + assert_eq!(failed["metadata"]["uuid"], UUID); +} + #[tokio::test] async fn get_skips_telemetry_in_airgap_mode() { const UUID: &str = "deadbeef-dead-4eef-8eef-deadbeefdead"; @@ -991,6 +1049,16 @@ async fn hosted_scan_reports_patch_applied_with_hosted_mode() { let applied = &bodies[1]; assert_eq!(applied["context"]["command"], "scan"); assert_eq!(applied["metadata"]["mode"], "hosted"); + // The pin is named: by patch UUID, never by package. + assert_eq!( + only_patch(applied), + &serde_json::json!({ + "uuid": HOSTED_UUID, + "ecosystem": "npm", + "mode": "hosted", + "outcome": "applied", + }) + ); // v5.0 records each confirmed pin as an `applied` event tagged // `details.mode: "hosted"` (v4's `redirect.redirected` count). let hosted_applied = doc["events"] @@ -1088,6 +1156,24 @@ async fn scan_reports_requested_and_project_modes() { env!("CARGO_PKG_VERSION"), "every event carries the client version" ); + // Where the binary under test sits decides the channel (a build + // directory no package manager owns is `standalone`), so only the + // shape is pinned here: one of the six ids, never a path. + let channel = scanned["context"]["channel"] + .as_str() + .expect("every event says how the binary was installed"); + assert!( + [ + "standalone", + "npm", + "pypi", + "cargo", + "launcher_cache", + "homebrew" + ] + .contains(&channel), + "unexpected channel id {channel}" + ); } /// A hosted run that fails after selecting patches reports @@ -1115,6 +1201,43 @@ async fn hosted_scan_failure_reports_patch_apply_failed() { assert_eq!(failed["context"]["command"], "scan"); assert_eq!(failed["metadata"]["mode"], "hosted"); assert_eq!(failed["error"]["type"], "Error"); + // The event carries the code the `--json` envelope reports, and names + // the patch the run could not pin. + let doc: serde_json::Value = serde_json::from_str(&stdout).expect("JSON envelope"); + assert_eq!( + failed["metadata"]["error_code"], doc["error"]["code"], + "{failed:#}\n{doc:#}" + ); + assert_eq!( + only_patch(failed), + &serde_json::json!({ + "uuid": HOSTED_UUID, + "ecosystem": "npm", + "mode": "hosted", + "outcome": "failed", + "code": doc["error"]["code"], + }) + ); +} + +/// The failure event's code does not depend on `--json`: a human run +/// reports the same one. +#[tokio::test] +async fn a_hosted_failure_is_coded_the_same_without_json() { + let mock = setup_hosted_mock(500).await; + let tmp = tempfile::tempdir().expect("tempdir"); + write_hosted_npm_project(tmp.path()); + + let (code, stdout, stderr) = run_human(tmp.path(), &mock.uri(), "scan", &["--yes"]); + assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}"); + + let bodies = telemetry_bodies(&mock).await; + let failed = bodies + .iter() + .find(|b| b["event_type"] == "patch_apply_failed") + .unwrap_or_else(|| panic!("a patch_apply_failed event: {bodies:#?}")); + assert_eq!(failed["metadata"]["error_code"], "reference_resolve_failed"); + assert_eq!(only_patch(failed)["uuid"], HOSTED_UUID); } /// `get --mode hosted` reports through the same path, under its own @@ -1149,6 +1272,401 @@ async fn hosted_get_reports_patch_applied_under_get() { // Telemetry never holds a command back // --------------------------------------------------------------------------- +// --------------------------------------------------------------------------- +// per-patch outcomes: apply / rollback / remove / agent-mode downloads +// --------------------------------------------------------------------------- + +const PATCHED_PURL: &str = "pkg:npm/tpkg@1.0.0"; +const PATCHED_UUID: &str = "aaaaaaaa-1111-4111-8111-aaaaaaaaaaaa"; +const ORIGINAL: &[u8] = b"module.exports = 'original';\n"; +const PATCHED: &[u8] = b"module.exports = 'patched';\n"; + +/// An agent-mode npm project with one patch recorded for `tpkg` +/// (manifest record and both blobs) and the installed file holding +/// `installed`. Returns the installed file's path. +fn write_agent_project(root: &Path, installed: &[u8]) -> std::path::PathBuf { + write_root_package_json(root); + write_npm_package(root, "tpkg", "1.0.0"); + let file = root.join("node_modules/tpkg/index.js"); + std::fs::write(&file, installed).unwrap(); + crate::common::write_in_place_patch_record( + &root.join(".socket"), + PATCHED_PURL, + PATCHED_UUID, + "package/index.js", + ORIGINAL, + PATCHED, + ); + file +} + +/// A mock that only records telemetry: the runs below need no patch API. +async fn telemetry_only_mock() -> MockServer { + setup_mock( + serde_json::json!({ "packages": [], "canAccessPaidPatches": false }), + None, + ) + .await +} + +/// The one patch entry an event names, asserting it is the only one. +fn only_patch(event: &serde_json::Value) -> &serde_json::Value { + let patches = event["metadata"]["patches"] + .as_array() + .unwrap_or_else(|| panic!("the event names its patches: {event:#}")); + assert_eq!(patches.len(), 1, "{event:#}"); + &patches[0] +} + +/// `apply` names the patches it acted on: the patch UUID with its +/// ecosystem, mode and outcome. A second run, with nothing left to do, +/// reports the same patch as skipped and applies none. +#[tokio::test] +async fn apply_reports_the_patches_it_applied() { + let mock = telemetry_only_mock().await; + let tmp = tempfile::tempdir().expect("tempdir"); + let file = write_agent_project(tmp.path(), ORIGINAL); + + let (code, stdout, stderr) = run_cmd(tmp.path(), &mock.uri(), "apply", &[], &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&file).unwrap(), PATCHED); + let (code, stdout, stderr) = run_cmd(tmp.path(), &mock.uri(), "apply", &[], &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + + let bodies = telemetry_bodies(&mock).await; + let types: Vec<&str> = bodies + .iter() + .map(|b| b["event_type"].as_str().unwrap()) + .collect(); + assert_eq!(types, ["patch_applied", "patch_applied"], "{bodies:#?}"); + + let applied = &bodies[0]; + assert_eq!(applied["context"]["command"], "apply"); + assert_eq!(applied["metadata"]["mode"], "agent"); + assert_eq!(applied["metadata"]["dry_run"], false); + assert_eq!(applied["metadata"]["patches_count"], 1); + assert_eq!( + only_patch(applied), + &serde_json::json!({ + "uuid": PATCHED_UUID, + "ecosystem": "npm", + "mode": "agent", + "outcome": "applied", + }) + ); + assert_eq!( + applied["metadata"]["outcomes"], + serde_json::json!({ "applied": 1 }) + ); + // No package name anywhere in the event. + assert!(!applied.to_string().contains("tpkg"), "{applied:#}"); + + let again = &bodies[1]; + assert_eq!(again["metadata"]["patches_count"], 0); + assert_eq!(only_patch(again)["outcome"], "skipped"); + assert_eq!(only_patch(again)["code"], "already_patched"); +} + +/// A rollback names the patch it rolled back, and says whether the user +/// asked for that patch or rolled the whole project back. +#[tokio::test] +async fn rollback_reports_the_patches_it_rolled_back() { + let mock = telemetry_only_mock().await; + let tmp = tempfile::tempdir().expect("tempdir"); + let file = write_agent_project(tmp.path(), PATCHED); + + let (code, stdout, stderr) = run_cmd(tmp.path(), &mock.uri(), "rollback", &[], &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&file).unwrap(), ORIGINAL); + + let bodies = telemetry_bodies(&mock).await; + assert_eq!(bodies.len(), 1, "{bodies:#?}"); + let event = &bodies[0]; + assert_eq!(event["event_type"], "patch_rolled_back"); + assert_eq!(event["context"]["command"], "rollback"); + assert_eq!( + event["metadata"], + serde_json::json!({ + "rolled_back_count": 1, + "dry_run": false, + "targeted": false, + "patches": [{ + "uuid": PATCHED_UUID, + "ecosystem": "npm", + "mode": "agent", + "outcome": "rolled_back", + }], + "outcomes": { "rolled_back": 1 }, + "ecosystems": ["npm"], + "modes": ["agent"], + }) + ); + // The envelope's count and the event's agree. + let doc: serde_json::Value = serde_json::from_str(&stdout).expect("JSON envelope"); + assert_eq!(doc["summary"]["rolledBack"], 1, "{doc:#}"); + assert!(!event.to_string().contains("tpkg"), "{event:#}"); +} + +/// A rollback of a named patch is `targeted`; a dry run is flagged, and +/// its patch is `verified` (restorable), not rolled back. +#[tokio::test] +async fn a_targeted_dry_run_rollback_is_flagged_as_both() { + let mock = telemetry_only_mock().await; + let tmp = tempfile::tempdir().expect("tempdir"); + let file = write_agent_project(tmp.path(), PATCHED); + + let (code, stdout, stderr) = run_cmd( + tmp.path(), + &mock.uri(), + "rollback", + &[PATCHED_PURL, "--dry-run"], + &[], + ); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(&file).unwrap(), + PATCHED, + "a dry run restores nothing" + ); + + let bodies = telemetry_bodies(&mock).await; + assert_eq!(bodies.len(), 1, "{bodies:#?}"); + let event = &bodies[0]; + assert_eq!(event["event_type"], "patch_rolled_back"); + assert_eq!(event["metadata"]["dry_run"], true); + assert_eq!(event["metadata"]["targeted"], true); + assert_eq!(only_patch(event)["uuid"], PATCHED_UUID); + assert_eq!(only_patch(event)["outcome"], "verified"); +} + +/// A rollback whose target matches nothing is a failure of the command, +/// not of a patch: the event carries the run's error code and names none. +#[tokio::test] +async fn a_rollback_that_matches_nothing_reports_its_error_code() { + let mock = telemetry_only_mock().await; + let tmp = tempfile::tempdir().expect("tempdir"); + write_agent_project(tmp.path(), PATCHED); + + let (code, stdout, stderr) = run_cmd( + tmp.path(), + &mock.uri(), + "rollback", + &["pkg:npm/not-patched@9.9.9"], + &[], + ); + assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}"); + + let bodies = telemetry_bodies(&mock).await; + assert_eq!(bodies.len(), 1, "{bodies:#?}"); + let event = &bodies[0]; + assert_eq!(event["event_type"], "patch_rollback_failed"); + assert_eq!(event["metadata"]["error_code"], "patch_not_found"); + assert_eq!(event["metadata"]["targeted"], true); + assert_eq!(event["metadata"]["rolled_back_count"], 0); + assert!(event["metadata"].get("patches").is_none(), "{event:#}"); + // The envelope reports the same code. + let doc: serde_json::Value = serde_json::from_str(&stdout).expect("JSON envelope"); + assert_eq!(doc["error"]["code"], "patch_not_found", "{doc:#}"); +} + +/// `remove` names the patch it took out. One event per run: a removal +/// that happened is never also reported as a failure. +#[tokio::test] +async fn remove_reports_the_patch_it_removed() { + let mock = telemetry_only_mock().await; + let tmp = tempfile::tempdir().expect("tempdir"); + let file = write_agent_project(tmp.path(), PATCHED); + + let (code, stdout, stderr) = run_cmd(tmp.path(), &mock.uri(), "remove", &[PATCHED_PURL], &[]); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&file).unwrap(), ORIGINAL); + + let bodies = telemetry_bodies(&mock).await; + assert_eq!(bodies.len(), 1, "{bodies:#?}"); + let event = &bodies[0]; + assert_eq!(event["event_type"], "patch_removed"); + assert_eq!(event["context"]["command"], "remove"); + assert_eq!( + event["metadata"], + serde_json::json!({ + "removed_count": 1, + "patches": [{ + "uuid": PATCHED_UUID, + "ecosystem": "npm", + "mode": "agent", + "outcome": "removed", + }], + "outcomes": { "removed": 1 }, + "ecosystems": ["npm"], + "modes": ["agent"], + }) + ); +} + +/// A `remove --dry-run` changes nothing and reports nothing; a `remove` +/// of something that is not patched reports the failure with its code. +#[tokio::test] +async fn remove_reports_no_dry_run_and_codes_its_failures() { + let mock = telemetry_only_mock().await; + let tmp = tempfile::tempdir().expect("tempdir"); + let file = write_agent_project(tmp.path(), PATCHED); + + let (code, stdout, stderr) = run_cmd( + tmp.path(), + &mock.uri(), + "remove", + &[PATCHED_PURL, "--dry-run"], + &[], + ); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!(std::fs::read(&file).unwrap(), PATCHED); + assert!( + telemetry_bodies(&mock).await.is_empty(), + "a dry-run remove reports nothing" + ); + + let (code, stdout, stderr) = run_cmd( + tmp.path(), + &mock.uri(), + "remove", + &["pkg:npm/not-patched@9.9.9"], + &[], + ); + assert_eq!(code, 1, "stdout:\n{stdout}\nstderr:\n{stderr}"); + let bodies = telemetry_bodies(&mock).await; + assert_eq!(bodies.len(), 1, "{bodies:#?}"); + assert_eq!(bodies[0]["event_type"], "patch_remove_failed"); + assert_eq!(bodies[0]["metadata"]["error_code"], "not_found"); + assert!(bodies[0]["metadata"].get("patches").is_none()); +} + +/// An agent-mode `scan` downloads the patch records it selects and +/// applies them. Both steps report, under the command the user ran, and +/// name the patch: the download as `patch_fetched` (it was counted only +/// for `get ` before), the apply as `patch_applied`. +#[tokio::test] +async fn an_agent_mode_scan_reports_its_downloads_and_its_applies() { + const PURL: &str = "pkg:npm/lodash@4.17.20"; + const UUID: &str = "12345678-1234-4123-8123-123456789abc"; + let batch = serde_json::json!({ + "packages": [{ + "purl": PURL, + "patches": [{ + "uuid": UUID, "purl": PURL, "tier": "free", + "cveIds": [], "ghsaIds": [], "severity": "high", + "title": "telemetry agent fixture" + }] + }], + "canAccessPaidPatches": false, + }); + // A new-file patch: afterHash is the git-blob sha256 of "patched\n". + let view = serde_json::json!({ + "uuid": UUID, + "purl": PURL, + "tier": "free", + "publishedAt": "2024-06-01T00:00:00Z", + "license": "MIT", + "description": "test patch", + "files": { + "package/index.js": { + "afterHash": "d2802877eb1c2f442d30d18abcb281cb2830875571624544f2f1acb36480997e", + "blobContent": "cGF0Y2hlZAo=", + } + }, + "vulnerabilities": {}, + }); + // With `--json` and without: the two take different paths through the + // download engine, and both report under `scan`. + for json in [true, false] { + let mock = setup_mock(batch.clone(), Some(view.clone())).await; + // The detail query the selection runs for each package the batch + // found a patch for. + Mock::given(method("GET")) + .and(wiremock::matchers::path_regex(format!( + "^/v0/orgs/{ORG_SLUG}/patches/by-package/.+$" + ))) + .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ + "patches": [{ + "uuid": UUID, "purl": PURL, + "publishedAt": "2024-06-01T00:00:00Z", + "description": "test patch", "license": "MIT", "tier": "free", + "vulnerabilities": {} + }], + "canAccessPaidPatches": false, + }))) + .mount(&mock) + .await; + let tmp = tempfile::tempdir().expect("tempdir"); + write_root_package_json(tmp.path()); + write_npm_package(tmp.path(), "lodash", "4.17.20"); + + let flags = ["--mode", "agent", "--yes"]; + let (code, stdout, stderr) = if json { + run_cmd(tmp.path(), &mock.uri(), "scan", &flags, &[]) + } else { + run_human(tmp.path(), &mock.uri(), "scan", &flags) + }; + assert_eq!(code, 0, "json={json}\nstdout:\n{stdout}\nstderr:\n{stderr}"); + assert_eq!( + std::fs::read(tmp.path().join("node_modules/lodash/index.js")).ok(), + Some(b"patched\n".to_vec()), + "json={json}\nstdout:\n{stdout}\nstderr:\n{stderr}" + ); + + let bodies = telemetry_bodies(&mock).await; + let types: Vec<&str> = bodies + .iter() + .map(|b| b["event_type"].as_str().unwrap()) + .collect(); + assert_eq!( + types, + ["patch_scanned", "patch_fetched", "patch_applied"], + "json={json}: {bodies:#?}" + ); + + let scanned = &bodies[0]; + assert_eq!(scanned["metadata"]["mode"], "agent"); + assert_eq!(scanned["metadata"]["dry_run"], false); + assert_eq!(scanned["metadata"]["packages_scanned"], 1); + assert_eq!( + scanned["metadata"]["packages_by_ecosystem"], + serde_json::json!({ "npm": 1 }) + ); + assert_eq!( + scanned["metadata"]["patches_by_ecosystem"], + serde_json::json!({ "npm": 1 }) + ); + + let fetched = &bodies[1]; + assert_eq!(fetched["context"]["command"], "scan", "json={json}"); + assert_eq!(fetched["metadata"]["mode"], "agent"); + assert_eq!(fetched["metadata"]["patches_count"], 1); + assert_eq!( + only_patch(fetched), + &serde_json::json!({ + "uuid": UUID, + "ecosystem": "npm", + "mode": "agent", + "outcome": "downloaded", + }) + ); + + let applied = &bodies[2]; + assert_eq!(applied["context"]["command"], "scan", "json={json}"); + assert_eq!(applied["metadata"]["mode"], "agent"); + assert_eq!(applied["metadata"]["patches_count"], 1); + assert_eq!(only_patch(applied)["uuid"], UUID); + assert_eq!(only_patch(applied)["outcome"], "applied"); + + // One run, one session: the three events are linked. + let sessions: std::collections::HashSet<&str> = bodies + .iter() + .map(|b| b["session_id"].as_str().unwrap()) + .collect(); + assert_eq!(sessions.len(), 1); + } +} + /// A telemetry endpoint the test answers by hand. It accepts one /// connection and reads one request, whose JSON body arrives on /// `received`; the `201` goes out only when the test sends on `answer`. diff --git a/crates/socket-patch-cli/tests/cli_parse_remove.rs b/crates/socket-patch-cli/tests/cli_parse_remove.rs index b836d922d..acd4f44cf 100644 --- a/crates/socket-patch-cli/tests/cli_parse_remove.rs +++ b/crates/socket-patch-cli/tests/cli_parse_remove.rs @@ -268,8 +268,13 @@ async fn run_removes_matching_patch_and_exits_zero() { manifest_path: "manifest.json".to_string(), yes: true, json: true, - // Keep the test fully offline: no telemetry network call. - offline: true, + // No telemetry network call. Not `offline: true`: `run()` + // mirrors its flags into the process environment, and a + // `SOCKET_OFFLINE` set there is read by the parse tests of this + // binary that run beside it (they expect the forced + // `SOCKET_TELEMETRY_DISABLED`, see `opt_out_defaults`). Nothing + // in this run reaches the network: the package is not installed, + // so no blob is fetched. no_telemetry: true, ..socket_patch_cli::args::GlobalArgs::default() }, diff --git a/crates/socket-patch-cli/tests/scan_vendor_e2e.rs b/crates/socket-patch-cli/tests/scan_vendor_e2e.rs index a0f158e01..2e77147b1 100644 --- a/crates/socket-patch-cli/tests/scan_vendor_e2e.rs +++ b/crates/socket-patch-cli/tests/scan_vendor_e2e.rs @@ -684,11 +684,10 @@ async fn scan_vendor_dry_run_previews_without_touching_disk() { /// recorded the error only in their JSON report, so the human path exited /// non-zero with no error output at all (the JSON report is discarded and /// the vendor engine just says "No vendorable patches in scope"). -#[tokio::test] -async fn scan_vendor_fetch_failure_reports_error() { - let mock = MockServer::start().await; - // Discovery succeeds (batch + per-package search, same shapes as - // `mount_patch_api`), but the view fetch fails. +/// A patch API whose discovery succeeds (batch + per-package search, same +/// shapes as `mount_patch_api`) and whose view fetch fails: the selected +/// patch cannot be downloaded. +async fn mount_patch_api_with_failing_view(mock: &MockServer) { Mock::given(method("POST")) .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/batch"))) .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ @@ -706,7 +705,7 @@ async fn scan_vendor_fetch_failure_reports_error() { }], "canAccessPaidPatches": false, }))) - .mount(&mock) + .mount(mock) .await; Mock::given(method("GET")) .and(path(format!( @@ -724,13 +723,19 @@ async fn scan_vendor_fetch_failure_reports_error() { }], "canAccessPaidPatches": false, }))) - .mount(&mock) + .mount(mock) .await; Mock::given(method("GET")) .and(path(format!("/v0/orgs/{ORG_SLUG}/patches/view/{UUID}"))) .respond_with(ResponseTemplate::new(500)) - .mount(&mock) + .mount(mock) .await; +} + +#[tokio::test] +async fn scan_vendor_fetch_failure_reports_error() { + let mock = MockServer::start().await; + mount_patch_api_with_failing_view(&mock).await; let tmp = tempfile::tempdir().unwrap(); write_fixture(tmp.path()); @@ -869,6 +874,190 @@ async fn scan_vendor_emits_no_telemetry_even_with_endpoint_env() { const SCOPED_CRAWLER_PURL: &str = "pkg:npm/@scope/left-pad@1.3.0"; const SCOPED_API_PURL: &str = "pkg:npm/%40scope/left-pad@1.3.0"; +/// Every telemetry event the mock received (either arm), in firing order. +async fn telemetry_events(mock: &MockServer) -> Vec { + let mut events: Vec = mock + .received_requests() + .await + .unwrap() + .iter() + .filter(|r| r.url.path().ends_with("/telemetry")) + .map(|r| serde_json::from_slice(&r.body).expect("telemetry body is JSON")) + .collect(); + events.sort_by_key(|e| e["event_sender_created_at"].as_str().unwrap().to_string()); + events +} + +/// A vendored scan whose download fails vendors nothing, and its failure +/// event names the patch it could not get. The vendor step works from the +/// records that did download, so without the download phase's failures +/// the event named no patch at all. +#[tokio::test] +async fn scan_vendor_download_failure_names_the_patch() { + let mock = MockServer::start().await; + mount_patch_api_with_failing_view(&mock).await; + for telemetry in [ + format!("/v0/orgs/{ORG_SLUG}/telemetry"), + "/patch/telemetry".to_string(), + ] { + Mock::given(method("POST")) + .and(path(telemetry)) + .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({}))) + .mount(&mock) + .await; + } + let tmp = tempfile::tempdir().unwrap(); + write_fixture(tmp.path()); + let mock_uri = mock.uri(); + + for json in [true, false] { + let mut argv = vec!["scan", "--mode", "vendored", "--yes"]; + if json { + argv.push("--json"); + } + argv.extend_from_slice(&[ + "--api-url", + mock_uri.as_str(), + "--api-token", + "fake-token", + "--org", + ORG_SLUG, + ]); + let before = telemetry_events(&mock).await.len(); + let (code, stdout, stderr) = run_cli_env( + tmp.path(), + &argv, + &[ + ("SOCKET_TELEMETRY_DISABLED", "0"), + ("SOCKET_API_URL", mock_uri.as_str()), + ("SOCKET_PROXY_URL", mock_uri.as_str()), + ], + ); + assert_eq!(code, 1, "json={json}; stdout={stdout}; stderr={stderr}"); + + let events = telemetry_events(&mock).await; + let failed: Vec<&serde_json::Value> = events[before..] + .iter() + .filter(|e| e["event_type"] == "patch_vendor_failed") + .collect(); + assert_eq!(failed.len(), 1, "json={json}: {events:#?}"); + let failed = failed[0]; + assert_eq!(failed["context"]["command"], "scan"); + assert_eq!(failed["metadata"]["mode"], "vendored"); + assert_eq!(failed["metadata"]["patches_count"], 0); + assert_eq!( + failed["metadata"]["outcomes"], + serde_json::json!({ "failed": 1 }) + ); + let patches = failed["metadata"]["patches"].as_array().unwrap(); + assert_eq!(patches.len(), 1, "json={json}: {failed:#}"); + assert_eq!(patches[0]["uuid"], UUID); + assert_eq!(patches[0]["mode"], "vendored"); + assert_eq!(patches[0]["outcome"], "failed"); + assert!( + patches[0]["code"] + .as_str() + .is_some_and(|code| !code.is_empty()), + "the failed download carries its code: {failed:#}" + ); + // Nothing was vendored, so nothing reports as vendored. + assert!( + !events[before..] + .iter() + .any(|e| e["event_type"] == "patch_vendored"), + "json={json}: {events:#?}" + ); + } +} + +/// With telemetry on, a vendored scan reports the vendoring under the +/// command the user ran, tagged `mode: "vendored"`, and names the patch by +/// UUID. `vendor --revert`, which takes every vendored patch back out and +/// used to report nothing, reports each as removed. +#[tokio::test] +async fn scan_vendor_and_revert_report_their_patches() { + let mock = MockServer::start().await; + mount_patch_api(&mock, UUID).await; + for telemetry in [ + format!("/v0/orgs/{ORG_SLUG}/telemetry"), + "/patch/telemetry".to_string(), + ] { + Mock::given(method("POST")) + .and(path(telemetry)) + .respond_with(ResponseTemplate::new(201).set_body_json(serde_json::json!({}))) + .mount(&mock) + .await; + } + let tmp = tempfile::tempdir().unwrap(); + write_fixture(tmp.path()); + let mock_uri = mock.uri(); + // The suite's opt-in (see `hermetic_command`), aimed at the mock. + let telemetry_on = [ + ("SOCKET_TELEMETRY_DISABLED", "0"), + ("SOCKET_API_URL", mock_uri.as_str()), + ("SOCKET_PROXY_URL", mock_uri.as_str()), + ]; + let auth = [ + "--api-url", + mock_uri.as_str(), + "--api-token", + "fake-token", + "--org", + ORG_SLUG, + ]; + + let mut scan = vec!["scan", "--json", "--mode", "vendored", "--yes"]; + scan.extend_from_slice(&auth); + let (code, stdout, stderr) = run_cli_env(tmp.path(), &scan, &telemetry_on); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + + let events = telemetry_events(&mock).await; + let vendored: Vec<&serde_json::Value> = events + .iter() + .filter(|e| e["event_type"] == "patch_vendored") + .collect(); + assert_eq!(vendored.len(), 1, "{events:#?}"); + let vendored = vendored[0]; + assert_eq!(vendored["context"]["command"], "scan"); + assert_eq!(vendored["metadata"]["mode"], "vendored"); + assert_eq!(vendored["metadata"]["dry_run"], false); + assert_eq!(vendored["metadata"]["patches_count"], 1); + assert_eq!( + vendored["metadata"]["patches"], + serde_json::json!([{ + "uuid": UUID, + "ecosystem": "npm", + "mode": "vendored", + "outcome": "applied", + }]) + ); + // By patch UUID only: the package is not named. + assert!(!vendored.to_string().contains("left-pad"), "{vendored:#}"); + let sent = events.len(); + + let mut revert = vec!["vendor", "--revert", "--json", "--yes"]; + revert.extend_from_slice(&auth); + let (code, stdout, stderr) = run_cli_env(tmp.path(), &revert, &telemetry_on); + assert_eq!(code, 0, "stdout={stdout}; stderr={stderr}"); + + let events = telemetry_events(&mock).await; + let reverted = &events[sent..]; + assert_eq!(reverted.len(), 1, "{reverted:#?}"); + let removed = &reverted[0]; + assert_eq!(removed["event_type"], "patch_removed"); + assert_eq!(removed["context"]["command"], "vendor"); + assert_eq!(removed["metadata"]["removed_count"], 1); + assert_eq!( + removed["metadata"]["patches"], + serde_json::json!([{ + "uuid": UUID, + "ecosystem": "npm", + "mode": "vendored", + "outcome": "removed", + }]) + ); +} + /// Like `write_fixture`, but the installed package is the SCOPED /// `@scope/left-pad` (the crawler reports the literal `@scope` form). fn write_scoped_fixture(root: &Path) { diff --git a/crates/socket-patch-cli/tests/update/self_update_telemetry_e2e.rs b/crates/socket-patch-cli/tests/update/self_update_telemetry_e2e.rs index 350d28c65..8f0f23cf4 100644 --- a/crates/socket-patch-cli/tests/update/self_update_telemetry_e2e.rs +++ b/crates/socket-patch-cli/tests/update/self_update_telemetry_e2e.rs @@ -8,7 +8,9 @@ use crate::update_fixture; -use update_fixture::{make_served_binary, run_installed, staged_install, FakeReleaseBuilder}; +use update_fixture::{ + make_served_binary, run_installed, staged_install, staged_install_at, FakeReleaseBuilder, +}; use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -75,10 +77,48 @@ async fn successful_update_reports_cli_updated() { assert_eq!(event["metadata"]["forced"], true); assert_eq!(event["metadata"]["pinned"], false); assert!(event.get("error").is_none()); + // The event is built after the swap. On Linux the path of the binary + // that ran reads as deleted by then, so its channel is worked out + // before the swap. + assert_eq!( + event["context"]["channel"], "standalone", + "the event still says how the binary that ran was installed" + ); release.verify_request_hygiene().await; } +/// A binary an npm package bundles reports `npm` as its channel in the +/// context of every event: here the one a forced update sends. +#[tokio::test] +async fn a_binary_inside_node_modules_reports_the_npm_channel() { + let install = staged_install_at("lib/node_modules/@socketsecurity/socket-patch-x/bin"); + let (served, _) = make_served_binary(); + let release = FakeReleaseBuilder::new(CURRENT) + .asset_for_current_target(&served) + .mount() + .await; + let telemetry = telemetry_mock().await; + + let (code, stdout, stderr) = run_installed( + &install, + &["--update", "--force", "--yes"], + &[ + ("SOCKET_UPDATE_BASE_URL", &release.base_url), + ("SOCKET_PROXY_URL", &telemetry.uri()), + ("SOCKET_TELEMETRY_DISABLED", "0"), + ], + ); + assert_eq!(code, 0, "stdout:\n{stdout}\nstderr:\n{stderr}"); + + let events = telemetry_events(&telemetry).await; + assert_eq!(events.len(), 1, "exactly one event: {events:#?}"); + let event = &events[0]; + assert_eq!(event["event_type"], "cli_updated"); + assert_eq!(event["context"]["channel"], "npm"); + assert_eq!(event["metadata"]["channel"], "npm"); +} + #[tokio::test] async fn failed_update_reports_cli_update_failed_with_its_code() { let install = staged_install(); diff --git a/crates/socket-patch-core/src/telemetry.rs b/crates/socket-patch-core/src/telemetry.rs index d0f1f800f..19800c00d 100644 --- a/crates/socket-patch-core/src/telemetry.rs +++ b/crates/socket-patch-core/src/telemetry.rs @@ -7,6 +7,7 @@ use uuid::Uuid; use crate::api::client::ApiRoute; use crate::constants::USER_AGENT; +use crate::update::channel::{detect_channel, ChannelEnv}; use crate::utils::env_compat::{is_offline_env, proxy_url_from_env}; use crate::utils::fs::home_dir; use crate::utils::socket_cli_config::env_truthy; @@ -118,6 +119,13 @@ struct PatchTelemetryContext { platform: String, arch: String, command: String, + /// How this binary was installed ([`InstallChannel::id`]): `standalone`, + /// `npm`, `cargo`, `homebrew`, `pypi` or `launcher_cache`. Left out when + /// the binary's own path cannot be read. + /// + /// [`InstallChannel::id`]: crate::update::channel::InstallChannel::id + #[serde(skip_serializing_if = "Option::is_none")] + channel: Option<&'static str>, } /// Error details for telemetry events. @@ -197,6 +205,30 @@ fn debug_log(message: &str) { // Build event // --------------------------------------------------------------------------- +/// The install channel of the running binary, worked out once per process +/// from the binary's own path: the check `--update` makes before it +/// replaces a binary. It names one of six channels and never a path. It +/// reads no project file, makes no request and does not ask the user +/// database for a home directory ([`ChannelEnv::from_env_vars`]). +/// +/// `None` when the binary's own path cannot be read: no `/proc`, or a +/// binary that was replaced or removed while it ran. +fn install_channel() -> Option<&'static str> { + static CHANNEL: Lazy> = Lazy::new(|| { + let exe = crate::update::resolve_install_path().ok()?; + Some(detect_channel(&exe, &ChannelEnv::from_env_vars()).id()) + }); + *CHANNEL +} + +/// Work the install channel out now, while the running binary is still +/// where it was started from. `--update` calls this before it swaps the +/// binary: on Linux the old path reads as deleted afterwards, and the +/// `cli_updated` event would go out without its channel. +pub fn prime_install_channel() { + let _ = install_channel(); +} + /// Build the telemetry context for the current environment. fn build_telemetry_context(command: &str) -> PatchTelemetryContext { PatchTelemetryContext { @@ -204,6 +236,7 @@ fn build_telemetry_context(command: &str) -> PatchTelemetryContext { platform: std::env::consts::OS.to_string(), arch: std::env::consts::ARCH.to_string(), command: command.to_string(), + channel: install_channel(), } } @@ -234,15 +267,28 @@ pub fn sanitize_error_message(message: &str) -> String { message.replace(home, "~") } +/// `text` cut to at most `max` characters, the last of them an ellipsis +/// when anything was dropped. +fn truncate_chars(text: String, max: usize) -> String { + match text.char_indices().nth(max.saturating_sub(1)) { + Some((cut, _)) if text[cut..].chars().nth(1).is_some() => { + format!("{}…", &text[..cut]) + } + _ => text, + } +} + /// Build a telemetry event. `error` is an `(error_type, message)` pair; the -/// message is home-dir-sanitized before it leaves the process. +/// message is sanitized ([`sanitize_error_message`]) and cut to +/// [`MAX_ERROR_MESSAGE_CHARS`] before it leaves the process, and the whole +/// event is made to fit [`MAX_EVENT_BYTES`] ([`fit`]). fn build_telemetry_event( event_type: PatchTelemetryEventType, command: &str, metadata: Option>, error: Option<(String, String)>, ) -> PatchTelemetryEvent { - PatchTelemetryEvent { + fit(PatchTelemetryEvent { event_sender_created_at: chrono_now_iso(), event_type: event_type.as_str().to_string(), context: build_telemetry_context(command), @@ -250,9 +296,55 @@ fn build_telemetry_event( metadata, error: error.map(|(error_type, message)| PatchTelemetryError { error_type, - message: Some(sanitize_error_message(&message)), + message: Some(truncate_chars( + sanitize_error_message(&message), + MAX_ERROR_MESSAGE_CHARS, + )), }), + }) +} + +/// The largest event body sent, in bytes of JSON. The server keeps a body +/// in a form its dashboards can read only up to 10,000 characters, and a +/// body never has more characters than bytes. +const MAX_EVENT_BYTES: usize = 9_000; + +/// The shortest an error message is cut to when an event is too large. +const MIN_ERROR_MESSAGE_CHARS: usize = 200; + +/// `event` cut down until its JSON body fits [`MAX_EVENT_BYTES`]. The +/// caps on the patch list and the error message leave room in almost +/// every event; what they do not bound is how much a message grows when +/// JSON escapes it (a quote or a newline doubles, a control character +/// becomes six). An event that is still too large gives up the tail of +/// its error message first, then entries off the end of its patch list +/// (the failed ones lead), flagged `patches_truncated`. +fn fit(mut event: PatchTelemetryEvent) -> PatchTelemetryEvent { + let too_large = |event: &PatchTelemetryEvent| { + serde_json::to_string(event).is_ok_and(|body| body.len() > MAX_EVENT_BYTES) + }; + while too_large(&event) { + if let Some(message) = event.error.as_mut().and_then(|e| e.message.as_mut()) { + let chars = message.chars().count(); + if chars > MIN_ERROR_MESSAGE_CHARS { + let shorter = (chars / 2).max(MIN_ERROR_MESSAGE_CHARS); + *message = truncate_chars(std::mem::take(message), shorter); + continue; + } + } + let Some(metadata) = event.metadata.as_mut() else { + break; + }; + match metadata + .get_mut("patches") + .and_then(serde_json::Value::as_array_mut) + { + Some(patches) if !patches.is_empty() => patches.truncate(patches.len() / 2), + _ => break, + } + metadata.insert("patches_truncated".to_string(), serde_json::json!(true)); } + event } /// Get the current time as an ISO 8601 string with millisecond precision, @@ -483,6 +575,111 @@ pub async fn flush(grace: Duration) { } } +// --------------------------------------------------------------------------- +// Per-patch outcomes +// --------------------------------------------------------------------------- + +/// The patch modes an event names (`mode`, and each [`PatchOutcome`]'s). +pub const MODE_AGENT: &str = "agent"; +pub const MODE_HOSTED: &str = "hosted"; +pub const MODE_VENDORED: &str = "vendored"; + +/// The [`PatchOutcome::outcome`] of a patch the run could not act on. +pub const OUTCOME_FAILED: &str = "failed"; + +/// How many patches one event names. A run over more names this many, +/// the failed ones first, and says so (`patches_truncated`); the counts +/// beside the list are of the whole run. +/// +/// The cap keeps an event small: the server stores an event's body in a +/// form its dashboards cannot read once the body passes 10,000 characters +/// (see [`MAX_EVENT_BYTES`]), and one entry is about 110. +pub const MAX_REPORTED_PATCHES: usize = 50; + +/// The longest error message an event carries, in characters. One error +/// can quote a whole command's output, and the event has to stay small +/// (see [`MAX_REPORTED_PATCHES`]). +const MAX_ERROR_MESSAGE_CHARS: usize = 1000; + +/// One patch a run acted on, as its event names it: by patch UUID, with +/// the ecosystem and the mode it was patched in, and what the run did to +/// it. Never the package name, a path or a file list. +/// +/// This is what lets Socket see that one patch is being rolled back, or +/// fails to apply, far more often than the others. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] +pub struct PatchOutcome { + /// The patch UUID. + pub uuid: String, + /// The ecosystem's CLI name (`npm`, `pypi`, …); empty when unknown. + pub ecosystem: String, + /// [`MODE_AGENT`], [`MODE_HOSTED`] or [`MODE_VENDORED`]. + pub mode: &'static str, + /// What happened: `applied`, `rolled_back`, `removed`, `downloaded`, + /// `failed`, `skipped`, … (the command's own vocabulary). + pub outcome: &'static str, + /// The stable code of a `failed` or `skipped` outcome + /// (`hash_mismatch`, `already_patched`, …). + #[serde(skip_serializing_if = "Option::is_none")] + pub code: Option, +} + +impl PatchOutcome { + /// How many of `patches` ended as `outcome`. + pub fn count(patches: &[PatchOutcome], outcome: &str) -> usize { + patches.iter().filter(|p| p.outcome == outcome).count() + } +} + +/// The fields an event about specific patches carries, added to `metadata` +/// (an object; the event's own keys win): +/// +/// * `patches`: at most [`MAX_REPORTED_PATCHES`] outcomes, and +/// `patches_truncated: true` when that cap dropped some; +/// * `outcomes`: how many patches ended each way, over the whole run; +/// * `ecosystems`, `modes`: the distinct values, sorted, over the whole run. +/// +/// A run that named no patch adds nothing. +fn with_patches(mut metadata: serde_json::Value, patches: &[PatchOutcome]) -> serde_json::Value { + use std::collections::{BTreeMap, BTreeSet}; + + let Some(fields) = metadata.as_object_mut() else { + return metadata; + }; + if patches.is_empty() { + return metadata; + } + let mut outcomes: BTreeMap<&str, usize> = BTreeMap::new(); + let mut ecosystems: BTreeSet<&str> = BTreeSet::new(); + let mut modes: BTreeSet<&str> = BTreeSet::new(); + for patch in patches { + *outcomes.entry(patch.outcome).or_default() += 1; + if !patch.ecosystem.is_empty() { + ecosystems.insert(&patch.ecosystem); + } + modes.insert(patch.mode); + } + // Failures first: when the cap drops entries, the ones worth + // investigating are the ones kept. Otherwise the run's own order. + let reported: Vec<&PatchOutcome> = patches + .iter() + .filter(|p| p.outcome == OUTCOME_FAILED) + .chain(patches.iter().filter(|p| p.outcome != OUTCOME_FAILED)) + .take(MAX_REPORTED_PATCHES) + .collect(); + let mut add = |key: &str, value: serde_json::Value| { + fields.entry(key).or_insert(value); + }; + if reported.len() < patches.len() { + add("patches_truncated", serde_json::json!(true)); + } + add("patches", serde_json::json!(reported)); + add("outcomes", serde_json::json!(outcomes)); + add("ecosystems", serde_json::json!(ecosystems)); + add("modes", serde_json::json!(modes)); + metadata +} + // --------------------------------------------------------------------------- // Per-event tracker wrappers (the public API) // @@ -520,34 +717,74 @@ fn fire( start_send(prepare_send(event, auth)); } -/// Track a successful in-place (agent mode) patch application. -pub async fn track_patch_applied(patches_count: usize, dry_run: bool, auth: &TelemetryAuth) { +/// Track a successful in-place (agent mode) patch application, as +/// `command` (`apply`, or the `scan` / `get` whose agent mode ran it): +/// `patches` are the patches the run acted on, `patches_count` how many +/// packages it patched. +pub async fn track_patch_applied( + command: &'static str, + patches_count: usize, + dry_run: bool, + patches: &[PatchOutcome], + auth: &TelemetryAuth, +) { fire( PatchTelemetryEventType::PatchApplied, - "apply", - serde_json::json!({ - "patches_count": patches_count, - "dry_run": dry_run, - "mode": "agent", - }), + command, + with_patches( + serde_json::json!({ + "patches_count": patches_count, + "dry_run": dry_run, + "mode": MODE_AGENT, + }), + patches, + ), None::<&str>, auth, ); } -/// Track a failed patch application. +/// The fields of a failure event: `fields`, the run's stable `error_code` +/// (the code its `--json` envelope reports, e.g. `patch_not_found`: what +/// tells a mistyped target from a patch that would not come off) and the +/// patches it acted on. +fn failure_metadata( + mut fields: serde_json::Value, + error_code: &str, + patches: &[PatchOutcome], +) -> serde_json::Value { + if let Some(fields) = fields.as_object_mut() { + fields.insert("error_code".to_string(), serde_json::json!(error_code)); + } + with_patches(fields, patches) +} + +/// Track a failed patch application. `patches` names what the run acted +/// on before it failed (the failed ones and the ones it did apply); empty +/// when it failed before reaching any. /// /// Accepts any `Display` type for the error (works with `&str`, `String`, /// `anyhow::Error`, `std::io::Error`, etc.). pub async fn track_patch_apply_failed( + command: &'static str, + error_code: &str, error: impl std::fmt::Display, dry_run: bool, + patches: &[PatchOutcome], auth: &TelemetryAuth, ) { fire( PatchTelemetryEventType::PatchApplyFailed, - "apply", - serde_json::json!({ "dry_run": dry_run, "mode": "agent" }), + command, + failure_metadata( + serde_json::json!({ + "patches_count": PatchOutcome::count(patches, "applied"), + "dry_run": dry_run, + "mode": MODE_AGENT, + }), + error_code, + patches, + ), Some(error), auth, ); @@ -558,23 +795,28 @@ pub async fn track_patch_apply_failed( /// `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. +/// rewritten; `patches` are the pins the run confirmed and the ones it +/// could not make. pub async fn track_patch_hosted( command: &'static str, patches_count: usize, files_count: usize, dry_run: bool, + patches: &[PatchOutcome], auth: &TelemetryAuth, ) { fire( PatchTelemetryEventType::PatchApplied, command, - serde_json::json!({ - "patches_count": patches_count, - "files_count": files_count, - "dry_run": dry_run, - "mode": "hosted", - }), + with_patches( + serde_json::json!({ + "patches_count": patches_count, + "files_count": files_count, + "dry_run": dry_run, + "mode": MODE_HOSTED, + }), + patches, + ), None::<&str>, auth, ); @@ -583,84 +825,174 @@ pub async fn track_patch_hosted( /// Track a failed hosted-mode run (see [`track_patch_hosted`]). pub async fn track_patch_hosted_failed( command: &'static str, + error_code: &str, error: impl std::fmt::Display, dry_run: bool, + patches: &[PatchOutcome], auth: &TelemetryAuth, ) { fire( PatchTelemetryEventType::PatchApplyFailed, command, - serde_json::json!({ "dry_run": dry_run, "mode": "hosted" }), + failure_metadata( + serde_json::json!({ "dry_run": dry_run, "mode": MODE_HOSTED }), + error_code, + patches, + ), Some(error), auth, ); } -/// Track a successful vendor run (count = packages vendored). -pub async fn track_patch_vendored(vendored_count: u32, dry_run: bool, auth: &TelemetryAuth) { +/// Track a successful vendor run, as `command` (`vendor`, or the `scan` / +/// `get` whose vendored mode ran it): `vendored_count` packages vendored, +/// `patches` what the run did to each. +pub async fn track_patch_vendored( + command: &'static str, + vendored_count: u32, + dry_run: bool, + patches: &[PatchOutcome], + auth: &TelemetryAuth, +) { fire( PatchTelemetryEventType::PatchVendored, - "vendor", - serde_json::json!({ "patches_count": vendored_count, "dry_run": dry_run }), + command, + with_patches( + serde_json::json!({ + "patches_count": vendored_count, + "dry_run": dry_run, + "mode": MODE_VENDORED, + }), + patches, + ), None::<&str>, auth, ); } -/// Track a failed vendor run. +/// Track a failed vendor run (see [`track_patch_vendored`]). `patches` +/// names what it acted on before it failed; empty when it failed before +/// reaching any. pub async fn track_patch_vendor_failed( + command: &'static str, + error_code: &str, error: impl std::fmt::Display, dry_run: bool, + patches: &[PatchOutcome], auth: &TelemetryAuth, ) { fire( PatchTelemetryEventType::PatchVendorFailed, - "vendor", - serde_json::json!({ "dry_run": dry_run }), + command, + failure_metadata( + serde_json::json!({ + "patches_count": PatchOutcome::count(patches, "applied"), + "dry_run": dry_run, + "mode": MODE_VENDORED, + }), + error_code, + patches, + ), Some(error), auth, ); } -/// Track a successful patch removal. -pub async fn track_patch_removed(removed_count: usize, auth: &TelemetryAuth) { +/// Track a patch removal that took `removed_count` patches out, as +/// `command` (`remove`, or `vendor` for its `--revert`). `patches` names +/// each one. +pub async fn track_patch_removed( + command: &'static str, + removed_count: usize, + patches: &[PatchOutcome], + auth: &TelemetryAuth, +) { fire( PatchTelemetryEventType::PatchRemoved, - "remove", - serde_json::json!({ "removed_count": removed_count }), + command, + with_patches( + serde_json::json!({ "removed_count": removed_count }), + patches, + ), None::<&str>, auth, ); } -/// 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) { +/// Track a patch removal that did not happen. Accepts any `Display` type +/// for the error; `patches` names the patches it could not remove, when +/// the run got as far as resolving them. +pub async fn track_patch_remove_failed( + command: &'static str, + error_code: &str, + error: impl std::fmt::Display, + patches: &[PatchOutcome], + auth: &TelemetryAuth, +) { fire( PatchTelemetryEventType::PatchRemoveFailed, - "remove", - serde_json::Value::Null, + command, + failure_metadata(serde_json::json!({}), error_code, patches), Some(error), auth, ); } -/// Track a successful patch rollback. -pub async fn track_patch_rolled_back(rolled_back_count: usize, auth: &TelemetryAuth) { +/// What a rollback run reports besides the patches themselves. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct RollbackRun { + /// How many patched packages the run restored (would restore, on a + /// dry run), across every mode. + pub rolled_back_count: usize, + /// A preview: nothing was restored. + pub dry_run: bool, + /// The user named the patches to roll back (a purl, a UUID, a path), + /// rather than rolling the whole project back. + pub targeted: bool, +} + +impl RollbackRun { + fn metadata(self) -> serde_json::Value { + serde_json::json!({ + "rolled_back_count": self.rolled_back_count, + "dry_run": self.dry_run, + "targeted": self.targeted, + }) + } +} + +/// Track a rollback that left nothing patched. `patches` names each patch +/// the run rolled back (`rolled_back`, or `verified` on a dry run) or had +/// nothing to do for (`skipped`). +pub async fn track_patch_rolled_back( + run: RollbackRun, + patches: &[PatchOutcome], + auth: &TelemetryAuth, +) { fire( PatchTelemetryEventType::PatchRolledBack, "rollback", - serde_json::json!({ "rolled_back_count": rolled_back_count }), + with_patches(run.metadata(), patches), None::<&str>, auth, ); } -/// 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) { +/// Track a rollback that left something patched, or never started. +/// Accepts any `Display` type for the error. `patches` names the patches +/// that failed and the ones the same run did roll back; empty when the +/// run failed before it resolved any. +pub async fn track_patch_rollback_failed( + error_code: &str, + error: impl std::fmt::Display, + run: RollbackRun, + patches: &[PatchOutcome], + auth: &TelemetryAuth, +) { fire( PatchTelemetryEventType::PatchRollbackFailed, "rollback", - serde_json::Value::Null, + failure_metadata(run.metadata(), error_code, patches), Some(error), auth, ); @@ -670,83 +1002,140 @@ pub async fn track_patch_rollback_failed(error: impl std::fmt::Display, auth: &T // Read-side trackers: scan + get // --------------------------------------------------------------------------- -/// Track a successful `scan`. Reports per-tier patch counts, whether the -/// call was downgraded to the public proxy after an auth-endpoint 401/403 -/// (`fallback_to_proxy`), 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. -/// -/// 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. -#[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, -) { +/// What a successful `scan` reports. +#[derive(Debug, Clone, Copy)] +pub struct ScanReport<'a> { + /// Packages the crawl found, per ecosystem (CLI name). Its keys are + /// the event's `ecosystems`, its sum `packages_scanned`: the + /// ecosystems the crawl found, not the `--ecosystems` filter. + pub packages_by_ecosystem: &'a std::collections::BTreeMap, + /// Patches the API offered for those packages, per ecosystem. + pub patches_by_ecosystem: &'a std::collections::BTreeMap, + pub free_patches: usize, + pub paid_patches: usize, + pub can_access_paid: bool, + /// The call was downgraded to the public proxy after an auth-endpoint + /// 401/403. + pub fallback_to_proxy: bool, + /// The mode the run was asked for (`hosted` / `vendored` / `agent`, + /// or `report` with none). + pub mode: &'a str, + /// The modes the project is already wired for, from its hosted + /// lockfile pins, vendor ledger and agent manifest. + pub project_modes: &'a [&'a str], + pub dry_run: bool, +} + +/// Track a successful `scan` of one project directory. +pub async fn track_patch_scanned(report: ScanReport<'_>, auth: &TelemetryAuth) { + let ecosystems: Vec<&String> = report.packages_by_ecosystem.keys().collect(); fire( PatchTelemetryEventType::PatchScanned, "scan", serde_json::json!({ - "packages_scanned": packages_scanned, - "free_patches": free_patches, - "paid_patches": paid_patches, - "can_access_paid": can_access_paid, + "packages_scanned": report.packages_by_ecosystem.values().sum::(), + "free_patches": report.free_patches, + "paid_patches": report.paid_patches, + "can_access_paid": report.can_access_paid, "ecosystems": ecosystems, - "fallback_to_proxy": fallback_to_proxy, - "mode": mode, - "project_modes": project_modes, + "packages_by_ecosystem": report.packages_by_ecosystem, + "patches_by_ecosystem": report.patches_by_ecosystem, + "fallback_to_proxy": report.fallback_to_proxy, + "mode": report.mode, + "project_modes": report.project_modes, + "dry_run": report.dry_run, }), None::<&str>, auth, ); } -/// Track a failed `scan`. +/// Track a failed `scan`: `error_code` is the code its `--json` envelope +/// reports, `mode` the mode the run was asked for. pub async fn track_patch_scan_failed( + error_code: &str, error: impl std::fmt::Display, fallback_to_proxy: bool, + mode: &str, auth: &TelemetryAuth, ) { fire( PatchTelemetryEventType::PatchScanFailed, "scan", - serde_json::json!({ "fallback_to_proxy": fallback_to_proxy }), + serde_json::json!({ + "error_code": error_code, + "fallback_to_proxy": fallback_to_proxy, + "mode": mode, + }), Some(error), 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. +/// Track a `get ` that resolved its patch. Reports patch identity, +/// the mode the run patches in, 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, + mode: &'static str, fallback_to_proxy: bool, auth: &TelemetryAuth, ) { + let patch = PatchOutcome { + uuid: uuid.to_string(), + ecosystem: ecosystem.to_string(), + mode, + outcome: "downloaded", + code: None, + }; fire( PatchTelemetryEventType::PatchFetched, "get", - serde_json::json!({ - "uuid": uuid, - "tier": tier, - "ecosystem": ecosystem, - "download_mode": "file", - "fallback_to_proxy": fallback_to_proxy, - }), + with_patches( + serde_json::json!({ + "uuid": uuid, + "tier": tier, + "ecosystem": ecosystem, + "mode": mode, + "patches_count": 1, + "download_mode": "file", + "fallback_to_proxy": fallback_to_proxy, + }), + std::slice::from_ref(&patch), + ), + None::<&str>, + auth, + ); +} + +/// Track the patch records an agent-mode run downloaded, as `command` +/// (`scan`, or a `get` by package or advisory): one event for the run, +/// naming each patch it downloaded (`downloaded`), already had +/// (`skipped`) or could not fetch (`failed`). `patches_count` is how many +/// it downloaded. A run that reached no patch sends nothing. +pub async fn track_patches_fetched( + command: &'static str, + patches: &[PatchOutcome], + auth: &TelemetryAuth, +) { + if patches.is_empty() { + return; + } + fire( + PatchTelemetryEventType::PatchFetched, + command, + with_patches( + serde_json::json!({ + "mode": MODE_AGENT, + "patches_count": PatchOutcome::count(patches, "downloaded"), + "download_mode": "file", + }), + patches, + ), None::<&str>, auth, ); @@ -766,9 +1155,12 @@ fn fetch_failed_uuid(identifier: &str) -> &str { /// 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. +/// a uuid is reported as empty. `error_code` is the code the run's +/// `--json` output reports (`not_found`, `paid_required`, +/// `patch_fetch_failed`). pub async fn track_patch_fetch_failed( uuid: &str, + error_code: &str, error: impl std::fmt::Display, fallback_to_proxy: bool, auth: &TelemetryAuth, @@ -778,6 +1170,7 @@ pub async fn track_patch_fetch_failed( "get", serde_json::json!({ "uuid": fetch_failed_uuid(uuid), + "error_code": error_code, "fallback_to_proxy": fallback_to_proxy }), Some(error), @@ -820,12 +1213,17 @@ pub async fn track_patch_repaired( ); } -/// Track a failed `repair`. -pub async fn track_patch_repair_failed(error: impl std::fmt::Display, auth: &TelemetryAuth) { +/// Track a failed `repair`: `error_code` is the code its `--json` +/// envelope reports. +pub async fn track_patch_repair_failed( + error_code: &str, + error: impl std::fmt::Display, + auth: &TelemetryAuth, +) { fire( PatchTelemetryEventType::PatchRepairFailed, "repair", - serde_json::Value::Null, + serde_json::json!({ "error_code": error_code }), Some(error), auth, ); @@ -856,13 +1254,14 @@ pub async fn track_vex_generated( ); } -/// Track a failed `vex` generation. -pub async fn track_vex_failed(error: impl std::fmt::Display, auth: &TelemetryAuth) { +/// Track a failed `vex` generation: `error_code` is the code its error +/// reports (and, as it always was, the event's error message). +pub async fn track_vex_failed(error_code: &str, auth: &TelemetryAuth) { fire( PatchTelemetryEventType::VexFailed, "vex", - serde_json::Value::Null, - Some(error), + serde_json::json!({ "error_code": error_code }), + Some(error_code), auth, ); } @@ -1478,7 +1877,29 @@ mod tests { .map(String::as_str) .collect(); ctx.sort_unstable(); - assert_eq!(ctx, ["arch", "command", "platform", "version"]); + // The channel is the id of the test binary's own install channel, + // never a path. It depends on where the build directory sits (a + // checkout under `node_modules` reads as npm), and is left out + // where the binary cannot read its own path. + match install_channel() { + Some(channel) => { + assert_eq!(ctx, ["arch", "channel", "command", "platform", "version"]); + assert_eq!(v["context"]["channel"], channel); + assert!( + [ + "standalone", + "npm", + "pypi", + "cargo", + "launcher_cache", + "homebrew" + ] + .contains(&channel), + "unexpected channel id {channel}" + ); + } + None => assert_eq!(ctx, ["arch", "command", "platform", "version"]), + } assert_eq!(v["error"]["type"], "Error"); assert_eq!(v["error"]["message"], "boom"); assert_eq!(v["metadata"]["patches_count"], 2); @@ -1494,11 +1915,42 @@ mod tests { ); } - /// Each public tracker posts the event type and metadata the backend - /// and its dashboards key on, to the org endpoint with the bearer. - #[tokio::test] - #[serial_test::serial] - async fn trackers_post_the_documented_events() { + const UUID_A: &str = "11111111-1111-4111-8111-111111111111"; + const UUID_B: &str = "22222222-2222-4222-8222-222222222222"; + + fn outcome( + uuid: &str, + ecosystem: &str, + mode: &'static str, + outcome: &'static str, + code: Option<&str>, + ) -> PatchOutcome { + PatchOutcome { + uuid: uuid.to_string(), + ecosystem: ecosystem.to_string(), + mode, + outcome, + code: code.map(str::to_string), + } + } + + /// The bodies an org-style mock received, in arrival order, each + /// checked for the bearer. + async fn posted(server: &wiremock::MockServer) -> Vec { + server + .received_requests() + .await + .unwrap() + .iter() + .map(|r| { + assert_eq!(r.headers.get("authorization").unwrap(), "Bearer tok"); + serde_json::from_slice(&r.body).unwrap() + }) + .collect() + } + + /// A mock of the org telemetry endpoint and the route to it. + async fn org_endpoint() -> (wiremock::MockServer, TelemetryAuth) { use wiremock::matchers::{method, path}; use wiremock::{Mock, MockServer, ResponseTemplate}; @@ -1508,66 +1960,113 @@ mod tests { .respond_with(ResponseTemplate::new(201)) .mount(&server) .await; - - let _on = TelemetryOn::new(); let auth = TelemetryAuth { url: format!("{}/v0/orgs/acme/telemetry", server.uri()), bearer: Some("tok".to_string()), }; + (server, auth) + } + + /// Each public tracker posts the event type and metadata the backend + /// and its dashboards key on, to the org endpoint with the bearer. + #[tokio::test] + #[serial_test::serial] + async fn trackers_post_the_documented_events() { + let (server, auth) = org_endpoint().await; + let _on = TelemetryOn::new(); // Sends run side by side, so each is waited for before the next // fires: the requests then arrive in the order asserted below. - track_patch_applied(3, false, &auth).await; + track_patch_applied( + "scan", + 3, + false, + &[outcome(UUID_A, "npm", MODE_AGENT, "applied", None)], + &auth, + ) + .await; flush(AMPLE).await; - track_patch_hosted("scan", 2, 1, false, &auth).await; + track_patch_hosted( + "scan", + 2, + 1, + false, + &[outcome(UUID_A, "npm", MODE_HOSTED, "applied", None)], + &auth, + ) + .await; flush(AMPLE).await; - track_patch_hosted_failed("get", "lockfile write failed", true, &auth).await; + track_patch_hosted_failed( + "get", + "lockfile_write_failed", + "lockfile write failed", + true, + &[outcome( + UUID_A, + "npm", + MODE_HOSTED, + OUTCOME_FAILED, + Some("lockfile_write_failed"), + )], + &auth, + ) + .await; flush(AMPLE).await; track_cli_updated("9.9.9", "standalone", false, false, &auth).await; flush(AMPLE).await; track_cli_update_failed("managed_install", "managed by npm", &auth).await; flush(AMPLE).await; - let ecosystems = vec!["npm".to_string(), "pypi".to_string()]; + let packages = [("npm".to_string(), 4), ("pypi".to_string(), 1)] + .into_iter() + .collect(); + let patches = [("npm".to_string(), 5)].into_iter().collect(); track_patch_scanned( - 5, - 3, - 2, - true, - &ecosystems, - true, - "hosted", - &["vendored"], + ScanReport { + packages_by_ecosystem: &packages, + patches_by_ecosystem: &patches, + free_patches: 3, + paid_patches: 2, + can_access_paid: true, + fallback_to_proxy: true, + mode: "hosted", + project_modes: &["vendored"], + dry_run: false, + }, &auth, ) .await; flush(AMPLE).await; - track_patch_scan_failed("all batches failed", true, &auth).await; + track_patch_scan_failed( + "api_batch_failed", + "all batches failed", + true, + "agent", + &auth, + ) + .await; flush(AMPLE).await; - let reqs = server.received_requests().await.unwrap(); - let bodies: Vec = reqs - .iter() - .map(|r| { - assert_eq!(r.headers.get("authorization").unwrap(), "Bearer tok"); - serde_json::from_slice(&r.body).unwrap() - }) - .collect(); + let bodies = posted(&server).await; assert_eq!(bodies.len(), 7); assert_eq!(bodies[0]["event_type"], "patch_applied"); - assert_eq!(bodies[0]["context"]["command"], "apply"); + assert_eq!(bodies[0]["context"]["command"], "scan"); assert_eq!(bodies[0]["metadata"]["mode"], "agent"); assert_eq!(bodies[0]["metadata"]["patches_count"], 3); + assert_eq!(bodies[0]["metadata"]["patches"][0]["uuid"], UUID_A); assert_eq!(bodies[1]["event_type"], "patch_applied"); assert_eq!(bodies[1]["context"]["command"], "scan"); assert_eq!(bodies[1]["metadata"]["mode"], "hosted"); assert_eq!(bodies[1]["metadata"]["patches_count"], 2); assert_eq!(bodies[1]["metadata"]["files_count"], 1); + assert_eq!(bodies[1]["metadata"]["patches"][0]["mode"], "hosted"); assert_eq!(bodies[2]["event_type"], "patch_apply_failed"); assert_eq!(bodies[2]["context"]["command"], "get"); assert_eq!(bodies[2]["metadata"]["mode"], "hosted"); assert_eq!(bodies[2]["metadata"]["dry_run"], true); + assert_eq!(bodies[2]["metadata"]["error_code"], "lockfile_write_failed"); + assert_eq!(bodies[2]["metadata"]["outcomes"]["failed"], 1); assert_eq!(bodies[2]["error"]["message"], "lockfile write failed"); assert_eq!(bodies[3]["event_type"], "cli_updated"); @@ -1589,7 +2088,16 @@ mod tests { bodies[5]["metadata"]["ecosystems"], serde_json::json!(["npm", "pypi"]) ); + assert_eq!( + bodies[5]["metadata"]["packages_by_ecosystem"], + serde_json::json!({ "npm": 4, "pypi": 1 }) + ); + assert_eq!( + bodies[5]["metadata"]["patches_by_ecosystem"], + serde_json::json!({ "npm": 5 }) + ); assert_eq!(bodies[5]["metadata"]["mode"], "hosted"); + assert_eq!(bodies[5]["metadata"]["dry_run"], false); assert_eq!( bodies[5]["metadata"]["project_modes"], serde_json::json!(["vendored"]) @@ -1598,9 +2106,437 @@ mod tests { assert_eq!(bodies[6]["event_type"], "patch_scan_failed"); assert_eq!(bodies[6]["context"]["command"], "scan"); assert_eq!(bodies[6]["metadata"]["fallback_to_proxy"], true); + assert_eq!(bodies[6]["metadata"]["error_code"], "api_batch_failed"); + assert_eq!(bodies[6]["metadata"]["mode"], "agent"); assert_eq!(bodies[6]["error"]["message"], "all batches failed"); } + /// The events that take a patch out name it: the patch UUID with its + /// ecosystem, mode and outcome, the exact counts over the run, and on + /// a failure the run's error code. This is what lets the server tell + /// which patch is being rolled back or removed. + #[tokio::test] + #[serial_test::serial] + async fn rollback_and_remove_events_name_their_patches() { + let (server, auth) = org_endpoint().await; + let _on = TelemetryOn::new(); + + let run = RollbackRun { + rolled_back_count: 2, + dry_run: false, + targeted: true, + }; + track_patch_rolled_back( + run, + &[ + outcome(UUID_A, "npm", MODE_AGENT, "rolled_back", None), + outcome(UUID_B, "pypi", MODE_VENDORED, "rolled_back", None), + ], + &auth, + ) + .await; + flush(AMPLE).await; + track_patch_rollback_failed( + "rollback_failed", + "One or more rollbacks failed", + RollbackRun { + rolled_back_count: 1, + dry_run: false, + targeted: false, + }, + &[ + outcome(UUID_A, "npm", MODE_AGENT, "rolled_back", None), + outcome( + UUID_B, + "gem", + MODE_HOSTED, + OUTCOME_FAILED, + Some("hosted_restore_refused"), + ), + ], + &auth, + ) + .await; + flush(AMPLE).await; + track_patch_rollback_failed( + "patch_not_found", + "No patch found matching identifier: lodash", + RollbackRun { + targeted: true, + ..RollbackRun::default() + }, + &[], + &auth, + ) + .await; + flush(AMPLE).await; + track_patch_removed( + "remove", + 1, + &[outcome(UUID_A, "npm", MODE_AGENT, "removed", None)], + &auth, + ) + .await; + flush(AMPLE).await; + track_patch_remove_failed( + "vendor", + "vendor_revert_kept", + "kept", + &[outcome( + UUID_B, + "cargo", + MODE_VENDORED, + OUTCOME_FAILED, + Some("vendor_revert_kept"), + )], + &auth, + ) + .await; + flush(AMPLE).await; + + let bodies = posted(&server).await; + assert_eq!(bodies.len(), 5); + + let rolled_back = &bodies[0]; + assert_eq!(rolled_back["event_type"], "patch_rolled_back"); + assert_eq!(rolled_back["context"]["command"], "rollback"); + assert_eq!( + rolled_back["metadata"], + serde_json::json!({ + "rolled_back_count": 2, + "dry_run": false, + "targeted": true, + "patches": [ + { "uuid": UUID_A, "ecosystem": "npm", "mode": "agent", "outcome": "rolled_back" }, + { "uuid": UUID_B, "ecosystem": "pypi", "mode": "vendored", "outcome": "rolled_back" }, + ], + "outcomes": { "rolled_back": 2 }, + "ecosystems": ["npm", "pypi"], + "modes": ["agent", "vendored"], + }) + ); + + let failed = &bodies[1]; + assert_eq!(failed["event_type"], "patch_rollback_failed"); + assert_eq!(failed["metadata"]["error_code"], "rollback_failed"); + assert_eq!(failed["metadata"]["rolled_back_count"], 1); + assert_eq!(failed["metadata"]["targeted"], false); + assert_eq!( + failed["metadata"]["outcomes"], + serde_json::json!({ "failed": 1, "rolled_back": 1 }) + ); + // The failed patch leads, with the code of its failure. + assert_eq!( + failed["metadata"]["patches"][0], + serde_json::json!({ + "uuid": UUID_B, + "ecosystem": "gem", + "mode": "hosted", + "outcome": "failed", + "code": "hosted_restore_refused", + }) + ); + assert_eq!(failed["metadata"]["patches"][1]["uuid"], UUID_A); + + // A run that never reached a patch names none, and its code says + // why: a mistyped target is not a patch that would not come off. + let unstarted = &bodies[2]; + assert_eq!(unstarted["event_type"], "patch_rollback_failed"); + assert_eq!( + unstarted["metadata"], + serde_json::json!({ + "rolled_back_count": 0, + "dry_run": false, + "targeted": true, + "error_code": "patch_not_found", + }) + ); + + let removed = &bodies[3]; + assert_eq!(removed["event_type"], "patch_removed"); + assert_eq!(removed["context"]["command"], "remove"); + assert_eq!(removed["metadata"]["removed_count"], 1); + assert_eq!(removed["metadata"]["patches"][0]["uuid"], UUID_A); + assert_eq!(removed["metadata"]["patches"][0]["outcome"], "removed"); + + let kept = &bodies[4]; + assert_eq!(kept["event_type"], "patch_remove_failed"); + assert_eq!(kept["context"]["command"], "vendor"); + assert_eq!(kept["metadata"]["error_code"], "vendor_revert_kept"); + assert_eq!(kept["metadata"]["patches"][0]["code"], "vendor_revert_kept"); + } + + /// Vendor and download events carry the mode, the command the user + /// ran and their patches. + #[tokio::test] + #[serial_test::serial] + async fn vendor_and_fetch_events_carry_mode_and_patches() { + let (server, auth) = org_endpoint().await; + let _on = TelemetryOn::new(); + + track_patch_vendored( + "scan", + 1, + false, + &[outcome(UUID_A, "npm", MODE_VENDORED, "applied", None)], + &auth, + ) + .await; + flush(AMPLE).await; + track_patch_vendor_failed( + "vendor", + "vendor_failed", + "vendor completed with failures", + false, + &[ + outcome(UUID_A, "npm", MODE_VENDORED, "applied", None), + outcome( + UUID_B, + "npm", + MODE_VENDORED, + OUTCOME_FAILED, + Some("no_local_source"), + ), + ], + &auth, + ) + .await; + flush(AMPLE).await; + track_patch_fetched(UUID_A, "free", "npm", MODE_HOSTED, false, &auth).await; + flush(AMPLE).await; + track_patches_fetched( + "scan", + &[ + outcome(UUID_A, "npm", MODE_AGENT, "downloaded", None), + outcome( + UUID_B, + "pypi", + MODE_AGENT, + "skipped", + Some("already_in_manifest"), + ), + ], + &auth, + ) + .await; + flush(AMPLE).await; + // A pass that reached no patch sends nothing. + track_patches_fetched("scan", &[], &auth).await; + flush(AMPLE).await; + + let bodies = posted(&server).await; + assert_eq!(bodies.len(), 4); + + assert_eq!(bodies[0]["event_type"], "patch_vendored"); + assert_eq!(bodies[0]["context"]["command"], "scan"); + assert_eq!(bodies[0]["metadata"]["mode"], "vendored"); + assert_eq!(bodies[0]["metadata"]["patches_count"], 1); + assert_eq!(bodies[0]["metadata"]["patches"][0]["uuid"], UUID_A); + + assert_eq!(bodies[1]["event_type"], "patch_vendor_failed"); + assert_eq!(bodies[1]["context"]["command"], "vendor"); + assert_eq!(bodies[1]["metadata"]["mode"], "vendored"); + assert_eq!(bodies[1]["metadata"]["error_code"], "vendor_failed"); + // What the failed run did vendor is counted, not lost. + assert_eq!(bodies[1]["metadata"]["patches_count"], 1); + assert_eq!(bodies[1]["metadata"]["patches"][0]["uuid"], UUID_B); + + assert_eq!(bodies[2]["event_type"], "patch_fetched"); + assert_eq!(bodies[2]["context"]["command"], "get"); + assert_eq!(bodies[2]["metadata"]["uuid"], UUID_A); + assert_eq!(bodies[2]["metadata"]["mode"], "hosted"); + assert_eq!(bodies[2]["metadata"]["patches_count"], 1); + assert_eq!(bodies[2]["metadata"]["download_mode"], "file"); + assert_eq!(bodies[2]["metadata"]["patches"][0]["outcome"], "downloaded"); + + assert_eq!(bodies[3]["event_type"], "patch_fetched"); + assert_eq!(bodies[3]["context"]["command"], "scan"); + assert_eq!(bodies[3]["metadata"]["mode"], "agent"); + assert_eq!(bodies[3]["metadata"]["patches_count"], 1); + assert_eq!( + bodies[3]["metadata"]["outcomes"], + serde_json::json!({ "downloaded": 1, "skipped": 1 }) + ); + } + + /// An event names at most [`MAX_REPORTED_PATCHES`] patches, the failed + /// ones first, and says when it dropped some; the counts beside the + /// list stay those of the whole run. + #[test] + fn a_long_run_reports_its_failures_first_and_exact_counts() { + let total = MAX_REPORTED_PATCHES + 30; + let patches: Vec = (0..total) + .map(|i| { + let uuid = format!("00000000-0000-4000-8000-{i:012}"); + if i % 20 == 19 { + outcome( + &uuid, + "pypi", + MODE_AGENT, + OUTCOME_FAILED, + Some("hash_mismatch"), + ) + } else { + outcome(&uuid, "npm", MODE_AGENT, "applied", None) + } + }) + .collect(); + let failed = PatchOutcome::count(&patches, OUTCOME_FAILED); + assert!(failed > 0 && failed < MAX_REPORTED_PATCHES); + + let metadata = with_patches(serde_json::json!({ "dry_run": false }), &patches); + let reported = metadata["patches"].as_array().unwrap(); + assert_eq!(reported.len(), MAX_REPORTED_PATCHES); + assert_eq!(metadata["patches_truncated"], true); + for entry in &reported[..failed] { + assert_eq!(entry["outcome"], "failed", "failures lead: {entry}"); + } + for entry in &reported[failed..] { + assert_eq!(entry["outcome"], "applied"); + } + // The run's own order is kept within each group. + assert_eq!( + reported[failed]["uuid"], + "00000000-0000-4000-8000-000000000000" + ); + assert_eq!( + metadata["outcomes"], + serde_json::json!({ "applied": total - failed, "failed": failed }) + ); + assert_eq!(metadata["ecosystems"], serde_json::json!(["npm", "pypi"])); + assert_eq!(metadata["modes"], serde_json::json!(["agent"])); + + // Under the cap nothing is flagged. + let short = with_patches(serde_json::json!({}), &patches[..3]); + assert_eq!(short["patches"].as_array().unwrap().len(), 3); + assert!(short.get("patches_truncated").is_none()); + // No patch, no fields; and the event's own keys are never replaced. + assert_eq!( + with_patches(serde_json::json!({ "dry_run": true }), &[]), + serde_json::json!({ "dry_run": true }) + ); + let own = with_patches( + serde_json::json!({ "ecosystems": ["cargo"] }), + &patches[..1], + ); + assert_eq!(own["ecosystems"], serde_json::json!(["cargo"])); + } + + /// The event a rollback failure builds for `failed` patches, every + /// entry with a long code, and `message`. + fn rollback_failure(failed: usize, message: String) -> PatchTelemetryEvent { + let patches: Vec = (0..failed) + .map(|i| { + outcome( + &format!("00000000-0000-4000-8000-{i:012}"), + "composer", + MODE_VENDORED, + OUTCOME_FAILED, + Some("replaced_patch_not_restored_before_update"), + ) + }) + .collect(); + let metadata = failure_metadata( + RollbackRun { + rolled_back_count: 1000, + dry_run: true, + targeted: true, + } + .metadata(), + "vendor_state_write_failed", + &patches, + ); + let serde_json::Value::Object(metadata) = metadata else { + panic!("metadata is an object"); + }; + build_telemetry_event( + PatchTelemetryEventType::PatchRollbackFailed, + "rollback", + Some(metadata.into_iter().collect()), + Some(("Error".to_string(), message)), + ) + } + + /// The server keeps an event's body readable to its dashboards only + /// up to 10,000 characters. The largest event a run can build stays + /// under that whatever its error message holds: plain text, or text + /// that grows when JSON escapes it (quotes, backslashes, newlines, + /// control characters, as in quoted command output or Windows paths). + #[test] + fn the_largest_event_fits_the_servers_readable_body() { + for (what, message) in [ + ("plain", "x".repeat(50_000)), + ("quotes and newlines", "\"line\"\n".repeat(10_000)), + ("control characters", "\u{1b}[31m".repeat(10_000)), + ( + "Windows paths", + r"C:\Users\dev\project\node_modules\".repeat(2_000), + ), + ("wide characters", "错误:补丁".repeat(10_000)), + ] { + // Four times the patch cap: as large as an event gets. + let event = rollback_failure(MAX_REPORTED_PATCHES * 4, message); + let body = serde_json::to_string(&event).unwrap(); + assert!( + body.len() <= MAX_EVENT_BYTES && body.chars().count() < 10_000, + "{what}: the event body is {} bytes", + body.len() + ); + // The event still says what failed and why. + let metadata = event.metadata.as_ref().unwrap(); + assert_eq!(metadata["error_code"], "vendor_state_write_failed"); + assert_eq!(metadata["outcomes"]["failed"], MAX_REPORTED_PATCHES * 4); + assert_eq!(metadata["patches_truncated"], true); + assert!( + !metadata["patches"].as_array().unwrap().is_empty(), + "{what}" + ); + let message = event.error.unwrap().message.unwrap(); + assert!(message.chars().count() >= MIN_ERROR_MESSAGE_CHARS, "{what}"); + } + } + + /// An event with room to spare is sent as built: its message cut to + /// the cap and no further, every patch named. Only one that would not + /// fit gives up more, and then the tail of its message before any + /// patch. + #[test] + fn an_event_that_fits_is_left_alone() { + let event = rollback_failure(5, "\"line\"\n".repeat(10_000)); + let message = event.error.as_ref().unwrap().message.as_ref().unwrap(); + assert_eq!(message.chars().count(), MAX_ERROR_MESSAGE_CHARS); + assert!(message.starts_with("\"line\"\n") && message.ends_with('…')); + let metadata = event.metadata.as_ref().unwrap(); + assert_eq!(metadata["patches"].as_array().unwrap().len(), 5); + assert!(metadata.get("patches_truncated").is_none()); + + // At the patch cap, a message this long does not fit beside the + // patches: the message is cut, the patches all stay. + let event = rollback_failure(MAX_REPORTED_PATCHES, "x".repeat(50_000)); + let message = event.error.as_ref().unwrap().message.as_ref().unwrap(); + assert!(message.chars().count() < MAX_ERROR_MESSAGE_CHARS); + assert!(message.chars().count() >= MIN_ERROR_MESSAGE_CHARS); + let metadata = event.metadata.as_ref().unwrap(); + assert_eq!( + metadata["patches"].as_array().unwrap().len(), + MAX_REPORTED_PATCHES + ); + assert!(metadata.get("patches_truncated").is_none()); + } + + #[test] + fn truncate_chars_cuts_on_a_character_and_only_when_too_long() { + assert_eq!(truncate_chars("short".to_string(), 10), "short"); + assert_eq!(truncate_chars("exactly10!".to_string(), 10), "exactly10!"); + assert_eq!( + truncate_chars("more than ten".to_string(), 10), + "more than…" + ); + // Multi-byte characters are counted, not their bytes. + assert_eq!(truncate_chars("ééééé".to_string(), 5), "ééééé"); + assert_eq!(truncate_chars("éééééé".to_string(), 5), "éééé…"); + } + #[test] fn test_build_telemetry_context() { let ctx = build_telemetry_context("apply"); diff --git a/crates/socket-patch-core/src/update/channel.rs b/crates/socket-patch-core/src/update/channel.rs index a9b94972b..4dfdfc176 100644 --- a/crates/socket-patch-core/src/update/channel.rs +++ b/crates/socket-patch-core/src/update/channel.rs @@ -56,21 +56,51 @@ pub struct ChannelEnv { read_yarn_config: bool, } +/// An environment variable naming a directory. Empty values count as +/// unset, matching the CLI-wide `env_non_empty` convention. +fn path_var(name: &str) -> Option { + std::env::var(name) + .ok() + .filter(|v| !v.is_empty()) + .map(PathBuf::from) +} + +/// `root` as [`detect_channel`] must see it: canonical, like the executable +/// path it is compared with. A home reached through a symlink, and every +/// Windows path (canonical paths there carry the `\\?\` prefix), would +/// otherwise never be a prefix of the executable's path, and a +/// `cargo install` would read as a standalone binary. +/// +/// A root that does not resolve is kept as it is: nothing is installed +/// under it. A relative one is kept too, so it goes on matching nothing +/// rather than being resolved against the working directory. +fn canonical_root(root: PathBuf) -> PathBuf { + if !root.is_absolute() { + return root; + } + std::fs::canonicalize(&root).unwrap_or(root) +} + impl ChannelEnv { - /// Snapshot the process environment. Empty values count as unset, - /// matching the CLI-wide `env_non_empty` convention. + /// Snapshot the process environment. pub fn from_env() -> Self { - fn path_var(name: &str) -> Option { - std::env::var(name) - .ok() - .filter(|v| !v.is_empty()) - .map(PathBuf::from) - } + Self::snapshot(crate::utils::cargo_home::cargo_home()) + } + + /// [`ChannelEnv::from_env`] from environment variables alone: cargo's + /// home is `CARGO_HOME` or `/.cargo`, and the user database is + /// never asked. For a caller that must not wait on a directory service + /// (the telemetry context). + pub fn from_env_vars() -> Self { + Self::snapshot(path_var("CARGO_HOME")) + } + + fn snapshot(cargo_home: Option) -> Self { ChannelEnv { - cargo_home: crate::utils::cargo_home::cargo_home(), - xdg_cache_home: path_var("XDG_CACHE_HOME"), - home: crate::utils::fs::home_dir(), - local_app_data: path_var("LOCALAPPDATA"), + cargo_home: cargo_home.map(canonical_root), + xdg_cache_home: path_var("XDG_CACHE_HOME").map(canonical_root), + home: crate::utils::fs::home_dir().map(canonical_root), + local_app_data: path_var("LOCALAPPDATA").map(canonical_root), yarn_global_folders: OnceLock::new(), read_yarn_config: true, } @@ -558,6 +588,61 @@ fn cargo_bin_dir(env: &ChannelEnv) -> Option { env.home.as_ref().map(|h| h.join(".cargo").join("bin")) } +#[cfg(all(test, unix))] +mod canonical_root_tests { + use super::*; + + /// A home reached through a symlink: the executable's canonical path + /// is under the real directory, so the root has to be canonical too + /// for a `cargo install` to be recognized. + #[test] + fn a_symlinked_home_still_names_its_cargo_bin() { + let tmp = tempfile::tempdir().unwrap(); + let real = tmp.path().join("data").join("home"); + std::fs::create_dir_all(real.join(".cargo").join("bin")).unwrap(); + let link = tmp.path().join("home"); + std::os::unix::fs::symlink(&real, &link).unwrap(); + let exe = real.join(".cargo").join("bin").join("socket-patch"); + std::fs::write(&exe, b"").unwrap(); + let exe = std::fs::canonicalize(&exe).unwrap(); + + let raw = ChannelEnv { + home: Some(link.clone()), + ..ChannelEnv::default() + }; + assert_eq!( + detect_channel(&exe, &raw), + InstallChannel::Standalone, + "the raw root is not a prefix of the canonical path" + ); + + let canonical = ChannelEnv { + home: Some(canonical_root(link.clone())), + ..ChannelEnv::default() + }; + assert_eq!(detect_channel(&exe, &canonical), InstallChannel::Cargo); + + // The same through CARGO_HOME. + let cargo_home = ChannelEnv { + cargo_home: Some(canonical_root(link.join(".cargo"))), + ..ChannelEnv::default() + }; + assert_eq!(detect_channel(&exe, &cargo_home), InstallChannel::Cargo); + } + + #[test] + fn a_root_that_does_not_resolve_or_is_relative_is_kept() { + let missing = PathBuf::from("/nonexistent-socket-patch-root/x"); + assert_eq!(canonical_root(missing.clone()), missing); + let relative = PathBuf::from("cache"); + assert_eq!( + canonical_root(relative.clone()), + relative, + "a relative root is not resolved against the working directory" + ); + } +} + /// Cache roots the pre-v5 gem launcher resolved, in its probe order: /// `$XDG_CACHE_HOME`, `~/.cache`, `%LOCALAPPDATA%`, and the launcher's /// Windows fallback when LOCALAPPDATA is unset — `~/AppData/Local` diff --git a/docs/configuration.md b/docs/configuration.md index 5c25ead05..30123819e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -76,7 +76,8 @@ files, and repository files cannot set credentials, API endpoints, or safety opt ## Telemetry Telemetry is on by default. Each command reports its outcome to Socket as one -JSON event (two for a `scan` or `get` that also applies patches). +JSON event (up to three for a `scan` or `get` that also downloads and applies +patches). ### What is sent @@ -90,29 +91,52 @@ Every event has these fields: | `context.version` | The Socket Patch version | | `context.platform`, `context.arch` | Operating system and CPU architecture (for example `linux`, `x86_64`) | | `context.command` | The subcommand (`scan`, `apply`, …) | +| `context.channel` | How this copy of Socket Patch was installed: `npm`, `cargo`, `homebrew`, `pypi` or `launcher_cache` when the binary sits where that tool puts it, and `standalone` for anywhere else (the install script, a downloaded binary, a container image). It names the channel only, never the path, and is left out when the binary cannot read its own location | | `metadata` | The per-event fields in the table below, and nothing else | -| `error.type`, `error.message` | Failure events only. URLs in the message are redacted (credentials, grant tokens, signed query values) and your home directory is replaced by `~`. The message can still quote a package name or a path in the project | +| `error.type`, `error.message` | Failure events only. URLs in the message are redacted (credentials, grant tokens, signed query values), your home directory is replaced by `~`, and a message longer than 1,000 characters is cut. The message can still quote a package name or a path in the project | | Command | Event on success | Event on failure | `metadata` fields | | --- | --- | --- | --- | -| `scan` | `patch_scanned` | `patch_scan_failed` | `packages_scanned`, `free_patches`, `paid_patches`, `can_access_paid`, `ecosystems` (names such as `npm`, not packages), `fallback_to_proxy`, `mode`, `project_modes` | -| `scan` / `get` in hosted mode | `patch_applied` | `patch_apply_failed` | `mode` (`hosted`), `patches_count`, `files_count`, `dry_run` | -| `apply`, and `scan` / `get` in agent mode | `patch_applied` | `patch_apply_failed` | `mode` (`agent`), `patches_count`, `dry_run` | -| `vendor`, and `scan` / `get` in vendored mode | `patch_vendored` | `patch_vendor_failed` | `patches_count`, `dry_run` | -| `get` | `patch_fetched` | `patch_fetch_failed` | `uuid` (the patch UUID), `tier`, `ecosystem`, `download_mode`, `fallback_to_proxy` | -| `remove` | `patch_removed` | `patch_remove_failed` | `removed_count` | -| `rollback` | `patch_rolled_back` | `patch_rollback_failed` | `rolled_back_count` | +| `scan` | `patch_scanned` | `patch_scan_failed` | `packages_scanned`, `free_patches`, `paid_patches`, `can_access_paid`, `ecosystems` (names such as `npm`, not packages), `packages_by_ecosystem` and `patches_by_ecosystem` (counts per ecosystem name), `fallback_to_proxy`, `mode`, `project_modes`, `dry_run` | +| `scan` / `get` in hosted mode | `patch_applied` | `patch_apply_failed` | `mode` (`hosted`), `patches_count`, `files_count`, `dry_run`, and the [patches](#patches-named-in-an-event) | +| `apply`, and `scan` / `get` in agent mode | `patch_applied` | `patch_apply_failed` | `mode` (`agent`), `patches_count`, `dry_run`, and the patches | +| `scan` / `get ` in agent mode | `patch_fetched` | — | `mode` (`agent`), `patches_count` (patch records downloaded), `download_mode`, and the patches | +| `vendor`, and `scan` / `get` in vendored mode | `patch_vendored` | `patch_vendor_failed` | `mode` (`vendored`), `patches_count`, `dry_run`, and the patches | +| `get ` | `patch_fetched` | `patch_fetch_failed` | `uuid` (the patch UUID), `tier`, `ecosystem`, `mode`, `patches_count`, `download_mode`, `fallback_to_proxy` | +| `remove`, and `vendor --revert` | `patch_removed` | `patch_remove_failed` | `removed_count`, and the patches. A `--dry-run` sends nothing | +| `rollback` | `patch_rolled_back` | `patch_rollback_failed` | `rolled_back_count`, `dry_run`, `targeted` (you named the patches to roll back, rather than rolling the project back), and the patches | | `list` | `patch_listed` | — | `patches_count` | | `repair` | `patch_repaired` | `patch_repair_failed` | `blobs_added`, `blobs_removed`, `bytes_freed` | | `vex` | `vex_generated` | `vex_failed` | `advisories_count`, `format`, `output_kind` | | `--update` | `cli_updated` | `cli_update_failed` | `from_version`, `to_version`, `channel`, `pinned`, `forced`; on failure `error_code` | -A failure event carries the subset of its row's fields known when it failed; -`patch_fetch_failed` reports `uuid` only when you asked for a patch by UUID. +A `scan` reports once for each project directory it scans. A failure event +carries the subset of its row's fields known when it failed, plus `error_code`: +the code the command's `--json` output reports (for example `patch_not_found` +or `rollback_failed`). `patch_fetch_failed` reports `uuid` only when you asked +for a patch by UUID. A command that stops on a usage error, or because another +run holds the lock, reports nothing. -An event carries no dependency list, no file contents, and no machine -identifier. The HTTP request has a `User-Agent` of `SocketPatchCLI/` -and, like any request, shows the server your IP address. +#### Patches named in an event + +An event about specific patches names them, so that Socket can see when one +patch fails to apply, or is rolled back, far more often than the others: + +| Field | Value | +| --- | --- | +| `patches` | Up to 50 entries, failed ones first. Each is `{uuid, ecosystem, mode, outcome}`: the patch UUID, the ecosystem name (`npm`, `pypi`, …), the mode it was patched in (`agent`, `hosted`, `vendored`), and what the run did (`applied`, `downloaded`, `rolled_back`, `removed`, `verified` on a dry run, `skipped`, `failed`). A `skipped` or `failed` entry adds `code`, the reason code `--json` reports (for example `already_patched`) | +| `patches_truncated` | `true` when the run acted on more than 50 patches | +| `outcomes` | How many patches ended each way, over the whole run | +| `ecosystems`, `modes` | The distinct ecosystems and modes of those patches | + +A patch UUID is Socket's identifier for one patch, and each patch is for one +version of one package, so these entries tell Socket which patched package +versions the run acted on. They hold no package name, path, or file list. + +Other than that, an event carries no dependency list, no file contents, and no +machine identifier. The HTTP request has a `User-Agent` of +`SocketPatchCLI/` and, like any request, shows the server your IP +address. ### Where it goes