use crate::{
Head, HttpError, Message,
session::{lock, simulated_capabilities},
transport::*,
};
use std::{
collections::{HashMap, VecDeque},
sync::{Arc, Mutex, Weak},
time::Duration,
};
pub trait Clock: Send + Sync + 'static {
fn now(&self) -> Duration;
fn schedule(&self, delay: Duration, job: Box<dyn FnOnce() + Send>);
}
#[derive(Default)]
pub struct RealClock;
impl Clock for RealClock {
fn now(&self) -> Duration {
crate::statistics::now()
}
fn schedule(&self, delay: Duration, job: Box<dyn FnOnce() + Send>) {
#[cfg(not(target_arch = "wasm32"))]
{
day_async::schedule(delay, job);
}
#[cfg(target_arch = "wasm32")]
{
crate::bridge::simulation_delay(delay.as_secs_f64() * 1000.0, job);
}
}
}
type Job = Box<dyn FnOnce() + Send>;
#[derive(Default)]
struct Manual {
now: Duration,
next: u64,
jobs: Vec<(Duration, u64, Job)>,
}
#[derive(Clone, Default)]
pub struct ManualClock(Arc<Mutex<Manual>>);
impl ManualClock {
pub fn advance(&self, by: Duration) {
let end = self.now() + by;
loop {
let job = {
let mut s = lock(&self.0);
let next = s
.jobs
.iter()
.enumerate()
.filter(|(_, j)| j.0 <= end)
.min_by_key(|(_, j)| (j.0, j.1))
.map(|(i, _)| i);
match next {
Some(i) => {
let (at, _, job) = s.jobs.remove(i);
s.now = at;
Some(job)
}
None => {
s.now = end;
None
}
}
};
match job {
Some(job) => job(),
None => break,
}
}
}
}
impl Clock for ManualClock {
fn now(&self) -> Duration {
lock(&self.0).now
}
fn schedule(&self, delay: Duration, job: Job) {
let mut s = lock(&self.0);
let at = s.now + delay;
let id = s.next;
s.next += 1;
s.jobs.push((at, id, job));
}
}
#[derive(Clone, Debug)]
pub struct Conditions {
pub latency: Duration,
pub bytes_per_second: Option<u64>,
pub failure_rate: f64,
pub seed: u64,
pub paused: bool,
pub offline: bool,
}
impl Default for Conditions {
fn default() -> Self {
Self {
latency: Duration::ZERO,
bytes_per_second: None,
failure_rate: 0.0,
seed: 1,
paused: false,
offline: false,
}
}
}
#[derive(Clone, Debug)]
pub struct Reply {
pub status: u16,
pub headers: Vec<(String, String)>,
pub chunks: Vec<Vec<u8>>,
pub delay: Duration,
pub fail_after_chunks: Option<usize>,
}
impl Reply {
pub fn new(status: u16, body: impl Into<Vec<u8>>) -> Self {
let body = body.into();
Self {
status,
headers: vec![],
chunks: body.chunks(16 * 1024).map(|c| c.to_vec()).collect(),
delay: Duration::ZERO,
fail_after_chunks: None,
}
}
pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.headers.push((name.into(), value.into()));
self
}
}
#[derive(Clone, Debug)]
pub struct RequestRecord {
pub method: String,
pub url: String,
pub ordinal: u64,
pub injected_failure: bool,
}
type Predicate = dyn Fn(&str, &str) -> bool + Send + Sync;
type Handler = dyn Fn(Prepared) -> Result<Reply, HttpError> + Send + Sync;
type WsHandler = dyn Fn(Message) -> Result<Message, HttpError> + Send + Sync;
struct Rule {
matches: Arc<Predicate>,
handler: Arc<Handler>,
}
struct State {
rules: Vec<Rule>,
ws: Vec<(Arc<Predicate>, Arc<WsHandler>)>,
conditions: Conditions,
strict: bool,
counts: HashMap<String, u64>,
history: VecDeque<RequestRecord>,
}
struct Inner {
state: Mutex<State>,
clock: Arc<dyn Clock>,
}
#[derive(Clone)]
pub struct Simulation(Arc<Inner>);
impl Default for Simulation {
fn default() -> Self {
Self::new()
}
}
impl Simulation {
pub fn new() -> Self {
Self::with_clock(Arc::new(RealClock))
}
pub fn with_clock(clock: Arc<dyn Clock>) -> Self {
Self(Arc::new(Inner {
state: Mutex::new(State {
rules: vec![],
ws: vec![],
conditions: Conditions::default(),
strict: true,
counts: HashMap::new(),
history: VecDeque::new(),
}),
clock,
}))
}
pub fn set_strict(&self, strict: bool) {
lock(&self.0.state).strict = strict;
}
pub fn set_conditions(&self, mut conditions: Conditions) {
conditions.failure_rate = if conditions.failure_rate.is_finite() {
conditions.failure_rate.clamp(0.0, 1.0)
} else {
0.0
};
lock(&self.0.state).conditions = conditions;
}
pub fn conditions(&self) -> Conditions {
lock(&self.0.state).conditions.clone()
}
pub fn handle(
&self,
matches: impl Fn(&str, &str) -> bool + Send + Sync + 'static,
handler: impl Fn(Prepared) -> Result<Reply, HttpError> + Send + Sync + 'static,
) {
lock(&self.0.state).rules.push(Rule {
matches: Arc::new(matches),
handler: Arc::new(handler),
});
}
pub fn route(
&self,
method: &str,
url: &str,
handler: impl Fn(Prepared) -> Result<Reply, HttpError> + Send + Sync + 'static,
) {
let method = method.to_owned();
let url = url.to_owned();
self.handle(move |m, u| m == method && u == url, handler);
}
pub fn websocket(
&self,
matches: impl Fn(&str, &str) -> bool + Send + Sync + 'static,
handler: impl Fn(Message) -> Result<Message, HttpError> + Send + Sync + 'static,
) {
lock(&self.0.state)
.ws
.push((Arc::new(matches), Arc::new(handler)));
}
pub fn websocket_echo(&self, url: &str) {
let url = url.to_owned();
self.websocket(move |_, u| u == url, Ok);
}
pub fn requests(&self) -> Vec<RequestRecord> {
lock(&self.0.state).history.iter().cloned().collect()
}
pub fn request_count(&self, method: &str, url: &str) -> u64 {
*lock(&self.0.state)
.counts
.get(&format!("{method} {url}"))
.unwrap_or(&0)
}
pub(crate) fn intercepts(&self, method: &str, url: &str) -> bool {
let (strict, rules) = {
let s = lock(&self.0.state);
(
s.strict,
s.rules
.iter()
.map(|r| r.matches.clone())
.chain(s.ws.iter().map(|r| r.0.clone()))
.collect::<Vec<_>>(),
)
};
strict || rules.iter().any(|m| m(method, url))
}
pub(crate) fn clock(&self) -> Arc<dyn Clock> {
self.0.clock.clone()
}
pub(crate) fn transport(&self) -> Arc<dyn Transport> {
Arc::new(self.clone())
}
fn fault(&self, method: &str, url: &str) -> bool {
let mut s = lock(&self.0.state);
let key = format!("{method} {url}");
let ordinal = {
let n = s.counts.entry(key.clone()).or_default();
*n += 1;
*n
};
let mut x = key.bytes().fold(0xcbf29ce484222325u64, |h, b| {
(h ^ b as u64).wrapping_mul(0x100000001b3)
}) ^ s.conditions.seed
^ ordinal.wrapping_mul(0x9e3779b97f4a7c15);
x = (x ^ (x >> 30)).wrapping_mul(0xbf58476d1ce4e5b9);
x = (x ^ (x >> 27)).wrapping_mul(0x94d049bb133111eb);
x ^= x >> 31;
let fail = s.conditions.offline
|| (x >> 11) as f64 / ((1u64 << 53) as f64) < s.conditions.failure_rate;
s.history.push_back(RequestRecord {
method: method.into(),
url: url.into(),
ordinal,
injected_failure: fail,
});
if s.history.len() > 256 {
s.history.pop_front();
}
fail
}
}
fn fault_error() -> HttpError {
HttpError::Io("simulated connection failure".into())
}
fn delay(c: &Conditions, bytes: u64) -> Duration {
c.bytes_per_second
.map(|rate| Duration::from_secs_f64(bytes as f64 / rate.max(1) as f64))
.unwrap_or_default()
}
impl Transport for Simulation {
fn capabilities(&self) -> crate::Capabilities {
simulated_capabilities()
}
fn start(&self, req: Prepared, events: Events) -> Arc<dyn Transfer> {
let failed = self.fault(&req.method, &req.url);
let url = req.url.clone();
let timeout = req.timeout_idle;
let uploaded = match &req.body {
PreparedBody::Bytes(b) => b.len() as u64,
PreparedBody::File { len, .. } => *len,
PreparedBody::Stream { len, .. } => len.unwrap_or(0),
PreparedBody::Empty => 0,
};
let rules = lock(&self.0.state)
.rules
.iter()
.map(|r| (r.matches.clone(), r.handler.clone()))
.collect::<Vec<_>>();
let bodyless = req.method == "HEAD";
let result = if failed {
Err(fault_error())
} else {
rules
.into_iter()
.find(|(m, _)| m(&req.method, &req.url))
.map(|(_, h)| h(req))
.unwrap_or_else(|| Err(HttpError::Io(format!("unexpected HTTP request: {url}"))))
};
let result = result.map(|mut reply| {
if bodyless || matches!(reply.status, 204 | 304) {
reply.chunks.clear();
}
reply
});
let initial = self.conditions().latency
+ delay(&self.conditions(), uploaded)
+ result.as_ref().map(|r| r.delay).unwrap_or_default();
let transfer = Arc::new_cyclic(|weak| SimTransfer {
this: weak.clone(),
sim: self.clone(),
events,
state: Mutex::new(HttpState {
result: Some(result),
chunks: VecDeque::new(),
head: false,
demand: 0,
over: false,
busy: true,
sent: 0,
fail_after: None,
last_activity: self.0.clock.now(),
}),
url,
uploaded,
timeout,
});
let weak = Arc::downgrade(&transfer);
self.0.clock.schedule(
initial,
Box::new(move || {
if let Some(t) = weak.upgrade() {
t.deliver();
}
}),
);
transfer.watch_timeout(timeout);
transfer
}
fn websocket(&self, req: Prepared, events: WsEvents) -> Arc<dyn Socket> {
let rules = lock(&self.0.state).ws.clone();
let handler = rules
.into_iter()
.find(|(m, _)| m(&req.method, &req.url))
.map(|(_, h)| h);
let failed = self.fault(&req.method, &req.url);
let socket = Arc::new_cyclic(|weak| SimSocket {
this: weak.clone(),
sim: self.clone(),
events,
handler,
state: Mutex::new(WsState {
queue: VecDeque::new(),
demand: 0,
over: false,
busy: false,
}),
url: req.url,
});
socket.open_after(
self.conditions().latency,
req.protocols.first().cloned(),
failed,
self.0.clock.now() + req.timeout_idle,
);
socket
}
}
struct HttpState {
result: Option<Result<Reply, HttpError>>,
chunks: VecDeque<Vec<u8>>,
head: bool,
demand: u32,
over: bool,
busy: bool,
sent: usize,
fail_after: Option<usize>,
last_activity: Duration,
}
struct SimTransfer {
this: Weak<Self>,
sim: Simulation,
events: Events,
state: Mutex<HttpState>,
url: String,
uploaded: u64,
timeout: Duration,
}
impl SimTransfer {
fn watch_timeout(&self, delay: Duration) {
let weak = self.this.clone();
self.sim.0.clock.schedule(
delay,
Box::new(move || {
if let Some(t) = weak.upgrade() {
let (over, elapsed) = {
let s = lock(&t.state);
(s.over, t.sim.0.clock.now().saturating_sub(s.last_activity))
};
if over {
return;
}
if elapsed >= t.timeout {
t.finish(HttpError::Timeout);
} else {
t.watch_timeout(t.timeout - elapsed);
}
}
}),
);
}
fn finish(&self, error: HttpError) {
let notify = {
let mut s = lock(&self.state);
if s.over {
false
} else {
s.over = true;
s.chunks.clear();
s.result = None;
true
}
};
if notify {
(self.events)(Event::Failed(error));
}
}
fn schedule(&self, wait: Duration) {
let weak = self.this.clone();
self.sim.0.clock.schedule(
wait,
Box::new(move || {
if let Some(t) = weak.upgrade() {
t.deliver();
}
}),
);
}
fn deliver(&self) {
if lock(&self.state).over {
return;
}
let c = self.sim.conditions();
if c.offline {
return self.finish(fault_error());
}
if c.paused {
self.schedule(Duration::from_millis(10));
return;
}
let event = {
let mut s = lock(&self.state);
s.busy = false;
if let Some(result) = s.result.take() {
match result {
Err(e) => {
s.over = true;
Event::Failed(e)
}
Ok(r) => {
s.fail_after = r.fail_after_chunks;
if s.fail_after == Some(0) {
s.over = true;
Event::Failed(fault_error())
} else {
let expected = Some(r.chunks.iter().map(|b| b.len() as u64).sum());
s.chunks = r.chunks.into();
s.head = true;
Event::Head(Head {
status: r.status,
headers: r.headers,
url: self.url.clone(),
expected_length: expected,
})
}
}
}
} else if s.fail_after == Some(s.sent) {
s.over = true;
s.chunks.clear();
Event::Failed(fault_error())
} else if s.chunks.is_empty() {
s.over = true;
Event::End
} else if s.demand > 0 {
s.demand -= 1;
s.sent += 1;
Event::Chunk(s.chunks.pop_front().unwrap())
} else {
return;
}
};
if matches!(event, Event::Head(_)) && self.uploaded > 0 {
(self.events)(Event::Sent {
sent: self.uploaded,
total: Some(self.uploaded),
});
}
lock(&self.state).last_activity = self.sim.0.clock.now();
(self.events)(event);
self.kick();
}
fn kick(&self) {
let c = self.sim.conditions();
let wait = {
let mut s = lock(&self.state);
if s.over || s.busy || !s.head || (!s.chunks.is_empty() && s.demand == 0) {
return;
}
s.busy = true;
delay(&c, s.chunks.front().map(|b| b.len() as u64).unwrap_or(0))
};
self.schedule(wait);
}
}
impl Transfer for SimTransfer {
fn demand(&self, n: u32) {
let mut s = lock(&self.state);
s.demand = s.demand.saturating_add(n);
drop(s);
self.kick();
}
fn answer(&self, _: QuestionId, _: Answer) {}
fn cancel(&self) {
self.finish(HttpError::Cancelled)
}
}
struct WsState {
queue: VecDeque<Message>,
demand: u32,
over: bool,
busy: bool,
}
struct SimSocket {
this: Weak<Self>,
sim: Simulation,
events: WsEvents,
handler: Option<Arc<WsHandler>>,
state: Mutex<WsState>,
url: String,
}
impl SimSocket {
fn open_after(
&self,
delay: Duration,
protocol: Option<String>,
failed: bool,
deadline: Duration,
) {
let weak = self.this.clone();
self.sim.0.clock.schedule(
delay,
Box::new(move || {
if let Some(s) = weak.upgrade() {
if lock(&s.state).over {
return;
}
let conditions = s.sim.conditions();
if s.sim.0.clock.now() >= deadline {
s.fail(HttpError::Timeout);
} else if failed || conditions.offline || s.handler.is_none() {
s.fail(fault_error());
} else if conditions.paused {
s.open_after(Duration::from_millis(10), protocol, failed, deadline);
} else {
(s.events)(WsEvent::Open { protocol });
}
}
}),
);
}
fn fail(&self, e: HttpError) {
let mut s = lock(&self.state);
if s.over {
return;
}
s.over = true;
s.queue.clear();
drop(s);
(self.events)(WsEvent::Failed(e));
}
fn kick(&self) {
let wait = {
let mut s = lock(&self.state);
if s.over || s.busy || s.demand == 0 || s.queue.is_empty() {
return;
}
s.busy = true;
delay(
&self.sim.conditions(),
crate::statistics::message_len(s.queue.front().unwrap()),
)
};
let weak = self.this.clone();
self.sim.0.clock.schedule(
wait,
Box::new(move || {
if let Some(s) = weak.upgrade() {
s.deliver();
}
}),
);
}
fn deliver(&self) {
let c = self.sim.conditions();
if c.offline {
return self.fail(fault_error());
}
if c.paused {
let weak = self.this.clone();
self.sim.0.clock.schedule(
Duration::from_millis(10),
Box::new(move || {
if let Some(s) = weak.upgrade() {
s.deliver();
}
}),
);
return;
}
let msg = {
let mut s = lock(&self.state);
s.busy = false;
if s.over || s.demand == 0 {
return;
}
s.demand -= 1;
s.queue.pop_front()
};
if let Some(m) = msg {
(self.events)(WsEvent::Message(m));
}
self.kick();
}
}
impl Socket for SimSocket {
fn send(&self, message: Message, done: Completion) {
if lock(&self.state).over {
done(Err(HttpError::Cancelled));
return;
}
if self.sim.fault("WS-SEND", &self.url) {
self.fail(fault_error());
done(Err(fault_error()));
return;
}
match self
.handler
.as_ref()
.ok_or(HttpError::Unsupported)
.and_then(|h| h(message))
{
Ok(reply) => {
if let Message::Close { code, reason } = reply {
self.close(code, &reason);
done(Ok(()));
return;
}
let mut s = lock(&self.state);
if s.queue.len() >= 64 {
drop(s);
done(Err(HttpError::Io("simulated WebSocket queue full".into())));
return;
}
s.queue.push_back(reply);
drop(s);
done(Ok(()));
self.kick();
}
Err(e) => {
self.fail(e.clone());
done(Err(e));
}
}
}
fn ping(&self, done: Completion) {
done(if lock(&self.state).over {
Err(HttpError::Cancelled)
} else {
Ok(())
});
}
fn close(&self, code: u16, reason: &str) {
let mut s = lock(&self.state);
if s.over {
return;
}
s.over = true;
s.queue.clear();
drop(s);
(self.events)(WsEvent::Closed {
code,
reason: reason.into(),
});
}
fn demand(&self, n: u32) {
let mut s = lock(&self.state);
s.demand = s.demand.saturating_add(n);
drop(s);
self.kick();
}
}