From 74bd7b485aff863015fa02b2c8d4df3742808ee5 Mon Sep 17 00:00:00 2001 From: Piotr Osiewicz <24362066+osiewicz@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:20:53 +0100 Subject: [PATCH] Remove resource locks while retaining shared acquisition --- Cargo.lock | 1 - crates/managed_resources/Cargo.toml | 1 - .../src/managed_resources.rs | 201 ++++++++---------- 3 files changed, 94 insertions(+), 109 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 070e90b011f..c3627adfac7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10498,7 +10498,6 @@ name = "managed_resources" version = "0.1.0" dependencies = [ "anyhow", - "async-lock", "futures 0.3.34", "gpui", "serde", diff --git a/crates/managed_resources/Cargo.toml b/crates/managed_resources/Cargo.toml index 2f8e6714c57..9f75a537dbb 100644 --- a/crates/managed_resources/Cargo.toml +++ b/crates/managed_resources/Cargo.toml @@ -14,7 +14,6 @@ doctest = false [dependencies] anyhow.workspace = true -async-lock.workspace = true futures.workspace = true gpui.workspace = true serde = { workspace = true, features = ["derive"] } diff --git a/crates/managed_resources/src/managed_resources.rs b/crates/managed_resources/src/managed_resources.rs index b3c5a965fe9..1a60cb536a0 100644 --- a/crates/managed_resources/src/managed_resources.rs +++ b/crates/managed_resources/src/managed_resources.rs @@ -10,7 +10,6 @@ //! In order to interact with a resource, you ought to implement [ManagedResourceCommand]. //! One example of a resource is a language server binary. Zed may need to install it on user's behalf. The user may also want us to use the binary available on their system. //! But then, whenever we want to invoke said binary, we should let the user know as well, as running arbitrary processes on their PC might affect their machine state. -use async_lock::{RwLock, RwLockUpgradableReadGuard, RwLockWriteGuard}; use futures::{ FutureExt, future::{LocalBoxFuture, Shared}, @@ -96,8 +95,7 @@ pub trait ManagedResourceCommand: Sized + 'static { /// Describe the specific operation for approval without performing it. fn permission_description(&self, resource: &Resource) -> String; - /// Await resource-using background work: the store releases its read guard - /// when this future completes or is dropped. + /// Await background work so completion, errors, and cancellation follow this command. fn run( self, resource: &Resource, @@ -293,21 +291,14 @@ impl ManagedResourceStore { cx.notify(); } - /// Resource approval and acquisition are shared; commands may run concurrently. - /// Commands without a configured permission require separate approval, which is not persisted. - /// Dropping the returned task cancels that command, not shared acquisition. - /// Management permission only gates deferred actions, never existing resources. - /// Revocation cannot cancel commands or management attempts already running. - pub fn execute_command( + fn acquire_resource( &mut self, - key: Resource::Key, + key: Rc, context: Rc, bill: ResourceExecutionBill, - command: impl ManagedResourceCommand, cx: &mut Context, - ) -> Task> { + ) -> ResourceTask { let id = Resource::id(&key); - let key = Rc::new(key); let entry = self .resources .entry(id.clone()) @@ -318,10 +309,10 @@ impl ManagedResourceStore { permission_revision: 0, }); if entry.resource_type != TypeId::of::() { - return Task::ready(Err(ResourceAccessError::ConflictingResourceType)); + return Task::ready(Err(ResourceAccessError::ConflictingResourceType)).shared(); } - let resource = if let Some(pending) = &entry.pending { + if let Some(pending) = &entry.pending { pending.clone() } else { let value = entry.value.clone(); @@ -334,7 +325,12 @@ impl ManagedResourceStore { async move |this, cx| { let result = async { if let Some(value) = value { - return Ok(value); + let resource = value + .downcast::() + .map_err(|_| ResourceAccessError::ConflictingResourceType)?; + if resource.is_current(&context) { + return Ok(resource as Arc); + } } let acquisition = Resource::obtain(&key, &context) .await @@ -349,7 +345,7 @@ impl ManagedResourceStore { })? } }; - Ok(Arc::new(RwLock::new(resource)) as Arc) + Ok(Arc::new(resource) as Arc) } .await; this.update(cx, |this, _| { @@ -367,39 +363,53 @@ impl ManagedResourceStore { .shared(); entry.pending = Some(pending.clone()); pending - }; + } + } + + /// Resource approval and acquisition are shared; commands may run concurrently. + /// Dropping the returned task cancels that command, not shared acquisition. + /// Management permission only gates deferred actions, never existing resources. + /// Revocation cannot cancel commands or management attempts already running. + /// Resource implementations are responsible for coordinating mutations with use. + pub fn execute_command( + &mut self, + key: Resource::Key, + context: Rc, + bill: ResourceExecutionBill, + command: impl ManagedResourceCommand, + cx: &mut Context, + ) -> Task> { + let id = Resource::id(&key); + let key = Rc::new(key); + let mut acquisition = + self.acquire_resource::(key.clone(), context.clone(), bill.clone(), cx); cx.spawn(async move |this, cx| { - let resource = resource.await?; + let resource = loop { + let resource = acquisition + .await? + .downcast::() + .map_err(|_| ResourceAccessError::ConflictingResourceType)?; + if resource.is_current(&context) { + break resource; + } + // A shared acquisition may have used another caller's configuration. + acquisition = this + .update(cx, |this, cx| { + this.acquire_resource::( + key.clone(), + context.clone(), + bill.clone(), + cx, + ) + }) + .map_err(|_| ResourceAccessError::StoreDropped)?; + }; let payload = serde_json::to_value(command.command_kind()) .map_err(|error| ResourceAccessError::CommandPayload(Arc::new(error)))?; let request_approval = this .read_with(cx, |this, _| this.request_approval.clone()) .map_err(|_| ResourceAccessError::StoreDropped)?; - let resource = resource - .downcast::>() - .map_err(|_| ResourceAccessError::ConflictingResourceType)?; - // Keep the resource unchanged between describing the operation and completing it. - let resource = resource.upgradable_read().await; - let resource = if resource.is_current(&context) { - RwLockUpgradableReadGuard::downgrade(resource) - } else { - let mut resource = RwLockUpgradableReadGuard::upgrade(resource).await; - let acquisition = Resource::obtain(&key, &context) - .await - .map_err(|error| ResourceAccessError::Obtain(Arc::new(error)))?; - let replacement = match acquisition { - ResourceAcquisition::Ready { resource, .. } => resource, - ResourceAcquisition::RequiresAction(action) => { - Self::ensure_permission(&this, &id, &bill, cx).await?; - action() - .await - .map_err(|error| ResourceAccessError::Obtain(Arc::new(error)))? - } - }; - *resource = replacement; - RwLockWriteGuard::downgrade(resource) - }; let request = ResourcePermissionRequest::ExecuteCommand { resource: id.clone(), description: command.permission_description(&resource), @@ -707,7 +717,7 @@ mod tests { } #[gpui::test] - async fn configuration_changes_wait_for_commands_and_preserve_resource_on_failure( + async fn configuration_changes_do_not_wait_for_commands_and_preserve_resource_on_failure( cx: &mut TestAppContext, ) { let allow_management = Rc::new(Cell::new(true)); @@ -750,14 +760,12 @@ mod tests { update_value: Some(21), ..Default::default() }); - let mut refreshing = execute::<0>(&store, "first", &replacement, TestCommand::Read, cx); + let refreshing = execute::<0>(&store, "first", &replacement, TestCommand::Read, cx); cx.run_until_parked(); - assert!(poll!(&mut refreshing).is_pending()); - assert_eq!(replacement.obtain_count.get(), 0); - finish.send(()).expect("command still running"); - assert_eq!(running.await.expect("permission"), Ok(9)); assert_eq!(refreshing.await.expect("permission"), Ok(21)); assert_eq!(replacement.obtain_count.get(), 1); + finish.send(()).expect("command still running"); + assert_eq!(running.await.expect("permission"), Ok(9)); let broken = Rc::new(TestContext { configuration: 2, @@ -1562,64 +1570,43 @@ mod tests { } #[gpui::test] - async fn resource_writes_exclude_commands(cx: &mut TestAppContext) { - for cancel_command in [false, true] { - let store = new_store(cx); - let context = Rc::new(TestContext::default()); - let id = TestResource::id(&"first"); - store.update(cx, |store, cx| { - store.set_permission(id.clone(), ResourcePermission::Allowed, cx); - }); - let (ready, wait) = oneshot::channel(); - let started = Rc::new(Cell::new(false)); - let command = execute::<0>( - &store, - "first", - &context, - TestCommand::Wait { - started: started.clone(), - ready: wait, - value: 7, - }, - cx, - ); - cx.run_until_parked(); - assert!(started.get()); - let resource = store.read_with(cx, |store, _| { - store - .resources - .get(&id) - .expect("resource cached") - .value - .clone() - .expect("resource acquired") - .downcast::>() - .expect("resource type") - }); - let mut modification = Box::pin(resource.write()); - assert!(poll!(&mut modification).is_pending()); - if cancel_command { - drop(command); - cx.run_until_parked(); - } else { - ready.send(()).expect("command waiting"); - assert_eq!(command.await.expect("command completed"), Ok(12)); - } - let mut writer = modification.await; - assert_eq!( - writer.value.load(SeqCst), - if cancel_command { 5 } else { 12 } - ); - let mut read = execute::<0>(&store, "first", &context, TestCommand::Read, cx); - cx.run_until_parked(); - assert!(poll!(&mut read).is_pending()); - *writer = Counter { - value: AtomicUsize::new(23), - configuration: context.configuration, - }; - drop(writer); - assert_eq!(read.await.expect("read after modification"), Ok(23)); - } + async fn concurrent_refreshes_share_acquisition_and_respect_configuration( + cx: &mut TestAppContext, + ) { + let store = new_store(cx); + store.update(cx, |store, cx| { + store.set_permission(TestResource::id(&"first"), ResourcePermission::Allowed, cx); + }); + let original = Rc::new(TestContext::default()); + assert_eq!( + execute::<0>(&store, "first", &original, TestCommand::Read, cx) + .await + .expect("original"), + Ok(5) + ); + let (ready, wait) = oneshot::channel(); + let replacement = Rc::new(TestContext { + configuration: 1, + update_value: Some(23), + obtain_ready: Rc::new(Cell::new(Some(wait))), + ..Default::default() + }); + let first = execute::<0>(&store, "first", &replacement, TestCommand::Read, cx); + let second = execute::<0>(&store, "first", &replacement, TestCommand::Read, cx); + cx.run_until_parked(); + assert_eq!(replacement.obtain_count.get(), 1); + let different = Rc::new(TestContext { + configuration: 2, + update_value: Some(41), + ..Default::default() + }); + let third = execute::<0>(&store, "first", &different, TestCommand::Read, cx); + ready.send(()).expect("refresh waiting"); + assert_eq!(first.await.expect("first refresh"), Ok(23)); + assert_eq!(second.await.expect("shared refresh"), Ok(23)); + assert_eq!(third.await.expect("different configuration"), Ok(41)); + assert_eq!(replacement.obtain_count.get(), 1); + assert_eq!(different.obtain_count.get(), 1); } #[gpui::test]