aboutsummaryrefslogtreecommitdiff
path: root/src/modules/semaphore.rs
blob: 7aa8283eb5201f8c9b4c800402e46c939f49fa88 (plain)
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 serde::Deserialize;
use serde_yml::Value;
use std::{future::Future, pin::Pin, sync::Arc};
use tokio::sync::Semaphore;

pub struct SemaphoreKind;

#[derive(Deserialize)]
struct SemaphoreConfig {
    permits: usize,
    next: DynNode,
}

struct SemaphoreState {
    config: SemaphoreConfig,
    semaphore: Semaphore,
}

impl NodeKind for SemaphoreKind {
    fn name(&self) -> &'static str {
        "semaphore"
    }
    fn instanciate(&self, config: Value) -> Result<Arc<dyn Node>> {
        let config = serde_yml::from_value::<SemaphoreConfig>(config)?;
        Ok(Arc::new(SemaphoreState {
            semaphore: Semaphore::new(config.permits),
            config,
        }))
    }
}
impl Node for SemaphoreState {
    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 {
            let _permit = self.semaphore.acquire().await;
            let resp = self.config.next.handle(context, request).await?;
            drop(_permit);
            Ok(resp)
        })
    }
}