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";
const MAX_FILE_BYTES: u64 = 8 * 1024 * 1024;
const SYNC_INTERVAL: Duration = Duration::from_millis(200);
#[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 {
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,
}
}
}
pub(crate) struct Journal {
dir: PathBuf,
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,
disabled: bool,
}
#[derive(Default)]
struct Reader {
offsets: HashMap<String, u64>,
last_sync: Option<Instant>,
synced_once: bool,
}
pub(crate) struct Batch {
pub entries: Vec<JournalEntry>,
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();
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
}
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)?;
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(())
}
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()
}
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());
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 }
}
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()
}
}
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)
}