1
0
forked from ROMEO/nexosim

Revert "Merge pull request #12 from asynchronics/feature/event-sinks"

This reverts commit 7e881afb63, reversing
changes made to 9d78e4f72a.
This commit is contained in:
Serge Barral
2024-03-06 16:16:55 +01:00
parent 43e41012d2
commit 1be2f48a00
25 changed files with 870 additions and 573 deletions

View File

@ -3,7 +3,7 @@
use std::error::Error;
use std::fmt;
use std::future::Future;
use std::num::NonZeroUsize;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
@ -13,7 +13,7 @@ use std::time::Duration;
use pin_project_lite::pin_project;
use recycle_box::{coerce_box, RecycleBox};
use crate::channel::Sender;
use crate::channel::{ChannelId, Sender};
use crate::executor::Executor;
use crate::model::{InputFn, Model};
use crate::time::{MonotonicTime, TearableAtomicTime};
@ -21,15 +21,7 @@ use crate::util::priority_queue::PriorityQueue;
use crate::util::sync_cell::SyncCellReader;
/// Shorthand for the scheduler queue type.
// Why use both time and channel ID as the key? The short answer is that this
// ensures that events targeting the same channel are sent in the order they
// were scheduled. More precisely, this ensures that events targeting the same
// channel are ordered contiguously in the priority queue, which in turns allows
// the event loop to easily aggregate such events into single futures and thus
// control their relative order of execution.
pub(crate) type SchedulerQueue =
PriorityQueue<(MonotonicTime, NonZeroUsize), Box<dyn ScheduledEvent>>;
pub(crate) type SchedulerQueue = PriorityQueue<(MonotonicTime, ChannelId), Box<dyn ScheduledEvent>>;
/// Trait abstracting over time-absolute and time-relative deadlines.
///
@ -487,7 +479,7 @@ impl Error for SchedulingError {}
/// Schedules an event at a future time.
///
/// This function does not check whether the specified time lies in the future
/// This method does not check whether the specified time lies in the future
/// of the current simulation time.
pub(crate) fn schedule_event_at_unchecked<M, F, T, S>(
time: MonotonicTime,
@ -503,7 +495,7 @@ pub(crate) fn schedule_event_at_unchecked<M, F, T, S>(
{
let channel_id = sender.channel_id();
let event_dispatcher = Box::new(EventDispatcher::new(dispatch_event(func, arg, sender)));
let event_dispatcher = Box::new(new_event_dispatcher(func, arg, sender));
let mut scheduler_queue = scheduler_queue.lock().unwrap();
scheduler_queue.insert((time, channel_id), event_dispatcher);
@ -511,7 +503,7 @@ pub(crate) fn schedule_event_at_unchecked<M, F, T, S>(
/// Schedules an event at a future time, returning an event key.
///
/// This function does not check whether the specified time lies in the future
/// This method does not check whether the specified time lies in the future
/// of the current simulation time.
pub(crate) fn schedule_keyed_event_at_unchecked<M, F, T, S>(
time: MonotonicTime,
@ -529,8 +521,10 @@ where
let event_key = EventKey::new();
let channel_id = sender.channel_id();
let event_dispatcher = Box::new(KeyedEventDispatcher::new(
|ek| dispatch_keyed_event(ek, func, arg, sender),
event_key.clone(),
func,
arg,
sender,
));
let mut scheduler_queue = scheduler_queue.lock().unwrap();
@ -541,7 +535,7 @@ where
/// Schedules a periodic event at a future time.
///
/// This function does not check whether the specified time lies in the future
/// This method does not check whether the specified time lies in the future
/// of the current simulation time.
pub(crate) fn schedule_periodic_event_at_unchecked<M, F, T, S>(
time: MonotonicTime,
@ -558,10 +552,7 @@ pub(crate) fn schedule_periodic_event_at_unchecked<M, F, T, S>(
{
let channel_id = sender.channel_id();
let event_dispatcher = Box::new(PeriodicEventDispatcher::new(
|| dispatch_event(func, arg, sender),
period,
));
let event_dispatcher = Box::new(PeriodicEventDispatcher::new(func, arg, sender, period));
let mut scheduler_queue = scheduler_queue.lock().unwrap();
scheduler_queue.insert((time, channel_id), event_dispatcher);
@ -569,7 +560,7 @@ pub(crate) fn schedule_periodic_event_at_unchecked<M, F, T, S>(
/// Schedules an event at a future time, returning an event key.
///
/// This function does not check whether the specified time lies in the future
/// This method does not check whether the specified time lies in the future
/// of the current simulation time.
pub(crate) fn schedule_periodic_keyed_event_at_unchecked<M, F, T, S>(
time: MonotonicTime,
@ -588,9 +579,11 @@ where
let event_key = EventKey::new();
let channel_id = sender.channel_id();
let event_dispatcher = Box::new(PeriodicKeyedEventDispatcher::new(
|ek| dispatch_keyed_event(ek, func, arg, sender),
period,
event_key.clone(),
func,
arg,
sender,
period,
));
let mut scheduler_queue = scheduler_queue.lock().unwrap();
@ -621,8 +614,8 @@ pub(crate) trait ScheduledEvent: Send {
}
pin_project! {
/// An object that can be converted to a future dispatching a
/// non-cancellable event.
/// Object that can be converted to a future dispatching a non-cancellable
/// event.
///
/// Note that this particular event dispatcher is in fact already a future:
/// since the future cannot be cancelled and the dispatcher does not need to
@ -634,14 +627,23 @@ pin_project! {
}
}
impl<F> EventDispatcher<F>
/// Constructs a new `EventDispatcher`.
///
/// Due to some limitations of type inference or of my understanding of it, the
/// constructor for this event dispatchers is a freestanding function.
fn new_event_dispatcher<M, F, T, S>(
func: F,
arg: T,
sender: Sender<M>,
) -> EventDispatcher<impl Future<Output = ()>>
where
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + Clone + 'static,
{
/// Constructs a new `EventDispatcher`.
pub(crate) fn new(fut: F) -> Self {
EventDispatcher { fut }
}
let fut = dispatch_event(func, arg, sender);
EventDispatcher { fut }
}
impl<F> Future for EventDispatcher<F>
@ -675,78 +677,112 @@ where
}
}
/// An object that can be converted to a future dispatching a non-cancellable,
/// periodic event.
pub(crate) struct PeriodicEventDispatcher<G, F>
/// Object that can be converted to a future dispatching a non-cancellable periodic
/// event.
pub(crate) struct PeriodicEventDispatcher<M, F, T, S>
where
G: (FnOnce() -> F) + Clone + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
{
/// A clonable generator for the dispatching future.
gen: G,
/// The event repetition period.
func: F,
arg: T,
sender: Sender<M>,
period: Duration,
_input_kind: PhantomData<S>,
}
impl<G, F> PeriodicEventDispatcher<G, F>
impl<M, F, T, S> PeriodicEventDispatcher<M, F, T, S>
where
G: (FnOnce() -> F) + Clone + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + Clone + 'static,
{
/// Constructs a new `PeriodicEventDispatcher`.
fn new(gen: G, period: Duration) -> Self {
Self { gen, period }
fn new(func: F, arg: T, sender: Sender<M>, period: Duration) -> Self {
Self {
func,
arg,
sender,
period,
_input_kind: PhantomData,
}
}
}
impl<G, F> ScheduledEvent for PeriodicEventDispatcher<G, F>
impl<M, F, T, S> ScheduledEvent for PeriodicEventDispatcher<M, F, T, S>
where
G: (FnOnce() -> F) + Clone + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S> + Clone,
T: Send + Clone + 'static,
S: Send + 'static,
{
fn is_cancelled(&self) -> bool {
false
}
fn next(&self) -> Option<(Box<dyn ScheduledEvent>, Duration)> {
let event = Box::new(Self::new(self.gen.clone(), self.period));
let event = Box::new(Self::new(
self.func.clone(),
self.arg.clone(),
self.sender.clone(),
self.period,
));
Some((event, self.period))
}
fn into_future(self: Box<Self>) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin((self.gen)())
let Self {
func, arg, sender, ..
} = *self;
Box::pin(dispatch_event(func, arg, sender))
}
fn spawn_and_forget(self: Box<Self>, executor: &Executor) {
executor.spawn_and_forget((self.gen)());
let Self {
func, arg, sender, ..
} = *self;
let fut = dispatch_event(func, arg, sender);
executor.spawn_and_forget(fut);
}
}
/// An object that can be converted to a future dispatching a cancellable event.
pub(crate) struct KeyedEventDispatcher<G, F>
/// Object that can be converted to a future dispatching a cancellable event.
pub(crate) struct KeyedEventDispatcher<M, F, T, S>
where
G: (FnOnce(EventKey) -> F) + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + Clone + 'static,
{
/// A generator for the dispatching future.
gen: G,
/// The event cancellation key.
event_key: EventKey,
func: F,
arg: T,
sender: Sender<M>,
_input_kind: PhantomData<S>,
}
impl<G, F> KeyedEventDispatcher<G, F>
impl<M, F, T, S> KeyedEventDispatcher<M, F, T, S>
where
G: (FnOnce(EventKey) -> F) + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + Clone + 'static,
{
/// Constructs a new `KeyedEventDispatcher`.
fn new(gen: G, event_key: EventKey) -> Self {
Self { gen, event_key }
fn new(event_key: EventKey, func: F, arg: T, sender: Sender<M>) -> Self {
Self {
event_key,
func,
arg,
sender,
_input_kind: PhantomData,
}
}
}
impl<G, F> ScheduledEvent for KeyedEventDispatcher<G, F>
impl<M, F, T, S> ScheduledEvent for KeyedEventDispatcher<M, F, T, S>
where
G: (FnOnce(EventKey) -> F) + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + Clone + 'static,
S: Send + 'static,
{
fn is_cancelled(&self) -> bool {
self.event_key.is_cancelled()
@ -755,74 +791,116 @@ where
None
}
fn into_future(self: Box<Self>) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin((self.gen)(self.event_key))
let Self {
event_key,
func,
arg,
sender,
..
} = *self;
Box::pin(dispatch_keyed_event(event_key, func, arg, sender))
}
fn spawn_and_forget(self: Box<Self>, executor: &Executor) {
executor.spawn_and_forget((self.gen)(self.event_key));
let Self {
event_key,
func,
arg,
sender,
..
} = *self;
let fut = dispatch_keyed_event(event_key, func, arg, sender);
executor.spawn_and_forget(fut);
}
}
/// An object that can be converted to a future dispatching a periodic,
/// cancellable event.
pub(crate) struct PeriodicKeyedEventDispatcher<G, F>
/// Object that can be converted to a future dispatching a cancellable event.
pub(crate) struct PeriodicKeyedEventDispatcher<M, F, T, S>
where
G: (FnOnce(EventKey) -> F) + Clone + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + Clone + 'static,
{
/// A clonable generator for the dispatching future.
gen: G,
/// The repetition period.
period: Duration,
/// The event cancellation key.
event_key: EventKey,
func: F,
arg: T,
sender: Sender<M>,
period: Duration,
_input_kind: PhantomData<S>,
}
impl<G, F> PeriodicKeyedEventDispatcher<G, F>
impl<M, F, T, S> PeriodicKeyedEventDispatcher<M, F, T, S>
where
G: (FnOnce(EventKey) -> F) + Clone + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + Clone + 'static,
{
/// Constructs a new `KeyedEventDispatcher`.
fn new(gen: G, period: Duration, event_key: EventKey) -> Self {
fn new(event_key: EventKey, func: F, arg: T, sender: Sender<M>, period: Duration) -> Self {
Self {
gen,
period,
event_key,
func,
arg,
sender,
period,
_input_kind: PhantomData,
}
}
}
impl<G, F> ScheduledEvent for PeriodicKeyedEventDispatcher<G, F>
impl<M, F, T, S> ScheduledEvent for PeriodicKeyedEventDispatcher<M, F, T, S>
where
G: (FnOnce(EventKey) -> F) + Clone + Send + 'static,
F: Future<Output = ()> + Send + 'static,
M: Model,
F: for<'a> InputFn<'a, M, T, S> + Clone,
T: Send + Clone + 'static,
S: Send + 'static,
{
fn is_cancelled(&self) -> bool {
self.event_key.is_cancelled()
}
fn next(&self) -> Option<(Box<dyn ScheduledEvent>, Duration)> {
let event = Box::new(Self::new(
self.gen.clone(),
self.period,
self.event_key.clone(),
self.func.clone(),
self.arg.clone(),
self.sender.clone(),
self.period,
));
Some((event, self.period))
}
fn into_future(self: Box<Self>) -> Pin<Box<dyn Future<Output = ()> + Send>> {
Box::pin((self.gen)(self.event_key))
let Self {
event_key,
func,
arg,
sender,
..
} = *self;
Box::pin(dispatch_keyed_event(event_key, func, arg, sender))
}
fn spawn_and_forget(self: Box<Self>, executor: &Executor) {
executor.spawn_and_forget((self.gen)(self.event_key));
let Self {
event_key,
func,
arg,
sender,
..
} = *self;
let fut = dispatch_keyed_event(event_key, func, arg, sender);
executor.spawn_and_forget(fut);
}
}
/// Asynchronously dispatches a non-cancellable event to a model input.
pub(crate) async fn dispatch_event<M, F, T, S>(func: F, arg: T, sender: Sender<M>)
/// Asynchronously dispatch a regular, non-cancellable event.
async fn dispatch_event<M, F, T, S>(func: F, arg: T, sender: Sender<M>)
where
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + 'static,
T: Send + Clone + 'static,
{
let _ = sender
.send(
@ -838,13 +916,9 @@ where
.await;
}
/// Asynchronously dispatches a cancellable event to a model input.
pub(crate) async fn dispatch_keyed_event<M, F, T, S>(
event_key: EventKey,
func: F,
arg: T,
sender: Sender<M>,
) where
/// Asynchronously dispatch a cancellable event.
async fn dispatch_keyed_event<M, F, T, S>(event_key: EventKey, func: F, arg: T, sender: Sender<M>)
where
M: Model,
F: for<'a> InputFn<'a, M, T, S>,
T: Send + Clone + 'static,