Skip to content

Commit bc39fe8

Browse files
shengyfuCopilot
andcommitted
Preserve native Git metadata and shared RPC error diagnostics
Keep native gitfile and commondir paths lossless across shared validation and ignore discovery. Vendor only the locked ignore release with its small native parser patch, preserving ignore semantics and direct checkout distribution. Validate null-ID JSON-RPC errors without relaxing successful or mismatched response IDs. Add full lifecycle, precedence, repair and envelope regressions. Co-authored-by: Copilot App <[email protected]>
1 parent 8b767f2 commit bc39fe8

32 files changed

Lines changed: 8303 additions & 48 deletions

‎Cargo.lock‎

Lines changed: 0 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
[workspace]
22
members = ["tgrep-core", "tgrep-cli"]
3+
exclude = ["vendor/ignore"]
34
resolver = "2"
45

56
[workspace.package]

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1052,6 +1052,10 @@ cd tgrep
10521052
cargo install --path tgrep-cli --locked
10531053
```
10541054

1055+
Keep `vendor/ignore` in the checkout: it contains the locked dependency with a
1056+
small native Git-metadata path fix. Source installs and release builds use it
1057+
directly; see its [provenance and patch notes](vendor/ignore/PATCHES.md).
1058+
10551059
### Homebrew (Linux, macOS)
10561060

10571061
```bash

‎SHARED_WORKTREE_INDEXES.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -519,12 +519,23 @@ only. All requests have this envelope (including `hello`):
519519
Successful results repeat `protocol`, `instance` and `repository`. Errors have
520520
`error.code` and `error.message`, never success-shaped empty results. V1 rejects
521521
unknown envelope/parameter fields, malformed options and incompatible identities.
522+
Clients require the matching request ID on successful responses. A valid error
523+
object (integer code, string message, no result) may instead have an explicit
524+
null ID when rejected before request parsing, preserving connection-queue
525+
saturation diagnostics. Missing/mismatched IDs and malformed errors are rejected.
522526
Search RPCs must omit `passthru` or set it to `false`; `true` is rejected with a
523527
scan-required error because indexed candidates omit nonmatching files. The CLI
524528
keeps `--passthru` on its existing filesystem-scan path when it emits all lines.
525529
Canonical worktree roots must be UTF-8 for JSON transport. CLI and server reject
526530
unsupported roots, including Unicode aliases to them, before serialization or
527531
generation publication; the core API's native-path support is unchanged.
532+
Gitfile and `commondir` targets retain native path bytes on Unix, even when
533+
metadata lives outside a UTF-8 worktree. Discovery and identity revalidation
534+
share the same decoder without spawning Git on the daemon's hot query path.
535+
The existing `ignore` dependency is vendored at its locked version with the
536+
same native-path correction in Git ignore-source discovery; ignore precedence,
537+
nested repository boundaries and malformed-ignore failures are preserved.
538+
See [dependency provenance and distribution](vendor/ignore/PATCHES.md).
528539
Instance IDs prevent stale metadata/port reuse; they are not authentication
529540
against hostile local processes. Storage, repository metadata and the loopback
530541
user environment are trusted.

