libbeachcomber 0.5.1

Client library for querying the beachcomber (comb) shell state daemon
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! # beachcomber-client
//!
//! A lightweight, synchronous client for the beachcomber (`comb`) shell state daemon.
//!
//! ```rust,no_run
//! use beachcomber_client::{Client, CombResult};
//!
//! let client = Client::new();
//! match client.get("git.branch", Some("/path/to/repo")) {
//!     Ok(CombResult::Hit { data, age_ms, stale }) => {
//!         println!("branch: {}", data.get_str("git.branch").unwrap_or("?"));
//!     }
//!     Ok(CombResult::Miss) => println!("not cached yet"),
//!     Err(e) => println!("error: {}", e),
//! }
//! ```

use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::time::Duration;

/// Result of a cache query.
#[derive(Debug)]
pub enum CombResult {
    /// Cache hit — data is available.
    Hit {
        data: CombData,
        age_ms: u128,
        stale: bool,
    },
    /// Cache miss — provider hasn't computed this yet.
    /// The daemon will compute it in the background; retry shortly.
    Miss,
}

/// Parsed response data from a provider.
#[derive(Debug, Clone)]
pub struct CombData {
    value: serde_json::Value,
}

impl CombData {
    /// Create from a raw JSON value (useful for testing).
    pub fn from_json(value: serde_json::Value) -> Self {
        Self { value }
    }

    /// Get a string field. For single-field queries (e.g., "git.branch"),
    /// this returns the value directly. For full provider queries (e.g., "git"),
    /// access fields by name.
    pub fn get_str(&self, field: &str) -> Option<&str> {
        if let Some(obj) = self.value.as_object() {
            obj.get(field).and_then(|v| v.as_str())
        } else {
            self.value.as_str()
        }
    }

    pub fn get_bool(&self, field: &str) -> Option<bool> {
        if let Some(obj) = self.value.as_object() {
            obj.get(field).and_then(|v| v.as_bool())
        } else {
            self.value.as_bool()
        }
    }

    pub fn get_i64(&self, field: &str) -> Option<i64> {
        if let Some(obj) = self.value.as_object() {
            obj.get(field).and_then(|v| v.as_i64())
        } else {
            self.value.as_i64()
        }
    }

    pub fn get_f64(&self, field: &str) -> Option<f64> {
        if let Some(obj) = self.value.as_object() {
            obj.get(field).and_then(|v| v.as_f64())
        } else {
            self.value.as_f64()
        }
    }

    /// Get the raw serde_json::Value.
    pub fn as_value(&self) -> &serde_json::Value {
        &self.value
    }

    /// Get as raw text (for single-field queries like "git.branch").
    pub fn as_text(&self) -> Option<String> {
        match &self.value {
            serde_json::Value::String(s) => Some(s.clone()),
            serde_json::Value::Number(n) => Some(n.to_string()),
            serde_json::Value::Bool(b) => Some(b.to_string()),
            serde_json::Value::Null => None,
            other => Some(other.to_string()),
        }
    }
}

/// Error type for client operations.
#[derive(Debug)]
pub enum CombError {
    /// Daemon is not running and could not be started.
    DaemonNotRunning,
    /// Socket connection failed.
    ConnectionFailed(std::io::Error),
    /// Request/response I/O failed.
    IoError(std::io::Error),
    /// Response couldn't be parsed.
    ParseError(String),
    /// Server returned an error.
    ServerError(String),
    /// Operation timed out.
    Timeout,
}

impl std::fmt::Display for CombError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            CombError::DaemonNotRunning => write!(f, "comb daemon is not running"),
            CombError::ConnectionFailed(e) => write!(f, "connection failed: {}", e),
            CombError::IoError(e) => write!(f, "I/O error: {}", e),
            CombError::ParseError(s) => write!(f, "parse error: {}", s),
            CombError::ServerError(s) => write!(f, "server error: {}", s),
            CombError::Timeout => write!(f, "operation timed out"),
        }
    }
}

impl std::error::Error for CombError {}

impl From<std::io::Error> for CombError {
    fn from(e: std::io::Error) -> Self {
        CombError::IoError(e)
    }
}

/// Configuration for the client.
#[derive(Debug, Clone)]
pub struct ClientConfig {
    /// Read/write timeout for socket operations.
    pub timeout: Duration,
    /// Whether to attempt starting the daemon if it's not running.
    pub auto_start: bool,
}

