laravel-rust-studio 0.1.1

See what a running Laravel for Rust application did: requests with their queries, errors with their source lines, mail, queued jobs, and durable workflows. For you in the browser, and for coding agents over MCP.
Documentation
//! Cross-process telemetry journal.
//!
//! A Laravel application usually runs as several processes: the web server, one or more
//! `queue:work` workers, the scheduler, and one-off console commands. Each process appends what it
//! captures to its own JSON-lines file in `storage/studio/`, and the process serving the Studio UI
//! tails the other processes' files. That's how a workflow step's email, sent from a queue worker,
//! shows up in the web server's Studio, and how telemetry survives the restarts `laravel dev` does
//! on every save.

use std::collections::{HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU32, Ordering};
use std::time::{Duration, Instant, SystemTime};

use serde::{Deserialize, Serialize};

use crate::types::{
    CacheRecord, ExceptionRecord, HttpClientRecord, JobActivityRecord, LogRecord, MailRecord, QueryRecord, TraceRecord,
    WorkflowActivityRecord,
};

const EXTENSION: &str = ".jsonl";

/// A process starts a new file once its current one grows past this size.
const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024;

/// How often, at most, a reader looks at the journal directory.
const SYNC_INTERVAL: Duration = Duration::from_millis(200);

/// One captured record, as a journal line holds it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "t", content = "d", rename_all = "snake_case")]
pub(crate) enum JournalEntry {
    Trace(Box<TraceRecord>),
    Query(QueryRecord),
    Log(LogRecord),
    Exception(ExceptionRecord),
    Mail(MailRecord),
    Http(HttpClientRecord),
    Cache(CacheRecord),
    Workflow(WorkflowActivityRecord),
    Job(JobActivityRecord),
}

impl JournalEntry {
    /// When the record was captured, to order records read from several files.
    pub(crate) fn timestamp_ms(&self) -> i64 {
        match self {
            Self::Trace(trace) => trace.finished_at_ms,
            Self::Query(query) => query.started_at_ms,
            Self::Log(log) => log.timestamp_ms,
            Self::Exception(exception) => exception.timestamp_ms,
            Self::Mail(mail) => mail.timestamp_ms,
            Self::Http(request) => request.timestamp_ms,
            Self::Cache(operation) => operation.timestamp_ms,
            Self::Workflow(activity) => activity.updated_at_ms,
            Self::Job(activity) => activity.timestamp_ms,
        }
    }
}

/// The journal directory, this process's file in it, and how far this process has read the others.
pub(crate) struct Journal {
    dir: PathBuf,
    /// The start of every file name this process writes, so it never reads its own records back.
    prefix: String,
    max_total_bytes: u64,
    retention: Duration,
    writer: Mutex<Writer>,
    reader: Mutex<Reader>,
}

#[derive(Default)]
struct Writer {
    file: Option<File>,
    written: u64,
    sequence: u32,
    /// Set once a write fails, such as on a read-only disk, so the process stops trying.
    disabled: bool,
}

#[derive(Default)]
struct Reader {
    offsets: HashMap<String, u64>,
    last_sync: Option<Instant>,
    synced_once: bool,
}

/// What one look at the journal directory found.
pub(crate) struct Batch {
    pub entries: Vec<JournalEntry>,
    /// Whether this is the reader's first look, which loads the history earlier runs left.
    pub initial: bool,
}

impl Journal {
    pub(crate) fn new(dir: PathBuf, role: &str, max_total_bytes: u64, retention: Duration) -> Self {
        let role: String = role
            .chars()
            .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
            .collect();
        let started = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map(|elapsed| elapsed.as_millis())
            .unwrap_or_default();

        // Two journals of one process, as tests make, still need files of their own...
        static INSTANCES: AtomicU32 = AtomicU32::new(0);
        let instance = INSTANCES.fetch_add(1, Ordering::Relaxed);

        Self {
            dir,
            prefix: format!("{role}-{}-{started}-{instance}-", std::process::id()),
            max_total_bytes,
            retention,
            writer: Mutex::default(),
            reader: Mutex::default(),
        }
    }

    pub(crate) fn dir(&self) -> &Path {
        &self.dir
    }

    /// Append a record to this process's file. A failure turns the journal off for this process
    /// rather than disturb the application.
    pub(crate) fn append(&self, entry: &JournalEntry) {
        let Ok(mut line) = serde_json::to_vec(entry) else {
            return;
        };
        line.push(b'\n');

        let Ok(mut writer) = self.writer.lock() else {
            return;
        };
        if writer.disabled {
            return;
        }
        if (writer.file.is_none() || writer.written >= MAX_FILE_BYTES) && self.open_next(&mut writer).is_err() {
            writer.disabled = true;
            return;
        }
        let Some(file) = writer.file.as_mut() else {
            return;
        };
        match file.write_all(&line) {
            Ok(()) => writer.written += line.len() as u64,
            Err(_) => writer.disabled = true,
        }
    }

