gadget_sdk/runners/
mod.rs

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
use crate::config::GadgetConfiguration;
use crate::error;
use crate::event_utils::InitializableEventHandler;
use std::future::Future;
use std::pin::Pin;
use tokio::sync::oneshot;

pub mod eigenlayer;
#[cfg(feature = "symbiotic")]
pub mod symbiotic;

pub mod jobs;
pub mod tangle;
pub use jobs::*;

#[derive(thiserror::Error, Debug)]
pub enum RunnerError {
    #[error("No jobs registered. Make sure to add a job with `BlueprintRunner::add_job`")]
    NoJobs,
    #[error("Job already initialized")]
    AlreadyInitialized,

    #[error("You are currently not an active operator\nPlease checkout the docs here: https://docs.tangle.tools/restake/join_operator/join")]
    NotActiveOperator,

    #[error(transparent)]
    Recv(#[from] tokio::sync::oneshot::error::RecvError),

    #[error("Environment not set")]
    EnvNotSet,

    #[error("Receiver error")]
    ReceiverError,

    #[error(transparent)]
    ConfigError(#[from] crate::config::Error),

    #[error(transparent)]
    SubxtError(#[from] subxt::Error),

    #[error(transparent)]
    KeystoreError(#[from] crate::keystore::Error),

    #[error(transparent)]
    ContractError(#[from] alloy_contract::Error),

    #[error(transparent)]
    PendingTransactionError(#[from] alloy_provider::PendingTransactionError),

    #[error(transparent)]
    ElContractsError(#[from] eigensdk::client_elcontracts::error::ElContractsError),

    #[error(transparent)]
    AvsRegistryError(#[from] eigensdk::client_avsregistry::error::AvsRegistryError),

    #[error("Transaction error: {0}")]
    TransactionError(String),

    #[error(transparent)]
    TransportError(#[from] alloy_transport::RpcError<alloy_transport::TransportErrorKind>),

    #[error("Environment not set")]
    EnvironmentNotSet,

    #[error("Eigenlayer error: {0}")]
    EigenlayerError(String),

    #[error("Signature error: {0}")]
    SignatureError(String),

    #[error("Symbiotic error: {0}")]
    SymbioticError(String),

    #[error("Invalid protocol: {0}")]
    InvalidProtocol(String),

    #[error("Storage error: {0}")]
    StorageError(String),
}

#[async_trait::async_trait]
pub trait BlueprintConfig: Send + Sync + 'static {
    async fn register(
        &self,
        _env: &GadgetConfiguration<parking_lot::RawRwLock>,
    ) -> Result<(), RunnerError> {
        Ok(())
    }
    async fn requires_registration(
        &self,
        _env: &GadgetConfiguration<parking_lot::RawRwLock>,
    ) -> Result<bool, RunnerError> {
        Ok(true)
    }
}

impl BlueprintConfig for () {}

#[async_trait::async_trait]
pub trait BackgroundService: Send + Sync + 'static {
    async fn start(&self) -> Result<oneshot::Receiver<Result<(), RunnerError>>, RunnerError>;
}

pub struct BlueprintRunner {
    pub(crate) config: Box<dyn BlueprintConfig>,
    pub(crate) jobs: Vec<Box<dyn InitializableEventHandler + Send + 'static>>,
    pub(crate) env: GadgetConfiguration<parking_lot::RawRwLock>,
    pub(crate) background_services: Vec<Box<dyn BackgroundService>>,
}

impl BlueprintRunner {
    pub fn new<C: BlueprintConfig + 'static>(
        config: C,
        env: GadgetConfiguration<parking_lot::RawRwLock>,
    ) -> Self {
        Self {
            config: Box::new(config),
            jobs: Vec::new(),
            background_services: Vec::new(),
            env,
        }
    }

    pub fn job<J, T>(&mut self, job: J) -> &mut Self
    where
        J: Into<JobBuilder<T>>,
        T: InitializableEventHandler + Send + 'static,
    {
        let JobBuilder { event_handler } = job.into();
        self.jobs.push(Box::new(event_handler));
        self
    }

    pub fn background_service(&mut self, service: Box<dyn BackgroundService>) -> &mut Self {
        self.background_services.push(service);
        self
    }

    pub async fn run(&mut self) -> Result<(), RunnerError> {
        if self.config.requires_registration(&self.env).await? {
            self.config.register(&self.env).await?;
        }

        let mut background_receivers = Vec::new();
        for service in &self.background_services {
            let receiver = service.start().await?;
            background_receivers.push(receiver);
        }

        let mut all_futures = Vec::new();

        // Handle job futures
        for job in self.jobs.drain(..) {
            all_futures.push(Box::pin(async move {
                match job.init_event_handler().await {
                    Some(receiver) => receiver.await.map_err(RunnerError::Recv)?,
                    None => Ok(()),
                }
            })
                as Pin<Box<dyn Future<Output = Result<(), crate::Error>> + Send>>);
        }

        // Handle background services
        for receiver in background_receivers {
            all_futures.push(Box::pin(async move {
                receiver
                    .await
                    .map_err(|e| crate::Error::Runner(RunnerError::Recv(e)))
                    .and(Ok(()))
            })
                as Pin<Box<dyn Future<Output = Result<(), crate::Error>> + Send>>);
        }

        while !all_futures.is_empty() {
            let (result, _index, remaining) = futures::future::select_all(all_futures).await;
            if let Err(e) = result {
                crate::error!("Job or background service failed: {:?}", e);
            }

            all_futures = remaining;
        }

        Ok(())
    }
}