impl Default for ClientConfig {
    fn default() -> Self {
        Self {
            timeout: Duration::from_millis(100),
            auto_start: true,
        }
    }
}

/// A synchronous client for the beachcomber daemon.
///
/// Each method call creates a new socket connection. For multiple
/// queries in sequence, use [`Session`] instead.
pub struct Client {
    config: ClientConfig,
}

impl Client {
    /// Create a client with default configuration (100ms timeout, auto-start enabled).
    pub fn new() -> Self {
        Self {
            config: ClientConfig::default(),
        }
    }

    /// Create a client with custom configuration.
    pub fn with_config(config: ClientConfig) -> Self {
        Self { config }
    }

    /// Query a single key. Returns Hit with data, Miss, or an error.
    ///
    /// Examples:
    /// - `client.get("git.branch", Some("/path/to/repo"))` — single field
    /// - `client.get("git", Some("/path/to/repo"))` — all fields
    /// - `client.get("hostname.short", None)` — global provider
    pub fn get(&self, key: &str, path: Option<&str>) -> Result<CombResult, CombError> {
        let socket_path = self.find_or_start_socket()?;
        let mut stream = self.connect(&socket_path)?;

        let mut request = serde_json::json!({ "op": "get", "key": key });
        if let Some(p) = path {
            request["path"] = serde_json::json!(p);
        }

        self.send_recv(&mut stream, &request)
    }

    /// Trigger recomputation of a provider. Fire-and-forget.
    pub fn poke(&self, key: &str, path: Option<&str>) -> Result<(), CombError> {
        let socket_path = self.find_or_start_socket()?;
        let mut stream = self.connect(&socket_path)?;

        let mut request = serde_json::json!({ "op": "poke", "key": key });
        if let Some(p) = path {
            request["path"] = serde_json::json!(p);
        }

        let msg = format!("{}\n", serde_json::to_string(&request).unwrap());
        stream.write_all(msg.as_bytes())?;

        // Read response but don't care about content
        let mut reader = BufReader::new(stream);
        let mut line = String::new();
        reader.read_line(&mut line)?;
        Ok(())
    }

    /// Open a persistent session for multiple queries on one connection.
    pub fn session(&self) -> Result<Session, CombError> {
        let socket_path = self.find_or_start_socket()?;
        let stream = self.connect(&socket_path)?;
        Ok(Session::new(stream))
    }

    fn find_or_start_socket(&self) -> Result<PathBuf, CombError> {
        let path = socket_path();

        // Check if daemon is listening
        if UnixStream::connect(&path).is_ok() {
            return Ok(path);
        }

        if !self.config.auto_start {
            return Err(CombError::DaemonNotRunning);
        }

        // Try to start the daemon
        start_daemon(&path)?;

        // Wait for it to be ready
        let mut delay = Duration::from_millis(10);
        for _ in 0..8 {
            std::thread::sleep(delay);
            if UnixStream::connect(&path).is_ok() {
                return Ok(path);
            }
            delay = (delay * 2).min(Duration::from_millis(500));
        }

        Err(CombError::DaemonNotRunning)
    }

    fn connect(&self, path: &PathBuf) -> Result<UnixStream, CombError> {
        let stream = UnixStream::connect(path).map_err(CombError::ConnectionFailed)?;
        stream.set_read_timeout(Some(self.config.timeout))?;
        stream.set_write_timeout(Some(self.config.timeout))?;
        Ok(stream)
    }

