Skip to main content

cortex_runtime/audit/
ledger_sync.rs

1//! Optional remote ledger sync — POST audit events to a remote endpoint.
2
3use crate::audit::logger::AuditEvent;
4use std::sync::Arc;
5use tokio::sync::mpsc;
6
7/// Async ledger sync that sends audit events to a remote URL.
8pub struct LedgerSync {
9    tx: mpsc::Sender<AuditEvent>,
10}
11
12impl LedgerSync {
13    /// Create a new ledger sync that POSTs events to the given URL.
14    ///
15    /// Returns None if CORTEX_LEDGER_URL is not set.
16    pub fn from_env() -> Option<Self> {
17        let url = std::env::var("CORTEX_LEDGER_URL").ok()?;
18        let (tx, rx) = mpsc::channel(1000);
19
20        tokio::spawn(async move {
21            sync_loop(url, rx).await;
22        });
23
24        Some(Self { tx })
25    }
26
27    /// Queue an event for remote sync.
28    pub async fn send(&self, event: AuditEvent) {
29        // Non-blocking, failure-tolerant
30        let _ = self.tx.try_send(event);
31    }
32}
33
34async fn sync_loop(url: String, mut rx: mpsc::Receiver<AuditEvent>) {
35    let client = reqwest::Client::new();
36
37    while let Some(event) = rx.recv().await {
38        // Best-effort POST, ignore failures
39        let _ = client
40            .post(&url)
41            .json(&event)
42            .timeout(std::time::Duration::from_secs(5))
43            .send()
44            .await;
45    }
46}