posthog_rs/
global.rs

1use std::sync::OnceLock;
2
3use crate::{client, Client, ClientOptions, Error, Event};
4
5static GLOBAL_CLIENT: OnceLock<Client> = OnceLock::new();
6static GLOBAL_DISABLE: OnceLock<bool> = OnceLock::new();
7
8/// [`init_global_client`] will initialize a globally available client singleton. This singleton
9/// can be used when you don't need more than one instance and have no need to regularly change
10/// the client options.
11/// # Errors
12/// This function returns [`Error::AlreadyInitialized`] if called more than once.
13#[cfg(feature = "async-client")]
14pub async fn init_global_client<C: Into<ClientOptions>>(options: C) -> Result<(), Error> {
15    if is_disabled() {
16        return Ok(());
17    }
18
19    let client = client(options).await;
20    GLOBAL_CLIENT
21        .set(client)
22        .map_err(|_| Error::AlreadyInitialized)
23}
24
25/// [`init_global_client`] will initialize a globally available client singleton. This singleton
26/// can be used when you don't need more than one instance and have no need to regularly change
27/// the client options.
28/// # Errors
29/// This function returns [`Error::AlreadyInitialized`] if called more than once.
30#[cfg(not(feature = "async-client"))]
31pub fn init_global_client<C: Into<ClientOptions>>(options: C) -> Result<(), Error> {
32    if is_disabled() {
33        return Ok(());
34    }
35
36    let client = client(options);
37    GLOBAL_CLIENT
38        .set(client)
39        .map_err(|_| Error::AlreadyInitialized)
40}
41
42/// [`disable`] prevents the global client from being initialized.
43/// **NOTE:** It does *not* prevent use of the global client once initialized.
44pub fn disable() {
45    let _ = GLOBAL_DISABLE.set(true);
46}
47
48/// [`is_disabled`] returns true if the global client has been disabled.
49/// **NOTE:** A disabled global client can still be used as long as it was
50/// initialized before it was disabled.
51pub fn is_disabled() -> bool {
52    *GLOBAL_DISABLE.get().unwrap_or(&false)
53}
54
55/// Capture the provided event, sending it to PostHog using the global client.
56#[cfg(feature = "async-client")]
57pub async fn capture(event: Event) -> Result<(), Error> {
58    let client = GLOBAL_CLIENT.get().ok_or(Error::NotInitialized)?;
59    client.capture(event).await
60}
61
62/// Capture the provided event, sending it to PostHog using the global client.
63#[cfg(not(feature = "async-client"))]
64pub fn capture(event: Event) -> Result<(), Error> {
65    let client = GLOBAL_CLIENT.get().ok_or(Error::NotInitialized)?;
66    client.capture(event)
67}