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
19 changes: 19 additions & 0 deletions crates/dim-app-server/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,16 @@ pub enum ShutdownReason {
Forced,
}

/// Feature `testing`: a hold on one unregistered worktree removal after its
/// content check and before the store's final Session check. It notifies
/// `reached` once held and returns once `release` is notified.
#[cfg(feature = "testing")]
#[derive(Default)]
pub struct UnregisteredRemovalHold {
pub reached: tokio::sync::Notify,
pub release: tokio::sync::Notify,
}

/// Feature `testing`: a hold on one subscription's `follow` task. It notifies
/// `waiting` once it is held, `cancelled` once retirement cancels it, and
/// returns once `release` is notified.
Expand Down Expand Up @@ -335,6 +345,15 @@ impl RunningServer {
.get::<AgentIndex>()
.map(|index| index.idle_admitted())
}
/// Holds the next unregistered worktree removal after its content check,
/// so a test can create a Session before the store's final check. Feature
/// `testing` only.
#[cfg(feature = "testing")]
pub fn hold_next_unregistered_removal(&self) -> Option<Arc<UnregisteredRemovalHold>> {
self.root
.get::<worktrees::ManagedWorktrees>()
.map(|managed| managed.hold_next_unregistered_removal())
}
/// Holds the next subscription's `follow` task open until `release`, so a
/// test can keep an attach or detach in flight at a known point. Feature
/// `testing` only.
Expand Down
104 changes: 76 additions & 28 deletions crates/dim-app-server/src/storage/face.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,13 @@ impl Store {
) -> impl Future<Output = Result<bool>> {
self.0.remove_worktree(directory, remove)
}
pub fn remove_unregistered_directory(
&self,
path: PathBuf,
remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>> + Send + 'static,
) -> impl Future<Output = Result<bool>> {
self.0.remove_unregistered_directory(path, remove)
}
}

#[derive(Deserialize)]
Expand Down Expand Up @@ -289,7 +296,8 @@ impl HostDispatch for Store {
"hasRecords":"async", "delete":"async", "fork":"async",
"sessionConfigText":"async", "createOwnedSession":"async",
"worktreeDirectories":"async", "sessionsUnderWorkspace":"async",
"removeWorktreeDirectory":"async", "worktreeUsages":"async", "removeWorktree":"async"
"removeWorktreeDirectory":"async", "worktreeUsages":"async", "removeWorktree":"async",
"removeUnregisteredDirectory":"async"
}))
}
fn invoke(&self, method: &str, args: Value) -> Reply {
Expand All @@ -311,6 +319,7 @@ impl HostDispatch for Store {
if args.next().is_some() {
return Err(Error::value("unexpected removeWorktree argument"));
}
let remove = removal(remove);
let owner = self.clone();
return Ok(Value::future(async move {
let removed = owner
Expand All @@ -319,39 +328,43 @@ impl HostDispatch for Store {
repository: directory.repository.into(),
root: directory.root.into(),
},
move |path| {
Box::pin(async move {
let result = async {
let value = remove
.call_async(Value::List(vec![json!(path).into()]))
.await?;
if let Value::Reference(reference) = value
&& reference.is_future()
{
reference.wait_async().await?;
}
Ok::<_, Error>(())
}
.await;
result.map_err(|error| {
let message = match &error {
Error::Remote { message, .. } => message.clone(),
_ => error.to_string(),
};
match error.code() {
Some("invalid") => AgentError::InvalidInput(message),
Some("cancelled") => AgentError::Cancelled(message),
_ => AgentError::Storage(message),
}
})
})
},
remove,
)
.await
.map_err(failure)?;
Ok(json!({"removed":removed}).into())
}));
}
if method == "removeUnregisteredDirectory" {
let mut args = args.list()?.into_iter();
let root = args
.next()
.ok_or_else(|| Error::value("missing directory"))?
.json()?;
if !root.is_object() {
return Err(Error::value("store request must be an object"));
}
let root: Root =
serde_json::from_value(root).map_err(|error| Error::value(error.to_string()))?;
let remove = args
.next()
.ok_or_else(|| Error::value("missing removal callback"))?
.reference()?;
if args.next().is_some() {
return Err(Error::value(
"unexpected removeUnregisteredDirectory argument",
));
}
let remove = removal(remove);
let owner = self.clone();
return Ok(Value::future(async move {
let removed = owner
.remove_unregistered_directory(root.root.into(), remove)
.await
.map_err(failure)?;
Ok(json!({"removed":removed}).into())
}));
}
let [request]: [serde_json::Value; 1] = serde_json::from_value(args.json()?)
.map_err(|error| Error::value(error.to_string()))?;
if !request.is_object() {
Expand Down Expand Up @@ -497,6 +510,41 @@ impl HostDispatch for Store {
}))
}
}
/// One removal callback as the owner takes it: the bridge reference is
/// awaited with the checked path, and its error keeps the `invalid`,
/// `cancelled` or `storage` kind the caller raised.
fn removal(
remove: rutis_bridge::session::Reference,
) -> impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>> {
move |path| {
Box::pin(async move {
let result = async {
let value = remove
.call_async(Value::List(vec![json!(path).into()]))
.await?;
if let Value::Reference(reference) = value
&& reference.is_future()
{
reference.wait_async().await?;
}
Ok::<_, Error>(())
}
.await;
result.map_err(|error| {
let message = match &error {
Error::Remote { message, .. } => message.clone(),
_ => error.to_string(),
};
match error.code() {
Some("invalid") => AgentError::InvalidInput(message),
Some("cancelled") => AgentError::Cancelled(message),
_ => AgentError::Storage(message),
}
})
})
}
}

