use std::any::Any;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::future::Future;
use std::hash::Hash;
use std::pin::Pin;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::task::{Context, Poll, Waker};
use crate::capability::HNil;
use crate::failure::Never;
use crate::failure::{Cause, Exit};
use crate::kernel::{Effect, Instr, erase, erase_exit, succeed, suspend, sync, yield_fiber};
use crate::layer::Layer;
use crate::runtime::{FiberContext, FiberRef, spawn_fiber};
use crate::scope::Scope;
const STABLE_ROUNDS: u32 = 2;
const MAX_ROUNDS: u32 = 64;
fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(PoisonError::into_inner)
}
pub trait Request: Clone + Eq + Hash + Send + Sync + 'static {
type Output: Clone + Send + Sync + 'static;
type Error: Clone + Send + Sync + 'static;
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ResolverId(u64);
impl ResolverId {
fn fresh() -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
Self(NEXT.fetch_add(1, Ordering::Relaxed))
}
}
pub type BatchResults<Q> = Vec<Result<<Q as Request>::Output, <Q as Request>::Error>>;
type BatchFn<Q, R> =
dyn Fn(Vec<Q>) -> Effect<BatchResults<Q>, <Q as Request>::Error, R> + Send + Sync;
type Outcome<Q> = Result<<Q as Request>::Output, Cause<<Q as Request>::Error>>;
pub struct RequestResolver<Q: Request, R = HNil> {
shared: Arc<Shared<Q, R>>,
}
impl<Q: Request, R> Clone for RequestResolver<Q, R> {
fn clone(&self) -> Self {
Self {
shared: Arc::clone(&self.shared),
}
}
}
impl<Q: Request, R> fmt::Debug for RequestResolver<Q, R> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("RequestResolver")
.field(&self.shared.id)
.finish()
}
}
impl<Q: Request, R: Send + Sync + 'static> RequestResolver<Q, R> {
pub fn make_batched<F>(run: F) -> Self
where
F: Fn(Vec<Q>) -> Effect<BatchResults<Q>, Q::Error, R> + Send + Sync + 'static,
{
Self {
shared: Arc::new(Shared {
id: ResolverId::fresh(),
run: Box::new(run),
window: Mutex::new(None),
}),
}
}
pub fn id(&self) -> ResolverId {
self.shared.id
}
}
pub fn request<Q, R>(req: Q, resolver: &RequestResolver<Q, R>) -> Effect<Q::Output, Q::Error, R>
where
Q: Request,
R: Send + Sync + 'static,
{
let shared = Arc::clone(&resolver.shared);
Effect::from_instr(Instr::Async(Box::new(move |env, fiber| {
let (slot, opened) = match RequestCache::current_in(fiber) {
Some(cache) => cache.lookup_or_submit(&shared, req, fiber.parent()),
None => shared.submit(req, fiber.parent()),
};
if opened {
let ctx = FiberContext::new_detached(fiber);
let _ = spawn_fiber(&ctx, flush(shared).into_instr(), Arc::clone(env));
}
Box::pin(async move { erase_exit(SlotFuture(slot).await) })
})))
}
impl<A, E, R> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
pub fn request<Q>(req: Q, resolver: &RequestResolver<Q, R>) -> Self
where
Q: Request<Output = A, Error = E>,
{
request(req, resolver)
}
pub fn with_request_cache(self, cache: &RequestCache) -> Self {
cache.provide(self)
}
pub fn with_request_caching(self, enabled: bool) -> Self {
caching_ref().locally(enabled, self)
}
}
pub const DEFAULT_REQUEST_CACHE_CAPACITY: usize = 65_536;
#[derive(Clone)]
pub struct RequestCache {
inner: Arc<CacheInner>,
}
struct CacheInner {
capacity: usize,
state: Mutex<CacheState>,
}
#[derive(Default)]
struct CacheState {
maps: HashMap<ResolverId, Box<dyn ErasedMap>>,
order: VecDeque<ResolverId>,
}
trait ErasedMap: Send {
fn as_any_mut(&mut self) -> &mut dyn Any;
fn evict_oldest(&mut self) -> bool;
}
struct TypedMap<Q: Request> {
slots: HashMap<Q, Arc<Slot<Outcome<Q>>>>,
order: VecDeque<Q>,
}
impl<Q: Request> ErasedMap for TypedMap<Q> {
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn evict_oldest(&mut self) -> bool {
if let Some(q) = self.order.pop_front() {
self.slots.remove(&q);
}
self.order.is_empty()
}
}
impl Default for RequestCache {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for RequestCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RequestCache")
.field("len", &self.len())
.field("capacity", &self.inner.capacity)
.finish()
}
}
impl RequestCache {
pub fn new() -> Self {
Self::with_capacity(DEFAULT_REQUEST_CACHE_CAPACITY)
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
inner: Arc::new(CacheInner {
capacity: capacity.max(1),
state: Mutex::default(),
}),
}
}
pub fn capacity(&self) -> usize {
self.inner.capacity
}
pub fn len(&self) -> usize {
lock(&self.inner.state).order.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn clear(&self) {
*lock(&self.inner.state) = CacheState::default();
}
pub fn provide<A, E, R>(&self, eff: Effect<A, E, R>) -> Effect<A, E, R>
where
A: Send + 'static,
E: Send + 'static,
R: Send + Sync + 'static,
{
cache_ref().locally(self.clone(), caching_ref().locally(true, eff))
}
pub fn provide_scoped<E: Send + 'static, R: Send + Sync + 'static>(
&self,
scope: &Scope,
) -> Effect<(), E, R> {
let cache = self.clone();
let scope = scope.clone();
Effect::from_instr(Instr::WithFiber(Box::new(move |_, fiber| {
let prev_cache = cache_ref().get_in(fiber);
let prev_on = caching_ref().get_in(fiber);
let (here, there) = (Arc::clone(fiber), Arc::clone(fiber));
let restore = sync(move || {
cache_ref().set_in(&there, prev_cache);
caching_ref().set_in(&there, prev_on);
});
scope
.add_finalizer::<E, R>(restore)
.map(move |()| {
cache_ref().set_in(&here, cache);
caching_ref().set_in(&here, true);
})
.into_instr()
})))
}
pub fn layer<E: Send + 'static>(&self) -> Layer<HNil, E> {
let cache = self.clone();
Layer::scoped(move |scope| cache.provide_scoped::<E, HNil>(&scope).map(|()| HNil))
}
pub fn current<E: Send + 'static, R: Send + Sync + 'static>() -> Effect<Option<Self>, E, R> {
Effect::from_instr(Instr::WithFiber(Box::new(|_, fiber| {
Instr::Pure(Ok(erase(Self::current_in(fiber))))
})))
}
pub fn current_in(fiber: &FiberContext) -> Option<Self> {
caching_ref()
.get_in(fiber)
.then(|| cache_ref().get_in(fiber))
}
fn lookup_or_submit<Q: Request, R>(
&self,
shared: &Shared<Q, R>,
req: Q,
parent: Option<Arc<FiberContext>>,
) -> (Arc<Slot<Outcome<Q>>>, bool) {
let mut state = lock(&self.inner.state);
let CacheState { maps, order } = &mut *state;
let map = maps.entry(shared.id).or_insert_with(|| {
Box::new(TypedMap::<Q> {
slots: HashMap::new(),
order: VecDeque::new(),
})
});
let Some(typed) = map.as_any_mut().downcast_mut::<TypedMap<Q>>() else {
unreachable!("id_effect: request cache entry of a foreign request type (kernel bug)")
};
if let Some(slot) = typed.slots.get(&req) {
return (Arc::clone(slot), false);
}
let (slot, opened) = shared.submit(req.clone(), parent);
typed.slots.insert(req.clone(), Arc::clone(&slot));
typed.order.push_back(req);
order.push_back(shared.id);
while order.len() > self.inner.capacity {
let Some(id) = order.pop_front() else { break };
if maps.get_mut(&id).is_some_and(|m| m.evict_oldest()) {
maps.remove(&id);
}
}
(slot, opened)
}
}
fn caching_ref() -> &'static FiberRef<bool> {
static ON: OnceLock<FiberRef<bool>> = OnceLock::new();
ON.get_or_init(|| FiberRef::new(false))
}
fn cache_ref() -> &'static FiberRef<RequestCache> {
static CACHE: OnceLock<FiberRef<RequestCache>> = OnceLock::new();
CACHE.get_or_init(|| FiberRef::new(RequestCache::new()))
}
struct Shared<Q: Request, R> {
id: ResolverId,
run: Box<BatchFn<Q, R>>,
window: Mutex<Option<Window<Q>>>,
}
impl<Q: Request, R> Shared<Q, R> {
fn submit(&self, req: Q, parent: Option<Arc<FiberContext>>) -> (Arc<Slot<Outcome<Q>>>, bool) {
let mut window = lock(&self.window);
let opened = window.is_none();
let w = window.get_or_insert_with(Window::default);
w.parents.push(parent);
let slot = match w.index.entry(req) {
Entry::Occupied(e) => Arc::clone(&w.slots[*e.get()]),
Entry::Vacant(e) => {
let slot = Arc::new(Slot::default());
w.keys.push(e.key().clone());
w.slots.push(Arc::clone(&slot));
e.insert(w.slots.len() - 1);
slot
}
};
(slot, opened)
}
fn status(&self) -> (usize, bool) {
lock(&self.window)
.as_ref()
.map_or((0, true), |w| (w.parents.len(), w.settled()))
}
fn close(&self) -> Option<(Vec<Q>, Batch<Q>)> {
lock(&self.window)
.take()
.map(|w| (w.keys, Batch { slots: w.slots }))
}
}
struct Window<Q: Request> {
keys: Vec<Q>,
slots: Vec<Arc<Slot<Outcome<Q>>>>,
index: HashMap<Q, usize>,
parents: Vec<Option<Arc<FiberContext>>>,
}
impl<Q: Request> Default for Window<Q> {
fn default() -> Self {
Self {
keys: Vec::new(),
slots: Vec::new(),
index: HashMap::new(),
parents: Vec::new(),
}
}
}
impl<Q: Request> Window<Q> {
fn settled(&self) -> bool {
let mut waiting: HashMap<*const FiberContext, (usize, &Arc<FiberContext>)> = HashMap::new();
for p in self.parents.iter().flatten() {
waiting.entry(Arc::as_ptr(p)).or_insert((0, p)).0 += 1;
}
waiting.values().all(|(n, p)| *n >= p.live_children())
}
}
fn flush<Q: Request, R: Send + Sync + 'static>(shared: Arc<Shared<Q, R>>) -> Effect<(), Never, R> {
let guard = FlushGuard {
shared: Arc::clone(&shared),
closed: false,
};
yield_fiber()
.then(settle(shared, 1, 0, 0))
.flat_map(move |()| {
let mut guard = guard;
guard.closed = true;
let Some((keys, batch)) = guard.shared.close() else {
return succeed(());
};
let shared = Arc::clone(&guard.shared);
suspend(move || (shared.run)(keys))
.exit()
.map(move |exit| batch.complete(exit))
})
}
fn settle<Q: Request, R: Send + Sync + 'static>(
shared: Arc<Shared<Q, R>>,
round: u32,
seen: usize,
stable: u32,
) -> Effect<(), Never, R> {
suspend(move || {
let (n, settled) = shared.status();
let stable = if n == seen { stable + 1 } else { 0 };
if settled || stable >= STABLE_ROUNDS || round >= MAX_ROUNDS {
succeed(())
} else {
yield_fiber().flat_map(move |()| settle(shared, round + 1, n, stable))
}
})
}
struct FlushGuard<Q: Request, R> {
shared: Arc<Shared<Q, R>>,
closed: bool,
}
impl<Q: Request, R> Drop for FlushGuard<Q, R> {
fn drop(&mut self) {
if !self.closed {
drop(self.shared.close());
}
}
}
struct Batch<Q: Request> {
slots: Vec<Arc<Slot<Outcome<Q>>>>,
}
impl<Q: Request> Batch<Q> {
fn complete(mut self, exit: Exit<BatchResults<Q>, Q::Error>) {
let slots = std::mem::take(&mut self.slots);
match exit {
Exit::Success(results) if results.len() == slots.len() => {
for (slot, r) in slots.iter().zip(results) {
slot.complete(r.map_err(Cause::Fail));
}
}
Exit::Success(results) => {
let msg = format!(
"id_effect: request resolver returned {} results for {} requests",
results.len(),
slots.len()
);
for slot in &slots {
slot.complete(Err(Cause::Die(msg.as_str().into())));
}
}
Exit::Failure(cause) => {
for slot in &slots {
slot.complete(Err(cause.clone()));
}
}
}
}
}
impl<Q: Request> Drop for Batch<Q> {
fn drop(&mut self) {
for slot in self.slots.drain(..) {
slot.complete(Err(Cause::Die(
"id_effect: request batch dropped before its resolver finished".into(),
)));
}
}
}
struct Slot<T> {
state: Mutex<SlotState<T>>,
}
struct SlotState<T> {
value: Option<T>,
wakers: Vec<Waker>,
}
impl<T> Default for Slot<T> {
fn default() -> Self {
Self {
state: Mutex::new(SlotState {
value: None,
wakers: Vec::new(),
}),
}
}
}
impl<T: Clone> Slot<T> {
fn complete(&self, v: T) {
let wakers = {
let mut s = lock(&self.state);
if s.value.is_some() {
return;
}
s.value = Some(v);
std::mem::take(&mut s.wakers)
};
for w in wakers {
w.wake();
}
}
fn poll_get(&self, cx: &mut Context<'_>) -> Poll<T> {
let mut s = lock(&self.state);
if let Some(v) = &s.value {
return Poll::Ready(v.clone());
}
if !s.wakers.iter().any(|w| w.will_wake(cx.waker())) {
s.wakers.push(cx.waker().clone());
}
Poll::Pending
}
}
struct SlotFuture<T>(Arc<Slot<T>>);
impl<T: Clone> Future for SlotFuture<T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<T> {
self.0.poll_get(cx)
}
}