balius_sdk/
_internal.rs

1use std::{
2    collections::{BTreeMap, HashMap},
3    sync::{LazyLock, RwLock},
4};
5
6use crate::wit;
7
8type ChannelId = u32;
9
10pub trait Handler: Send + Sync + 'static {
11    fn handle(
12        &self,
13        config: wit::Config,
14        event: wit::Event,
15    ) -> Result<wit::Response, wit::HandleError>;
16}
17
18pub(crate) struct Channel {
19    pub(crate) handler: Box<dyn Handler>,
20    pub(crate) pattern: wit::balius::app::driver::EventPattern,
21}
22
23type ChannelRegistry = HashMap<ChannelId, Channel>;
24
25#[derive(Default)]
26pub struct Worker {
27    pub(crate) channels: ChannelRegistry,
28    pub(crate) config: Option<wit::Config>,
29    pub(crate) requested_signers: BTreeMap<String, String>,
30    pub(crate) signers: BTreeMap<String, Vec<u8>>,
31}
32
33static WORKER: LazyLock<RwLock<Worker>> = LazyLock::new(|| RwLock::new(Worker::default()));
34
35pub fn global_init_worker(env: wit::Config, mut worker: Worker) {
36    worker.init(env);
37
38    for (id, handler) in worker.channels.iter() {
39        wit::balius::app::driver::register_channel(*id, &handler.pattern);
40    }
41
42    for (name, algorithm) in worker.requested_signers.iter() {
43        worker.signers.insert(
44            name.clone(),
45            wit::balius::app::driver::register_signer(name, algorithm),
46        );
47    }
48
49    let mut singelton = WORKER.write().unwrap();
50    *singelton = worker;
51}
52
53pub fn global_handle_request(id: u32, evt: wit::Event) -> Result<wit::Response, wit::HandleError> {
54    let worker = WORKER.read().unwrap();
55
56    let channel = worker.channels.get(&id).ok_or(wit::HandleError {
57        code: 1,
58        message: "no channel".to_owned(),
59    })?;
60
61    let config = match &worker.config {
62        Some(e) => e.clone(),
63        None => {
64            return Err(wit::HandleError {
65                code: 0,
66                message: "no config".to_owned(),
67            })
68        }
69    };
70
71    channel.handler.handle(config, evt)
72}
73
74pub fn global_get_public_keys() -> BTreeMap<String, Vec<u8>> {
75    let worker = WORKER.read().unwrap();
76    worker.signers.clone()
77}