fn failure(error: AgentError) -> Error {
let code = match &error {
AgentError::InvalidInput(_) => "invalid",
Expand Down
50 changes: 50 additions & 0 deletions crates/dim-app-server/src/storage/timeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1900,6 +1900,56 @@ impl SessionStore {
Ok(removed > 0)
}

/// Removes an unregistered directory under the store's exclusion: the
/// ownership lock is held from the final record and workspace checks
/// through `remove`, so a Session created or a directory recorded after
/// the check fails this call and a creation after the removal re-checks
/// its missing workspace. The checks and the removal run in their own
/// task, so dropping the caller does not release the lock while the
/// removal is still running. The path is a store path, absolute without
/// relative components, and neither a recorded worktree directory nor a
/// stored Session workspace may be at or under it; `remove` re-checks the
/// unregistered facts and performs the deletion. Returns whether the
/// directory was still present when the lock was acquired; `false` means
/// another removal already finished.
pub async fn remove_unregistered_directory(
&self,
path: PathBuf,
remove: impl FnOnce(PathBuf) -> BoxFuture<'static, Result<()>> + Send + 'static,
) -> Result<bool> {
stored_worktree_path(&path)?;
let store = self.clone();
tokio::spawn(async move {
let _ownership = store.ownership.lock().await;
match tokio::fs::symlink_metadata(&path).await {
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
Err(_) => {}
}
let directories = store.worktree_directories().await?;
if let Some(record) = directories
.iter()
.find(|record| record.directory.root.starts_with(&path))
{
return Err(AgentError::InvalidInput(format!(
"{} is a recorded worktree directory; remove it by task id",
record.directory.root.display()
)));
}
let sessions = store.sessions_under_workspace(&path).await?;
if let Some(session) = sessions.first() {
return Err(AgentError::InvalidInput(format!(
"Session {session} uses {}",
path.display()
)));
}
remove(path).await?;
Ok(true)
})
.await
.map_err(|error| AgentError::Storage(format!("the removal task failed: {error}")))?
}

/// Lists the Session associations of a recorded directory. An unknown
/// directory or a candidate without remaining associations has no usages.
pub async fn worktree_usages(
Expand Down
Loading