use std::cell::Cell;
use std::collections::BTreeMap;
use std::future::Future;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::pin::Pin;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Poll, Wake, Waker};
use std::thread::ThreadId;
use std::time::Duration;
use iced_futures::futures::Stream;
use crate::effects::{Spawn, TaskState, UntypedTaskId};
use crate::time::VirtualClock;
pub(crate) const BLOCKING_THREAD: &str = "icedwright-blocking";
pub(crate) fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
#[derive(Debug, Default)]
pub(crate) struct Signal {
generation: Mutex<u64>,
changed: Condvar,
}
impl Signal {
pub(crate) fn notify(&self) {
*lock(&self.generation) += 1;
self.changed.notify_all();
}
pub(crate) fn generation(&self) -> u64 {
*lock(&self.generation)
}
pub(crate) fn wait_past(&self, seen: u64, limit: Duration) -> u64 {
let guard = lock(&self.generation);
let (guard, _) = self
.changed
.wait_timeout_while(guard, limit, |generation| *generation <= seen)
.unwrap_or_else(PoisonError::into_inner);
*guard
}
}
#[derive(Debug, Clone, Default)]
pub(crate) struct Blocking {
count: Arc<AtomicUsize>,
signal: Arc<Signal>,
in_round: Arc<(Mutex<bool>, Condvar)>,
}
impl Blocking {
pub(crate) fn new(signal: Arc<Signal>) -> Self {
Self {
count: Arc::default(),
signal,
in_round: Arc::default(),
}
}
pub(crate) fn in_flight(&self) -> usize {
self.count.load(Ordering::SeqCst)
}
pub(crate) fn round<T>(&self, round: impl FnOnce() -> T) -> T {
let (flag, ended) = &*self.in_round;
*lock(flag) = true;
let out = round();
*lock(flag) = false;
ended.notify_all();
out
}
fn on_start(&self) -> impl Fn() + Send + Sync + 'static {
let in_round = self.in_round.clone();
move || {
let (flag, ended) = &*in_round;
let mut running = lock(flag);
while *running {
running = ended.wait(running).unwrap_or_else(PoisonError::into_inner);
}
}
}
fn on_spawn(&self) -> impl Fn() -> String + Send + Sync + 'static {
let count = self.count.clone();
move || {
count.fetch_add(1, Ordering::SeqCst);
BLOCKING_THREAD.to_owned()
}
}
fn on_stop(&self) -> impl Fn() + Send + Sync + 'static {
let count = self.count.clone();
let signal = self.signal.clone();
move || {
count.fetch_sub(1, Ordering::SeqCst);
signal.notify();
}
}
}
pub(crate) fn build(blocking: &Blocking) -> std::io::Result<tokio::runtime::Runtime> {
tokio::runtime::Builder::new_current_thread()
.enable_time()
.enable_io()
.start_paused(true)
.max_blocking_threads(1)
.thread_keep_alive(Duration::ZERO)
.thread_name_fn(blocking.on_spawn())
.on_thread_start(blocking.on_start())
.on_thread_stop(blocking.on_stop())
.build()
}
#[derive(Debug)]
pub(crate) struct TaskRecord {
pub(crate) spawn: Spawn,
pub(crate) spawned_at: icedwright_types::VirtualInstant,
pub(crate) state: TaskState,
pub(crate) polls: u64,
pub(crate) produced: Vec<String>,
pub(crate) foreign_wakes: u32,
pub(crate) held: bool,
pub(crate) waker: Option<Waker>,
pub(crate) abort: Option<tokio::task::AbortHandle>,
pub(crate) replaced: bool,
}
impl TaskRecord {
pub(crate) fn new(spawn: Spawn, spawned_at: icedwright_types::VirtualInstant) -> Self {
Self {
spawn,
spawned_at,
state: TaskState::Pending,
polls: 0,
produced: Vec::new(),
foreign_wakes: 0,
held: false,
waker: None,
abort: None,
replaced: false,
}
}
}
#[derive(Debug, Default)]
pub(crate) struct Book {
next_id: u64,
pub(crate) tasks: BTreeMap<UntypedTaskId, TaskRecord>,
pub(crate) polls: u64,
pub(crate) completions: u64,
pub(crate) panics: Vec<(UntypedTaskId, String)>,
pub(crate) foreign: Vec<UntypedTaskId>,
}
impl Book {
pub(crate) fn allocate(&mut self) -> UntypedTaskId {
self.next_id += 1;
UntypedTaskId::new(self.next_id)
}
pub(crate) fn insert(&mut self, record: TaskRecord) -> UntypedTaskId {
let id = self.allocate();
self.tasks.insert(id, record);
id
}
}
pub(crate) type SharedBook = Arc<Mutex<Book>>;
thread_local! {
static CURRENT: Cell<Option<UntypedTaskId>> = const { Cell::new(None) };
}
pub(crate) fn current_task() -> Option<UntypedTaskId> {
CURRENT.with(Cell::get)
}
#[derive(Debug)]
pub(crate) struct WakeHub {
harness: ThreadId,
book: SharedBook,
signal: Arc<Signal>,
activity: Arc<tokio::sync::Notify>,
held: Mutex<Vec<Waker>>,
hold_subscriptions: bool,
deliveries: Mutex<Vec<(UntypedTaskId, Waker)>>,
}
impl WakeHub {
pub(crate) fn new(
harness: ThreadId,
book: SharedBook,
signal: Arc<Signal>,
activity: Arc<tokio::sync::Notify>,
hold_subscriptions: bool,
) -> Self {
Self {
harness,
book,
signal,
activity,
held: Mutex::default(),
hold_subscriptions,
deliveries: Mutex::default(),
}
}
fn wake(&self, inner: &Waker, task: UntypedTaskId) {
let thread = std::thread::current();
if thread.id() == self.harness {
inner.wake_by_ref();
} else if thread.name() == Some(BLOCKING_THREAD) {
lock(&self.held).push(inner.clone());
} else if self.is_held_source(task) {
let mut deliveries = lock(&self.deliveries);
if !deliveries.iter().any(|(held, _)| *held == task) {
deliveries.push((task, inner.clone()));
}
} else {
inner.wake_by_ref();
}
self.woke(task);
}
fn is_held_source(&self, task: UntypedTaskId) -> bool {
self.hold_subscriptions
&& lock(&self.book)
.tasks
.get(&task)
.is_some_and(|record| record.spawn == Spawn::Subscription)
}
pub(crate) fn deliver_held(&self) {
let held = std::mem::take(&mut *lock(&self.held));
held.into_iter().for_each(Waker::wake);
}
pub(crate) fn deliver_sources(&self) -> Option<UntypedTaskId> {
let deliveries = std::mem::take(&mut *lock(&self.deliveries));
let first = deliveries.first().map(|(task, _)| *task);
deliveries.into_iter().for_each(|(_, waker)| waker.wake());
first
}
fn woke(&self, task: UntypedTaskId) {
let thread = std::thread::current();
if thread.id() == self.harness {
return;
}
if thread.name() != Some(BLOCKING_THREAD) {
let mut book = lock(&self.book);
book.foreign.push(task);
if let Some(record) = book.tasks.get_mut(&task) {
record.foreign_wakes = record.foreign_wakes.saturating_add(1);
}
}
self.signal.notify();
}
}
struct ProbeWaker {
inner: Waker,
task: UntypedTaskId,
hub: Arc<WakeHub>,
}
impl Wake for ProbeWaker {
fn wake(self: Arc<Self>) {
self.hub.wake(&self.inner, self.task);
}
fn wake_by_ref(self: &Arc<Self>) {
self.hub.wake(&self.inner, self.task);
}
}
pub(crate) struct Instrumented<T> {
inner: T,
id: UntypedTaskId,
book: SharedBook,
hub: Arc<WakeHub>,
done: bool,
}
impl<T> Instrumented<T> {
pub(crate) fn new(inner: T, id: UntypedTaskId, book: SharedBook, hub: Arc<WakeHub>) -> Self {
Self {
inner,
id,
book,
hub,
done: false,
}
}
fn before_poll(&mut self, cx: &Context<'_>) -> Option<()> {
self.hub.activity.notify_waiters();
let mut book = lock(&self.book);
book.polls += 1;
let record = book.tasks.get_mut(&self.id)?;
record.polls += 1;
if record.held {
record.state = TaskState::Held;
record.waker = Some(cx.waker().clone());
return Some(());
}
None
}
fn poll_with<R>(
&mut self,
cx: &mut Context<'_>,
poll: impl FnOnce(&mut T, &mut Context<'_>) -> Poll<R>,
) -> Option<Poll<R>> {
if self.before_poll(cx).is_some() {
return Some(Poll::Pending);
}
let waker = Waker::from(Arc::new(ProbeWaker {
inner: cx.waker().clone(),
task: self.id,
hub: self.hub.clone(),
}));
let mut probed = Context::from_waker(&waker);
let previous = CURRENT.with(|current| current.replace(Some(self.id)));
let result = catch_unwind(AssertUnwindSafe(|| poll(&mut self.inner, &mut probed)));
CURRENT.with(|current| current.set(previous));
match result {
Ok(poll) => Some(poll),
Err(payload) => {
let message = panic_message(payload.as_ref());
let mut book = lock(&self.book);
book.panics.push((self.id, message));
if let Some(record) = book.tasks.get_mut(&self.id) {
record.state = TaskState::Failed;
}
self.done = true;
None
}
}
}
fn finished(&mut self) {
self.done = true;
let mut book = lock(&self.book);
book.completions += 1;
if let Some(record) = book.tasks.get_mut(&self.id)
&& record.state != TaskState::Aborted
{
record.state = TaskState::Finished;
}
}
}
fn panic_message(payload: &(dyn std::any::Any + Send)) -> String {
if let Some(text) = payload.downcast_ref::<&str>() {
return (*text).to_owned();
}
if let Some(text) = payload.downcast_ref::<String>() {
return text.clone();
}
"a panic with a non-string payload".to_owned()
}
impl<S: Stream + Unpin> Stream for Instrumented<S> {
type Item = S::Item;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<S::Item>> {
if self.done {
return Poll::Ready(None);
}
let Some(poll) = self.poll_with(cx, |inner, cx| Pin::new(inner).poll_next(cx)) else {
return Poll::Ready(None);
};
if let Poll::Ready(None) = poll {
self.finished();
}
poll
}
}
impl<F: Future<Output = ()> + Unpin> Future for Instrumented<F> {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
if self.done {
return Poll::Ready(());
}
let Some(poll) = self.poll_with(cx, |inner, cx| Pin::new(inner).poll(cx)) else {
return Poll::Ready(());
};
if poll.is_ready() {
self.finished();
}
poll
}
}
#[derive(Debug, Clone)]
pub(crate) struct HarnessExecutor {
handle: tokio::runtime::Handle,
book: SharedBook,
hub: Arc<WakeHub>,
clock: VirtualClock,
}
impl HarnessExecutor {
pub(crate) fn new(
handle: tokio::runtime::Handle,
book: SharedBook,
hub: Arc<WakeHub>,
clock: VirtualClock,
) -> Self {
Self {
handle,
book,
hub,
clock,
}
}
pub(crate) fn spawn_task(
&self,
future: impl Future<Output = ()> + Send + 'static,
id: UntypedTaskId,
) {
let _enter = self.handle.enter();
let handle = self.handle.spawn(future);
if let Some(record) = lock(&self.book).tasks.get_mut(&id) {
record.abort = Some(handle.abort_handle());
}
}
pub(crate) fn hub(&self) -> Arc<WakeHub> {
self.hub.clone()
}
}
impl iced_futures::Executor for HarnessExecutor {
fn new() -> Result<Self, iced_futures::futures::io::Error> {
Err(std::io::Error::other(
"the harness executor is built by the harness, never by iced",
))
}
fn spawn(&self, future: impl Future<Output = ()> + Send + 'static) {
let _enter = self.handle.enter();
let at = self.clock.of(tokio::time::Instant::now());
let id = lock(&self.book).insert(TaskRecord::new(Spawn::Subscription, at));
let instrumented =
Instrumented::new(Box::pin(future), id, self.book.clone(), self.hub.clone());
let handle = self.handle.spawn(instrumented);
if let Some(record) = lock(&self.book).tasks.get_mut(&id) {
record.abort = Some(handle.abort_handle());
}
}
fn block_on<T>(&self, future: impl Future<Output = T>) -> T {
self.handle.block_on(future)
}
fn enter<R>(&self, f: impl FnOnce() -> R) -> R {
let _enter = self.handle.enter();
f()
}
}
#[cfg(test)]
mod tests {
use super::*;
use iced_futures::futures::{StreamExt, stream};
fn book() -> SharedBook {
Arc::default()
}
fn hub(book: &SharedBook) -> Arc<WakeHub> {
Arc::new(WakeHub::new(
std::thread::current().id(),
book.clone(),
Arc::default(),
Arc::default(),
false,
))
}
fn record(book: &SharedBook) -> UntypedTaskId {
lock(book).insert(TaskRecord::new(
Spawn::Boot,
icedwright_types::VirtualInstant::__from_offset(
icedwright_types::VirtualDuration::ZERO,
),
))
}
fn runtime(blocking: &Blocking) -> tokio::runtime::Runtime {
build(blocking).unwrap()
}
#[test]
fn blocking_work_counts_from_the_moment_spawn_blocking_returns() {
let blocking = Blocking::new(Arc::default());
let rt = runtime(&blocking);
let (release, gate) = std::sync::mpsc::channel::<()>();
let seen = rt.block_on(async {
let handle = tokio::task::spawn_blocking(move || {
let _ = gate.recv();
});
let seen = blocking.in_flight();
release.send(()).unwrap();
handle.await.unwrap();
seen
});
assert_eq!(seen, 1);
let signal = blocking.signal.clone();
let mut generation = signal.generation();
while blocking.in_flight() != 0 {
generation = signal.wait_past(generation, Duration::from_secs(15));
}
assert_eq!(blocking.in_flight(), 0);
}
#[test]
fn two_queued_jobs_keep_the_count_at_one_until_the_second_finishes() {
let blocking = Blocking::new(Arc::default());
let rt = runtime(&blocking);
let (first_go, first_gate) = std::sync::mpsc::channel::<()>();
let (second_go, second_gate) = std::sync::mpsc::channel::<()>();
let order = Arc::new(Mutex::new(Vec::new()));
let (a, b) = (order.clone(), order.clone());
let counts = rt.block_on(async {
let first = tokio::task::spawn_blocking(move || {
let _ = first_gate.recv();
lock(&a).push(1);
});
let second = tokio::task::spawn_blocking(move || {
let _ = second_gate.recv();
lock(&b).push(2);
});
let queued = blocking.in_flight();
first_go.send(()).unwrap();
first.await.unwrap();
let between = blocking.in_flight();
second_go.send(()).unwrap();
second.await.unwrap();
(queued, between)
});
assert_eq!(counts, (1, 1));
assert_eq!(*lock(&order), vec![1, 2]);
}
#[test]
fn a_panic_inside_a_poll_is_caught_and_recorded() {
let book = book();
let hub = hub(&book);
let id = record(&book);
let panicking = stream::once(async { panic!("boom") }).map(|()| 1).boxed();
let mut instrumented = Instrumented::new(panicking, id, book.clone(), hub);
let rt = runtime(&Blocking::default());
let next = rt.block_on(instrumented.next());
assert_eq!(next, None);
let book = lock(&book);
assert_eq!(book.panics, vec![(id, "boom".to_owned())]);
assert_eq!(book.tasks[&id].state, TaskState::Failed);
}
#[test]
fn a_held_task_is_not_polled() {
let book = book();
let id = record(&book);
lock(&book).tasks.get_mut(&id).unwrap().held = true;
let polled = Arc::new(AtomicUsize::new(0));
let counter = polled.clone();
let inner = stream::poll_fn(move |_| {
counter.fetch_add(1, Ordering::SeqCst);
Poll::Ready(Some(1))
})
.boxed();
let mut instrumented = Instrumented::new(inner, id, book.clone(), hub(&book));
let waker = Waker::noop();
let mut cx = Context::from_waker(waker);
assert!(Pin::new(&mut instrumented).poll_next(&mut cx).is_pending());
assert_eq!(polled.load(Ordering::SeqCst), 0);
assert_eq!(lock(&book).tasks[&id].state, TaskState::Held);
}
#[test]
fn a_wake_from_a_joined_thread_is_foreign_and_one_from_the_harness_thread_is_not() {
let book = book();
let hub = hub(&book);
let id = record(&book);
let waker = Waker::from(Arc::new(ProbeWaker {
inner: Waker::noop().clone(),
task: id,
hub: hub.clone(),
}));
waker.wake_by_ref();
assert!(lock(&book).foreign.is_empty());
let remote = waker.clone();
std::thread::spawn(move || remote.wake()).join().unwrap();
assert_eq!(lock(&book).foreign, vec![id]);
assert_eq!(lock(&book).tasks[&id].foreign_wakes, 1);
}
#[test]
fn a_wake_from_the_blocking_thread_is_owned_work() {
let book = book();
let hub = hub(&book);
let id = record(&book);
let waker = Waker::from(Arc::new(ProbeWaker {
inner: Waker::noop().clone(),
task: id,
hub,
}));
std::thread::Builder::new()
.name(BLOCKING_THREAD.to_owned())
.spawn(move || waker.wake())
.unwrap()
.join()
.unwrap();
assert!(lock(&book).foreign.is_empty());
}
#[test]
fn blocking_work_starts_only_after_the_round_that_spawned_it() {
let blocking = Blocking::new(Arc::default());
let rt = runtime(&blocking);
let ran = Arc::new(AtomicUsize::new(0));
let job = ran.clone();
let handle = blocking.round(|| {
let _entered = rt.enter();
let handle = tokio::task::spawn_blocking(move || job.fetch_add(1, Ordering::SeqCst));
rt.block_on(tokio::task::yield_now());
assert_eq!(ran.load(Ordering::SeqCst), 0);
handle
});
assert_eq!(rt.block_on(handle).unwrap(), 0);
assert_eq!(ran.load(Ordering::SeqCst), 1);
}
#[test]
fn a_wake_from_the_blocking_thread_waits_for_the_next_turn() {
struct Count(AtomicUsize);
impl Wake for Count {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let book = book();
let hub = hub(&book);
let id = record(&book);
let count = Arc::new(Count(AtomicUsize::new(0)));
let waker = Waker::from(Arc::new(ProbeWaker {
inner: Waker::from(count.clone()),
task: id,
hub: hub.clone(),
}));
std::thread::Builder::new()
.name(BLOCKING_THREAD.to_owned())
.spawn(move || waker.wake())
.unwrap()
.join()
.unwrap();
assert_eq!(count.0.load(Ordering::SeqCst), 0);
hub.deliver_held();
assert_eq!(count.0.load(Ordering::SeqCst), 1);
hub.deliver_held();
assert_eq!(count.0.load(Ordering::SeqCst), 1);
}
#[test]
fn a_declared_subscription_delivery_waits_until_the_sources_are_waited_on() {
struct Count(AtomicUsize);
impl Wake for Count {
fn wake(self: Arc<Self>) {
self.0.fetch_add(1, Ordering::SeqCst);
}
}
let book = book();
let hub = Arc::new(WakeHub::new(
std::thread::current().id(),
book.clone(),
Arc::default(),
Arc::default(),
true,
));
let id = lock(&book).insert(TaskRecord::new(
Spawn::Subscription,
icedwright_types::VirtualInstant::__from_offset(
icedwright_types::VirtualDuration::ZERO,
),
));
let count = Arc::new(Count(AtomicUsize::new(0)));
let waker = Waker::from(Arc::new(ProbeWaker {
inner: Waker::from(count.clone()),
task: id,
hub: hub.clone(),
}));
let twice = waker.clone();
std::thread::spawn(move || {
waker.wake();
twice.wake();
})
.join()
.unwrap();
hub.deliver_held();
assert_eq!(count.0.load(Ordering::SeqCst), 0);
assert_eq!(lock(&book).foreign, vec![id, id]);
assert_eq!(hub.deliver_sources(), Some(id));
assert_eq!(count.0.load(Ordering::SeqCst), 1);
assert_eq!(hub.deliver_sources(), None);
}
#[test]
fn the_signal_wakes_a_waiter_from_another_thread() {
let signal = Arc::new(Signal::default());
let seen = signal.generation();
let remote = signal.clone();
let thread = std::thread::spawn(move || remote.notify());
let after = signal.wait_past(seen, Duration::from_secs(15));
thread.join().unwrap();
assert!(after > seen);
}
}