~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/vuln-notif

0
0
main
71 lines · 1.6 KB Raw History
use std::io::Write;
use std::sync::{Arc, Mutex};

use serde_json::{Map, Value};

pub trait EventSink: Send + Sync {
    fn write_line(&self, line: &str);
}

pub struct StdoutSink;

impl EventSink for StdoutSink {
    fn write_line(&self, line: &str) {
        let mut out = std::io::stdout().lock();
        let _ = writeln!(out, "{line}");
        let _ = out.flush();
    }
}

#[derive(Default)]
pub struct CaptureSink {
    lines: Mutex<Vec<String>>,
}

impl CaptureSink {
    pub fn lines(&self) -> Vec<String> {
        self.lines.lock().expect("capture sink poisoned").clone()
    }
}

impl EventSink for CaptureSink {
    fn write_line(&self, line: &str) {
        self.lines
            .lock()
            .expect("capture sink poisoned")
            .push(line.to_owned());
    }
}

#[derive(Clone)]
pub struct Output {
    sink: Arc<dyn EventSink>,
}

impl Output {
    pub fn new(sink: Arc<dyn EventSink>) -> Self {
        Self { sink }
    }

    pub fn stdout() -> Self {
        Self::new(Arc::new(StdoutSink))
    }

    pub fn emit(&self, event: &str, fields: Value) {
        let mut map = Map::new();
        map.insert("event".into(), Value::String(event.into()));
        if let Value::Object(fields) = fields {
            for (key, value) in fields {
                if key == "event" {
                    continue;
                }
                map.insert(key, value);
            }
        }
        self.sink.write_line(&Value::Object(map).to_string());
    }

    pub fn emit_value(&self, value: Value) {
        self.sink.write_line(&value.to_string());
    }
}