    fn open_next(&self, writer: &mut Writer) -> std::io::Result<()> {
        fs::create_dir_all(&self.dir)?;
        // What Studio captures holds queries and mail, and doesn't belong in the application's
        // repository. The directory ignores itself, so nothing about it shows in `git status`...
        let ignore = self.dir.join(".gitignore");
        if !ignore.exists() {
            let _ = fs::write(ignore, "*\n");
        }
        self.clean_up();

        let name = format!("{}{}{EXTENSION}", self.prefix, writer.sequence);
        let file = OpenOptions::new().create(true).append(true).open(self.dir.join(name))?;
        writer.sequence += 1;
        writer.written = file.metadata().map(|metadata| metadata.len()).unwrap_or(0);
        writer.file = Some(file);

        Ok(())
    }

    /// Delete files past the retention, then the oldest files of other runs while the directory is
    /// over its size limit.
    fn clean_up(&self) {
        let now = SystemTime::now();
        let mut kept: Vec<(PathBuf, SystemTime, u64, bool)> = Vec::new();
        for (name, path, modified, len) in self.files() {
            let own = name.starts_with(&self.prefix);
            let expired = now.duration_since(modified).is_ok_and(|age| age > self.retention);
            if expired && !own {
                let _ = fs::remove_file(path);
            } else {
                kept.push((path, modified, len, own));
            }
        }

        let mut total: u64 = kept.iter().map(|(_, _, len, _)| len).sum();
        kept.sort_by_key(|(_, modified, _, _)| *modified);
        for (path, _, len, own) in kept {
            if total <= self.max_total_bytes {
                break;
            }
            if !own && fs::remove_file(path).is_ok() {
                total = total.saturating_sub(len);
            }
        }
    }

    fn files(&self) -> Vec<(String, PathBuf, SystemTime, u64)> {
        let Ok(entries) = fs::read_dir(&self.dir) else {
            return Vec::new();
        };

        entries
            .flatten()
            .filter_map(|entry| {
                let name = entry.file_name().to_string_lossy().into_owned();
                if !name.ends_with(EXTENSION) {
                    return None;
                }
                let metadata = entry.metadata().ok()?;
                let modified = metadata.modified().unwrap_or(SystemTime::UNIX_EPOCH);

                Some((name, entry.path(), modified, metadata.len()))
            })
            .collect()
    }

    /// Read what other processes appended since the last look, oldest first. Unless `force` is
    /// set, looks closer together than [`SYNC_INTERVAL`] return nothing.
    pub(crate) fn read_new(&self, force: bool) -> Batch {
        let mut entries = Vec::new();
        let Ok(mut reader) = self.reader.lock() else {
            return Batch {
                entries,
                initial: false,
            };
        };
        if !force && reader.last_sync.is_some_and(|last| last.elapsed() < SYNC_INTERVAL) {
            return Batch {
                entries,
                initial: false,
            };
        }
        reader.last_sync = Some(Instant::now());
        let initial = !reader.synced_once;
        reader.synced_once = true;

        let mut seen = HashSet::new();
        for (name, path, _, len) in self.files() {
            if name.starts_with(&self.prefix) {
                continue;
            }
            seen.insert(name.clone());

            // A file shorter than what was read of it was cleared, so read it from its start...
            let offset = reader
                .offsets
                .get(&name)
                .copied()
                .filter(|offset| *offset <= len)
                .unwrap_or(0);
            if offset < len
                && let Some(read) = read_lines(&path, offset, len, &mut entries)
            {
                reader.offsets.insert(name, offset + read);
            } else {
                reader.offsets.insert(name, offset);
            }
        }
        reader.offsets.retain(|name, _| seen.contains(name));
        drop(reader);

        entries.sort_by_key(JournalEntry::timestamp_ms);

        Batch { entries, initial }
    }

    /// Empty every journal file. Files are emptied rather than deleted, because a process that
    /// still appends to a deleted file would write where no reader looks.
    pub(crate) fn clear(&self) {
        for (_, path, _, _) in self.files() {
            if let Ok(file) = OpenOptions::new().write(true).open(path) {
                let _ = file.set_len(0);
            }
        }
        if let Ok(mut writer) = self.writer.lock() {
            writer.written = 0;
        }
        if let Ok(mut reader) = self.reader.lock() {
            reader.offsets.clear();
        }
    }
}

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

/// Parse the complete lines of `path` between `offset` and `len`, and return how many bytes they
/// took. A last line that's still being written waits for the next look.
fn read_lines(path: &Path, offset: u64, len: u64, entries: &mut Vec<JournalEntry>) -> Option<u64> {
    let mut file = File::open(path).ok()?;
    file.seek(SeekFrom::Start(offset)).ok()?;
    let mut buffer = Vec::with_capacity(usize::try_from(len - offset).unwrap_or(0));
    file.take(len - offset).read_to_end(&mut buffer).ok()?;

    let complete = buffer.iter().rposition(|byte| *byte == b'\n')? + 1;
    for line in buffer[..complete].split(|byte| *byte == b'\n') {
        if !line.is_empty()
            && let Ok(entry) = serde_json::from_slice(line)
        {
            entries.push(entry);
        }
    }

    Some(complete as u64)
}