Skip to content
Closed
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
4 changes: 2 additions & 2 deletions crates/dim-agent-scheduler/src/loops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,7 +300,7 @@ pub async fn read(
files: &dim_app_server::plugin_files::FileScope,
) -> Result<Vec<Loop>, SchedulerError> {
files
.with_lock(LOOPS_FILE, |current| (None, decode(current)))
.update_text(LOOPS_FILE, |current| (None, decode(current)))
.await?
}

Expand All @@ -311,7 +311,7 @@ async fn update<R: Send + 'static>(
change: impl FnOnce(&mut Vec<Loop>) -> Result<(bool, R), SchedulerError> + Send + 'static,
) -> Result<R, SchedulerError> {
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)),
Expand Down
4 changes: 2 additions & 2 deletions crates/dim-agent-scheduler/src/runs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ fn encode(runs: Vec<Delivery>) -> String {
/// history.
pub async fn read(files: &FileScope) -> Result<Vec<Delivery>, SchedulerError> {
files
.with_lock(RUNS_FILE, |current| (None, decode(current)))
.update_text(RUNS_FILE, |current| (None, decode(current)))
.await?
}

Expand All @@ -360,7 +360,7 @@ pub async fn update<R: Send + 'static>(
change: impl FnOnce(&mut Vec<Delivery>) -> Result<(bool, R), SchedulerError> + Send + 'static,
) -> Result<R, SchedulerError> {
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)),
Expand Down
4 changes: 2 additions & 2 deletions crates/dim-agent-scheduler/src/wakeups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ pub async fn read(
files: &dim_app_server::plugin_files::FileScope,
) -> Result<Vec<Wakeup>, SchedulerError> {
files
.with_lock(WAKEUPS_FILE, |current| (None, decode(current)))
.update_text(WAKEUPS_FILE, |current| (None, decode(current)))
.await?
}

Expand All @@ -167,7 +167,7 @@ async fn update<R: Send + 'static>(
change: impl FnOnce(&mut Vec<Wakeup>) -> Result<(bool, R), SchedulerError> + Send + 'static,
) -> Result<R, SchedulerError> {
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)),
Expand Down
4 changes: 2 additions & 2 deletions crates/dim-agent-scheduler/tests/data_faces_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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, ())
Expand All @@ -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, ())
Expand Down
2 changes: 1 addition & 1 deletion crates/dim-agent-scheduler/tests/lifecycle_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
6 changes: 3 additions & 3 deletions crates/dim-agent-scheduler/tests/plugin_file_transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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:?}"),
Expand Down
102 changes: 55 additions & 47 deletions crates/dim-app-server/src/plugin_files.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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)),
}
}))
}
}
Expand Down Expand Up @@ -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<R: Send + 'static>(
pub async fn update_text<R: Send + 'static>(
&self,
name: &str,
change: impl FnOnce(Option<&str>) -> (Option<String>, R) + Send + 'static,
) -> Result<R, PluginFileError> {
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
Expand Down Expand Up @@ -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<R: Send + 'static, RFuture>(
&self,
name: &str,
cancelled: impl Future<Output = ()> + Send + 'static,
action: impl FnOnce(FileLease, CancellationToken) -> RFuture + Send + 'static,
) -> impl Future<Output = Result<R, FileStorageError>> + Send + 'static
where
RFuture: Future<Output = R> + 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<R: Send + 'static>(
&self,
name: &str,
Expand Down Expand Up @@ -739,14 +751,10 @@ impl FileScope {
}

async fn transact_file<R>(
storage: Arc<FileStorage>,
path: FilePath,
mut lease: FileLease,
stopping: CancellationToken,
change: impl FnOnce(Option<&str>) -> (Option<String>, R),
) -> Result<R, PluginFileError> {
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 {
Expand Down
6 changes: 3 additions & 3 deletions crates/dim-app-server/tests/plugin_files_flow.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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)
))
Expand Down Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions crates/dim-event-hub/src/store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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) => {
Expand Down
4 changes: 2 additions & 2 deletions crates/dim-modality/src/task.rs
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ fn parse(text: &str) -> Result<TaskRecord, serde_json::Error> {
/// taken and the bytes are left unchanged.
pub async fn load(files: &FileScope, task_id: &str) -> Result<Option<TaskRecord>, StoreError> {
let parsed = files
.with_lock(&record_name(task_id), |text| {
.update_text(&record_name(task_id), |text| {
(None, text.map(parse).transpose())
})
.await?;
Expand All @@ -246,7 +246,7 @@ pub async fn write(
) -> Result<Write, StoreError> {
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),
Expand Down