use core::future::Future;
use std::{sync::Arc, thread::JoinHandle, time::Instant};
use agnostic_lite::RuntimeLite;
use crate::{
batch::{Batcher, Debounce, Push},
conduit::{Arm, select},
drive::{ItemId, channel::Outbox, lane::block_until},
source::{Feed, ShutdownSignal, Stopper, Yielded, shutdown_signal},
};
use super::{Registry, RootAdvance, RootKey, Stamp};
#[cfg(test)]
mod tests;
const THREAD_NAME: &str = "ingraph-registry";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DriverEngine {
Task,
Thread,
}
impl DriverEngine {
#[inline]
#[must_use]
pub const fn as_str(&self) -> &'static str {
match self {
Self::Task => "task",
Self::Thread => "thread",
}
}
}
pub struct RegistryDriver {
stop: Option<Stopper>,
body: Option<JoinHandle<()>>,
}
impl core::fmt::Debug for RegistryDriver {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RegistryDriver")
.field("engine", &self.engine())
.finish()
}
}
impl RegistryDriver {
#[must_use]
pub fn spawn<Root>(
registry: Arc<Registry<Root>>,
keys: Yielded<Root>,
head: Outbox<ItemId, Root>,
) -> Self
where
Root: RootKey,
{
let (stop, halt) = shutdown_signal();
let machine = Machine::new(registry, head);
let body = std::thread::Builder::new()
.name(THREAD_NAME.to_owned())
.spawn(move || run_parked(machine, &keys, &halt))
.expect("the registry driver thread");
Self {
stop: Some(stop),
body: Some(body),
}
}
#[must_use]
pub fn spawn_on<R, Root>(
registry: Arc<Registry<Root>>,
keys: Yielded<Root>,
head: Outbox<ItemId, Root>,
) -> Self
where
R: RuntimeLite,
Root: RootKey,
{
let (stop, halt) = shutdown_signal();
R::spawn_detach(run_task::<R, Root>(
Machine::new(registry, head),
keys,
halt,
));
Self::stopping(stop)
}
#[inline]
#[must_use]
pub(crate) const fn stopping(stop: Stopper) -> Self {
Self {
stop: Some(stop),
body: None,
}
}
#[inline]
#[must_use]
pub const fn engine(&self) -> DriverEngine {
match self.body {
Some(_) => DriverEngine::Thread,
None => DriverEngine::Task,
}
}
}
pub(crate) fn body<R, Root>(
registry: Arc<Registry<Root>>,
keys: Yielded<Root>,
head: Outbox<ItemId, Root>,
halt: ShutdownSignal,
) -> impl Future<Output = ()> + Send + 'static
where
R: RuntimeLite,
Root: RootKey,
{
run_task::<R, Root>(Machine::new(registry, head), keys, halt)
}
impl Drop for RegistryDriver {
fn drop(&mut self) {
drop(self.stop.take());
if let Some(body) = self.body.take() {
let _ = body.join();
}
}
}
enum Turn<Root> {
Key(Root),
Ended,
Due,
Halt,
}
struct Machine<Root: 'static> {
registry: Arc<Registry<Root>>,
head: Feed<Root>,
debounce: Debounce<Root>,
batcher: Batcher<Root>,
}
impl<Root: RootKey> Machine<Root> {
fn new(registry: Arc<Registry<Root>>, head: Outbox<ItemId, Root>) -> Self {
let options = registry.options();
Self {
registry,
head: Feed::bridging(head),
debounce: Debounce::new(options.debounce()),
batcher: Batcher::new(options.batch_max_items(), options.batch_max_wait()),
}
}
fn deadline(&self) -> Option<Instant> {
match (self.debounce.deadline(), self.batcher.deadline()) {
(Some(quiet), Some(batch)) => Some(quiet.min(batch)),
(deadline, None) | (None, deadline) => deadline,
}
}
#[inline]
fn touched(&mut self, key: Root, now: Instant) {
self.debounce.touch(key, now);
}
fn ripened(&mut self, now: Instant) -> Vec<Vec<Root>> {
let mut closed = Vec::new();
for key in self.debounce.ripe(now) {
let mut offered = key;
loop {
match self.batcher.push(offered, now) {
Push::Queued => break,
Push::Full => {
closed.push(self.batcher.drain());
break;
}
Push::Refused(back) => {
closed.push(self.batcher.drain());
offered = back;
}
}
}
}
closed
}
fn due(&mut self, now: Instant) -> Option<Vec<Root>> {
self.batcher.ready(now).then(|| self.batcher.drain())
}
fn ended(&mut self, now: Instant) -> Vec<Vec<Root>> {
let all = now.checked_add(self.debounce.quiet()).unwrap_or(now);
let mut closed = self.ripened(all);
let last = self.batcher.drain();
if !last.is_empty() {
closed.push(last);
}
closed
}
fn retune(&mut self) {
if !self.debounce.is_empty() || !self.batcher.is_empty() {
return;
}
let options = self.registry.options();
if options.debounce() != self.debounce.quiet() {
self.debounce = Debounce::new(options.debounce());
}
if options.batch_max_items() != self.batcher.max_items()
|| options.batch_max_wait() != self.batcher.max_wait()
{
self.batcher = Batcher::new(options.batch_max_items(), options.batch_max_wait());
}
}
async fn send(&mut self, batch: Vec<Root>) {
let stamp = Stamp::now();
let mut flying = Vec::with_capacity(batch.len());
for key in batch {
match self.registry.intake(&key, stamp) {
RootAdvance::Moved | RootAdvance::Unchanged => {}
RootAdvance::Queued | RootAdvance::Coalesced | RootAdvance::Declined => continue,
}
let _taken = self.registry.dispatched(&key, stamp);
match self.head.give_acked_async(key.clone()).await {
Ok(acked) => flying.push((key, acked)),
Err(_unacked) => {
let _balanced = self.registry.observed(&key, stamp);
}
}
}
for (key, acked) in flying {
let _answered = acked.settled_async().await;
let _released = self.registry.observed(&key, Stamp::now());
}
}
async fn worked(&mut self, now: Instant) {
for batch in self.ripened(now) {
self.send(batch).await;
}
if let Some(batch) = self.due(now) {
self.send(batch).await;
}
}
}
async fn pushed<Root>(keys: &Yielded<Root>) -> Turn<Root> {
keys.take_async().await.map_or(Turn::Ended, Turn::Key)
}
async fn halted<Root>(halt: &ShutdownSignal) -> Turn<Root> {
halt.arm(true, || Turn::Halt).await.unwrap_or(Turn::Halt)
}
async fn run_task<R, Root>(mut machine: Machine<Root>, keys: Yielded<Root>, halt: ShutdownSignal)
where
R: RuntimeLite,
Root: RootKey,
{
let mut from = 0;
loop {
machine.retune();
let deadline = machine.deadline();
let turn = {
let wait = deadline.map(|at| at.saturating_duration_since(Instant::now()));
let mut pushing = core::pin::pin!(pushed(&keys));
let mut stopping = core::pin::pin!(halted(&halt));
let mut sleeping = core::pin::pin!(async move {
match wait {
Some(wait) => {
let _woke = R::sleep(wait).await;
}
None => core::future::pending().await,
}
Turn::Due
});
let mut arms: [Arm<'_, Turn<Root>>; 3] =
[pushing.as_mut(), stopping.as_mut(), sleeping.as_mut()];
select(from, &mut arms).await
};
let Some((index, turn)) = turn else {
machine.worked(Instant::now()).await;
continue;
};
from = index + 1;
match turn {
Turn::Key(key) => {
let now = Instant::now();
machine.touched(key, now);
for key in keys.drain() {
machine.touched(key, now);
}
}
Turn::Due => {}
Turn::Ended => {
let now = Instant::now();
for batch in machine.ended(now) {
machine.send(batch).await;
}
return;
}
Turn::Halt => return,
}
machine.worked(Instant::now()).await;
}
}
fn run_parked<Root>(mut machine: Machine<Root>, keys: &Yielded<Root>, halt: &ShutdownSignal)
where
Root: RootKey,
{
let mut from = 0;
loop {
machine.retune();
let deadline = machine.deadline();
let parked = {
let mut pushing = core::pin::pin!(pushed(keys));
let mut stopping = core::pin::pin!(halted(halt));
let mut arms: [Arm<'_, Turn<Root>>; 2] = [pushing.as_mut(), stopping.as_mut()];
block_until(select(from, &mut arms), deadline)
};
let turn = match parked {
Some(Some((index, turn))) => {
from = index + 1;
turn
}
None | Some(None) => Turn::Due,
};
match turn {
Turn::Key(key) => {
let now = Instant::now();
machine.touched(key, now);
for key in keys.drain() {
machine.touched(key, now);
}
}
Turn::Due => {}
Turn::Ended => {
let now = Instant::now();
for batch in machine.ended(now) {
block_on_batch(&mut machine, batch);
}
return;
}
Turn::Halt => return,
}
let now = Instant::now();
for batch in machine.ripened(now) {
block_on_batch(&mut machine, batch);
}
if let Some(batch) = machine.due(now) {
block_on_batch(&mut machine, batch);
}
}
}
fn block_on_batch<Root>(machine: &mut Machine<Root>, batch: Vec<Root>)
where
Root: RootKey,
{
let sent = block_until(machine.send(batch), None);
debug_assert!(
sent.is_some(),
"a park with no deadline runs the future to completion"
);
}