use std::{future::Future, time::Instant};
use super::{Outcome, RepositoryMonitor};
use crate::{
Repository, Result,
error::{ResultExt, message},
};
struct WorkerOwned<T: Send + 'static> {
value: Option<T>,
runtime: tokio::runtime::Handle,
}
impl<T: Send + 'static> Drop for WorkerOwned<T> {
fn drop(&mut self) {
if let Some(value) = self.value.take() {
self.runtime.spawn_blocking(move || drop(value));
}
}
}
impl RepositoryMonitor {
pub fn service_async(
mut self,
now: Instant,
opener: impl FnMut() -> Result<Repository> + Send + 'static,
) -> impl Future<Output = Result<(Self, Outcome)>> {
let runtime = tokio::runtime::Handle::current();
let task = tokio::task::spawn_blocking(move || {
let outcome = self.service(now, opener);
WorkerOwned {
value: Some((self, outcome)),
runtime,
}
});
async move {
let mut reply = task.await.or_raise(|| message("servicing repository notifications"))?;
Ok(reply
.value
.take()
.expect("the service worker returns one complete outcome"))
}
}
pub(super) fn install_async_wakers(&mut self) {
for domain in [&mut self.metadata, &mut self.worktree] {
if let Some(watcher) = &mut domain.watcher {
let wake = self.wake.clone();
watcher.set_waker(move || wake.notify_one());
}
}
for other in self.other_worktrees.values_mut() {
other.wake = self.wake.clone();
other.install_async_wakers();
}
}
fn async_ready(&self, now: Instant) -> bool {
self.backlog
|| [&self.metadata, &self.worktree]
.into_iter()
.any(|domain| domain.watcher.as_ref().is_some_and(gix_notify::Watcher::is_ready))
|| self.async_deadline().is_some_and(|deadline| deadline <= now)
|| self.other_worktrees.values().any(|other| other.async_ready(now))
}
fn async_deadline(&self) -> Option<Instant> {
[self.maintenance, self.pending_metadata.deadline]
.into_iter()
.flatten()
.chain(self.other_worktrees.values().filter_map(Self::async_deadline))
.min()
}
pub async fn ready_async(&self) {
if !self.active() {
return;
}
loop {
let notified = self.wake.notified();
if self.async_ready(Instant::now()) {
return;
}
match self.async_deadline() {
Some(deadline) => tokio::select! {
_ = notified => {},
_ = tokio::time::sleep_until(deadline.into()) => return,
},
None => notified.await,
}
}
}
pub fn shutdown_async(self) -> impl Future<Output = Result<()>> {
let task = tokio::task::spawn_blocking(move || drop(self));
async move {
task.await
.or_raise(|| message("shutting down repository notifications"))
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
#[tokio::test(flavor = "current_thread")]
async fn abandoning_a_completed_worker_reply_drops_its_value_off_the_executor() -> gix_error::TestResult {
struct RecordDrop(Option<tokio::sync::oneshot::Sender<std::thread::ThreadId>>);
impl Drop for RecordDrop {
fn drop(&mut self) {
if let Some(record) = self.0.take() {
let _ = record.send(std::thread::current().id());
}
}
}
let executor = std::thread::current().id();
let runtime = tokio::runtime::Handle::current();
let (record, mut dropped) = tokio::sync::oneshot::channel();
let task = tokio::task::spawn_blocking(move || WorkerOwned {
value: Some(RecordDrop(Some(record))),
runtime,
});
tokio::time::timeout(Duration::from_secs(2), async {
while !task.is_finished() {
tokio::task::yield_now().await;
}
})
.await?;
assert!(
matches!(
dropped.try_recv(),
Err(tokio::sync::oneshot::error::TryRecvError::Empty)
),
"the completed task retains its value until the reply is claimed or abandoned"
);
let reply = async move { task.await };
drop(reply);
assert_ne!(
tokio::time::timeout(Duration::from_secs(2), dropped).await??,
executor,
"abandoning an unclaimed completed reply drops its contained value on a blocking worker"
);
Ok(())
}
}