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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
use async_trait::async_trait;
use anchor_lang::Event;
use solana_sdk::commitment_config::CommitmentConfig;
use solana_client::nonblocking::pubsub_client;
use solana_client::rpc_config::{RpcTransactionLogsConfig, RpcTransactionLogsFilter};
use solana_program::pubkey::Pubkey;
use crate::OnDemandError;
use base64::engine::general_purpose;
use base64::Engine;
use futures::StreamExt;
use tokio::sync::mpsc;
use tokio::time::Duration;
use tokio_util::sync::CancellationToken;
use std::collections::HashMap;
use std::marker::PhantomData;
use std::sync::Arc;

// Create a sender trait so we can handle both bounded and unbounded channels
// Then implement the trait for both mpsc::Sender and mpsc::UnboundedSender
// Originally I used an enum for each channel type but dynamic dispatch introduces performance concerns

#[async_trait]
pub trait EventSenderTrait<E: Event + Send + Sync + 'static>: Send + Sync {
    async fn send(&self, event: E) -> Result<(), OnDemandError>;
}

#[async_trait]
impl<E> EventSenderTrait<E> for mpsc::Sender<E>
where
    E: Event + Send + Sync + 'static,
{
    async fn send(&self, event: E) -> Result<(), OnDemandError> {
        self.send(event).await.map_err(|_e| OnDemandError::NetworkError)
    }
}

#[async_trait]
impl<E> EventSenderTrait<E> for mpsc::UnboundedSender<E>
where
    E: Event + Send + Sync + 'static,
{
    async fn send(&self, event: E) -> Result<(), OnDemandError> {
        self.send(event).map_err(|_e| OnDemandError::NetworkError)
    }
}

#[async_trait]
pub trait EventHandler: Send + Sync {
    async fn handle_event(&self, data: &[u8]) -> Result<(), OnDemandError>;
}

pub struct EventHandlerImpl<E, S>
where
    E: Event + Send + Sync + 'static,
    S: EventSenderTrait<E>,
{
    sender: Arc<S>,
    _marker: PhantomData<E>,
}

#[async_trait]
impl<E, S> EventHandler for EventHandlerImpl<E, S>
where
    E: Event + Send + Sync + 'static,
    S: EventSenderTrait<E>,
{
    async fn handle_event(&self, data: &[u8]) -> Result<(), OnDemandError> {
        match E::try_from_slice(data) {
            Ok(event) => self.sender.send(event).await,
            Err(_) => Err(OnDemandError::AnchorParseError),
        }
    }
}

impl<E, S> EventHandlerImpl<E, S>
where
    E: Event + Send + Sync + 'static,
    S: EventSenderTrait<E>,
{
    pub fn new(sender: S) -> Self {
        EventHandlerImpl {
            sender: Arc::new(sender),
            _marker: PhantomData,
        }
    }
}

/// A builder for creating a new PubSubEventClient
/// ```
/// use tokio::sync::mpsc;
/// use switchboard_solana::{ FunctionVerifyEvent, *SWITCHBOARD_ON_DEMAND_PROGRAM_ID };
///
///
/// let (fn_verify_sender, mut fn_verify_recv) = tokio::sync::mpsc::unbounded_channel::<FunctionVerifyEvent>();
///
/// let event_watcher = pubsub::PubSubEventClientBuilder::new(*SWITCHBOARD_ON_DEMAND_PROGRAM_ID, "https://api.mainnet-beta.solana.com".to_string())
///     .add_event_handler(fn_verify_sender);
///
/// let handler = tokio::spawn(async move {
///     loop {
///         tokio::select! {
///             Some(event) = fn_verify_recv.recv() => {
///                 info!("[Rpc][Event] FunctionVerifyEvent - Function: {:?}", event.function);
///             }
///         }
///     }
/// });
///
/// tokio::select! {
///     _ = handler => {
///         info!("[Rpc] handler exited");
///         return Ok(());
///     }
///     _ = event_watcher.start() => {
///         info!("[Rpc] event_watcher exited");
///         return Ok(());
///     }
/// }
/// ````
pub struct PubSubEventClientBuilder {
    program_id: Pubkey,
    websocket_url: String,

    /// Other pubkeys to watch for mentions in order to process logs
    other_pubkeys: Vec<Pubkey>,

    /// The maximum number of times to retry connecting to the websocket.
    /// None means the websocket will continiously retry.
    max_retries: Option<i32>,
}

pub struct PubSubEventClientWithHandlers {
    program_id: Pubkey,
    websocket_url: String,
    other_pubkeys: Vec<Pubkey>,

    // The maximum number of times to retry connecting to the websocket
    max_retries: Option<i32>,

    cancellation_token: CancellationToken,

    event_handlers: HashMap<[u8; 8], Box<dyn EventHandler>>,
}

impl PubSubEventClientBuilder {
    // Creates a new builder with the provided WebSocket URL
    pub fn new(program_id: Pubkey, websocket_url: String) -> Self {
        Self {
            program_id,
            websocket_url: websocket_url
                .replace("https://", "wss://")
                .replace("http://", "ws://"),
            other_pubkeys: Vec::new(),

            max_retries: None,
        }
    }