    fn send_recv(
        &self,
        stream: &mut UnixStream,
        request: &serde_json::Value,
    ) -> Result<CombResult, CombError> {
        let msg = format!("{}\n", serde_json::to_string(request).unwrap());
        stream.write_all(msg.as_bytes())?;

        let mut reader = BufReader::new(stream);
        let mut line = String::new();
        reader.read_line(&mut line).map_err(|e| {
            if e.kind() == std::io::ErrorKind::WouldBlock
                || e.kind() == std::io::ErrorKind::TimedOut
            {
                CombError::Timeout
            } else {
                CombError::IoError(e)
            }
        })?;

        parse_response(&line)
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

/// A persistent connection for multiple queries.
///
/// More efficient than individual `Client::get` calls when querying
/// multiple values in sequence (one connection vs. N connections).
pub struct Session {
    reader: BufReader<UnixStream>,
}

impl Session {
    fn new(stream: UnixStream) -> Self {
        Self {
            reader: BufReader::new(stream),
        }
    }

    /// Query a single key on this persistent connection.
    pub fn get(&mut self, key: &str, path: Option<&str>) -> Result<CombResult, CombError> {
        let mut request = serde_json::json!({ "op": "get", "key": key });
        if let Some(p) = path {
            request["path"] = serde_json::json!(p);
        }

        let msg = format!("{}\n", serde_json::to_string(&request).unwrap());
        self.reader.get_mut().write_all(msg.as_bytes())?;

        let mut line = String::new();
        self.reader.read_line(&mut line)?;

        parse_response(&line)
    }

    /// Set connection context so subsequent queries don't need explicit paths.
    pub fn set_context(&mut self, path: &str) -> Result<(), CombError> {
        let request = serde_json::json!({ "op": "context", "path": path });
        let msg = format!("{}\n", serde_json::to_string(&request).unwrap());
        self.reader.get_mut().write_all(msg.as_bytes())?;

        let mut line = String::new();
        self.reader.read_line(&mut line)?;
        Ok(())
    }

    /// Trigger recomputation.
    pub fn poke(&mut self, key: &str, path: Option<&str>) -> Result<(), CombError> {
        let mut request = serde_json::json!({ "op": "poke", "key": key });
        if let Some(p) = path {
            request["path"] = serde_json::json!(p);
        }
        let msg = format!("{}\n", serde_json::to_string(&request).unwrap());
        self.reader.get_mut().write_all(msg.as_bytes())?;

        let mut line = String::new();
        self.reader.read_line(&mut line)?;
        Ok(())
    }
}

// --- Internal helpers ---

fn parse_response(line: &str) -> Result<CombResult, CombError> {
    let resp: serde_json::Value =
        serde_json::from_str(line.trim()).map_err(|e| CombError::ParseError(e.to_string()))?;

    let ok = resp.get("ok").and_then(|v| v.as_bool()).unwrap_or(false);

    if !ok {
        let error = resp
            .get("error")
            .and_then(|v| v.as_str())
            .unwrap_or("unknown error")
            .to_string();
        return Err(CombError::ServerError(error));
    }

    match resp.get("data") {
        Some(serde_json::Value::Null) | None => Ok(CombResult::Miss),
        Some(data) => {
            let age_ms = resp
                .get("age_ms")
                .and_then(|v| v.as_u64())
                .map(|v| v as u128)
                .unwrap_or(0);
            let stale = resp.get("stale").and_then(|v| v.as_bool()).unwrap_or(false);
            Ok(CombResult::Hit {
                data: CombData {
                    value: data.clone(),
                },
                age_ms,
                stale,
            })
        }
    }
}

/// Find the beachcomber socket path.
pub fn socket_path() -> PathBuf {
    if let Ok(runtime_dir) = std::env::var("XDG_RUNTIME_DIR") {
        let path = PathBuf::from(runtime_dir).join("beachcomber").join("sock");
        if path.exists() {
            return path;
        }
    }

    let uid = unsafe { libc::getuid() };
    let tmpdir = std::env::var("TMPDIR").unwrap_or_else(|_| "/tmp".to_string());
    PathBuf::from(tmpdir)
        .join(format!("beachcomber-{}", uid))
        .join("sock")
}

/// Attempt to start the comb daemon via socket activation.
fn start_daemon(socket_path: &PathBuf) -> Result<(), CombError> {
    use std::process::Command;

    // Find comb binary
    let comb = which_comb().ok_or(CombError::DaemonNotRunning)?;

    if let Some(parent) = socket_path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }

    Command::new(&comb)
        .arg("daemon")
        .arg("--socket")
        .arg(socket_path.as_os_str())
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .map_err(CombError::ConnectionFailed)?;

    Ok(())
}

fn which_comb() -> Option<PathBuf> {
    // Check PATH for comb binary
    if let Ok(path) = std::env::var("PATH") {
        for dir in path.split(':') {
            let candidate = PathBuf::from(dir).join("comb");
            if candidate.exists() {
                return Some(candidate);
            }
        }
    }
    None
}