#![allow(dead_code)]
use std::error::Error;
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use redup_abstractions::{Health, Phase};
use redup_bootstrap::{
Builder, Context, Module, ModuleError, NoSettings, Service, Stopper, async_trait,
};
use redup_config::Source;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio_util::sync::CancellationToken;
pub(crate) const LISTENER: &str = "bootstrap:\n rest:\n host: 127.0.0.1\n port: 0\n";
const NAMES: [&str; 5] = ["Alpha", "Bravo", "Charlie", "Delta", "Echo"];
pub(crate) type Alpha = Recorder<0>;
pub(crate) type Bravo = Recorder<1>;
pub(crate) type Charlie = Recorder<2>;
pub(crate) type Delta = Recorder<3>;
#[derive(Clone, Default)]
pub(crate) struct Events(Arc<Mutex<Vec<String>>>);
impl Events {
pub(crate) fn log(&self, event: &str) {
locked(&self.0).push(event.to_owned());
}
pub(crate) fn get(&self) -> Vec<String> {
locked(&self.0).clone()
}
pub(crate) fn none() -> Result<(tempfile::TempDir, Source), Box<dyn Error>> {
Events::source("bootstrap:\n rest: ~\n")
}
pub(crate) fn source(yaml: &str) -> Result<(tempfile::TempDir, Source), Box<dyn Error>> {
let directory = tempfile::tempdir()?;
std::fs::write(directory.path().join("config.yaml"), yaml)?;
let source = Source::directory(directory.path());
Ok((directory, source))
}
pub(crate) async fn assemble(
source: &Source,
modules: &[(usize, Arc<Behaviour>)],
) -> Result<redup_bootstrap::Instance, Box<dyn Error>> {
let mut builder = Builder::new(source, Service::new("trial", "0.0.0"))?;
for (id, behaviour) in modules {
match id {
0 => {
builder.add::<Alpha>(Arc::clone(behaviour)).await?;
}
1 => {
builder.add::<Bravo>(Arc::clone(behaviour)).await?;
}
2 => {
builder.add::<Charlie>(Arc::clone(behaviour)).await?;
}
3 => {
builder.add::<Delta>(Arc::clone(behaviour)).await?;
}
other => return Err(format!("module #{other} is not declared").into()),
}
}
Ok(builder.build())
}
}
pub(crate) struct Behaviour {
events: Events,
name: Mutex<&'static str>,
with_health: bool,
phase: Mutex<Phase>,
drain: Mutex<Option<Duration>>,
fail_start: AtomicBool,
fail_drain: AtomicBool,
fail_stop: AtomicBool,
panic_start: AtomicBool,
fatal: Mutex<Option<String>>,
token: Mutex<Option<CancellationToken>>,
health: Mutex<Option<Health>>,
stopper: Mutex<Option<Stopper>>,
}
impl Behaviour {
pub(crate) fn new(events: &Events) -> Self {
Self {
events: events.clone(),
name: Mutex::new(""),
with_health: false,
phase: Mutex::new(Phase::Starting),
drain: Mutex::new(None),
fail_start: AtomicBool::new(false),
fail_drain: AtomicBool::new(false),
fail_stop: AtomicBool::new(false),
panic_start: AtomicBool::new(false),
fatal: Mutex::new(None),
token: Mutex::new(None),
health: Mutex::new(None),
stopper: Mutex::new(None),
}
}
pub(crate) fn with_health(mut self, phase: Phase) -> Self {
self.with_health = true;
*locked(&self.phase) = phase;
self
}
pub(crate) fn drain_for(self, for_time: Duration) -> Self {
*locked(&self.drain) = Some(for_time);
self
}
pub(crate) fn failing_start(self) -> Self {
self.fail_start.store(true, Ordering::SeqCst);
self
}
pub(crate) fn panicking_start(self) -> Self {
self.panic_start.store(true, Ordering::SeqCst);
self
}
pub(crate) fn fatal_on_start(self, reason: &str) -> Self {
*locked(&self.fatal) = Some(reason.to_owned());
self
}
pub(crate) fn failing_drain(self) -> Self {
self.fail_drain.store(true, Ordering::SeqCst);
self
}
pub(crate) fn failing_stop(self) -> Self {
self.fail_stop.store(true, Ordering::SeqCst);
self
}
pub(crate) fn set_phase(&self, phase: Phase) {
let health = locked(&self.health).clone();
if let Some(health) = health {
health.set(phase);
}
}
pub(crate) fn token(&self) -> Option<CancellationToken> {
locked(&self.token).clone()
}
fn point(&self, point: &str) {
let cancelled = locked(&self.token)
.as_ref()
.is_some_and(CancellationToken::is_cancelled);
self.events.log(&format!(
"{}: {point}{}",
self.name(),
if cancelled { " (token cancelled)" } else { "" }
));
}
fn name(&self) -> &'static str {
*locked(&self.name)
}
}
pub(crate) struct Recorder<const ID: usize>(Arc<Behaviour>);
#[allow(clippy::panic)]
fn boom() -> ! {
panic!("boom")
}
#[async_trait]
impl<const ID: usize> Module for Recorder<ID> {
const NAME: &'static str = NAMES[ID];
type Config = NoSettings;
type Args = Arc<Behaviour>;
async fn create(
_: NoSettings,
behaviour: Arc<Behaviour>,
ctx: &mut Context<'_>,
) -> Result<Self, ModuleError> {
*locked(&behaviour.token) = Some(ctx.token());
*locked(&behaviour.stopper) = Some(ctx.stopper());
*locked(&behaviour.name) = Self::NAME;
if behaviour.with_health {
*locked(&behaviour.health) = Some(ctx.health());
}
behaviour.point("create");
Ok(Self(behaviour))
}
async fn start(&self) -> Result<(), ModuleError> {
self.0.point("start");
if self.0.panic_start.load(Ordering::SeqCst) {
boom();
}
if self.0.fail_start.load(Ordering::SeqCst) {
return Err("start failed".into());
}
let fatal = locked(&self.0.fatal).clone();
if let Some(reason) = fatal {
let stopper = locked(&self.0.stopper).clone();
if let Some(stopper) = stopper {
stopper.fatal(reason);
}
}
let health = locked(&self.0.health).clone();
if let Some(health) = health {
health.set(*locked(&self.0.phase));
}
Ok(())
}
async fn drain(&self) -> Result<(), ModuleError> {
self.0.point("drain");
let for_time = *locked(&self.0.drain);
if let Some(for_time) = for_time {
tokio::time::sleep(for_time).await;
}
if self.0.fail_drain.load(Ordering::SeqCst) {
return Err("drain failed".into());
}
self.0.events.log(&format!("{}: drained", self.0.name()));
Ok(())
}
async fn stop(&self) -> Result<(), ModuleError> {
self.0.point("stop");
if self.0.fail_stop.load(Ordering::SeqCst) {
return Err("stop failed".into());
}
Ok(())
}
}
pub(crate) fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn has(events: &[String], point: &str) -> bool {
events.iter().any(|event| event == point)
}
pub(crate) struct Reply {
pub(crate) status: u16,
pub(crate) content_type: String,
pub(crate) body: String,
}
pub(crate) async fn get(address: SocketAddr, path: &str) -> Result<Reply, Box<dyn Error>> {
get_with(address, path, &[]).await
}
pub(crate) async fn get_with(
address: SocketAddr,
path: &str,
headers: &[(&str, &str)],
) -> Result<Reply, Box<dyn Error>> {
let mut stream = tokio::net::TcpStream::connect(address).await?;
let mut request = format!("GET {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n");
for (name, value) in headers {
request.push_str(&format!("{name}: {value}\r\n"));
}
request.push_str("\r\n");
stream.write_all(request.as_bytes()).await?;
let mut response = Vec::new();
stream.read_to_end(&mut response).await?;
stream.shutdown().await?;
let text = String::from_utf8(response)?;
let (head, body) = text
.split_once("\r\n\r\n")
.ok_or("no header end in the response")?;
let status = head
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.ok_or("no status line in the response")?
.parse()?;
let content_type = head
.lines()
.filter_map(|line| line.split_once(':'))
.find(|(name, _)| name.eq_ignore_ascii_case("content-type"))
.map(|(_, value)| value.trim().to_owned())
.ok_or("no content type in the response")?;
Ok(Reply {
status,
content_type,
body: body.to_owned(),
})
}