Skip to main content

roder_api/tools/
scheduling.rs

1use tokio::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
2
3use super::ToolExecutionMode;
4
5/// A fair shared-read/exclusive-write resource barrier. Share the same instance
6/// with nested dispatchers through `ToolExecutionHandles::execution_barrier`.
7#[derive(Default)]
8pub struct ToolExecutionBarrier {
9    barrier: RwLock<()>,
10}
11
12/// Releasing or cancelling an execution drops its scheduling guard.
13pub struct ToolExecutionGuard<'a> {
14    _guard: BarrierGuard<'a>,
15}
16
17enum BarrierGuard<'a> {
18    Read { _guard: RwLockReadGuard<'a, ()> },
19    Write { _guard: RwLockWriteGuard<'a, ()> },
20}
21
22impl ToolExecutionBarrier {
23    /// Coordinators hold no resource guard while awaiting nested work.
24    pub async fn acquire(&self, mode: ToolExecutionMode) -> Option<ToolExecutionGuard<'_>> {
25        let guard = match mode {
26            ToolExecutionMode::SharedRead => BarrierGuard::Read {
27                _guard: self.barrier.read().await,
28            },
29            ToolExecutionMode::Exclusive => BarrierGuard::Write {
30                _guard: self.barrier.write().await,
31            },
32            ToolExecutionMode::Coordinator => return None,
33        };
34        Some(ToolExecutionGuard { _guard: guard })
35    }
36}