surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
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
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! `<SURJECTION_HOME>/logs/surjection.log` (SPEC 4.5): one redacted line per
//! event, size-capped and rotated. Local only, never uploaded.
//!
//! Callers log event names and chosen fields only: never messages, secret
//! or environment values, headers, file contents or search words. Each
//! field value still goes through the [`Redactor`] before it is written.
//!
//! The CLI and the app [`install`] one [`Logger`] per process and
//! [`uninstall`] it before they exit; with none installed (core tests,
//! library callers) [`event`] does nothing.

use std::fmt::{self, Display, Write as _};
use std::fs::{File, OpenOptions, TryLockError};
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, Sender};
use std::sync::{Arc, Mutex, PoisonError, RwLock};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant, SystemTime};

use super::redact::Redactor;
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::fs::long;
use crate::paths::SurjectionHome;
use crate::store::utc_datetime;

/// The log file inside `logs/`.
pub const LOG_FILE: &str = "surjection.log";
/// The lock writers hold while appending and rotating.
pub const LOCK_FILE: &str = "surjection.log.lock";
/// Set to `off` (or `0`, `false`, `no`) to turn the log off.
pub const LOG_ENV_VAR: &str = "SURJECTION_LOG";

/// How long the writer waits for the lock before appending without
/// rotating.
const LOCK_WAIT: Duration = Duration::from_millis(500);
const LOCK_POLL: Duration = Duration::from_millis(5);
/// Attempts to open the log file (another process may be renaming it).
const OPEN_ATTEMPTS: usize = 3;
const OPEN_RETRY: Duration = Duration::from_millis(20);
/// How long [`Logger::flush`] waits for the writer.
const FLUSH_WAIT: Duration = Duration::from_secs(2);

/// When the log rotates and how many older files stay.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rotation {
    /// The current file never grows past this (a single longer line
    /// still gets its own file).
    pub max_bytes: u64,
    /// Older files kept: `surjection.log.1` (newest) to `surjection.log.<keep>`.
    pub keep: usize,
}

impl Rotation {
    /// 1 MiB, two older files.
    pub const DEFAULT: Rotation = Rotation {
        max_bytes: 1024 * 1024,
        keep: 2,
    };
}

/// One event as the caller gave it; rendered and redacted by the writer.
struct Record {
    time: SystemTime,
    event: String,
    fields: Vec<(String, String)>,
}

enum Message {
    Line(Record),
    Rotation(Rotation),
    /// Answered once everything sent before it is written.
    Flush(Sender<()>),
}

/// Writes redacted lines to one data folder's log. The caller only queues
/// the event; one background thread renders, redacts and writes (file
/// I/O, the lock, rotation and retries never run on the caller's thread).
/// Dropping the logger writes what is queued before it returns.
pub struct Logger {
    path: PathBuf,
    env: Env,
    sender: Mutex<Option<Sender<Message>>>,
    writer: Mutex<Option<JoinHandle<()>>>,
}

impl fmt::Debug for Logger {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Logger")
            .field("path", &self.path)
            .finish_non_exhaustive()
    }
}

impl Logger {
    /// The log of `home`, written as `source` (`cli`, `app`); `None` when
    /// [`LOG_ENV_VAR`] turns it off (or the writer thread cannot start).
    pub fn for_home(env: &Env, home: &SurjectionHome, source: &'static str) -> Option<Logger> {
        let off = env
            .var(LOG_ENV_VAR)
            .or_else(|| env.var(crate::brand::legacy::LOG_ENV_VAR))
            .and_then(|value| value.to_str())
            .is_some_and(|value| {
                matches!(
                    value.trim().to_ascii_lowercase().as_str(),
                    "off" | "0" | "false" | "no"
                )
            });
        if off {
            return None;
        }
        let sink = Sink {
            data: home.path.clone(),
            dir: home.logs_dir(),
            source,
            redactor: Redactor::new(env, &home.path),
            rotation: Rotation::DEFAULT,
            ready: false,
        };
        let path = sink.path();
        let (sender, receiver) = mpsc::channel();
        let writer = thread::Builder::new()
            .name("surjection-log".to_owned())
            .spawn(move || sink.run(receiver))
            .ok()?;
        Some(Logger {
            path,
            env: env.clone(),
            sender: Mutex::new(Some(sender)),
            writer: Mutex::new(Some(writer)),
        })
    }

    pub fn with_rotation(self, rotation: Rotation) -> Self {
        self.send(Message::Rotation(rotation));
        self
    }

    /// The current log file.
    pub fn path(&self) -> PathBuf {
        self.path.clone()
    }

    /// Queues one line. Nothing is written while the data folder does not
    /// exist (a log never creates it); I/O errors are ignored.
    pub fn write(&self, event: &str, fields: &[(&str, &dyn Display)]) {
        self.send(Message::Line(Record {
            time: self.env.now(),
            event: clean(event),
            fields: fields
                .iter()
                .map(|(key, value)| (clean(key), value.to_string()))
                .collect(),
        }));
    }

