1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
/*
This file is part of gnix (https://codeberg.org/metamuffin/gnix)
which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse};
use crate::{config::DynNode, error::ServiceError};
use anyhow::Result;
use rand_distr::Distribution;
use serde::Deserialize;
use serde_yml::Value;
use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
use tokio::time::sleep;
pub struct DelayKind;
#[derive(Deserialize)]
struct Delay {
duration: u64,
stdev: u64,
next: DynNode,
}
impl NodeKind for DelayKind {
fn name(&self) -> &'static str {
"delay"
}
fn instanciate(&self, config: Value) -> Result<Arc<dyn Node>> {
Ok(Arc::new(serde_yml::from_value::<Delay>(config)?))
}
}
impl Node for Delay {
fn handle<'a>(
&'a self,
context: &'a mut NodeContext,
request: NodeRequest,
) -> Pin<Box<dyn Future<Output = Result<NodeResponse, ServiceError>> + Send + Sync + 'a>> {
Box::pin(async move {
sleep(Duration::from_millis(if self.stdev == 0 {
self.duration
} else {
self.duration.saturating_add_signed(
rand_distr::Normal::new(0., self.stdev as f32)
.unwrap()
.sample(&mut rand::rng()) as i64,
)
}))
.await;
self.next.handle(context, request).await
})
}
}
|