Skip to content

Commit 5d8378e

Browse files
Route hosted pnpm pins through one named registry per patch (#2167)
* Route hosted pnpm pins through one named registry per patch On pnpm 11.20 and newer, hosted mode now has pnpm verify each patched package against the patch server instead of trusting the whole lock, and keeps the patch installed when pnpm resolves again. What the scan writes. Each patch gets its own named registry in pnpm-workspace.yaml, `socket-<first 8 hex digits of the patch UUID>`, whose address is the directory the patch's tarball is served from (the grant's `npmRegistryUrl`, used verbatim). An override routes the patched release to it (`'name@version': 'socket-<id>:version'`), and every governing pnpm-lock.yaml is rewritten to exactly what pnpm writes for that: the `overrides:` record, `name@socket-<id>:version` keys and references, importer specifiers. No `trustLockfile` is written. - A name that is taken (two patches sharing eight digits, or a registry of the user's) takes four more digits at a time. - A registry is the CLI's only by its name together with its address, a patch's directory on a patch server; everything else under `namedRegistries` and `overrides` is the user's and is never touched. A lock key under a registry the user named `socket` is not read as a hosted release. - The route is taken only when every hosted pin has an address and the project's pnpm pins prove 11.20; otherwise the whole lock stays on `trustLockfile` and the warning names the packages or the reason. A run granted only part of the project's patches leaves the rest routed. A pin on a patch mirror stays on `trustLockfile`. - Lock shapes pnpm does not lock as a respelling stay on `trustLockfile`: a package installed with and without the patched release as its peer, a patched optional peer, and a routed release with a multi-paragraph deprecation message. - A patch replaced by a newer one has a new UUID, so its registry is renamed and the release's lock keys with it. - An override holds every dependency whose range admits the patched version. When a governing lock also holds a newer release in that range, the scan notes that pnpm may move its dependents to the patched one the next time it resolves. Cleanup. Nothing of the route outlives its use, per patch: the registry, the override, the lock's record and the registry-form keys go together. Every hosted scan reconciles them; `repair` and `scan --prune` do it offline from the files alone; `rollback`, `remove` and a switch to vendored mode take a restored package's entries with it. Each removal is reported (`registry_entry_unused`, `gc.removedRegistryEntries`), a dry run lists the same and writes nothing, and a pnpm-workspace.yaml a run created is deleted once nothing else is in it. A registry address is never printed. - The workspace overrides and the lock's record change together. A lock that cannot be read, or member locks that cannot be listed, keep the route whole: leaving the route does nothing and rollback refuses the pin. - With `--no-trust-lockfile-config`, a routed release stays on the patch it is routed to (`redirect_pnpm_registry_held`). - On a patch server the run was not told about, a cleanup leaves such registries alone and says so (`registry_cleanup_unknown_host`). The lock rewrite is pinned byte for byte to real pnpm by golden fixtures (scripts/gen-pnpm-registry-override-golden.mjs), generated with pnpm 12.22.0 and identical on 11.20.0 through 12.21.0. Real-pnpm e2e legs cover frozen installs, `pnpm add` / `update` / `dedupe` / `install --fix-lockfile`, a newer release in range, and every cleanup. Shapes written by unreleased builds of this branch are converted or removed by the next scan. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Keep a route the members' own pnpm locks still use A hosted scan that selects no patch tidies what is left of the pnpm registry route. In a workspace that keeps one lock per member (sharedWorkspaceLockfile: false) it read the root lock alone, which holds no patched package, so it took the registries and the overrides out of pnpm-workspace.yaml while the members' locks still routed their releases through them. pnpm then refused those locks. Such a run now reads the members' own locks whenever the root files name a route, as a run with a patch does, so an entry goes only when no lock of the workspace uses it. A test holds both: nothing changes while a member routes the release, and the route goes whole once none does. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Keep a pnpm lock that a Bazel hub reads off the registry route Hosted mode routes a patched pnpm release through a named registry of pnpm-workspace.yaml when the patch service offers one and the project pins pnpm 11.20 or later. A rules_js hub of a Bazel workspace reads the same lock with its own lock reader, and with update_pnpm_lock with a pnpm that sees the workspace file only where the call lists it. Run as the hub runs it, without that file, pnpm 11.28.13 and 12.22.0 reject a routed lock (ERR_PNPM_MISSING_NAMED_REGISTRY), and no Bazel build has been run on a routed lock. A scan that exits 0 must not leave a build that fails. So a lock that an npm.npm_translate_lock names (or may name: a pnpm_lock that is not a plain string) is never routed. The project is pinned exactly as on a patch service that offers no registry, which is the pin the Bazel legs build, and the warning names the call. A project routed before the hub was there leaves the route whole on its next scan, the locks and the workspace file together. Where the hub also hides the workspace file from a pnpm 11, main's answer comes first, while the files are read, and the root lock is not part of the run. The route then changes nothing at all: the members' own locks are pinned on trustLockfile, and a route of an earlier run stays as it is in the workspace file and in every lock, because the root lock records the same overrides and is not written. Taking the entries out of the file alone would have left a lock pnpm refuses. A pnpm-workspace.yaml that holds nothing but a route and that the hub lists now counts as a file that holds only what hosted mode writes: the scan that leaves the route would turn it into the file rollback removes, and the call would name a missing file. repair, scan --prune with no mode, rollback and remove settle a route from the lockfiles alone and pin nothing; tests hold them to the same result with and without the hub. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Say what holds the pnpm route back in a Bazel workspace The warning of a project whose pnpm lock a rules_js hub reads had runs of spaces in it, and it and the docs said that no Bazel build had been run on a routed lock. One has now: rules_js 3.6.0 on Bazel 9.3.2 builds a routed lock for a hub without update_pnpm_lock, with the patched bytes in the built packages, and rules_js 2.9.3 on Bazel 8.8.2 does too. The warning, the module docs and the docs now say what was measured and what holds the route back: the pnpm a hub runs with update_pnpm_lock sees pnpm-workspace.yaml only where the call lists it and may be older than pnpm 11.20, and no Bazel leg builds a routed lock that way yet. The rule is unchanged: a lock that a hub reads keeps the trustLockfile pin. A real-pnpm leg holds the project that was routed before its hub was added, on pnpm 11.20.0 and 12.22.0. Where the hub hides the workspace file from a pnpm 11, the scan changes neither file. Where the hub only reads the lock, the scan takes the registry, the override, the lock's record and the registry keys out in one run and pins the release. A frozen install from an empty store lands the patched bytes after either. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Never wait on a FIFO when deleting an emptied pnpm workspace file A hosted scan that takes the last of a registry route out of a pnpm-workspace.yaml it created deletes the file, after checking that it is still the regular file the run wrote. The check of what is at the path and the read were two steps, and the read was a plain one: a FIFO or a device put there in between made the command wait in open(2) with no timeout. The read now goes through the opener every other project file is read with, which never blocks and refuses what the opened handle shows is no regular file. A test holds the read to that with a FIFO at the path (it waited out its five seconds before), and another holds the step as a whole: the file the run wrote goes, a changed file, a link and a FIFO stay with the reason. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Find what a pnpm route left in a member's own lock repair, scan --prune and a hosted scan that crawls no package tidy what is left of the pnpm registry route only where a probe says the project holds some of it. The probe read the root pnpm-workspace.yaml and the root lock alone. In a workspace that keeps one lock per member (sharedWorkspaceLockfile: false), a member's lock can be the only file that still records an override of the route, and pnpm then refuses a frozen install of that member. The three commands did nothing there, and repair answered manifest_not_found. The probe now reads the members' own locks too, and a hosted scan that is granted nothing reads them on the same answer. In the golden workspace with the route taken out by hand everywhere but in one member's lock, each of the three takes the unused record out and the project is the one pnpm locked, byte for byte. A release that a member's lock still keys by a registry is no leftover: none of these commands restores a pin. It stays, and a hosted scan that is granted the patch puts the whole route back around it. Tests hold both. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Ask in one place whether a pnpm lock holds a route "This lock keys a release by a registry of ours, or records an override that routes one there" was written out four times: in the probe of what a route left behind, where a scan decides whether a project was routed, where it takes a route back out, and in the offline sweep. OverrideLock::holds_route() is that question now, and the four ask it. No behaviour changes. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Read what Bazel says of the pnpm locks once, with the files The plan of the pnpm registry route asked the Bazel workspace itself whether a hub reads a lock: a walk to the git root and a second parse of MODULE.bazel, synchronously, inside the planner, on every pass. And it took any refusal of the root pnpm lock for the Bazel one, so the route was blocked there only because the two readings happened to agree. The workspace is now read once, where the files are read and off the async runtime, and that one read answers both questions: whether a hub keeps the root lock out of the run, and whether one reads a lock. The answers travel with the files (CandidateFiles::pnpm_bazel), and the planner is a function of what was read. A root lock that a hub keeps out of the run blocks the route by that answer alone, with a reason of its own, and a pnpm refusal of another kind is no longer read as it. judge and the reader share one helper for the lock a hub call names. No run changes its files: a test holds the plan to the carried answer on a checkout with no Bazel file at all. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Take the pnpm route only where no Bazel hub can read the lock A scan routed a pnpm lock through a named registry in a Bazel workspace whenever no npm.npm_translate_lock call that it had read named the lock. A hub it could not see reads the lock all the same: one that a WORKSPACE file defines, one in a file that MODULE.bazel includes and that is missing or was not handed to the in-memory engine, one behind a use of the extension that is not a plain call. The pnpm such a hub runs would reject or rewrite the routed lock. The answer for a pin passes over what it cannot see, so that no project loses a patch. Declining the route costs nothing, the project gets the pin it gets today, so here doubt decides: the reader's doubts about the workspace or about the hub's tags, and a WORKSPACE file that says more than workspace(...), each keep the project off the route, and the warning names what was not read. A pnpm_lock that is no label counts as one that may be any lock. The in-memory engine now asks for the same Bazel files beside a pnpm lock as beside a gem lock (MODULE.bazel, the files it can include and the WORKSPACE files), so that it gives the answer of a checkout. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Say where a Bazel hub's call is for a project below the root The warning of a pnpm project that stays off the registry route named the hub's call as `MODULE.bazel:7`. For a project in a directory of the Bazel workspace that file is at the workspace's root, and a run in the project's directory has no file of that name beside it. The warning now says that its paths are from the root of the Bazel workspace, as the warning for a lock that is left to the hub does, for a call and for what could not be read alike. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Leave a lock to its Bazel hub whatever the scan was granted A hosted scan that is granted an npm patch asks the Bazel workspace about the pnpm lock, and where a hub would fail on a pin it leaves the root lock and pnpm-workspace.yaml alone. A scan granted no npm patch did not ask. In a project routed before the hub was added it took the unused entries of the route out of the lock and the workspace file, and with the last of them deleted the file a hub lists in its data, so the next bazel build failed on a missing file. Whether that happened turned on an unrelated patch being granted. Both no-patch paths now give the answer of a run with a patch: the scan that crawls packages and is granted nothing asks Bazel where the files are read, and the scan that crawls nothing asks before its sweep of the lockfiles. Each leaves the files and reports redirect_pnpm_bazel_workspace_hidden. A project that holds nothing of a route is still read no Bazel file for. repair and scan --prune without a mode are unchanged: they settle a route from the lockfiles alone. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Add no trustLockfile to a route that is left as it is Where a Bazel hub keeps the root pnpm lock out of a run, the members' own locks that an earlier run routed stay routed, and the run reported the route as left as it is. It still wrote `trustLockfile: true` to pnpm-workspace.yaml: the routed entries carry the patch server's tarball, and the run took that for a pin that needs the key. The key switched pnpm's verification off for the whole lock of a project that was still on per-package registries, in a run that wrote no lock. Such a run now writes nothing to the workspace file, which is byte for byte what it was, and says that the route stays instead of that the patches rely on trustLockfile. A release the run pins in the plain shape beside the routed ones still brings the key, which that pin needs. The test asserted a prefix of the file and so passed over the appended line; it now holds the run to no file and no edit. Where a route stays because a lock could not be converted back, the project no longer qualifies for it, and the key is still written as the fallback, as before. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Ask once, and cheaply, whether a pnpm project holds a route Every hosted scan, repair and scan --prune first asks whether the project holds anything of the pnpm registry route. Since that question looks in the members' own locks, it was expensive for a workspace that keeps one lock per member and never had a route: every call globbed the members and parsed each of their locks in full, the hosted scan asked whether or not the answer could matter, and a --prune pass asked again before its sweep. A scan granted nothing then listed the members and read their locks a second time. Now a lock is parsed only when its bytes name a route, the workspace file settles the question for a routed project before any lock is read, and a project without a workspace file lists no members. A hosted scan asks only when it selects no patch or was told to prune, each GC pass asks once and its sweep reuses the answer, and a scan granted nothing lists the members once for the question and for the read. A test holds the cheap test to the parsed answer on every lock of the golden projects, routed and not. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Check the emptied pnpm workspace file once, on the handle The step that deletes an emptied pnpm-workspace.yaml looked at the path, and then read it through a one-line function that existed only so that a test could call the read past that look. The look is now for a link alone, which is never followed or removed in the file's place. What else is at the path is settled by the opener itself, on the handle it opened: a FIFO or a device is refused there without a wait, and nothing stands between the check and the read. The test drives the whole step with a FIFO at the path under a timeout. Against a plain read it waits the timeout out and fails. The MODULE.bazel of a hub was written out in two test modules of the core crate; they share one fixture now. The copies in the CLI's integration tests stay: each of those files is a crate of its own. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Hold the pnpm route's Bazel rule on a real Bazel build Hosted mode does not route a pnpm lock through a named registry where a rules_js hub reads the lock. Nothing that runs a Bazel checked it: the stand-in patch service of the Bazel npm flows offered no registry, so the route was never in question there. The hosted flow on real Bazel now has both things the route asks for. Its patch service offers the patch's registry, and the checkout carries pnpm 12's mark in node_modules, which Bazel does not read. The flow's own assertions then say what the rule says: the lock is pinned on trustLockfile with the package under its plain key, the warning names the hub's call, and the Bazel build of that pin is the patched one. A test without a Bazel runs the flow's other steps on the same arrangement (the scan and its documents, the second scan, the undo), and shows that the same files in a checkout that is no Bazel workspace are routed, so the offer is live and the hub is what decides. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Test the empty hosted scan with a stale Bazel entry and a pnpm route The merge of main left two things in the hosted scan that crawls nothing: main's sweep of a stale entry of the Bazel workspace's block, and the cleanup of what a pnpm registry route left. The test puts both in one project and holds the run to both: the entry leaves the block, the route's three entries leave the lock and the workspace file, and the envelope carries the event of each and names the route's files as what the run rewrote. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Hand the in-memory engine the Bazel files of a lockless pnpm root The in-memory engine was handed the Bazel files of a workspace only beside a root pnpm-lock.yaml. A workspace that keeps one lock per member can have none, and a hub can read a member's own lock: on disk such a lock is kept off the registry route, and in memory, where MODULE.bazel and WORKSPACE were never fetched, it was routed. Path selection now asks for those files beside a pnpm-workspace.yaml as well, which is what marks such a root. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Keep an emptied pnpm workspace file under a hub that reads a lock A hosted scan that takes the last of a registry route out of a pnpm-workspace.yaml it created deletes the file. Under a Bazel hub that reads the pnpm lock and lists that file in its data, the next build would be handed a missing file. A scan with no npm patch did this where the hub reads the lock but runs no pnpm of its own, the one case in which the lock is not left to the hub altogether. A hosted scan now deletes the file only where no hub reads, or may read, a lock of the project. Under such a hub the unused entries still go and the file stays as the `packages` list it was created with. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Decide in one place whether a hosted scan leaves a lock to Bazel A hosted scan that crawls nothing asked whether a Bazel hub would fail on a pin in the root pnpm lock without looking for that lock. The scan that crawls a package asks the same and drops the answer where the project has no root lock, as a workspace with one lock per member can. So in such a workspace the two disagreed: the first tidied what a route had left in a member's lock, and the second left it and said that a pnpm-lock.yaml which does not exist "was not rewritten". The rule now sits with the answer itself: a project with no pnpm lock is asked nothing, and one without a root lock has no lock to leave to a hub. Both paths go through it, with the root lock read the same way. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Let a WORKSPACE file that is about something else leave the route be Any WORKSPACE file that said more than workspace(...) kept a pnpm project off the registry route, as a place where a rules_js hub might be defined unseen. A Bazel 8 or 9 repository that keeps such a file for an unrelated http_archive has no hub there. The file now counts only where it cannot be read or brings in rules_js: a load from @aspect_rules_js, a load of npm_translate_lock from anywhere, or a call of that rule under its own name or one a load gives it. That is how the other rulesets' lanes read the file. The warning names the line. A macro of a .bzl file that makes the call is not looked at, as there. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Count the root lock when a kept pnpm route is asked for trust Where a Bazel hub keeps the root pnpm lock out of a run and the members' locks stay routed, the run writes no trustLockfile when every hosted entry is under a key of its registry. It asked that of the locks it had read, which leaves out the very lock the hub withholds. A plain hosted pin there, from before the hub was added, is one that pnpm takes only with the key: the run reported the project as settled on its registries, wrote nothing, and pnpm 11 would reject that entry. The withheld root lock is now read for this one question and counted with the others, so such a project gets the key as it did before. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Look at the emptied pnpm workspace file again before unlinking it The step that deletes an emptied pnpm-workspace.yaml refuses a link at the path, then reads the file through an opener that follows links, then unlinks the path. Its comment said that a link is never removed in the file's place. A link that took the file's place between the look and the read, to a file with the same bytes, was read through and then unlinked. The path is now looked at once more after the read, and only what is a regular file at that look is unlinked. The comment says what the code does, and what it cannot: there is no unlink by handle, so the last look and the unlink are still two steps. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> * Say what the offline commands and the in-memory engine do not see Two limits of the pnpm registry route in a Bazel workspace were true of the code and missing from the docs. repair, scan --prune without a mode, rollback and remove read no Bazel file. Under a hub whose data lists a pnpm-workspace.yaml that a routed scan created, they still delete that file with the last of the route, and the build is then handed a missing file. The docs now say so where those commands are described, with the way round it. The route is taken "only where it is certain that no hub reads the lock". In memory that is certain of the files the engine was handed, and a Bazel root above the project is not among them, for the route as for the pin. The docs and the module docs say that beside the claim. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
1 parent fab1270 commit 5d8378e

198 files changed

Lines changed: 26553 additions & 2800 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎crates/socket-patch-cli/CLI_CONTRACT.md‎

Lines changed: 62 additions & 17 deletions
Large diffs are not rendered by default.

‎crates/socket-patch-cli/src/args.rs‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -325,13 +325,15 @@ pub struct GlobalArgs {
325325
pub no_telemetry: bool,
326326

327327
/// Hosted mode (`scan`/`get --mode hosted`): do NOT auto-configure
328-
/// `trustLockfile: true` in pnpm-workspace.yaml after a pnpm-lock.yaml
329-
/// (lockfileVersion >= 9) is repointed at the hosted patch server.
330-
/// pnpm >= 11 rejects the repointed lock without that trust grant, so
331-
/// opting out means every install needs `pnpm install --trust-lockfile`
332-
/// instead (the run's warning spells out both recoveries). Only
333-
/// hosted-mode `scan` and `get` read this; other subcommands accept it
334-
/// silently.
328+
/// pnpm-workspace.yaml after a pnpm-lock.yaml (lockfileVersion >= 9) is
329+
/// repointed at the hosted patch server. The run otherwise declares the
330+
/// patch server's registry of each patched package (`namedRegistries`)
331+
/// and routes the package to it (`overrides`), or sets
332+
/// `trustLockfile: true` where that does not apply. pnpm >= 11 rejects
333+
/// the repointed lock without one of them, so opting out means setting
334+
/// `trustLockfile: true` yourself or installing with
335+
/// `pnpm install --trust-lockfile`. Only hosted-mode `scan` and `get`
336+
/// read this; other subcommands accept it silently.
335337
#[arg(
336338
help_heading = GLOBAL_OPTIONS,
337339
long = "no-trust-lockfile-config",

‎crates/socket-patch-cli/src/commands/mod.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ pub(crate) mod lock_cli;
1212
pub(crate) mod measured;
1313
pub(crate) mod projects_below;
1414
pub(crate) mod pypi_reinstall;
15+
pub(crate) mod registry_gc;
1516
pub mod remove;
1617
pub mod repair;
1718
pub mod report;
Lines changed: 318 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,318 @@
1+
//! Cleanup of hosted mode's pnpm registry route: the entries of it that no
2+
//! lockfile uses any more (the registry of a patch, the `overrides` entry
3+
//! of pnpm-workspace.yaml that routes its release, that override's record
4+
//! in a lock). A helper module, not a command.
5+
//!
6+
//! A hosted scan takes them out as part of its rewrite and reports them
7+
//! through [`record`]. `repair`'s cleanup phase and the `--prune` pass of a
8+
//! scan in another mode reconcile with [`sweep`], from the project's files
9+
//! alone: no patch service or registry is asked.
10+
11+
use socket_patch_core::hosted::guidance::RegistryEntry;
12+
use socket_patch_core::patch::redirect::upstream::{sweep_pnpm_registry_route, RestoreOptions};
13+
14+
use crate::args::GlobalArgs;
15+
use crate::json_envelope::{Envelope, PatchAction, PatchEvent};
16+
17+
/// `errorCode` of the `removed` (`verified` on a dry run) event of each
18+
/// entry taken out.
19+
pub(crate) const REGISTRY_ENTRY_UNUSED: &str = "registry_entry_unused";
20+
21+
/// Warning: the project's pnpm locks or its workspace file could not be
22+
/// read to tell what still uses the route; nothing was removed.
23+
pub(crate) const REGISTRY_CLEANUP_SKIPPED: &str = "registry_cleanup_skipped";
24+
25+
/// Warning: the cleaned files could not be written; they are as they were
26+
/// (or the detail names each one that is not).
27+
pub(crate) const REGISTRY_CLEANUP_FAILED: &str = "registry_cleanup_failed";
28+
29+
/// Warning: the workspace file declares registries in the shape of a
30+
/// patch's registry on a host the run was not given as a patch server.
31+
/// They were left alone, so nothing of them was tidied; the detail names
32+
/// the host and the setting that lets the command tidy them.
33+
pub(crate) const REGISTRY_CLEANUP_UNKNOWN_HOST: &str = "registry_cleanup_unknown_host";
34+
35+
/// The [`REGISTRY_CLEANUP_UNKNOWN_HOST`] detail for `count` registries on
36+
/// `origin` (`http(s)://host[:port]`). The origin is all of an address
37+
/// that is ever shown: the rest holds a grant's token.
38+
fn unknown_host_detail(origin: &str, count: usize) -> String {
39+
let (registries, were, those, them) = match count {
40+
1 => (
41+
"1 pnpm registry of a hosted patch".to_string(),
42+
"was",
43+
"that registry",
44+
"it",
45+
),
46+
count => (
47+
format!("{count} pnpm registries of hosted patches"),
48+
"were",
49+
"those registries",
50+
"them",
51+
),
52+
};
53+
format!(
54+
"{registries} on {origin} {were} left alone: this run was not given that host as a \
55+
patch server, so it cannot tell {those} from the project's own; pass \
56+
`--patch-server-url {origin}` (or set SOCKET_PATCH_SERVER_URL) to let this command \
57+
tidy what no lockfile uses of {them}"
58+
)
59+
}
60+
61+
/// What a [`sweep`] did.
62+
#[derive(Debug, Default)]
63+
pub(crate) struct RegistryGc {
64+
/// The entries removed (on a dry run: that would be). Empty when the
65+
/// files could not be written.
66+
pub(crate) entries: Vec<RegistryEntry>,
67+
/// Root-relative files rewritten or deleted (or that would be).
68+
pub(crate) files: Vec<String>,
69+
pub(crate) warnings: Vec<(&'static str, String)>,
70+
}
71+
72+
/// Whether the project holds anything of a registry route: asked before a
73+
/// lock is taken for a [`sweep`], so a project without one never gains a
74+
/// `.socket/`.
75+
pub(crate) async fn route_present(common: &GlobalArgs) -> bool {
76+
!common.is_global()
77+
&& socket_patch_core::hosted::engine::pnpm_route_present(&common.project_root()).await
78+
}
79+
80+
/// [`route_present`], asked at most once by the pass that holds it. The
81+
/// question lists the members of a workspace and reads their locks, and
82+
/// its answer does not change between the check that keeps a project
83+
/// without a route free of a `.socket/` and the sweep the check is for.
84+
#[derive(Debug, Default)]
85+
pub(crate) struct RouteProbe(Option<bool>);
86+
87+
impl RouteProbe {
88+
pub(crate) async fn present(&mut self, common: &GlobalArgs) -> bool {
89+
match self.0 {
90+
Some(known) => known,
91+
None => *self.0.insert(route_present(common).await),
92+
}
93+
}
94+
}
95+
96+
/// Take the unused entries of the project's registry route out of its
97+
/// pnpm-workspace.yaml and pnpm locks (`dry_run`: say what would go).
98+
/// A wet sweep runs under the caller's apply lock. A global-scope run has
99+
/// no project lockfiles to judge by and sweeps nothing.
100+
pub(crate) async fn sweep(common: &GlobalArgs, dry_run: bool) -> RegistryGc {
101+
if common.is_global() {
102+
return RegistryGc::default();
103+
}
104+
let opts = RestoreOptions {
105+
dry_run,
106+
offline: true,
107+
patch_server_origins: crate::commands::hosted_unwind::patch_server_origins(common),
108+
bun_lockb: false,
109+
};
110+
let swept = sweep_pnpm_registry_route(&common.project_root(), &opts).await;
111+
let mut out = RegistryGc::default();
112+
if let Some(why) = swept.unread {
113+
out.warnings.push((
114+
REGISTRY_CLEANUP_SKIPPED,
115+
format!(
116+
"the pnpm registry entries of hosted patches were not checked for unused \
117+
ones: {why}"
118+
),
119+
));
120+
return out;
121+
}
122+
out.warnings
123+
.extend(swept.unknown_hosts.iter().map(|(origin, count)| {
124+
(
125+
REGISTRY_CLEANUP_UNKNOWN_HOST,
126+
unknown_host_detail(origin, *count),
127+
)
128+
}));
129+
if let Some(why) = swept.flush_error {
130+
out.warnings.push((
131+
REGISTRY_CLEANUP_FAILED,
132+
format!("unused pnpm registry entries of hosted patches were not removed: {why}"),
133+
));
134+
out.files = swept.half_applied;
135+
return out;
136+
}
137+
out.entries = socket_patch_core::hosted::guidance::pnpm_registry_entries_removed(&swept.edits);
138+
out.files = swept.files;
139+
out
140+
}
141+
142+
/// The event of one removed entry: artifact-level (no `purl`), `removed`
143+
/// or, on a dry run, `verified`. A registry's address carries its grant's
144+
/// token, so it is not in the event.
145+
fn event(entry: &RegistryEntry, dry_run: bool) -> PatchEvent {
146+
let mut details = serde_json::json!({
147+
"mode": crate::commands::HOSTED_MODE_LABEL,
148+
"file": entry.file,
149+
"entry": entry.kind.as_str(),
150+
"key": entry.key,
151+
});
152+
if let Some(value) = entry.shown_value() {
153+
details["value"] = value.into();
154+
}
155+
let action = if dry_run {
156+
PatchAction::Verified
157+
} else {
158+
PatchAction::Removed
159+
};
160+
PatchEvent::artifact(action)
161+
.with_reason(
162+
REGISTRY_ENTRY_UNUSED,
163+
format!("{}: no lockfile uses it any more", entry.describe()),
164+
)
165+
.with_details(details)
166+
}
167+
168+
/// Report the removed entries in `env`, one event each. Pushed directly,
169+
/// as the GC carrier event is: the `summary` counters count patches.
170+
pub(crate) fn record(env: &mut Envelope, entries: &[RegistryEntry], dry_run: bool) {
171+
env.events
172+
.extend(entries.iter().map(|entry| event(entry, dry_run)));
173+
}
174+
175+
/// The human lines for the removed entries: a headline, then one line per
176+
/// entry. Empty when nothing was removed.
177+
pub(crate) fn lines(entries: &[RegistryEntry], dry_run: bool) -> Vec<String> {
178+
if entries.is_empty() {
179+
return Vec::new();
180+
}
181+
let count = crate::ui::plural(
182+
entries.len(),
183+
"pnpm registry entry",
184+
"pnpm registry entries",
185+
);
186+
let headline = if dry_run {
187+
format!("Would remove {count} that no lockfile uses any more:")
188+
} else {
189+
format!("Removed {count} that no lockfile uses any more:")
190+
};
191+
std::iter::once(headline)
192+
.chain(
193+
entries
194+
.iter()
195+
.map(|entry| format!(" - {}", entry.describe())),
196+
)
197+
.collect()
198+
}
199+
200+
#[cfg(test)]
201+
mod tests {
202+
use super::*;
203+
use socket_patch_core::hosted::guidance::RegistryEntryKind;
204+
205+
fn entry(kind: RegistryEntryKind, key: &str, value: &str) -> RegistryEntry {
206+
RegistryEntry {
207+
file: "pnpm-workspace.yaml".into(),
208+
kind,
209+
key: key.into(),
210+
value: value.into(),
211+
}
212+
}
213+
214+
/// A registry's address carries the token of its grant: it reaches
215+
/// neither the envelope nor the terminal.
216+
#[test]
217+
fn a_registry_address_is_never_shown() {
218+
const TOKEN: &str = "9f6b2c4e-1d3a-4f6b-8c2d-7e5a9b1c3d5f";
219+
let address = format!(
220+
"https://patch.test/patch/npm/left-pad/1.3.0/{TOKEN}/11111111-1111-4111-8111-111111111111/"
221+
);
222+
let entries = [
223+
entry(RegistryEntryKind::Registry, "socket-11111111", &address),
224+
entry(
225+
RegistryEntryKind::Override,
226+
"left-pad@1.3.0",
227+
"socket-11111111:1.3.0",
228+
),
229+
];
230+
let mut env = Envelope::new(crate::json_envelope::Command::Repair);
231+
record(&mut env, &entries, false);
232+
let json = env.to_pretty_json();
233+
assert!(!json.contains(TOKEN), "{json}");
234+
let shown = lines(&entries, false).join("\n");
235+
assert!(!shown.contains(TOKEN), "{shown}");
236+
assert_eq!(
237+
shown,
238+
"Removed 2 pnpm registry entries that no lockfile uses any more:\n \
239+
- namedRegistries entry `socket-11111111` of pnpm-workspace.yaml\n \
240+
- overrides entry `left-pad@1.3.0` of pnpm-workspace.yaml"
241+
);
242+
// One artifact-level event per entry, counted by no summary field.
243+
let value = env.to_value();
244+
assert_eq!(value["summary"]["removed"], 0);
245+
assert_eq!(
246+
value["events"][1],
247+
serde_json::json!({
248+
"action": "removed",
249+
"errorCode": "registry_entry_unused",
250+
"reason": "overrides entry `left-pad@1.3.0` of pnpm-workspace.yaml: \
251+
no lockfile uses it any more",
252+
"details": {
253+
"mode": "hosted",
254+
"file": "pnpm-workspace.yaml",
255+
"entry": "override",
256+
"key": "left-pad@1.3.0",
257+
"value": "socket-11111111:1.3.0",
258+
},
259+
})
260+
);
261+
assert_eq!(
262+
value["events"][0]["details"],
263+
serde_json::json!({
264+
"mode": "hosted",
265+
"file": "pnpm-workspace.yaml",
266+
"entry": "registry",
267+
"key": "socket-11111111",
268+
})
269+
);
270+
}
271+
272+
/// The notice for registries passed over on a host the run was not
273+
/// told of names the host by its origin, how many there are, and the
274+
/// setting that lets the command tidy them, in one sentence that
275+
/// reads right for one registry and for several.
276+
#[test]
277+
fn the_unknown_host_notice_names_the_origin_and_the_setting() {
278+
const ORIGIN: &str = "https://patch.staging.example:8443";
279+
let one = unknown_host_detail(ORIGIN, 1);
280+
assert_eq!(
281+
one,
282+
"1 pnpm registry of a hosted patch on https://patch.staging.example:8443 was left \
283+
alone: this run was not given that host as a patch server, so it cannot tell that \
284+
registry from the project's own; pass `--patch-server-url \
285+
https://patch.staging.example:8443` (or set SOCKET_PATCH_SERVER_URL) to let this \
286+
command tidy what no lockfile uses of it"
287+
);
288+
let several = unknown_host_detail(ORIGIN, 3);
289+
assert!(
290+
several.starts_with(
291+
"3 pnpm registries of hosted patches on https://patch.staging.example:8443 were \
292+
left alone:"
293+
) && several.contains("those registries")
294+
&& several.ends_with("of them"),
295+
"{several}"
296+
);
297+
for detail in [one, several] {
298+
assert!(!detail.contains('\n') && !detail.ends_with('.'), "{detail}");
299+
}
300+
}
301+
302+
#[test]
303+
fn a_dry_run_says_what_would_go() {
304+
let entries = [entry(
305+
RegistryEntryKind::Override,
306+
"left-pad@1.3.0",
307+
"socket-11111111:1.3.0",
308+
)];
309+
let mut env = Envelope::new(crate::json_envelope::Command::Repair);
310+
record(&mut env, &entries, true);
311+
assert_eq!(env.to_value()["events"][0]["action"], "verified");
312+
assert_eq!(
313+
lines(&entries, true)[0],
314+
"Would remove 1 pnpm registry entry that no lockfile uses any more:"
315+
);
316+
assert!(lines(&[], true).is_empty());
317+
}
318+
}

0 commit comments

Comments
 (0)