    /// Waits (up to two seconds) until every line queued so far is written.
    pub fn flush(&self) {
        let (ack, done) = mpsc::channel();
        self.send(Message::Flush(ack));
        let _ = done.recv_timeout(FLUSH_WAIT);
    }

    fn send(&self, message: Message) {
        if let Some(sender) = self
            .sender
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .as_ref()
        {
            let _ = sender.send(message);
        }
    }
}

impl Drop for Logger {
    fn drop(&mut self) {
        // Closing the channel ends the writer once it has written the rest.
        drop(
            self.sender
                .lock()
                .unwrap_or_else(PoisonError::into_inner)
                .take(),
        );
        if let Some(writer) = self
            .writer
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
        {
            let _ = writer.join();
        }
    }
}

/// The writer thread's side: where and how lines are written.
struct Sink {
    data: PathBuf,
    dir: PathBuf,
    source: &'static str,
    redactor: Redactor,
    rotation: Rotation,
    /// `logs/` exists: checked until it does, then never again.
    ready: bool,
}

impl Sink {
    fn path(&self) -> PathBuf {
        self.dir.join(LOG_FILE)
    }

    /// Writes whatever has arrived, in batches, until the channel closes.
    fn run(mut self, receiver: Receiver<Message>) {
        while let Ok(first) = receiver.recv() {
            let mut lines = Vec::new();
            let mut acks = Vec::new();
            for message in std::iter::once(first).chain(receiver.try_iter()) {
                match message {
                    Message::Line(record) => lines.push(self.render(&record)),
                    Message::Rotation(rotation) => self.rotation = rotation,
                    Message::Flush(ack) => acks.push(ack),
                }
            }
            self.write(&lines);
            for ack in acks {
                let _ = ack.send(());
            }
        }
    }

    fn render(&self, record: &Record) -> String {
        let mut line = format!(
            "{} {} pid={} {}",
            utc_datetime(record.time),
            self.source,
            std::process::id(),
            record.event
        );
        // Each value is redacted before it is quoted, so a value with
        // quotes or backslashes is still matched as it was resolved.
        for (key, value) in &record.fields {
            let value = self.redactor.redact(value);
            let _ = write!(line, " {key}={}", Quoted(&value));
        }
        line.push('\n');
        line
    }

    /// Appends `lines` under the lock, one write call per line, rotating
    /// before a line that would push the file past the cap.
    fn write(&mut self, lines: &[String]) {
        if lines.is_empty() {
            return;
        }
        if !self.ready {
            if !long(&self.data).is_dir() || std::fs::create_dir_all(long(&self.dir)).is_err() {
                return;
            }
            self.ready = true;
        }
        let lock = self.lock();
        let current = self.path();
        let mut file = open_append(&current);
        let mut size = std::fs::metadata(long(&current)).map_or(0, |meta| meta.len());
        for line in lines {
            let incoming = line.len() as u64;
            if lock.is_some() && size > 0 && size + incoming > self.rotation.max_bytes {
                drop(file.take());
                self.rotate();
                file = open_append(&current);
                size = 0;
            }
            if let Some(file) = file.as_mut() {
                // A whole line per write call, even from a writer that
                // could not get the lock.
                if file.write_all(line.as_bytes()).is_ok() {
                    size += incoming;
                }
            }
        }
        drop(file);
        if let Some(lock) = lock {
            let _ = lock.unlock();
        }
    }

    fn lock(&self) -> Option<File> {
        let file = OpenOptions::new()
            .read(true)
            .write(true)
            .create(true)
            .truncate(false)
            .open(long(&self.dir.join(LOCK_FILE)))
            .ok()?;
        let deadline = Instant::now() + LOCK_WAIT;
        loop {
            match file.try_lock() {
                Ok(()) => return Some(file),
                Err(TryLockError::WouldBlock) if Instant::now() < deadline => {
                    thread::sleep(LOCK_POLL);
                }
                Err(_) => return None,
            }
        }
    }

    /// `.N-1 -> .N ... .1 -> .2`, current `-> .1`. Runs under the lock.
    fn rotate(&self) {
        let current = self.path();
        let numbered = |n: usize| self.dir.join(format!("{LOG_FILE}.{n}"));
        if self.rotation.keep == 0 {
            let _ = std::fs::remove_file(long(&current));
            return;
        }
        for n in (1..self.rotation.keep).rev() {
            let from = numbered(n);
            if long(&from).exists() {
                let _ = std::fs::rename(long(&from), long(&numbered(n + 1)));
            }
        }
        let _ = std::fs::rename(long(&current), long(&numbered(1)));
    }
}

/// The log file opened for appending, retried briefly (another process
/// may hold it while it rotates).
fn open_append(path: &Path) -> Option<File> {
    for attempt in 0..OPEN_ATTEMPTS {
        if let Ok(file) = OpenOptions::new()
            .create(true)
            .append(true)
            .open(long(path))
        {
            return Some(file);
        }
        if attempt + 1 < OPEN_ATTEMPTS {
            thread::sleep(OPEN_RETRY);
        }
    }
    None
}

