Skip to main content

nexus_common/db/connectors/
pubky.rs

1use pubky::Client;
2use std::sync::Arc;
3use thiserror::Error;
4use tokio::sync::OnceCell;
5use tracing::debug;
6
7static PUBKY_CLIENT_SINGLETON: OnceCell<Arc<Client>> = OnceCell::const_new();
8
9#[derive(Debug, Error)]
10pub enum PubkyClientError {
11    #[error("PubkyClient not initialized")]
12    NotInitialized,
13
14    #[error("Client initialization error: {0}")]
15    ClientError(String),
16}
17
18pub struct PubkyClient;
19
20impl PubkyClient {
21    pub async fn initialise(testnet: bool) -> Result<(), PubkyClientError> {
22        PUBKY_CLIENT_SINGLETON
23            .get_or_try_init(|| async {
24                debug!(
25                    "Initialising PubkyClient in {} mode",
26                    if testnet { "testnet" } else { "mainnet" }
27                );
28                let client = match testnet {
29                    true => Client::builder()
30                        .testnet()
31                        .build()
32                        .map_err(|e| PubkyClientError::ClientError(e.to_string()))?,
33                    false => Client::builder()
34                        .build()
35                        .map_err(|e| PubkyClientError::ClientError(e.to_string()))?,
36                };
37                Ok(Arc::new(client))
38            })
39            .await
40            .map(|_| ())
41    }
42    /// Retrieves an instance of the `PubkyClient`
43    pub fn get() -> Result<Arc<Client>, PubkyClientError> {
44        PUBKY_CLIENT_SINGLETON
45            .get()
46            .cloned()
47            .ok_or(PubkyClientError::NotInitialized)
48    }
49
50    /// Initializes the `PUBKY_CONNECTOR_SINGLETON` with a provided `Client` instance.
51    ///
52    /// # Usage:
53    /// - This function is primarily intended for **watcher tests** where a controlled `Client` instance
54    ///   needs to be injected instead of relying on environment-based initialization
55    pub async fn init_from_client(client: Client) -> Result<(), PubkyClientError> {
56        PUBKY_CLIENT_SINGLETON
57            .get_or_try_init(|| async { Ok(Arc::new(client)) })
58            .await
59            .map(|_| ())
60    }
61}