Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/socket-patch-cli/CLI_CONTRACT.md
Original file line number Diff line number Diff line change
Expand Up @@ -2008,7 +2008,7 @@ writes nothing) and `gc.removedRegistryEntries` counts them; in a hosted-only pr
has zeros for the `.socket/` sweeps, which did not run, and is absent when the project holds
nothing of a route. A hosted-only project takes the apply lock only when there is an entry to
remove on a wet run, so `.socket/` is never left behind. A file a routed scan created is deleted
once it holds nothing else; a file of the user's keeps their bytes. Agent blob acquisition skips vendored records and lockfile-referenced UUIDs, so repairing a vendored project does not populate `.socket/blobs`.
once it holds nothing else; a file of the user's keeps their bytes. Agent blob acquisition skips vendored records and lockfile-referenced UUIDs, so repairing a vendored project does not populate `.socket/blobs`. The one exception is a project that has such blobs committed under `.socket/blob/`: `repair` copies them (nothing is downloaded), see `legacy_blob_dir`.

### Path convention + patch-UUID recovery (stable)

Expand Down Expand Up @@ -2799,6 +2799,7 @@ command's integration tests check its output.
| `invalid_purl` | apply `--check` / rollback: `failed`; remove: top-level error | A manifest key that is not a `pkg:<type>/<name>` purl at all (a hand-edited manifest): no version of the CLI can match it to a package. `apply` fails it by name as `apply_failed` (exit 1; every other patch still applies), `apply --check` reports it as drift, `rollback` as a failed entry whose record is kept (exit 1), and `remove` refuses it unless `--skip-rollback` is given. Correct the key or remove the entry. |
| `no_local_source` | `skipped`/`failed` | Agent patch application cannot obtain the required local or downloaded patch source. Vendored mode consumes complete server artifacts and no longer stages patch blobs. |
| `offline_missing_sources` / `sources_download_failed` | apply run-level `warnings[]` | apply (additive): the patch sources were unavailable — `--offline` with no local source, or the download left a patch with no source — so nothing was attempted. The envelope keeps its pinned shape (`partialFailure`, empty `events[]`, zero summary, no top-level `error`); the warning is its machine-readable reason (the human path prints the staging `Error:` line on stderr instead, even under `--silent`). |
| `legacy_blob_dir` | apply + repair run-level `warnings[]` | apply (additive): a blob the run needs is not in `.socket/blobs/` and a file of that name is in `.socket/blob/` (patch files committed under the older folder name). The run reads it from there instead of downloading it, so such a project applies with `--offline` and keeps applying when the patch service no longer serves the patch; the nested apply of `get` and `scan` does the same and the caller carries the warning. A file is used only when it is a regular file reached through no link and its bytes hash (git-sha256) to its name; any other file is ignored and the blob is downloaded as before. Only a blob absent from `.socket/blobs/` is looked for: an entry there that is corrupt fails the apply as before, and is `repair`'s to restore. `apply` writes nothing under `.socket/`. The detail gives the count and the remedies, in this order: `socket-patch scan`, which updates the patches (a project in this layout often holds one that has since been replaced) and stores their files in `.socket/blobs/`, or `socket-patch repair`, which copies the files as they are; then commit `.socket/`. Human mode prints it as a `Warning:` line on stderr, muted by `--silent`. repair: the blobs the manifest references (the whole manifest, vendored records included, as `apply` stages them) that `.socket/blobs/` lacks or holds corrupt were copied from `.socket/blob/` before any download, with `--offline` too; human mode prints the count and that `.socket/blobs/` is to be committed. `--dry-run` reports the copy and makes none. `.socket/blob/` itself is never modified or removed, and no sweep reads it. |
| `paid_required` | `skipped` + status=`paidRequired` | get: every patch found needs a paid plan and the caller's token isn't entitled (exit 0); one `skipped` event per patch, `details.tier`. `get <uuid>` on the public proxy reports it both for a `tier: "paid"` view and for the proxy's 403 refusal, whose event then carries only `uuid` (no `purl`: the proxy never named it). `scan` never reports it: it leaves paid patches out of the selection and counts them in `paidPatches` / `canAccessPaidPatches`. |
| `download_failed` | `failed` | repair/get/scan: network or 404 on patch fetch. |
| `patch_lookup_failed` | `failed` + scan run-level `warnings[]` | scan: the patch API gave no answer for this package while it answered for others (the token-less per-package path: a transport error, a `5xx`, a throttle that outlasted its retries, a response that is not the service's), so the package was NOT checked for patches. One `failed` event per package (`error`: its own error; a scan-level event recorded before the mode runs, so it carries no `details.mode`) and one warning naming them (`<n> of <total> packages could not be checked for patches (…): <first error>`); the scan goes on with the answered packages and ends `partialFailure`, exit 1. No package answered is the top-level `api_batch_failed` error instead. |
Expand Down
5 changes: 5 additions & 0 deletions crates/socket-patch-cli/src/commands/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3766,6 +3766,11 @@ async fn apply_patches_inner(
.map(|d| d.stores.as_slice())
.unwrap_or(&[]);
let mut run_warnings: Vec<RunWarning> = ledger_warning.into_iter().collect();
// Patch files read from the legacy `.socket/blob` folder: the run is
// whole, and `repair` moves them where every other command looks.
if let Some((code, detail)) = staged.legacy_blob_dir_warning() {
run_warnings.push(RunWarning::new(code, detail));
}
if let Some(value) = gem_discovery
.as_ref()
.and_then(|d| d.skipped_config_path.as_deref())
Expand Down
212 changes: 205 additions & 7 deletions crates/socket-patch-cli/src/commands/fetch_stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,20 @@
//! persistent `.socket/blobs` cache is only ever read; downloads are
//! discarded when the overlay drops (filling the cache is `repair`'s job,
//! so `apply` leaves `.socket/` as it found it).

use std::collections::HashSet;
//!
//! A blob `.socket/blobs` lacks is looked for in `.socket/blob` before it
//! is downloaded: an older commit layout kept a project's patch files
//! there, and such a project has them in its repository but nowhere the
//! cache looks. Each is read into memory, verified against its name, and
//! handed to the pipeline as an in-memory source, so nothing is written
//! and a run that finds them all needs no network.

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

use socket_patch_core::api::blob_fetcher::{
fetch_missing_blobs, get_missing_blobs, FetchMissingBlobsResult,
fetch_blobs_replacing, get_missing_blobs, legacy_dir_exists, read_legacy_blob,
FetchMissingBlobsResult, LEGACY_BLOBS_DIR,
};
use socket_patch_core::manifest::schema::PatchManifest;
use socket_patch_core::patch::apply::PatchSources;
Expand All @@ -22,6 +30,9 @@ use crate::ui::{plural, StatusLine};
/// `TempDir` alive — sources become invalid when this is dropped.
pub(crate) struct StagedSources {
blobs: PathBuf,
/// Blobs read from the legacy `.socket/blob` folder ([`legacy_blobs`]),
/// by hash: verified bytes the pipeline reads before `blobs`.
legacy: HashMap<String, Vec<u8>>,
_stage: Option<TempDir>,
}

Expand All @@ -30,9 +41,62 @@ impl StagedSources {
pub(crate) fn as_patch_sources(&self) -> PatchSources<'_> {
PatchSources {
blobs_path: &self.blobs,
mem_blobs: None,
mem_blobs: (!self.legacy.is_empty()).then_some(&self.legacy),
}
}

/// The advisory for a run that read patch files from the legacy
/// `.socket/blob` folder, `None` when it read none.
///
/// `scan` is the first remedy: a project in that layout was set up long
/// ago and often holds a patch that has since been replaced, and now
/// that its `apply` runs offline this line is the only notice it gets.
/// `scan` moves the manifest to the current patches and stores their
/// files in `.socket/blobs`; `repair` only copies the files as they
/// are.
pub(crate) fn legacy_blob_dir_warning(&self) -> Option<(&'static str, String)> {
let n = self.legacy.len();
(n > 0).then(|| {
(
LEGACY_BLOB_DIR,
format!(
"read {} from `.socket/{LEGACY_BLOBS_DIR}/`; socket-patch keeps patch \
files in `.socket/blobs/`. Run `socket-patch scan` to update the patches \
and store their files there (or `socket-patch repair` to copy them as \
they are), then commit `.socket/`",
plural(n, "patch file", "patch files")
),
)
})
}
}

/// Run-warning code: the run read patch files from the legacy
/// `.socket/blob` folder.
pub(crate) const LEGACY_BLOB_DIR: &str = "legacy_blob_dir";

/// The blobs of `missing` (hashes `.socket/blobs` lacks) that the legacy
/// folder `socket_dir/blob` holds, verified ([`read_legacy_blob`]). Empty,
/// after one `lstat`, for a project with no such folder.
///
/// All of them are read up front, on every run, a no-op run included: the
/// offline gate and the download plan need to know now which hashes have a
/// usable source, and only a read can tell (a file is one only when its
/// bytes hash to its name). Holding the verified bytes is also what makes
/// the bytes checked the bytes written. It replaces a download of the same
/// blobs on every run; `repair` ends it.
async fn legacy_blobs(socket_dir: &Path, missing: &HashSet<String>) -> HashMap<String, Vec<u8>> {
let legacy_dir = socket_dir.join(LEGACY_BLOBS_DIR);
let mut found = HashMap::new();
if !legacy_dir_exists(&legacy_dir).await {
return found;
}
for hash in missing {
if let Some(bytes) = read_legacy_blob(&legacy_dir, hash).await {
found.insert(hash.clone(), bytes);
}
}
found
}

/// The staging outcome.
Expand Down Expand Up @@ -159,7 +223,11 @@ pub(crate) async fn stage_patch_sources(
let quiet = common.silent || common.json;
let socket_blobs_path = socket_dir.join("blobs");

let missing_blobs = get_missing_blobs(manifest, &socket_blobs_path).await;
let mut missing_blobs = get_missing_blobs(manifest, &socket_blobs_path).await;
// What the cache lacks and the legacy folder holds is not missing: it
// is neither an offline failure nor a download.
let legacy = legacy_blobs(socket_dir, &missing_blobs).await;
missing_blobs.retain(|hash| !legacy.contains_key(hash));

if common.offline {
let no_source_purls = patches_without_source(manifest, &missing_blobs);
Expand All @@ -186,6 +254,7 @@ pub(crate) async fn stage_patch_sources(
if common.offline || missing_blobs.is_empty() {
return Ok(StageOutcome::Ready(StagedSources {
blobs: socket_blobs_path,
legacy,
Comment thread
mikolalysenko marked this conversation as resolved.
Resolved
_stage: None,
}));
}
Expand All @@ -207,6 +276,7 @@ pub(crate) async fn stage_patch_sources(
.map_err(|e| e.to_string())?;
let staged = StagedSources {
blobs: stage.path().join("blobs"),
legacy,
_stage: Some(stage),
};
tokio::fs::create_dir_all(&staged.blobs)
Expand All @@ -220,7 +290,12 @@ pub(crate) async fn stage_patch_sources(
let client = common.api_client(client).await;
let mut status = StatusLine::stderr(common.json, common.silent);
status.set("Downloading missing patch artifacts...");
let fetch_result = fetch_missing_blobs(manifest, &staged.blobs, client, None).await;
// What the overlay lacks, less the legacy folder's blobs: those are
// absent from the overlay too, and are not downloads.
let mut to_fetch = get_missing_blobs(manifest, &staged.blobs).await;
to_fetch.retain(|hash| !staged.legacy.contains_key(hash));
let to_fetch: Vec<String> = to_fetch.into_iter().collect();
let fetch_result = fetch_blobs_replacing(&to_fetch, &staged.blobs, client, None).await;
status.finish();
if !quiet {
for line in format_fetch_summary(&fetch_result) {
Expand All @@ -232,7 +307,8 @@ pub(crate) async fn stage_patch_sources(
// with no usable source at the staged path — the same coverage rule as
// the offline gate.
if fetch_result.failed > 0 {
let missing_blobs = get_missing_blobs(manifest, &staged.blobs).await;
let mut missing_blobs = get_missing_blobs(manifest, &staged.blobs).await;
missing_blobs.retain(|hash| !staged.legacy.contains_key(hash));
if !patches_without_source(manifest, &missing_blobs).is_empty() {
// An error, so it prints even under --silent, with the per-blob
// reasons the quiet summary above held back.
Expand Down Expand Up @@ -358,6 +434,128 @@ mod tests {
);
}

/// A manifest with one patch of one file whose patched bytes are
/// `after`, and that blob's hash.
fn manifest_for(after: &[u8]) -> (PatchManifest, String) {
let hash = socket_patch_core::hash::git_sha256::compute_git_sha256_from_bytes(after);
let mut manifest = manifest_with_one_patch();
for record in manifest.patches.values_mut() {
for file in record.files.values_mut() {
file.after_hash = hash.clone();
}
}
(manifest, hash)
}

/// A blob `.socket/blobs` lacks and `.socket/blob` holds is a source:
/// offline or online, the run is Ready with the bytes in memory, no
/// overlay, no API client, and nothing written under `.socket/`.
#[tokio::test]
async fn stage_reads_a_missing_blob_from_the_legacy_folder() {
let tmp = tempfile::tempdir().unwrap();
let socket_dir = tmp.path().join(".socket");
let legacy = socket_dir.join("blob");
std::fs::create_dir_all(&legacy).unwrap();
let (manifest, hash) = manifest_for(b"patched");
std::fs::write(legacy.join(&hash), b"patched").unwrap();

for offline in [true, false] {
let args = GlobalArgs {
offline,
..offline_args()
};
let client = RunApiClient::new();
let outcome = stage_patch_sources(&args, &manifest, &socket_dir, &client)
.await
.expect("no hard failure");
let StageOutcome::Ready(staged) = outcome else {
panic!("a legacy blob is a source (offline: {offline})");
};
assert!(staged._stage.is_none(), "nothing to download, no overlay");
assert!(!client.initialized(), "nothing to download, no client");
let sources = staged.as_patch_sources();
assert_eq!(
sources
.mem_blobs
.and_then(|m| m.get(&hash))
.map(Vec::as_slice),
Some(&b"patched"[..])
);
let (code, detail) = staged.legacy_blob_dir_warning().expect("advisory");
assert_eq!(code, "legacy_blob_dir");
assert_eq!(
detail,
"read 1 patch file from `.socket/blob/`; socket-patch keeps patch files in \
`.socket/blobs/`. Run `socket-patch scan` to update the patches and store \
their files there (or `socket-patch repair` to copy them as they are), then \
commit `.socket/`"
);
assert!(!socket_dir.join("blobs").exists(), "apply writes no cache");
}
}

/// A legacy file that does not hash to its name is no source: offline
/// the run is Unavailable, as without the folder. And a run with every
/// blob cached never reads the folder (no advisory).
#[tokio::test]
async fn stage_ignores_a_corrupt_legacy_blob_and_an_unneeded_folder() {
let tmp = tempfile::tempdir().unwrap();
let socket_dir = tmp.path().join(".socket");
let legacy = socket_dir.join("blob");
std::fs::create_dir_all(&legacy).unwrap();
let (manifest, hash) = manifest_for(b"patched");
std::fs::write(legacy.join(&hash), b"patched\r\n").unwrap();

let client = RunApiClient::new();
let outcome = stage_patch_sources(&offline_args(), &manifest, &socket_dir, &client)
.await
.expect("no hard failure");
assert!(matches!(outcome, StageOutcome::Unavailable));

std::fs::write(legacy.join(&hash), b"patched").unwrap();
std::fs::create_dir_all(socket_dir.join("blobs")).unwrap();
std::fs::write(socket_dir.join("blobs").join(&hash), b"patched").unwrap();
let outcome = stage_patch_sources(&offline_args(), &manifest, &socket_dir, &client)
.await
.expect("no hard failure");
let StageOutcome::Ready(staged) = outcome else {
panic!("cached");
};
assert!(staged.as_patch_sources().mem_blobs.is_none());
assert!(staged.legacy_blob_dir_warning().is_none());
}

/// The legacy folder covers one of a patch's two files: only the other
/// is asked of the server, and when that fails the patch still has no
/// whole source.
#[tokio::test]
async fn stage_downloads_only_what_the_legacy_folder_lacks() {
let tmp = tempfile::tempdir().unwrap();
let socket_dir = tmp.path().join(".socket");
let legacy = socket_dir.join("blob");
std::fs::create_dir_all(&legacy).unwrap();
let (mut manifest, hash) = manifest_for(b"patched");
std::fs::write(legacy.join(&hash), b"patched").unwrap();
for record in manifest.patches.values_mut() {
record.files.insert(
"other.js".to_string(),
PatchFileInfo {
before_hash: "b".repeat(64),
after_hash: "c".repeat(64),
mode: None,
},
);
}

let args = dead_endpoint_args();
let client = RunApiClient::new();
let outcome = stage_patch_sources(&args, &manifest, &socket_dir, &client)
.await
.expect("no hard failure");
assert!(matches!(outcome, StageOutcome::Unavailable));
assert!(client.initialized(), "the uncovered blob is a download");
}

/// GlobalArgs wired to a guaranteed-unreachable API endpoint: explicit
/// token + org overrides keep client construction network-free, and the
/// URL points at a port that was just bound and released, so every fetch
Expand Down
Loading
Loading