loglink 0.1.0

Send logs to a remote server
Documentation
use std::time::Duration;
use tokio::sync::mpsc;
use tokio::time;

use crate::event::LogEvent;
use crate::log_handle::LogHandle;
use crate::{RT, ToPayload};

#[derive(Clone)]
pub struct LogClient {
    endpoint: String,
    auth: Option<String>,
    batch_size: usize,
    flush_interval: Duration,
}

impl LogClient {
    pub fn new(endpoint: impl Into<String>) -> Self {
        Self {
            endpoint: endpoint.into(),
            auth: None,
            batch_size: 10,
            flush_interval: Duration::from_secs(5),
        }
    }

    pub fn with_auth(mut self, key: impl ToString) -> Self {
        self.auth = Some(key.to_string());
        self
    }

    pub fn with_batch_size(mut self, size: usize) -> Self {
        self.batch_size = size;
        self
    }

    pub fn with_flush_interval(mut self, duration: Duration) -> Self {
        self.flush_interval = duration;
        self
    }

    // Start background sender — returns handle to send events
    pub fn spawn<T: ToPayload + Send + Sync + 'static>(self) -> LogHandle<T> {
        let (tx, mut rx) = mpsc::channel(1000);
        let rt = RT.get().unwrap();

        rt.spawn(async move {
            let mut batch = Vec::with_capacity(self.batch_size);
            let mut interval = time::interval(self.flush_interval);

            loop {
                tokio::select! {
                    event = rx.recv() => {
                        if let Some(Some(e)) = event {
                            batch.push(e);
                            if batch.len() >= self.batch_size {
                                let _ = self.send_batch(&batch).await;
                                batch.clear();
                            }
                        } else {
                            break; // channel closed
                        }
                    }
                    _ = interval.tick() => {
                        if !batch.is_empty() {
                            let _ = self.send_batch(&batch).await;
                            batch.clear();
                        }
                    }
                }
            }

            println!("GOT NONE!!!");

            // Final flush
            if !batch.is_empty() {
                let _ = self.send_batch(&batch).await;
            }
        });

        LogHandle { sender: tx }
    }

    async fn send_batch<T: ToPayload>(&self, batch: &[LogEvent<T>]) -> Result<(), ureq::Error> {
        ureq::post(&self.endpoint)
            .header(
                "Authorization",
                format!(
                    "Bearer: {}",
                    self.auth.as_ref().unwrap_or(&"anon".to_string())
                ),
            )
            .send_json(batch)
            .map(|_| ())
    }
}