/// Event and key names: printable ASCII without spaces or `=`.
fn clean(name: &str) -> String {
    name.chars()
        .map(|c| {
            if c.is_ascii_graphic() && c != '=' {
                c
            } else {
                '_'
            }
        })
        .collect()
}

/// A field value: bare when it is one plain word, else quoted with `"`,
/// `\` and control characters escaped.
struct Quoted<'a>(&'a str);

impl Display for Quoted<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let plain = !self.0.is_empty()
            && self
                .0
                .chars()
                .all(|c| c.is_ascii_graphic() && !matches!(c, '"' | '\\' | '='));
        if plain {
            return f.write_str(self.0);
        }
        f.write_char('"')?;
        for c in self.0.chars() {
            match c {
                '"' => f.write_str("\\\"")?,
                '\\' => f.write_str("\\\\")?,
                '\n' => f.write_str("\\n")?,
                c if c.is_control() => f.write_char(' ')?,
                c => f.write_char(c)?,
            }
        }
        f.write_char('"')
    }
}

static SINK: RwLock<Option<Arc<Logger>>> = RwLock::new(None);

/// Makes `logger` the process's log.
pub fn install(logger: Logger) {
    *SINK.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(logger));
}

/// Stops logging in this process after writing every queued line (call it
/// before the process exits).
pub fn uninstall() {
    let logger = SINK.write().unwrap_or_else(PoisonError::into_inner).take();
    if let Some(logger) = logger {
        // Another thread may still hold the logger for a moment: flush so
        // the lines are written even when this is not the last reference.
        logger.flush();
    }
}

/// Logs one event to the installed logger, if any.
pub fn event(name: &str, fields: &[(&str, &dyn Display)]) {
    let logger = SINK
        .read()
        .unwrap_or_else(PoisonError::into_inner)
        .as_ref()
        .map(Arc::clone);
    if let Some(logger) = logger {
        logger.write(name, fields);
    }
}

/// Logs the end of a command or IPC call `name`: `outcome=ok`, or
/// `outcome=error code=<code>`, and how long it took.
pub fn finished(event_name: &str, name: &str, error: Option<ErrorCode>, started: Instant) {
    let duration = started.elapsed().as_millis();
    match error {
        None => event(
            event_name,
            &[
                ("name", &name),
                ("outcome", &"ok"),
                ("duration_ms", &duration),
            ],
        ),
        Some(code) => event(
            event_name,
            &[
                ("name", &name),
                ("outcome", &"error"),
                ("code", &code.as_str()),
                ("duration_ms", &duration),
            ],
        ),
    }
}

/// Logs a network request: the host only (never the path or query), the
/// HTTP status or the error code, and how long it took.
pub fn http(kind: &str, url: &str, result: Result<u16, &CoreError>, started: Instant) {
    let host = url::Url::parse(url)
        .ok()
        .and_then(|url| url.host_str().map(str::to_owned))
        .unwrap_or_else(|| "unknown".to_owned());
    let duration = started.elapsed().as_millis();
    match result {
        Ok(status) => event(
            "http",
            &[
                ("kind", &kind),
                ("host", &host),
                ("status", &status),
                ("duration_ms", &duration),
            ],
        ),
        Err(err) => event(
            "http",
            &[
                ("kind", &kind),
                ("host", &host),
                ("code", &err.code().as_str()),
                ("duration_ms", &duration),
            ],
        ),
    }
}

/// The last `n` lines of the log of `home` (the newest older file fills
/// in when the current one is short). Lines were redacted when written.
pub fn tail(home: &SurjectionHome, n: usize) -> Vec<String> {
    let dir = home.logs_dir();
    let read = |path: &Path| std::fs::read(long(path)).ok();
    let lines_of = |bytes: Vec<u8>| -> Vec<String> {
        String::from_utf8_lossy(&bytes)
            .lines()
            .filter(|line| !line.trim().is_empty())
            .map(str::to_owned)
            .collect()
    };
    let mut lines = read(&dir.join(LOG_FILE)).map(lines_of).unwrap_or_default();
    if lines.len() < n
        && let Some(older) = read(&dir.join(format!("{LOG_FILE}.1"))).map(lines_of)
    {
        let mut all = older;
        all.extend(lines);
        lines = all;
    }
    let skip = lines.len().saturating_sub(n);
    lines.split_off(skip)
}

/// The `code=` values of `lines`, newest first, with how often each
/// appears.
pub fn error_codes(lines: &[String]) -> Vec<(String, usize)> {
    let mut codes: Vec<(String, usize)> = Vec::new();
    for line in lines.iter().rev() {
        let Some(code) = line
            .split_whitespace()
            .find_map(|word| word.strip_prefix("code="))
            .filter(|code| !code.is_empty())
        else {
            continue;
        };
        match codes.iter_mut().find(|(known, _)| known == code) {
            Some((_, count)) => *count += 1,
            None => codes.push((code.to_owned(), 1)),
        }
    }
    codes
}