‎tgrep-cli/src/serve/shared/mod.rs‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -42,21 +42,13 @@ fn validate_repository(root: &Path, repository: &Repository) -> Result<()> {
4242
worktree_root(root)? == root,
4343
"root is no longer a worktree root"
4444
);
45-
let git_dir = tgrep_core::git_index::git_dir(root).context("missing worktree Git directory")?;
45+
let (git_dir, common_dir) = tgrep_core::git_index::read_repository_dirs(root)
46+
.context("reading worktree Git directories")?;
4647
let git_dir = std::fs::canonicalize(git_dir)?;
4748
ensure!(
4849
git_dir == repository.git_dir(),
4950
"worktree Git directory changed; reattach"
5051
);
51-
let common_dir = match std::fs::read_to_string(git_dir.join("commondir")) {
52-
Ok(target) => {
53-
let target = target.trim();
54-
ensure!(!target.is_empty(), "empty Git common directory");
55-
git_dir.join(target)
56-
}
57-
Err(error) if error.kind() == std::io::ErrorKind::NotFound => git_dir.clone(),
58-
Err(error) => return Err(error.into()),
59-
};
6052
ensure!(
6153
std::fs::canonicalize(common_dir)? == repository.common_dir(),
6254
"worktree repository changed; reattach"

‎tgrep-cli/src/serve/shared/protocol.rs‎

Lines changed: 114 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,12 +193,24 @@ impl Client {
193193
let line = read_line(&mut stream, MAX_RESPONSE)?;
194194
let response: Value = serde_json::from_slice(&line)?;
195195
ensure!(
196-
response["jsonrpc"] == "2.0" && response["id"] == 1,
196+
response.is_object() && response["jsonrpc"] == "2.0",
197197
"invalid shared RPC response"
198198
);
199199
if let Some(error) = response.get("error") {
200-
bail!("shared daemon: {}", error["message"]);
200+
ensure!(
201+
response.get("id").is_some_and(|id| id == 1 || id.is_null())
202+
&& response.get("result").is_none()
203+
&& error.is_object()
204+
&& error["code"].is_i64()
205+
&& error["message"].is_string(),
206+
"invalid shared RPC error response"
207+
);
208+
bail!(
209+
"shared daemon: {}",
210+
error["message"].as_str().expect("validated message")
211+
);
201212
}
213+
ensure!(response["id"] == 1, "invalid shared RPC response");
202214
let result = response
203215
.get("result")
204216
.context("missing shared RPC result")?;
@@ -304,3 +316,103 @@ pub fn run_lifecycle(command: Lifecycle) -> Result<()> {
304316
println!("{}", client.request(method, params)?);
305317
Ok(())
306318
}
319+
320+
#[cfg(test)]
321+
mod tests {
322+
use super::*;
323+
use std::net::TcpListener;
324+
use std::thread;
325+
use std::time::Instant;
326+
327+
fn exchange(response: Value) -> Result<Value> {
328+
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
329+
listener.set_nonblocking(true).unwrap();
330+
let client = Client {
331+
registration: Registration {
332+
protocol: PROTOCOL,
333+
instance: "test-instance".into(),
334+
repository: "test-repository".into(),
335+
pid: std::process::id(),
336+
port: listener.local_addr().unwrap().port(),
337+
storage: PathBuf::new(),
338+
},
339+
root: PathBuf::new(),
340+
};
341+
let worker = thread::spawn(move || {
342+
let started = Instant::now();
343+
let mut stream = loop {
344+
match listener.accept() {
345+
Ok((stream, _)) => break stream,
346+
Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
347+
assert!(started.elapsed() < Duration::from_secs(5));
348+
thread::sleep(Duration::from_millis(10));
349+
}
350+
Err(error) => panic!("{error}"),
351+
}
352+
};
353+
stream
354+
.set_read_timeout(Some(Duration::from_secs(5)))
355+
.unwrap();
356+
stream
357+
.set_write_timeout(Some(Duration::from_secs(5)))
358+
.unwrap();
359+
let request: Value =
360+
serde_json::from_slice(&read_line(&mut stream, MAX_REQUEST).unwrap()).unwrap();
361+
assert_eq!(request["id"], 1);
362+
assert_eq!(request["method"], "hello");
363+
writeln!(stream, "{response}").unwrap();
364+
});
365+
let result = client.request("hello", json!({}));
366+
worker.join().unwrap();
367+
result
368+
}
369+
370+
#[test]
371+
fn rpc_response_envelopes_preserve_queue_diagnostics() {
372+
let success = json!({
373+
"protocol":PROTOCOL,"instance":"test-instance","repository":"test-repository"
374+
});
375+
assert_eq!(
376+
exchange(json!({"jsonrpc":"2.0","id":1,"result":success})).unwrap(),
377+
success
378+
);
379+
let error = json!({"code":-32001,"message":"shared connection queue full"});
380+
for id in [json!(null), json!(1)] {
381+
let failure = exchange(json!({"jsonrpc":"2.0","id":id,"error":error})).unwrap_err();
382+
assert!(
383+
failure.to_string().contains("shared connection queue full"),
384+
"{failure:#}"
385+
);
386+
}
387+
for response in [
388+
json!(null),
389+
json!([]),
390+
json!("not an envelope"),
391+
json!({"jsonrpc":"1.0","id":null,"error":error}),
392+
json!({"id":null,"error":error}),
393+
json!({"jsonrpc":"2.0","error":error}),
394+
json!({"jsonrpc":"2.0","id":2,"error":error}),
395+
json!({"jsonrpc":"2.0","id":"1","error":error}),
396+
json!({"jsonrpc":"2.0","id":null,"error":null}),
397+
json!({"jsonrpc":"2.0","id":null,"error":[]}),
398+
json!({"jsonrpc":"2.0","id":null,"error":{"message":"shared connection queue full"}}),
399+
json!({"jsonrpc":"2.0","id":null,"error":{"code":"-32001","message":"shared connection queue full"}}),
400+
json!({"jsonrpc":"2.0","id":null,"error":{"code":-1.5,"message":"shared connection queue full"}}),
401+
json!({"jsonrpc":"2.0","id":null,"error":{"code":-32001}}),
402+
json!({"jsonrpc":"2.0","id":null,"error":{"code":-32001,"message":{}}}),
403+
json!({"jsonrpc":"2.0","id":1,"error":error,"result":success}),
404+
json!({"jsonrpc":"2.0","id":null,"error":error,"result":null}),
405+
json!({"jsonrpc":"2.0","id":null,"result":success}),
406+
json!({"jsonrpc":"2.0","id":2,"result":success}),
407+
json!({"jsonrpc":"2.0","id":"1","result":success}),
408+
json!({"jsonrpc":"2.0","result":success}),
409+
json!({"jsonrpc":"2.0","id":1}),
410+
] {
411+
let failure = exchange(response.clone()).unwrap_err();
412+
assert!(
413+
!failure.to_string().contains("shared connection queue full"),
414+
"{response}: {failure:#}"
415+
);
416+
}
417+
}
418+
}

0 commit comments

Comments
 (0)