Skip to content

Commit 2e4be2c

Browse files
authored
fix(workspace): 远程会话结束时释放它建立的搜索索引 (1lck/Lithe-IDEA#2277) (#165)
workspace 新增会话结束钩子(on_session_end / is_registered),remote.disconnect、 断线后遗忘会话和 remote.closeAll 都会运行;project 的搜索索引键带上会话, 缓存初始化时登记钩子,会话结束即删掉该会话的全部索引。仍持有旧会话的请求 先插入槽位再检查会话是否还在,不会在会话结束后留下新条目。
1 parent 96973e1 commit 2e4be2c

8 files changed

Lines changed: 206 additions & 20 deletions

File tree

‎rust/contracts/rust-core-api.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6214,7 +6214,13 @@ ends with its programs once the server's idle timeout (ten minutes) passes
62146214
without a client; one whose programs were kept lasts until they end. `remote.closeAll` (no payload, returning
62156215
`{ closed }` with the number of connections) ends all of them; the host calls
62166216
it while quitting because exiting without it can leave the OpenSSH tree and
6217-
the remote server running. Requests over it take `sessionId`:
6217+
the remote server running. Every session id is new, so when a connection
6218+
leaves Core — through `remote.disconnect`, `remote.closeAll`, or a broken link
6219+
that makes a request return `connection_closed` — Core also drops the search
6220+
indexes built through it, including one a request that still held the
6221+
session was building; the client does not call
6222+
`workspace.searchIndex.invalidate` for them, and cannot once the session is
6223+
gone. Requests over it take `sessionId`:
62186224

62196225
| Command | Request | Result |
62206226
| --- | --- | --- |

‎rust/crates/core/src/tests/remote_sessions.rs‎

Lines changed: 65 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -307,11 +307,8 @@ fn remote_build_detects_a_root_opened_through_a_host_symbolic_link() {
307307

308308
impl Drop for HostFixture {
309309
fn drop(&mut self) {
310-
let _ = crate::execute_json(&json!({
311-
"id": test_support::unique_id(), "command": "workspace.searchIndex.invalidate", "timeoutMilliseconds": 1_000,
312-
"remoteWorkspace": {"sessionId": self.id, "localRoot": self.root.join("placeholder"), "remoteRoot": self.root.join("host")},
313-
"payload": {"root": self.root.join("placeholder")}
314-
}).to_string());
310+
// Unregistering runs the session-end hooks, which drop the search
311+
// indexes the session built.
315312
test_support::unregister(&self.id);
316313
let _ = self.socket.shutdown(Shutdown::Both);
317314
if self.done.recv_timeout(STEP + STEP).is_ok() {
@@ -465,6 +462,69 @@ fn remote_search_reads_host_content_and_applies_incremental_updates_without_loca
465462
assert_eq!(local["ok"], true, "{local}");
466463
}
467464

465+
// Every session ends with a new id, so indexes keyed by an ended session can
466+
// never be reached again and must not stay cached (1lck/Lithe-IDEA#2277).
467+
#[test]
468+
fn ending_a_remote_session_releases_its_search_indexes() {
469+
let search = |host: &HostFixture| {
470+
std::fs::write(host.root.join("host/Indexed.txt"), "IndexedWord\n").unwrap();
471+
host.call("workspace.searchEverywhere", json!({"query": "Indexed"}));
472+
host.call("workspace.search", json!({"query": "IndexedWord"}));
473+
assert!(lithe_project::cached_indexes_for_session(&host.id) > 0);
474+
};
475+
476+
// `remote.disconnect` releases the indexes of the session it closes.
477+
let closed = HostFixture::new();
478+
search(&closed);
479+
let disconnected: Value = serde_json::from_str(&crate::execute_json(
480+
&json!({
481+
"id": test_support::unique_id(), "command": "remote.disconnect",
482+
"payload": {"sessionId": closed.id, "programs": "end"}
483+
})
484+
.to_string(),
485+
))
486+
.unwrap();
487+
assert_eq!(disconnected["ok"], true, "{disconnected}");
488+
assert_eq!(lithe_project::cached_indexes_for_session(&closed.id), 0);
489+
490+
// A request that already held the host when the session ended still
491+
// builds its index, but must not leave it cached.
492+
let racing = HostFixture::new();
493+
search(&racing);
494+
let held = {
495+
let workspace: lithe_workspace::Workspace = serde_json::from_value(json!({
496+
"sessionId": racing.id,
497+
"localRoot": racing.root.join("placeholder"),
498+
"remoteRoot": racing.root.join("host"),
499+
}))
500+
.unwrap();
501+
let _scope = lithe_workspace::Scope::begin(Some(workspace)).unwrap();
502+
lithe_workspace::current().unwrap()
503+
};
504+
let link = test_support::forget_keeping_link(&racing.id);
505+
assert_eq!(lithe_project::cached_indexes_for_session(&racing.id), 0);
506+
let found = {
507+
let _scope = lithe_workspace::enter(Some(held));
508+
lithe_project::search(
509+
serde_json::from_value(json!({
510+
"root": racing.root.join("placeholder"),
511+
"query": "IndexedWord",
512+
}))
513+
.unwrap(),
514+
)
515+
.unwrap()
516+
};
517+
assert!(
518+
found
519+
.matches
520+
.iter()
521+
.any(|item| item.kind == "content" && item.path == "Indexed.txt"),
522+
"the held host must still search the host"
523+
);
524+
assert_eq!(lithe_project::cached_indexes_for_session(&racing.id), 0);
525+
drop(link);
526+
}
527+
468528
#[test]
469529
fn real_remote_git_status_stage_commit_and_history_never_touch_the_placeholder() {
470530
let host = HostFixture::new();

‎rust/crates/project/Cargo.toml‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ license = "Apache-2.0"
66
description = "Project services for Lithe: workspace files, indexing policy, search, local history, document rendering and Markdown outlines"
77

88
[features]
9-
# Lets lithe-core's tests trace which directories a workspace scan enumerates.
9+
# Lets lithe-core's tests trace which directories a workspace scan enumerates and count
10+
# the search indexes a remote session still holds.
1011
test-support = []
1112

1213
[dependencies]

‎rust/crates/project/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@ pub use html_preview::*;
3636
pub use markdown::*;
3737
pub use markdown_outline::*;
3838
pub use markdown_reference::*;
39+
#[cfg(feature = "test-support")]
40+
pub use search_index::cached_indexes_for_session;
3941
pub use search_paging::{project_search_page, search_page, SearchPageRequest};
4042
pub use search_preferences::*;
4143

‎rust/crates/project/src/search_index.rs‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ pub(crate) struct SearchIndexStats {
5151
struct IndexKey {
5252
root: PathBuf,
5353
host: PathBuf,
54+
/// The remote session the index reads through; `None` for this machine.
55+
session: Option<String>,
5456
hidden_directories: Vec<String>,
5557
hidden_file_patterns: Vec<String>,
5658
names_only: bool,
@@ -70,13 +72,29 @@ type IndexSlot = Arc<std::sync::Mutex<Option<SharedIndex>>>;
7072
static INDEX_CACHE: OnceLock<std::sync::Mutex<HashMap<IndexKey, IndexSlot>>> = OnceLock::new();
7173

7274
fn cache() -> &'static std::sync::Mutex<HashMap<IndexKey, IndexSlot>> {
73-
INDEX_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
75+
INDEX_CACHE.get_or_init(|| {
76+
// Every session ends with a new id, so without this a process that
77+
// reconnects or reopens remote workspaces keeps one content index and
78+
// one name index per session until it exits (1lck/Lithe-IDEA#2277).
79+
workspace::sessions::on_session_end(release_session);
80+
std::sync::Mutex::new(HashMap::new())
81+
})
82+
}
83+
84+
/// Drops every index built through `session`, including in-flight builds,
85+
/// which can then no longer publish into the cache.
86+
fn release_session(session: &str) {
87+
let Ok(mut indexes) = cache().lock() else {
88+
return;
89+
};
90+
indexes.retain(|key, _| key.session.as_deref() != Some(session));
7491
}
7592

7693
fn key(root: &Path, rules: &VisibilityRules) -> IndexKey {
7794
IndexKey {
7895
root: root.to_path_buf(),
7996
host: workspace::identity_key(root),
97+
session: workspace::current().map(|host| host.session_id().to_owned()),
8098
hidden_directories: rules.hidden_directories.clone(),
8199
hidden_file_patterns: rules.hidden_file_patterns.clone(),
82100
names_only: false,
@@ -120,10 +138,11 @@ fn get_index(
120138
rules: &VisibilityRules,
121139
names_only: bool,
122140
) -> Result<SharedIndex, CoreError> {
141+
let mut cache_key = key(root, rules);
142+
cache_key.names_only = names_only;
143+
let session = cache_key.session.clone();
123144
let slot = {
124145
let mut indexes = cache().lock().map_err(|_| index_lock_error())?;
125-
let mut cache_key = key(root, rules);
126-
cache_key.names_only = names_only;
127146
// Keep one visibility variant per workspace/source, including in-flight builds.
128147
indexes.retain(|existing, _| {
129148
existing.host != cache_key.host
@@ -136,6 +155,12 @@ fn get_index(
136155
.or_insert_with(|| Arc::new(std::sync::Mutex::new(None))),
137156
)
138157
};
158+
// The session may have ended while this request still held its host.
159+
// Checking after the insert closes the gap: either the check sees the
160+
// session gone, or its end hook runs after the insert and removes it.
161+
if let Some(session) = session.filter(|session| !workspace::sessions::is_registered(session)) {
162+
release_session(&session);
163+
}
139164
let mut index = slot.lock().map_err(|_| index_lock_error())?;
140165
if let Some(index) = index.as_ref() {
141166
return Ok(Arc::clone(index));
@@ -151,6 +176,18 @@ fn index_lock_error() -> CoreError {
151176
CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned")
152177
}
153178

179+
/// Counts cached indexes, built or still building, that read through
180+
/// `session`, so lithe-core's tests can prove that ending a session releases them.
181+
#[cfg(feature = "test-support")]
182+
pub fn cached_indexes_for_session(session: &str) -> usize {
183+
cache().lock().map_or(0, |indexes| {
184+
indexes
185+
.keys()
186+
.filter(|key| key.session.as_deref() == Some(session))
187+
.count()
188+
})
189+
}
190+
154191
pub(crate) fn invalidate_root(root: &Path) {
155192
let Ok(mut indexes) = cache().lock() else {
156193
return;

‎rust/crates/workspace/src/scope.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,9 @@ impl Host {
152152
.unwrap_or_else(|| path.to_owned())
153153
}
154154

155-
pub(crate) fn identity(&self) -> &str {
155+
/// The id of the session this host belongs to, which keys process-wide
156+
/// state released through [`crate::sessions::on_session_end`].
157+
pub fn session_id(&self) -> &str {
156158
&self.workspace.session_id
157159
}
158160
}
@@ -221,7 +223,7 @@ pub fn remote_path(path: &Path) -> PathBuf {
221223
/// Includes host identity in process-local repository coordination keys.
222224
pub fn identity_key(path: &Path) -> PathBuf {
223225
current()
224-
.map(|host| PathBuf::from(host.identity()).join(path.strip_prefix("/").unwrap_or(path)))
226+
.map(|host| PathBuf::from(host.session_id()).join(path.strip_prefix("/").unwrap_or(path)))
225227
.unwrap_or_else(|| path.to_owned())
226228
}
227229

‎rust/crates/workspace/src/sessions.rs‎

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,54 @@ pub(crate) fn lookup(id: &str) -> Result<Arc<Connection>, CoreError> {
373373
})
374374
}
375375

376+
/// Releases process-wide state another crate keys by a session id, such as
377+
/// the search indexes `lithe-project` builds over a remote workspace.
378+
pub type SessionEndHook = fn(&str);
379+
380+
fn session_end_hooks() -> &'static Mutex<Vec<SessionEndHook>> {
381+
static HOOKS: OnceLock<Mutex<Vec<SessionEndHook>>> = OnceLock::new();
382+
HOOKS.get_or_init(Mutex::default)
383+
}
384+
385+
/// Runs `hook` with the id of every session that leaves the registry from now
386+
/// on: `remote.disconnect`, a broken link that forgets the session, and
387+
/// application exit. Session ids are never reused, so state keyed by an ended
388+
/// id can never be reached again. Registering a hook twice runs it once.
389+
///
390+
/// A caller that may insert state for a session after the session ended must
391+
/// insert first and then check [`is_registered`]: either the check sees the
392+
/// session gone, or the hook runs after the insert and removes it.
393+
pub fn on_session_end(hook: SessionEndHook) {
394+
let mut hooks = session_end_hooks()
395+
.lock()
396+
.unwrap_or_else(|poisoned| poisoned.into_inner());
397+
if !hooks
398+
.iter()
399+
.any(|existing| std::ptr::fn_addr_eq(*existing, hook))
400+
{
401+
hooks.push(hook);
402+
}
403+
}
404+
405+
/// Whether `id` names a session that is still registered.
406+
pub fn is_registered(id: &str) -> bool {
407+
registry()
408+
.lock()
409+
.unwrap_or_else(|poisoned| poisoned.into_inner())
410+
.contains_key(id)
411+
}
412+
413+
/// Runs the session-end hooks for `id`, which has just left the registry.
414+
pub(crate) fn ended(id: &str) {
415+
let hooks = session_end_hooks()
416+
.lock()
417+
.unwrap_or_else(|poisoned| poisoned.into_inner())
418+
.clone();
419+
for hook in hooks {
420+
hook(id);
421+
}
422+
}
423+
376424
/// The key of a workspace's machine-local records, its trust and its port
377425
/// records: the connection's target and the workspace's real path as the host
378426
/// resolves it, so a symbolic link or another spelling of the path never
@@ -405,11 +453,12 @@ pub(crate) fn workspace_key(
405453
/// Removes a connection whose session ended and closes it in the background,
406454
/// so the host reconnects instead of retrying a dead session.
407455
pub(crate) fn forget(id: &str) {
408-
if let Some(connection) = registry()
456+
let connection = registry()
409457
.lock()
410458
.unwrap_or_else(|poisoned| poisoned.into_inner())
411-
.remove(id)
412-
{
459+
.remove(id);
460+
if let Some(connection) = connection {
461+
ended(id);
413462
std::thread::spawn(move || connection.close());
414463
}
415464
}
@@ -1167,6 +1216,7 @@ pub fn disconnect(request: DisconnectRequest) -> DisconnectResult {
11671216
let Some(connection) = connection else {
11681217
return DisconnectResult::default();
11691218
};
1219+
ended(&request.session_id);
11701220
let kept = match request.programs {
11711221
ProgramsOnClose::End => {
11721222
connection.close();
@@ -1199,13 +1249,19 @@ pub(crate) fn close_registered() -> usize {
11991249
/// Drains the owned registry, allowing isolated lifecycle tests without closing
12001250
/// unrelated sessions concurrently exercising the application registry.
12011251
pub(crate) fn close_registry(connections: &Mutex<HashMap<String, Arc<Connection>>>) -> usize {
1202-
let connections: Vec<Arc<Connection>> = connections
1252+
let connections: Vec<(String, Arc<Connection>)> = connections
12031253
.lock()
12041254
.unwrap_or_else(|poisoned| poisoned.into_inner())
12051255
.drain()
1206-
.map(|(_, connection)| connection)
12071256
.collect();
12081257
let count = connections.len();
1258+
let connections: Vec<Arc<Connection>> = connections
1259+
.into_iter()
1260+
.map(|(id, connection)| {
1261+
ended(&id);
1262+
connection
1263+
})
1264+
.collect();
12091265
let closers: Vec<_> = connections
12101266
.into_iter()
12111267
.map(|connection| std::thread::spawn(move || connection.close()))

‎rust/crates/workspace/src/test_support.rs‎

Lines changed: 25 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Hooks for `lithe-core`'s end-to-end tests, which drive real Core commands
22
//! against an in-process host server instead of an SSH child.
33
4-
use crate::sessions::{lookup, nonce, registry, Connection, ConnectionTransport};
4+
use crate::sessions::{ended, lookup, nonce, registry, Connection, ConnectionTransport};
55
use lithe_remote::client::trust::Target;
66
use lithe_remote::client::{RemoteSession, TransportChain};
77
use std::sync::Arc;
@@ -32,13 +32,35 @@ pub fn drop_link(id: &str) {
3232
lookup(id).unwrap().close();
3333
}
3434

35-
/// Removes the session from the registry and shuts it down.
35+
/// Removes the session from the registry, runs the session-end hooks and
36+
/// shuts it down, as `remote.disconnect` does.
3637
pub fn unregister(id: &str) {
37-
if let Some(connection) = registry().lock().unwrap().remove(id) {
38+
let connection = registry().lock().unwrap().remove(id);
39+
if let Some(connection) = connection {
40+
ended(id);
3841
connection.close();
3942
}
4043
}
4144

45+
/// Removes the session from the registry and runs the session-end hooks but
46+
/// leaves its link open, as a request that already holds the session's host
47+
/// sees when `remote.disconnect` runs at the same time. Dropping the result
48+
/// closes the link.
49+
pub fn forget_keeping_link(id: &str) -> KeptLink {
50+
let connection = registry().lock().unwrap().remove(id).unwrap();
51+
ended(id);
52+
KeptLink(connection)
53+
}
54+
55+
/// An unregistered session's link, closed when dropped.
56+
pub struct KeptLink(Arc<Connection>);
57+
58+
impl Drop for KeptLink {
59+
fn drop(&mut self) {
60+
self.0.close();
61+
}
62+
}
63+
4264
/// A fresh unguessable id, the same shape as session ids.
4365
pub fn unique_id() -> String {
4466
nonce()

0 commit comments

Comments
 (0)