#![allow(dead_code, unused_macros, clippy::result_large_err)]
use std::error::Error;
use std::fmt;
use std::marker::PhantomData;
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use ulo::{
App, AppBuilder, BoxError, BoxFuture, Guard, Module, ModuleDef, ModuleIdentity, StartupError, Timer, Transport, TypeName,
Wired, WiringError, WiringErrors,
};
pub struct Empty;
impl Module for Empty {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_type::<Self>()
}
fn register(&self, _m: &mut ModuleDef<'_>) {}
}
pub struct Mod<K: 'static> {
register: Box<dyn Fn(&mut ModuleDef<'_>) + Send + Sync>,
_k: PhantomData<fn() -> K>,
}
impl<K: 'static> Mod<K> {
pub fn new(register: impl Fn(&mut ModuleDef<'_>) + Send + Sync + 'static) -> Self {
Mod { register: Box::new(register), _k: PhantomData }
}
pub fn bare() -> Self {
Mod::new(|_| {})
}
}
impl<K: 'static> Module for Mod<K> {
fn identity(&self) -> ModuleIdentity {
ModuleIdentity::of_type::<Self>()
}
fn register(&self, m: &mut ModuleDef<'_>) {
(self.register)(m);
}
}
pub fn mod_name<K: 'static>() -> String {
format!("Mod<{}>", TypeName::of::<K>())
}
pub fn keyed_mod_name<K: 'static, Q: 'static>() -> String {
format!("{} @ {}", mod_name::<K>(), TypeName::of::<Q>())
}
pub fn watchdog() {
static STARTED: std::sync::Once = std::sync::Once::new();
STARTED.call_once(|| {
std::thread::spawn(|| {
std::thread::sleep(Duration::from_secs(60));
eprintln!("watchdog: the test process ran past 60 s; a test is hung");
std::process::abort();
});
});
}
pub fn wire_result(root: impl Module) -> Result<App<Wired>, StartupError> {
watchdog();
App::builder(root).wire()
}
pub fn wire_err(root: impl Module) -> WiringErrors {
wiring_errors(wire_result(root))
}
pub fn wire_err_with(builder: AppBuilder) -> WiringErrors {
watchdog();
wiring_errors(builder.wire())
}
pub fn wiring_errors(outcome: Result<App<Wired>, StartupError>) -> WiringErrors {
match outcome {
Err(StartupError::Wiring(errors)) => errors,
Err(other) => panic!("wire() failed, but not with wiring errors: {other}"),
Ok(_) => panic!("wire() succeeded; the graph was expected to be refused"),
}
}
pub fn wires(root: impl Module) -> App<Wired> {
wires_with(App::builder(root))
}
pub fn wires_with(builder: AppBuilder) -> App<Wired> {
watchdog();
match builder.wire() {
Ok(app) => app,
Err(error) => panic!("wire() refused a graph that should wire:\n{error}"),
}
}
pub fn variants(errors: &WiringErrors) -> Vec<String> {
errors.iter().map(variant).collect()
}
pub fn variant(error: &WiringError) -> String {
format!("{error:?}").split([' ', '{', '(']).next().unwrap_or_default().to_owned()
}
macro_rules! entries {
($errors:expr, $pat:pat => $out:expr) => {{
let errors: &ulo::WiringErrors = &$errors;
errors
.iter()
.filter_map(|entry| match entry {
$pat => Some($out),
_ => None,
})
.collect::<Vec<_>>()
}};
}
macro_rules! entry {
($errors:expr, $pat:pat => $out:expr) => {{
let mut found = entries!($errors, $pat => $out);
assert!(
found.len() == 1,
"expected exactly one `{}` entry, found {}; the report:\n{}",
stringify!($pat),
found.len(),
$errors
);
found.remove(0)
}};
}
#[derive(Debug)]
pub struct Boom(pub String);
impl Boom {
pub fn new(text: impl Into<String>) -> Self {
Boom(text.into())
}
}
impl fmt::Display for Boom {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl Error for Boom {}
#[derive(Clone, Default)]
pub struct Probe(Arc<Mutex<Vec<&'static str>>>);
impl Probe {
pub fn new() -> Self {
Probe::default()
}
pub fn mark(&self, what: &'static str) {
self.0.lock().unwrap_or_else(PoisonError::into_inner).push(what);
}
pub fn log(&self) -> Vec<&'static str> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
pub fn is_empty(&self) -> bool {
self.log().is_empty()
}
}
pub struct Frozen(Instant);
impl Frozen {
pub fn new() -> Self {
Frozen(Instant::now() + Duration::from_secs(86_400))
}
}
impl Timer for Frozen {
fn sleep(&self, _d: Duration) -> BoxFuture<'static, ()> {
Box::pin(async {})
}
fn now(&self) -> Instant {
self.0
}
fn try_sleep(&self, d: Duration) -> BoxFuture<'static, Result<(), ulo::Refused>> {
let sleep = Timer::sleep(self, d);
Box::pin(async move {
sleep.await;
Ok(())
})
}
}
macro_rules! unit_service {
($($name:ident),+ $(,)?) => {$(
pub struct $name;
impl ulo::Construct for $name {
type Scope = ulo::scope::Singleton;
fn dependencies(_d: &mut ulo::Dependencies) {}
async fn construct(_r: &ulo::Resolver<'_>) -> Result<Self, ulo::ConstructError> {
Ok($name)
}
}
)+};
}
pub struct TA;
impl Transport for TA {
const KEY: &'static str = "a";
type Cx = ();
type Reply = ();
}
pub struct TB;
impl Transport for TB {
const KEY: &'static str = "b";
type Cx = ();
type Reply = ();
}
pub struct GuardA;
impl Guard<TA> for GuardA {
async fn can_activate(&self, _cx: &()) -> Result<bool, BoxError> {
Ok(true)
}
}
impl ulo::Construct for GuardA {
type Scope = ulo::scope::Singleton;
fn dependencies(_d: &mut ulo::Dependencies) {}
async fn construct(_r: &ulo::Resolver<'_>) -> Result<Self, ulo::ConstructError> {
Ok(GuardA)
}
}
#[derive(Clone, Default)]
pub struct Count(Arc<std::sync::atomic::AtomicUsize>);
impl Count {
pub fn new() -> Self {
Count::default()
}
pub fn bump(&self) -> usize {
self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1
}
pub fn get(&self) -> usize {
self.0.load(std::sync::atomic::Ordering::SeqCst)
}
}
macro_rules! reader {
($name:ident, $scope:ty $(, $field:ident : $ty:ty)* $(,)?) => {
pub struct $name;
impl ulo::Construct for $name {
type Scope = $scope;
fn dependencies(d: &mut ulo::Dependencies) {
$( d.field::<$ty>(stringify!($field)); )*
let _ = d;
}
async fn construct(r: &ulo::Resolver<'_>) -> Result<Self, ulo::ConstructError> {
$( let _ = <$ty as ulo::FromContainer>::from_container(r).await?; )*
let _ = r;
Ok($name)
}
}
};
}
macro_rules! controller {
($name:ident, $scope:ty, [$($field:ident : $ty:ty),*], |$m:ident| $body:expr) => {
reader!($name, $scope $(, $field : $ty)*);
impl ulo::Controller for $name {}
impl ulo::Handlers for $name {
fn mount($m: &mut ulo::Mount<'_>) {
$body
}
}
};
}
pub async fn connects(root: impl Module) -> ulo::App<ulo::Connected> {
watchdog();
match App::builder(root).wire() {
Ok(app) => match app.connect().await {
Ok(app) => app,
Err(error) => panic!("connect() failed on a graph that should connect:\n{error}"),
},
Err(error) => panic!("wire() refused a graph that should wire:\n{error}"),
}
}
pub async fn connect_err(root: impl Module) -> StartupError {
watchdog();
match wires(root).connect().await {
Err(error) => error,
Ok(_) => panic!("connect() succeeded; the graph was expected to fail while connecting"),
}
}
pub async fn read_q<T: ?Sized + Send + Sync + 'static, Q: 'static>(
app: &ulo::App<ulo::Connected>,
) -> Result<ulo::Dep<T, Q>, ulo::LookupError> {
app.execute(ulo::ExecOptions::new(), async |exec| exec.resolver().dep_qualified::<T, Q>().await)
.await
.expect("a connected app opens executions")
}
pub async fn read_many<T: ?Sized + Send + Sync + 'static>(
app: &ulo::App<ulo::Connected>,
) -> Result<ulo::Many<T>, ulo::LookupError> {
app.execute(ulo::ExecOptions::new(), async |exec| exec.resolver().many::<T>().await)
.await
.expect("a connected app opens executions")
}
pub async fn connected(root: impl Module) -> ulo::App<ulo::Connected> {
connected_with(App::builder(root)).await
}
pub async fn connected_with(builder: AppBuilder) -> ulo::App<ulo::Connected> {
watchdog();
match builder.wire() {
Ok(app) => app.connect().await.unwrap_or_else(|error| panic!("connect() failed:\n{error}")),
Err(error) => panic!("wire() refused a graph that should wire:\n{error}"),
}
}
pub async fn connected_on_tokio(root: impl Module) -> ulo::App<ulo::Connected> {
connected_with(App::builder(root).runtime(ulo_runtime_tokio::Tokio::current())).await
}
pub async fn close(app: ulo::App<ulo::Connected>) {
app.close(ulo::Signal::new("test")).await.unwrap_or_else(|error| panic!("close() failed: {error:?}"));
}
#[derive(Clone, Default)]
pub struct Log(Arc<Mutex<Vec<String>>>);
impl Log {
pub fn new() -> Self {
Log::default()
}
pub fn push(&self, event: impl Into<String>) {
self.0.lock().unwrap_or_else(PoisonError::into_inner).push(event.into());
}
pub fn events(&self) -> Vec<String> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
pub fn has(&self, event: &str) -> bool {
self.events().iter().any(|seen| seen == event)
}
pub fn count(&self, event: &str) -> usize {
self.events().iter().filter(|seen| *seen == event).count()
}
}
pub struct Gate(Mutex<(bool, Vec<std::task::Waker>)>);
impl Gate {
pub fn new(open: bool) -> Arc<Gate> {
Arc::new(Gate(Mutex::new((open, Vec::new()))))
}
pub fn open(&self) {
let waiting = {
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
state.0 = true;
std::mem::take(&mut state.1)
};
waiting.into_iter().for_each(std::task::Waker::wake);
}
pub async fn pass(&self) {
std::future::poll_fn(|cx| {
let mut state = self.0.lock().unwrap_or_else(PoisonError::into_inner);
if state.0 {
return std::task::Poll::Ready(());
}
state.1.push(cx.waker().clone());
std::task::Poll::Pending
})
.await
}
}
#[derive(Clone, Default)]
pub struct SleepLog(Arc<Mutex<Vec<Duration>>>);
impl SleepLog {
pub fn new() -> Self {
SleepLog::default()
}
pub fn asked(&self) -> Vec<Duration> {
self.0.lock().unwrap_or_else(PoisonError::into_inner).clone()
}
pub fn count(&self, d: Duration) -> usize {
self.asked().into_iter().filter(|asked| *asked == d).count()
}
}
pub struct Recorded(Instant, SleepLog);
impl Recorded {
pub fn new(log: &SleepLog) -> Self {
Recorded(Instant::now() + Duration::from_secs(86_400), log.clone())
}
}
impl Timer for Recorded {
fn sleep(&self, d: Duration) -> BoxFuture<'static, ()> {
self.1.0.lock().unwrap_or_else(PoisonError::into_inner).push(d);
Box::pin(async {})
}
fn now(&self) -> Instant {
self.0
}
fn try_sleep(&self, d: Duration) -> BoxFuture<'static, Result<(), ulo::Refused>> {
let sleep = Timer::sleep(self, d);
Box::pin(async move {
sleep.await;
Ok(())
})
}
}
pub struct Refusing(Instant, SleepLog);
impl Refusing {
pub fn new(log: &SleepLog) -> Self {
Refusing(Instant::now() + Duration::from_secs(86_400), log.clone())
}
}
impl Timer for Refusing {
fn sleep(&self, d: Duration) -> BoxFuture<'static, ()> {
self.1.0.lock().unwrap_or_else(PoisonError::into_inner).push(d);
Box::pin(async {})
}
fn now(&self) -> Instant {
self.0
}
fn try_sleep(&self, d: Duration) -> BoxFuture<'static, Result<(), ulo::Refused>> {
self.1.0.lock().unwrap_or_else(PoisonError::into_inner).push(d);
Box::pin(async { Err(ulo::Refused) })
}
}
#[derive(Clone, Copy)]
pub enum CloseMode {
Ok,
Err,
Panic,
Pending,
ErrAfter(Duration),
}
pub type OnDrain = Arc<dyn Fn(ulo::AppHandle, ulo::DrainToken) -> BoxFuture<'static, ()> + Send + Sync>;
pub struct TestServer<T> {
name: &'static str,
log: Log,
app: Option<ulo::AppHandle>,
fail_prepare: bool,
fail_bind: bool,
permanent: bool,
shut_down: bool,
close: CloseMode,
on_drain: Option<OnDrain>,
_t: PhantomData<fn() -> T>,
}
impl<T: Transport> TestServer<T> {
pub fn new(name: &'static str, log: &Log) -> Self {
TestServer {
name,
log: log.clone(),
app: None,
fail_prepare: false,
fail_bind: false,
permanent: false,
shut_down: false,
close: CloseMode::Ok,
on_drain: None,
_t: PhantomData,
}
}
pub fn fail_prepare(mut self) -> Self {
self.fail_prepare = true;
self
}
pub fn fail_bind(mut self) -> Self {
self.fail_bind = true;
self
}
pub fn permanent(mut self) -> Self {
self.permanent = true;
self
}
pub fn bind_on_a_dead_runtime(mut self) -> Self {
self.fail_bind = true;
self.shut_down = true;
self
}
pub fn close_with(mut self, mode: CloseMode) -> Self {
self.close = mode;
self
}
pub fn on_drain(mut self, f: OnDrain) -> Self {
self.on_drain = Some(f);
self
}
}
impl<T> TestServer<T> {
fn refusal(&self, text: &str) -> BoxError {
if self.shut_down {
return Box::new(ulo::Permanent::new(ulo::RuntimeShutDown::new(ulo::Refused)));
}
if self.permanent { Box::new(ulo::Permanent::new(Boom::new(text))) } else { Box::new(Boom::new(text)) }
}
}
impl<T: Transport> ulo::Server for TestServer<T> {
type Transport = T;
async fn prepare(&mut self, mounted: ulo::Mounted<'_, T>) -> Result<(), BoxError> {
self.log.push(format!("prepare {}", self.name));
self.app = Some(mounted.app().clone());
if self.fail_prepare { Err(self.refusal("prepare refused")) } else { Ok(()) }
}
async fn bind(&mut self, _mounted: ulo::Mounted<'_, T>) -> Result<(), BoxError> {
self.log.push(format!("bind {}", self.name));
if self.fail_bind { Err(self.refusal("bind refused")) } else { Ok(()) }
}
async fn serve(&self) -> Result<(), BoxError> {
std::future::pending().await
}
async fn drain(&self, token: ulo::DrainToken) {
self.log.push(format!("drain {}", self.name));
if let (Some(f), Some(app)) = (&self.on_drain, &self.app) {
f(app.clone(), token).await;
}
}
async fn close(&self) -> Result<(), BoxError> {
self.log.push(format!("close {}", self.name));
match self.close {
CloseMode::Ok => Ok(()),
CloseMode::Err => Err(Box::new(Boom::new("close refused"))),
CloseMode::Panic => panic!("close panics"),
CloseMode::Pending => std::future::pending().await,
CloseMode::ErrAfter(after) => {
tokio::time::sleep(after).await;
Err(Box::new(Boom::new(format!("close {} refused", self.name))))
}
}
}
}
pub type Queued = Box<dyn FnOnce(ulo::App<ulo::Connected>) -> ulo::App<ulo::Connected> + Send>;
pub async fn listened(builder: AppBuilder, servers: Vec<Queued>) -> Result<ulo::App<ulo::app::Bound>, StartupError> {
watchdog();
let mut app = builder.wire()?.connect().await?;
for queue in servers {
app = queue(app);
}
app.listen().await
}
pub fn server<S: ulo::Server>(s: S) -> Queued {
Box::new(move |app| app.bind(s))
}
pub const PATIENCE: Duration = Duration::from_secs(10);
pub async fn within<F: std::future::Future>(what: &str, fut: F) -> F::Output {
match tokio::time::timeout(PATIENCE, fut).await {
Ok(out) => out,
Err(_) => panic!("{what} did not finish within {PATIENCE:?}"),
}
}
#[macro_use]
pub mod pipeline;