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;
pub const LOG_FILE: &str = "surjection.log";
pub const LOCK_FILE: &str = "surjection.log.lock";
pub const LOG_ENV_VAR: &str = "SURJECTION_LOG";
const LOCK_WAIT: Duration = Duration::from_millis(500);
const LOCK_POLL: Duration = Duration::from_millis(5);
const OPEN_ATTEMPTS: usize = 3;
const OPEN_RETRY: Duration = Duration::from_millis(20);
const FLUSH_WAIT: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Rotation {
pub max_bytes: u64,
pub keep: usize,
}
impl Rotation {
pub const DEFAULT: Rotation = Rotation {
max_bytes: 1024 * 1024,
keep: 2,
};
}
struct Record {
time: SystemTime,
event: String,
fields: Vec<(String, String)>,
}
enum Message {
Line(Record),
Rotation(Rotation),
Flush(Sender<()>),
}
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 {
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
}
pub fn path(&self) -> PathBuf {
self.path.clone()
}
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(),
}));
}
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) {
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();
}
}
}
struct Sink {
data: PathBuf,
dir: PathBuf,
source: &'static str,
redactor: Redactor,
rotation: Rotation,
ready: bool,
}
impl Sink {
fn path(&self) -> PathBuf {
self.dir.join(LOG_FILE)
}
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
);
for (key, value) in &record.fields {
let value = self.redactor.redact(value);
let _ = write!(line, " {key}={}", Quoted(&value));
}
line.push('\n');
line
}
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(¤t);
let mut size = std::fs::metadata(long(¤t)).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(¤t);
size = 0;
}
if let Some(file) = file.as_mut() {
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,
}
}
}
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(¤t));
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(¤t), long(&numbered(1)));
}
}
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
}
fn clean(name: &str) -> String {
name.chars()
.map(|c| {
if c.is_ascii_graphic() && c != '=' {
c
} else {
'_'
}
})
.collect()
}
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);
pub fn install(logger: Logger) {
*SINK.write().unwrap_or_else(PoisonError::into_inner) = Some(Arc::new(logger));
}
pub fn uninstall() {
let logger = SINK.write().unwrap_or_else(PoisonError::into_inner).take();
if let Some(logger) = logger {
logger.flush();
}
}
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);
}
}
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),
],
),
}
}
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),
],
),
}
}
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)
}
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
}