From f314afa3953e45e115a5dd51b3eee3f6cc345884 Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sun, 22 Nov 2026 01:11:04 +0800 Subject: [PATCH 1/3] Run native and plugin file operations through the same lease owner --- crates/dim-app-server/src/plugin_files.rs | 123 ++++++++++++---------- 1 file changed, 67 insertions(+), 56 deletions(-) diff --git a/crates/dim-app-server/src/plugin_files.rs b/crates/dim-app-server/src/plugin_files.rs index 4cc0ef6de2..144aa4c585 100644 --- a/crates/dim-app-server/src/plugin_files.rs +++ b/crates/dim-app-server/src/plugin_files.rs @@ -293,59 +293,40 @@ impl FileScope { { return Err(invalid()); } - let path = match self.files.storage.path(self.files.root, name) { - Ok(path) => path, - Err(error) => return Ok(Value::future(async move { Ok(failure(error)) })), - }; - let _admission = self.files.admission.lock().unwrap(); - if self.stopping.is_cancelled() { - return Ok(Value::future(async { - Ok(failure(FileStorageError::Closed)) - })); - } - let scope = self.clone(); let acquisition = self.stopping.child_token(); let cancel_waiter = acquisition.clone().drop_guard(); - let owner = self.files.tasks.token(); - let task = self.tasks.spawn(async move { - let _owner = owner; - let acquire = acquire(&scope.files.storage, &path, &acquisition); - let cancelled = async { - match cancelled { - Some(reference) => { - let _ = reference.wait_async().await; - } - None => std::future::pending::<()>().await, - } - }; - let lease = tokio::select! { - _ = cancelled => { - acquisition.cancel(); - return Ok(failure(FileStorageError::Closed)); - } - result = acquire => match result { - Ok(lease) => lease, - Err(error) => return Ok(failure(error)), + let cancelled = async move { + match cancelled { + Some(reference) => { + let _ = reference.wait_async().await; } - }; - let lease = Arc::new(tokio::sync::Mutex::new(Some(lease))); - let result = match callback - .call_async(Value::List(vec![lease_value( - lease.clone(), - scope.tasks.clone(), - )])) - .await - { - Ok(value) => resolve(value).await, - Err(error) => Err(error), - }; - lease.lock().await.take(); - result.map(success) - }); + None => std::future::pending::<()>().await, + } + }; + let tasks = self.tasks.clone(); + let task = + self.with_file_lease(&name, acquisition, cancelled, move |lease, _| async move { + let lease = Arc::new(tokio::sync::Mutex::new(Some(lease))); + let result = match callback + .call_async(Value::List(vec![lease_value(lease.clone(), tasks)])) + .await + { + Ok(value) => resolve(value).await, + Err(error) => Err(error), + }; + lease.lock().await.take(); + result.map(success) + }); Ok(Value::future(async move { let _cancel_waiter = cancel_waiter; - task.await - .unwrap_or_else(|error| Ok(failure(FileStorageError::Worker(error)))) + match task { + Ok(task) => match task.await { + Ok(Ok(reply)) => reply, + Ok(Err(error)) => Ok(failure(error)), + Err(error) => Ok(failure(FileStorageError::Worker(error))), + }, + Err(error) => Ok(failure(error)), + } })) } } @@ -580,10 +561,16 @@ impl FileScope { name: &str, change: impl FnOnce(Option<&str>) -> (Option, R) + Send + 'static, ) -> Result { - self.run(name, move |storage, path, stopping| { - Box::pin(transact_file(storage, path, stopping, change)) - }) + self.with_file_lease( + name, + self.stopping.child_token(), + std::future::pending(), + move |lease, stopping| transact_file(lease, stopping, change), + ) + .map_err(file_error)? .await + .map_err(|error| PluginFileError::Io(error.to_string()))? + .map_err(file_error)? } /// The bytes of `name`, or `None` when it is absent. A binary file is its @@ -705,6 +692,34 @@ impl FileScope { .await } + fn with_file_lease( + &self, + name: &str, + stopping: CancellationToken, + cancelled: impl Future + Send + 'static, + action: impl FnOnce(FileLease, CancellationToken) -> RFuture + Send + 'static, + ) -> Result>, FileStorageError> + where + RFuture: Future + Send + 'static, + { + let files = &self.files; + let path = files.storage.path(files.root, name)?; + let _admission = files.admission.lock().unwrap(); + if self.stopping.is_cancelled() { + return Err(FileStorageError::Closed); + } + let storage = files.storage.clone(); + let owner = files.tasks.token(); + Ok(self.tasks.spawn(async move { + let _owner = owner; + let lease = tokio::select! { + _ = cancelled => { stopping.cancel(); return Err(FileStorageError::Closed); } + result = acquire(&storage, &path, &stopping) => result?, + }; + Ok(action(lease, stopping).await) + })) + } + async fn run( &self, name: &str, @@ -739,14 +754,10 @@ impl FileScope { } async fn transact_file( - storage: Arc, - path: FilePath, + mut lease: FileLease, stopping: CancellationToken, change: impl FnOnce(Option<&str>) -> (Option, R), ) -> Result { - let mut lease = acquire(&storage, &path, &stopping) - .await - .map_err(file_error)?; let current = read_text(&mut lease, &stopping).await.map_err(file_error)?; let (next, result) = change(current.as_deref()); if let Some(text) = next { From b5bb4b3c5be7ed6060bb557b59f9772ea903626b Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sun, 22 Nov 2026 02:03:21 +0800 Subject: [PATCH 2/3] Expose the acquired file lease to both lock callbacks --- crates/dim-agent-scheduler/src/loops.rs | 4 +- crates/dim-agent-scheduler/src/runs.rs | 4 +- crates/dim-agent-scheduler/src/wakeups.rs | 4 +- .../tests/data_faces_flow.rs | 4 +- .../tests/lifecycle_flow.rs | 2 +- .../tests/plugin_file_transactions.rs | 6 +- crates/dim-app-server/src/plugin_files.rs | 96 +++++++++---------- .../dim-app-server/tests/plugin_files_flow.rs | 6 +- crates/dim-event-hub/src/store.rs | 4 +- crates/dim-modality/src/task.rs | 4 +- 10 files changed, 66 insertions(+), 68 deletions(-) diff --git a/crates/dim-agent-scheduler/src/loops.rs b/crates/dim-agent-scheduler/src/loops.rs index 3f1d1c6e36..2b26d20274 100644 --- a/crates/dim-agent-scheduler/src/loops.rs +++ b/crates/dim-agent-scheduler/src/loops.rs @@ -300,7 +300,7 @@ pub async fn read( files: &dim_app_server::plugin_files::FileScope, ) -> Result, SchedulerError> { files - .with_lock(LOOPS_FILE, |current| (None, decode(current))) + .update_text(LOOPS_FILE, |current| (None, decode(current))) .await? } @@ -311,7 +311,7 @@ async fn update( change: impl FnOnce(&mut Vec) -> Result<(bool, R), SchedulerError> + Send + 'static, ) -> Result { files - .with_lock(LOOPS_FILE, move |current| { + .update_text(LOOPS_FILE, move |current| { let mut loops = match decode(current) { Ok(loops) => loops, Err(error) => return (None, Err(error)), diff --git a/crates/dim-agent-scheduler/src/runs.rs b/crates/dim-agent-scheduler/src/runs.rs index 1d780affa2..b590e00ea7 100644 --- a/crates/dim-agent-scheduler/src/runs.rs +++ b/crates/dim-agent-scheduler/src/runs.rs @@ -349,7 +349,7 @@ fn encode(runs: Vec) -> String { /// history. pub async fn read(files: &FileScope) -> Result, SchedulerError> { files - .with_lock(RUNS_FILE, |current| (None, decode(current))) + .update_text(RUNS_FILE, |current| (None, decode(current))) .await? } @@ -360,7 +360,7 @@ pub async fn update( change: impl FnOnce(&mut Vec) -> Result<(bool, R), SchedulerError> + Send + 'static, ) -> Result { files - .with_lock(RUNS_FILE, move |current| { + .update_text(RUNS_FILE, move |current| { let mut runs = match decode(current) { Ok(runs) => runs, Err(error) => return (None, Err(error)), diff --git a/crates/dim-agent-scheduler/src/wakeups.rs b/crates/dim-agent-scheduler/src/wakeups.rs index fab736c5cf..f6a3c14e24 100644 --- a/crates/dim-agent-scheduler/src/wakeups.rs +++ b/crates/dim-agent-scheduler/src/wakeups.rs @@ -156,7 +156,7 @@ pub async fn read( files: &dim_app_server::plugin_files::FileScope, ) -> Result, SchedulerError> { files - .with_lock(WAKEUPS_FILE, |current| (None, decode(current))) + .update_text(WAKEUPS_FILE, |current| (None, decode(current))) .await? } @@ -167,7 +167,7 @@ async fn update( change: impl FnOnce(&mut Vec) -> Result<(bool, R), SchedulerError> + Send + 'static, ) -> Result { files - .with_lock(WAKEUPS_FILE, move |current| { + .update_text(WAKEUPS_FILE, move |current| { let mut wakeups = match decode(current) { Ok(wakeups) => wakeups, Err(error) => return (None, Err(error)), diff --git a/crates/dim-agent-scheduler/tests/data_faces_flow.rs b/crates/dim-agent-scheduler/tests/data_faces_flow.rs index f529f16db7..d665c86712 100644 --- a/crates/dim-agent-scheduler/tests/data_faces_flow.rs +++ b/crates/dim-agent-scheduler/tests/data_faces_flow.rs @@ -159,7 +159,7 @@ impl Rig { let (entered, entered_rx) = tokio::sync::oneshot::channel(); let task = tokio::spawn(async move { files - .with_lock("scheduler/loops.json", move |_| { + .update_text("scheduler/loops.json", move |_| { entered.send(()).unwrap(); held.recv_timeout(Duration::from_secs(30)).unwrap(); (None, ()) @@ -182,7 +182,7 @@ impl Rig { let (entered, entered_rx) = tokio::sync::oneshot::channel(); let task = tokio::spawn(async move { files - .with_lock("scheduler/wakeups.json", move |_| { + .update_text("scheduler/wakeups.json", move |_| { entered.send(()).unwrap(); held.recv_timeout(Duration::from_secs(30)).unwrap(); (None, ()) diff --git a/crates/dim-agent-scheduler/tests/lifecycle_flow.rs b/crates/dim-agent-scheduler/tests/lifecycle_flow.rs index 7f239d2311..edaececd14 100644 --- a/crates/dim-agent-scheduler/tests/lifecycle_flow.rs +++ b/crates/dim-agent-scheduler/tests/lifecycle_flow.rs @@ -621,7 +621,7 @@ async fn hold_runs_file( let (entered, entered_rx) = tokio::sync::oneshot::channel(); let task = tokio::spawn(async move { files - .with_lock("scheduler/runs.json", move |_| { + .update_text("scheduler/runs.json", move |_| { entered.send(()).unwrap(); held.recv_timeout(std::time::Duration::from_secs(30)) .unwrap(); diff --git a/crates/dim-agent-scheduler/tests/plugin_file_transactions.rs b/crates/dim-agent-scheduler/tests/plugin_file_transactions.rs index 360ed88ae3..511a822ebd 100644 --- a/crates/dim-agent-scheduler/tests/plugin_file_transactions.rs +++ b/crates/dim-agent-scheduler/tests/plugin_file_transactions.rs @@ -30,17 +30,17 @@ impl DynPlugin for Probe { let observed = self.observed.clone(); tokio::spawn(async move { let created = files - .with_lock("scheduler/runs.json", |current| { + .update_text("scheduler/runs.json", |current| { (Some("first".to_owned()), current.map(str::to_owned)) }) .await; let read = files - .with_lock("scheduler/runs.json", |current| { + .update_text("scheduler/runs.json", |current| { (None, current.map(str::to_owned)) }) .await; let refused = files - .with_lock("scheduler/invalid.json", |_| (Some("never".to_owned()), ())) + .update_text("scheduler/invalid.json", |_| (Some("never".to_owned()), ())) .await; let _ = observed.set(json!({ "created": format!("{created:?}"), diff --git a/crates/dim-app-server/src/plugin_files.rs b/crates/dim-app-server/src/plugin_files.rs index 144aa4c585..c5e0c58475 100644 --- a/crates/dim-app-server/src/plugin_files.rs +++ b/crates/dim-app-server/src/plugin_files.rs @@ -293,38 +293,36 @@ impl FileScope { { return Err(invalid()); } - let acquisition = self.stopping.child_token(); + let acquisition = CancellationToken::new(); let cancel_waiter = acquisition.clone().drop_guard(); let cancelled = async move { - match cancelled { + tokio::select! { + _ = acquisition.cancelled() => (), + _ = async { match cancelled { Some(reference) => { let _ = reference.wait_async().await; } None => std::future::pending::<()>().await, + }} => (), } }; let tasks = self.tasks.clone(); - let task = - self.with_file_lease(&name, acquisition, cancelled, move |lease, _| async move { - let lease = Arc::new(tokio::sync::Mutex::new(Some(lease))); - let result = match callback - .call_async(Value::List(vec![lease_value(lease.clone(), tasks)])) - .await - { - Ok(value) => resolve(value).await, - Err(error) => Err(error), - }; - lease.lock().await.take(); - result.map(success) - }); + let task = self.with_lock(&name, cancelled, move |lease, _| async move { + let lease = Arc::new(tokio::sync::Mutex::new(Some(lease))); + let result = match callback + .call_async(Value::List(vec![lease_value(lease.clone(), tasks)])) + .await + { + Ok(value) => resolve(value).await, + Err(error) => Err(error), + }; + lease.lock().await.take(); + result.map(success) + }); Ok(Value::future(async move { let _cancel_waiter = cancel_waiter; - match task { - Ok(task) => match task.await { - Ok(Ok(reply)) => reply, - Ok(Err(error)) => Ok(failure(error)), - Err(error) => Ok(failure(FileStorageError::Worker(error))), - }, + match task.await { + Ok(reply) => reply, Err(error) => Ok(failure(error)), } })) @@ -556,20 +554,15 @@ impl FileScope { /// transaction returns. An envelope that is not version 1 fails with /// [`PluginFileError::InvalidData`] before `change` runs, and the bytes are /// left as they were. - pub async fn with_lock( + pub async fn update_text( &self, name: &str, change: impl FnOnce(Option<&str>) -> (Option, R) + Send + 'static, ) -> Result { - self.with_file_lease( - name, - self.stopping.child_token(), - std::future::pending(), - move |lease, stopping| transact_file(lease, stopping, change), - ) - .map_err(file_error)? + self.with_lock(name, std::future::pending(), move |lease, stopping| { + transact_file(lease, stopping, change) + }) .await - .map_err(|error| PluginFileError::Io(error.to_string()))? .map_err(file_error)? } @@ -692,32 +685,37 @@ impl FileScope { .await } - fn with_file_lease( + /// Runs one callback with the acquired lease. Cancellation while waiting for the lock skips the callback. + pub fn with_lock( &self, name: &str, - stopping: CancellationToken, cancelled: impl Future + Send + 'static, action: impl FnOnce(FileLease, CancellationToken) -> RFuture + Send + 'static, - ) -> Result>, FileStorageError> + ) -> impl Future> + Send + 'static where RFuture: Future + Send + 'static, { - let files = &self.files; - let path = files.storage.path(files.root, name)?; - let _admission = files.admission.lock().unwrap(); - if self.stopping.is_cancelled() { - return Err(FileStorageError::Closed); - } - let storage = files.storage.clone(); - let owner = files.tasks.token(); - Ok(self.tasks.spawn(async move { - let _owner = owner; - let lease = tokio::select! { - _ = cancelled => { stopping.cancel(); return Err(FileStorageError::Closed); } - result = acquire(&storage, &path, &stopping) => result?, - }; - Ok(action(lease, stopping).await) - })) + let start = || { + let files = &self.files; + let path = files.storage.path(files.root, name)?; + let _admission = files.admission.lock().unwrap(); + if self.stopping.is_cancelled() { + return Err(FileStorageError::Closed); + } + let storage = files.storage.clone(); + let owner = files.tasks.token(); + let stopping = self.stopping.child_token(); + Ok(self.tasks.spawn(async move { + let _owner = owner; + let lease = tokio::select! { + _ = cancelled => { stopping.cancel(); return Err(FileStorageError::Closed); } + result = acquire(&storage, &path, &stopping) => result?, + }; + Ok(action(lease, stopping).await) + })) + }; + let task = start(); + async move { task?.await.map_err(FileStorageError::Worker)? } } async fn run( diff --git a/crates/dim-app-server/tests/plugin_files_flow.rs b/crates/dim-app-server/tests/plugin_files_flow.rs index 40f3b04ed7..71660b9c93 100644 --- a/crates/dim-app-server/tests/plugin_files_flow.rs +++ b/crates/dim-app-server/tests/plugin_files_flow.rs @@ -634,7 +634,7 @@ async fn binary_files_round_trip_and_stream_without_an_envelope() { ); files - .with_lock("media/text.json", |_| (Some("inner".to_owned()), ())) + .update_text("media/text.json", |_| (Some("inner".to_owned()), ())) .await .unwrap(); let read = call( @@ -661,7 +661,7 @@ async fn binary_files_round_trip_and_stream_without_an_envelope() { ); assert_eq!( files - .with_lock("media/blob.bin", |current| ( + .update_text("media/blob.bin", |current| ( None, current.map(str::to_owned) )) @@ -811,7 +811,7 @@ async fn list_remove_and_work_directories_follow_the_root_and_its_leases() { .await .unwrap(); files - .with_lock("media/tasks/a1/task.json", |_| { + .update_text("media/tasks/a1/task.json", |_| { (Some("record".to_owned()), ()) }) .await diff --git a/crates/dim-event-hub/src/store.rs b/crates/dim-event-hub/src/store.rs index 1c0b91d291..a8b563af74 100644 --- a/crates/dim-event-hub/src/store.rs +++ b/crates/dim-event-hub/src/store.rs @@ -254,7 +254,7 @@ impl Store { let _guard = self.state.change_lock().await; let document = self .files - .with_lock(SUBSCRIPTIONS_FILE, |current| (None, decode(current))) + .update_text(SUBSCRIPTIONS_FILE, |current| (None, decode(current))) .await .map_err(|error| error.to_string())??; self.state.replace_subscriptions(document); @@ -288,7 +288,7 @@ impl Store { let _guard = self.state.change_lock().await; let outcome = self .files - .with_lock(SUBSCRIPTIONS_FILE, move |current| { + .update_text(SUBSCRIPTIONS_FILE, move |current| { let mut document = match decode(current) { Ok(document) => document, Err(error) => { diff --git a/crates/dim-modality/src/task.rs b/crates/dim-modality/src/task.rs index 371de85d2a..57fb79ce9b 100644 --- a/crates/dim-modality/src/task.rs +++ b/crates/dim-modality/src/task.rs @@ -222,7 +222,7 @@ fn parse(text: &str) -> Result { /// taken and the bytes are left unchanged. pub async fn load(files: &FileScope, task_id: &str) -> Result, StoreError> { let parsed = files - .with_lock(&record_name(task_id), |text| { + .update_text(&record_name(task_id), |text| { (None, text.map(parse).transpose()) }) .await?; @@ -246,7 +246,7 @@ pub async fn write( ) -> Result { let name = record_name(&record.task_id); let outcome = files - .with_lock(&name, move |text| { + .update_text(&name, move |text| { let current = match text { Some(text) => match parse(text) { Ok(current) => Some(current), From 68c67d92d0aef3cb09e63628db33041a218c6b8f Mon Sep 17 00:00:00 2001 From: eric8810 Date: Sun, 22 Nov 2026 02:07:48 +0800 Subject: [PATCH 3/3] Simplify cancellation of a remote lock acquisition --- crates/dim-app-server/src/plugin_files.rs | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/crates/dim-app-server/src/plugin_files.rs b/crates/dim-app-server/src/plugin_files.rs index c5e0c58475..3702104aa0 100644 --- a/crates/dim-app-server/src/plugin_files.rs +++ b/crates/dim-app-server/src/plugin_files.rs @@ -296,14 +296,13 @@ impl FileScope { let acquisition = CancellationToken::new(); let cancel_waiter = acquisition.clone().drop_guard(); let cancelled = async move { - tokio::select! { - _ = acquisition.cancelled() => (), - _ = async { match cancelled { - Some(reference) => { - let _ = reference.wait_async().await; + if let Some(reference) = cancelled { + tokio::select! { + _ = acquisition.cancelled() => (), + _ = reference.wait_async() => (), } - None => std::future::pending::<()>().await, - }} => (), + } else { + acquisition.cancelled().await } }; let tasks = self.tasks.clone();