    pub fn mentions(mut self, pubkey: Pubkey) -> Self {
        self.other_pubkeys.push(pubkey);
        self
    }

    pub fn set_max_retries(mut self, max_retries: i32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }

    pub fn add_event_handler<E: Event + Send + Sync + 'static, S: EventSenderTrait<E> + 'static>(
        self,
        sender: S,
    ) -> PubSubEventClientWithHandlers {
        PubSubEventClientWithHandlers {
            program_id: self.program_id,
            websocket_url: self.websocket_url,
            other_pubkeys: self.other_pubkeys,
            max_retries: self.max_retries,
            cancellation_token: CancellationToken::new(),
            event_handlers: HashMap::from([(
                E::DISCRIMINATOR,
                Box::new(EventHandlerImpl::<E, S>::new(sender)) as Box<dyn EventHandler + 'static>,
            )]),
        }
    }
}

impl PubSubEventClientWithHandlers {
    pub fn mentions(mut self, pubkey: Pubkey) -> Self {
        self.other_pubkeys.push(pubkey);
        self
    }

    pub fn set_max_retries(mut self, max_retries: i32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }

    pub fn add_event_handler<E: Event + Send + Sync + 'static, S: EventSenderTrait<E> + 'static>(
        mut self,
        sender: S,
    ) -> PubSubEventClientWithHandlers {
        self.event_handlers.insert(
            E::DISCRIMINATOR,
            Box::new(EventHandlerImpl::<E, S>::new(sender)) as Box<dyn EventHandler + 'static>,
        );
        self
    }

    pub fn abort(self) {
        self.cancellation_token.cancel();
    }

    pub async fn start(self) {
        let cancellation_token = self.cancellation_token.clone();
        tokio::select! {
            _ = cancellation_token.cancelled() => {
                // Perform cleanup
                log::info!("pubsub token cancelled");
            },
            _ = self.start_pubsub() => {
                // Perform cleanup
                log::info!("start_pubsub returned unexpectedly");
            }
        }
    }

    // Starts the client
    async fn start_pubsub(&self) {
        let mut retry_count = 0;
        // let max_retries = 3;
        let mut delay = Duration::from_millis(500); // start with a 500ms delay

        loop {
            // Create the pubsub client every iteration in case the internal channel closed
            let pubsub_client = pubsub_client::PubsubClient::new(&self.websocket_url)
                .await
                .expect("Failed to create pubsub client");

            // Attempt to connect
            let connection_result = pubsub_client
                .logs_subscribe(
                    RpcTransactionLogsFilter::Mentions(
                        vec![
                            vec![self.program_id.to_string()],
                            self.other_pubkeys
                                .iter()
                                .map(|pubkey| pubkey.to_string())
                                .collect(),
                        ]
                        .concat(),
                    ),
                    RpcTransactionLogsConfig {
                        commitment: Some(CommitmentConfig::processed()),
                    },
                )
                .await;

            match connection_result {
                Ok((mut stream, _handler)) => {
                    retry_count = 0; // Reset retry count on successful connection
                    delay = Duration::from_millis(500); // Reset delay on successful connection

                    while let Some(event) = stream.next().await {
                        // TODO: A better implementation might immediately spawn a new task to handle the event so we dont block here. We could push to a FIFO queue and have some workers ready to handle the events

                        // Handle the rpc log event
                        for line in event.value.logs {
                            if let Some(encoded_data) = line.strip_prefix("Program data: ") {
                                if let Ok(decoded_data) =
                                    general_purpose::STANDARD.decode(encoded_data)
                                {
                                    if decoded_data.len() <= 8 {
                                        continue;
                                    }

                                    // Found a valid base64 string. Let's try to match a discriminator
                                    let (disc, event_data) = decoded_data.split_at(8);
                                    if let Some(sender) = self.event_handlers.get(disc) {
                                        let _ = sender.handle_event(event_data).await;
                                    }
                                }
                            }
                        }
                    }

                    log::error!("[EVENT][WEBSOCKET] connection closed, attempting to reconnect...");
                }
                Err(e) => {
                    log::error!("[EVENT][WEBSOCKET] Failed to connect: {:?}", e);

                    match self.max_retries {
                        Some(max_retries) => {
                            if retry_count >= max_retries {
                                log::error!("[EVENT][WEBSOCKET] Maximum retry attempts reached, aborting...");
                                break;
                            }

                            tokio::time::sleep(delay).await; // wait before retrying
                            retry_count += 1;
                            delay = std::cmp::min(delay * 2, Duration::from_secs(5));
                            // Double the delay for next retry, up to 5 seconds
                        }
                        None => {
                            tokio::time::sleep(delay).await; // wait before retrying
                            retry_count += 1;
                            delay = std::cmp::min(delay * 2, Duration::from_secs(5));
                            // Double the delay for next retry, up to 5 seconds
                            continue;
                        }
                    }
                }
            }

            if let Some(max_retries) = self.max_retries {
                if retry_count >= max_retries {
                    log::error!("[EVENT][WEBSOCKET] Maximum retry attempts reached, aborting...");
                    break;
                }
            }
        }
    }
}