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 4cc0ef6de2..3702104aa0 100644 --- a/crates/dim-app-server/src/plugin_files.rs +++ b/crates/dim-app-server/src/plugin_files.rs @@ -293,47 +293,23 @@ 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 acquisition = CancellationToken::new(); 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 { + if let Some(reference) = cancelled { + tokio::select! { + _ = acquisition.cancelled() => (), + _ = reference.wait_async() => (), } - }; + } else { + acquisition.cancelled().await + } + }; + let tasks = self.tasks.clone(); + 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(), - scope.tasks.clone(), - )])) + .call_async(Value::List(vec![lease_value(lease.clone(), tasks)])) .await { Ok(value) => resolve(value).await, @@ -344,8 +320,10 @@ impl FileScope { }); Ok(Value::future(async move { let _cancel_waiter = cancel_waiter; - task.await - .unwrap_or_else(|error| Ok(failure(FileStorageError::Worker(error)))) + match task.await { + Ok(reply) => reply, + Err(error) => Ok(failure(error)), + } })) } } @@ -575,15 +553,16 @@ 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.run(name, move |storage, path, stopping| { - Box::pin(transact_file(storage, path, stopping, change)) + self.with_lock(name, std::future::pending(), move |lease, stopping| { + transact_file(lease, stopping, change) }) .await + .map_err(file_error)? } /// The bytes of `name`, or `None` when it is absent. A binary file is its @@ -705,6 +684,39 @@ impl FileScope { .await } + /// Runs one callback with the acquired lease. Cancellation while waiting for the lock skips the callback. + pub fn with_lock( + &self, + name: &str, + cancelled: impl Future + Send + 'static, + action: impl FnOnce(FileLease, CancellationToken) -> RFuture + Send + 'static, + ) -> impl Future> + Send + 'static + where + RFuture: Future + Send + 'static, + { + 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( &self, name: &str, @@ -739,14 +751,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 { 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),