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
|
/*
This file is part of gnix (https://codeberg.org/metamuffin/gnix)
which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
Copyright (C) 2025 metamuffin <metamuffin.org>
*/
use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse};
use crate::{config::DynNode, error::ServiceError};
use futures::Future;
use log::error;
use serde::Deserialize;
use std::{path::PathBuf, pin::Pin, sync::Arc, time::SystemTime};
use tokio::{
fs::{File, OpenOptions},
io::{AsyncWriteExt, BufWriter},
sync::RwLock,
};
pub struct AccessLogKind;
#[derive(Deserialize)]
struct AccessLogConfig {
file: PathBuf,
#[serde(default)]
flush: bool,
#[serde(default)]
reject_on_fail: bool,
next: DynNode,
}
struct AccessLog {
config: AccessLogConfig,
file: RwLock<Option<BufWriter<File>>>,
}
impl NodeKind for AccessLogKind {
fn name(&self) -> &'static str {
"access_log"
}
fn instanciate(&self, config: serde_yml::Value) -> anyhow::Result<Arc<dyn Node>> {
Ok(Arc::new(AccessLog {
config: serde_yml::from_value::<AccessLogConfig>(config)?,
file: Default::default(),
}))
}
}
impl Node for AccessLog {
fn handle<'a>(
&'a self,
context: &'a mut NodeContext,
request: NodeRequest,
) -> Pin<Box<dyn Future<Output = Result<NodeResponse, ServiceError>> + Send + Sync + 'a>> {
Box::pin(async move {
let mut g = self.file.write().await;
let log = match g.as_mut() {
Some(r) => r,
None => g.insert(BufWriter::new(
OpenOptions::new()
.append(true)
.create(true)
.open(&self.config.file)
.await?,
)),
};
let method = request.method().as_str();
let time = SystemTime::UNIX_EPOCH.elapsed().unwrap().as_micros();
let addr = context.addr;
let mut res = log
.write_all(format!("{time}\t{addr}\t{method}\t{:?}\n", request.uri()).as_bytes())
.await;
if self.config.flush && res.is_ok() {
res?;
res = log.flush().await;
}
if self.config.reject_on_fail {
res?
} else if let Err(e) = res {
error!("failed to write log: {e:?}")
}
self.config.next.handle(context, request).await
})
}
}
|