Skip to content
Merged
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
8 changes: 7 additions & 1 deletion rust/contracts/rust-core-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -6213,7 +6213,13 @@ ends with its programs once the server's idle timeout (ten minutes) passes
without a client; one whose programs were kept lasts until they end. `remote.closeAll` (no payload, returning
`{ closed }` with the number of connections) ends all of them; the host calls
it while quitting because exiting without it can leave the OpenSSH tree and
the remote server running. Requests over it take `sessionId`:
the remote server running. Every session id is new, so when a connection
leaves Core — through `remote.disconnect`, `remote.closeAll`, or a broken link
that makes a request return `connection_closed` — Core also drops the search
indexes built through it, including one a request that still held the
session was building; the client does not call
`workspace.searchIndex.invalidate` for them, and cannot once the session is
gone. Requests over it take `sessionId`:

| Command | Request | Result |
| --- | --- | --- |
Expand Down
70 changes: 65 additions & 5 deletions rust/crates/core/src/tests/remote_sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -307,11 +307,8 @@ fn remote_build_detects_a_root_opened_through_a_host_symbolic_link() {

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

// Every session ends with a new id, so indexes keyed by an ended session can
// never be reached again and must not stay cached (1lck/Lithe-IDEA#2277).
#[test]
fn ending_a_remote_session_releases_its_search_indexes() {
let search = |host: &HostFixture| {
std::fs::write(host.root.join("host/Indexed.txt"), "IndexedWord\n").unwrap();
host.call("workspace.searchEverywhere", json!({"query": "Indexed"}));
host.call("workspace.search", json!({"query": "IndexedWord"}));
assert!(lithe_project::cached_indexes_for_session(&host.id) > 0);
};

// `remote.disconnect` releases the indexes of the session it closes.
let closed = HostFixture::new();
search(&closed);
let disconnected: Value = serde_json::from_str(&crate::execute_json(
&json!({
"id": test_support::unique_id(), "command": "remote.disconnect",
"payload": {"sessionId": closed.id, "programs": "end"}
})
.to_string(),
))
.unwrap();
assert_eq!(disconnected["ok"], true, "{disconnected}");
assert_eq!(lithe_project::cached_indexes_for_session(&closed.id), 0);

// A request that already held the host when the session ended still
// builds its index, but must not leave it cached.
let racing = HostFixture::new();
search(&racing);
let held = {
let workspace: lithe_workspace::Workspace = serde_json::from_value(json!({
"sessionId": racing.id,
"localRoot": racing.root.join("placeholder"),
"remoteRoot": racing.root.join("host"),
}))
.unwrap();
let _scope = lithe_workspace::Scope::begin(Some(workspace)).unwrap();
lithe_workspace::current().unwrap()
};
let link = test_support::forget_keeping_link(&racing.id);
assert_eq!(lithe_project::cached_indexes_for_session(&racing.id), 0);
let found = {
let _scope = lithe_workspace::enter(Some(held));
lithe_project::search(
serde_json::from_value(json!({
"root": racing.root.join("placeholder"),
"query": "IndexedWord",
}))
.unwrap(),
)
.unwrap()
};
assert!(
found
.matches
.iter()
.any(|item| item.kind == "content" && item.path == "Indexed.txt"),
"the held host must still search the host"
);
assert_eq!(lithe_project::cached_indexes_for_session(&racing.id), 0);
drop(link);
}

#[test]
fn real_remote_git_status_stage_commit_and_history_never_touch_the_placeholder() {
let host = HostFixture::new();
Expand Down
3 changes: 2 additions & 1 deletion rust/crates/project/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ license = "Apache-2.0"
description = "Project services for Lithe: workspace files, indexing policy, search, local history, document rendering and Markdown outlines"

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

[dependencies]
Expand Down
2 changes: 2 additions & 0 deletions rust/crates/project/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ pub use html_preview::*;
pub use markdown::*;
pub use markdown_outline::*;
pub use markdown_reference::*;
#[cfg(feature = "test-support")]
pub use search_index::cached_indexes_for_session;
pub use search_paging::{project_search_page, search_page, SearchPageRequest};
pub use search_preferences::*;

Expand Down
43 changes: 40 additions & 3 deletions rust/crates/project/src/search_index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ pub(crate) struct SearchIndexStats {
struct IndexKey {
root: PathBuf,
host: PathBuf,
/// The remote session the index reads through; `None` for this machine.
session: Option<String>,
hidden_directories: Vec<String>,
hidden_file_patterns: Vec<String>,
names_only: bool,
Expand All @@ -70,13 +72,29 @@ type IndexSlot = Arc<std::sync::Mutex<Option<SharedIndex>>>;
static INDEX_CACHE: OnceLock<std::sync::Mutex<HashMap<IndexKey, IndexSlot>>> = OnceLock::new();

fn cache() -> &'static std::sync::Mutex<HashMap<IndexKey, IndexSlot>> {
INDEX_CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new()))
INDEX_CACHE.get_or_init(|| {
// Every session ends with a new id, so without this a process that
// reconnects or reopens remote workspaces keeps one content index and
// one name index per session until it exits (1lck/Lithe-IDEA#2277).
workspace::sessions::on_session_end(release_session);
std::sync::Mutex::new(HashMap::new())
})
}

/// Drops every index built through `session`, including in-flight builds,
/// which can then no longer publish into the cache.
fn release_session(session: &str) {
let Ok(mut indexes) = cache().lock() else {
return;
};
indexes.retain(|key, _| key.session.as_deref() != Some(session));
}

fn key(root: &Path, rules: &VisibilityRules) -> IndexKey {
IndexKey {
root: root.to_path_buf(),
host: workspace::identity_key(root),
session: workspace::current().map(|host| host.session_id().to_owned()),
hidden_directories: rules.hidden_directories.clone(),
hidden_file_patterns: rules.hidden_file_patterns.clone(),
names_only: false,
Expand Down Expand Up @@ -120,10 +138,11 @@ fn get_index(
rules: &VisibilityRules,
names_only: bool,
) -> Result<SharedIndex, CoreError> {
let mut cache_key = key(root, rules);
cache_key.names_only = names_only;
let session = cache_key.session.clone();
let slot = {
let mut indexes = cache().lock().map_err(|_| index_lock_error())?;
let mut cache_key = key(root, rules);
cache_key.names_only = names_only;
// Keep one visibility variant per workspace/source, including in-flight builds.
indexes.retain(|existing, _| {
existing.host != cache_key.host
Expand All @@ -136,6 +155,12 @@ fn get_index(
.or_insert_with(|| Arc::new(std::sync::Mutex::new(None))),
)
};
// The session may have ended while this request still held its host.
// Checking after the insert closes the gap: either the check sees the
// session gone, or its end hook runs after the insert and removes it.
if let Some(session) = session.filter(|session| !workspace::sessions::is_registered(session)) {
release_session(&session);
}
let mut index = slot.lock().map_err(|_| index_lock_error())?;
if let Some(index) = index.as_ref() {
return Ok(Arc::clone(index));
Expand All @@ -151,6 +176,18 @@ fn index_lock_error() -> CoreError {
CoreError::new(ErrorCode::Unknown, "Search index lock was poisoned")
}

/// Counts cached indexes, built or still building, that read through
/// `session`, so lithe-core's tests can prove that ending a session releases them.
#[cfg(feature = "test-support")]
pub fn cached_indexes_for_session(session: &str) -> usize {
cache().lock().map_or(0, |indexes| {
indexes
.keys()
.filter(|key| key.session.as_deref() == Some(session))
.count()
})
}

pub(crate) fn invalidate_root(root: &Path) {
let Ok(mut indexes) = cache().lock() else {
return;
Expand Down
6 changes: 4 additions & 2 deletions rust/crates/workspace/src/scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,9 @@ impl Host {
.unwrap_or_else(|| path.to_owned())
}

pub(crate) fn identity(&self) -> &str {
/// The id of the session this host belongs to, which keys process-wide
/// state released through [`crate::sessions::on_session_end`].
pub fn session_id(&self) -> &str {
&self.workspace.session_id
}
}
Expand Down Expand Up @@ -221,7 +223,7 @@ pub fn remote_path(path: &Path) -> PathBuf {
/// Includes host identity in process-local repository coordination keys.
pub fn identity_key(path: &Path) -> PathBuf {
current()
.map(|host| PathBuf::from(host.identity()).join(path.strip_prefix("/").unwrap_or(path)))
.map(|host| PathBuf::from(host.session_id()).join(path.strip_prefix("/").unwrap_or(path)))
.unwrap_or_else(|| path.to_owned())
}

Expand Down
66 changes: 61 additions & 5 deletions rust/crates/workspace/src/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,6 +373,54 @@ pub(crate) fn lookup(id: &str) -> Result<Arc<Connection>, CoreError> {
})
}

/// Releases process-wide state another crate keys by a session id, such as
/// the search indexes `lithe-project` builds over a remote workspace.
pub type SessionEndHook = fn(&str);

fn session_end_hooks() -> &'static Mutex<Vec<SessionEndHook>> {
static HOOKS: OnceLock<Mutex<Vec<SessionEndHook>>> = OnceLock::new();
HOOKS.get_or_init(Mutex::default)
}

/// Runs `hook` with the id of every session that leaves the registry from now
/// on: `remote.disconnect`, a broken link that forgets the session, and
/// application exit. Session ids are never reused, so state keyed by an ended
/// id can never be reached again. Registering a hook twice runs it once.
///
/// A caller that may insert state for a session after the session ended must
/// insert first and then check [`is_registered`]: either the check sees the
/// session gone, or the hook runs after the insert and removes it.
pub fn on_session_end(hook: SessionEndHook) {
let mut hooks = session_end_hooks()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !hooks
.iter()
.any(|existing| std::ptr::fn_addr_eq(*existing, hook))
{
hooks.push(hook);
}
}

/// Whether `id` names a session that is still registered.
pub fn is_registered(id: &str) -> bool {
registry()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.contains_key(id)
}

/// Runs the session-end hooks for `id`, which has just left the registry.
pub(crate) fn ended(id: &str) {
let hooks = session_end_hooks()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.clone();
for hook in hooks {
hook(id);
}
}

/// The key of a workspace's machine-local records, its trust and its port
/// records: the connection's target and the workspace's real path as the host
/// resolves it, so a symbolic link or another spelling of the path never
Expand Down Expand Up @@ -405,11 +453,12 @@ pub(crate) fn workspace_key(
/// Removes a connection whose session ended and closes it in the background,
/// so the host reconnects instead of retrying a dead session.
pub(crate) fn forget(id: &str) {
if let Some(connection) = registry()
let connection = registry()
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.remove(id)
{
.remove(id);
if let Some(connection) = connection {
ended(id);
std::thread::spawn(move || connection.close());
}
}
Expand Down Expand Up @@ -1167,6 +1216,7 @@ pub fn disconnect(request: DisconnectRequest) -> DisconnectResult {
let Some(connection) = connection else {
return DisconnectResult::default();
};
ended(&request.session_id);
let kept = match request.programs {
ProgramsOnClose::End => {
connection.close();
Expand Down Expand Up @@ -1199,13 +1249,19 @@ pub(crate) fn close_registered() -> usize {
/// Drains the owned registry, allowing isolated lifecycle tests without closing
/// unrelated sessions concurrently exercising the application registry.
pub(crate) fn close_registry(connections: &Mutex<HashMap<String, Arc<Connection>>>) -> usize {
let connections: Vec<Arc<Connection>> = connections
let connections: Vec<(String, Arc<Connection>)> = connections
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.drain()
.map(|(_, connection)| connection)
.collect();
let count = connections.len();
let connections: Vec<Arc<Connection>> = connections
.into_iter()
.map(|(id, connection)| {
ended(&id);
connection
})
.collect();
let closers: Vec<_> = connections
.into_iter()
.map(|connection| std::thread::spawn(move || connection.close()))
Expand Down
28 changes: 25 additions & 3 deletions rust/crates/workspace/src/test_support.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
//! Hooks for `lithe-core`'s end-to-end tests, which drive real Core commands
//! against an in-process host server instead of an SSH child.

use crate::sessions::{lookup, nonce, registry, Connection, ConnectionTransport};
use crate::sessions::{ended, lookup, nonce, registry, Connection, ConnectionTransport};
use lithe_remote::client::trust::Target;
use lithe_remote::client::{RemoteSession, TransportChain};
use std::sync::Arc;
Expand Down Expand Up @@ -32,13 +32,35 @@ pub fn drop_link(id: &str) {
lookup(id).unwrap().close();
}

/// Removes the session from the registry and shuts it down.
/// Removes the session from the registry, runs the session-end hooks and
/// shuts it down, as `remote.disconnect` does.
pub fn unregister(id: &str) {
if let Some(connection) = registry().lock().unwrap().remove(id) {
let connection = registry().lock().unwrap().remove(id);
if let Some(connection) = connection {
ended(id);
connection.close();
}
}

/// Removes the session from the registry and runs the session-end hooks but
/// leaves its link open, as a request that already holds the session's host
/// sees when `remote.disconnect` runs at the same time. Dropping the result
/// closes the link.
pub fn forget_keeping_link(id: &str) -> KeptLink {
let connection = registry().lock().unwrap().remove(id).unwrap();
ended(id);
KeptLink(connection)
}

/// An unregistered session's link, closed when dropped.
pub struct KeptLink(Arc<Connection>);

impl Drop for KeptLink {
fn drop(&mut self) {
self.0.close();
}
}

/// A fresh unguessable id, the same shape as session ids.
pub fn unique_id() -> String {
nonce()
Expand Down
Loading