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
use axum::{body::Body, extract::ConnectInfo, http::Request, response::Response};
use futures::future::BoxFuture;
use http::header::{HeaderValue, HOST, USER_AGENT};
use serde::Serialize;
use std::{
task::{Context, Poll},
thread::spawn,
time::Instant,
net::SocketAddr
};
use reqwest::blocking::Client;
use tower::{Layer, Service};
#[derive(Debug, Serialize)]
struct Data {
api_key: String,
hostname: String,
ip_address: String,
path: String,
user_agent: String,
method: String,
response_time: u32,
status: u16,
framework: String,
}
impl Data {
pub fn new(
api_key: String,
hostname: String,
ip_address: String,
path: String,
user_agent: String,
method: String,
response_time: u32,
status: u16,
) -> Self {
Self {
api_key,
hostname,
ip_address,
path,
user_agent,
method,
response_time,
status,
framework: String::from("Axum"),
}
}
}
#[derive(Clone)]
pub struct Analytics {
api_key: String,
}
impl Analytics {
pub fn new(api_key: String) -> Self {
Self { api_key }
}
}
impl<S> Layer<S> for Analytics {
type Service = AnalyticsMiddleware<S>;
fn layer(&self, inner: S) -> Self::Service {
AnalyticsMiddleware {
api_key: self.api_key.clone(),
inner,
}
}
}
#[derive(Clone)]
pub struct AnalyticsMiddleware<S> {
api_key: String,
inner: S,
}
pub trait HeaderValueExt {
fn to_string(&self) -> String;
}
impl HeaderValueExt for HeaderValue {
fn to_string(&self) -> String {
self.to_str().unwrap_or_default().to_string()
}
}
fn log_request(data: Data) {
let _ = Client::new()
.post("https://api-analytics-server.vercel.app/api/log-request")
.json(&data)
.send();
}
impl<S> Service<Request<Body>> for AnalyticsMiddleware<S>
where
S: Service<Request<Body>, Response = Response> + Send + 'static,
S::Future: Send + 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<Body>) -> Self::Future {
let now = Instant::now();
let api_key = self.api_key.clone();
let hostname = req.headers().get(HOST).map(|x| x.to_string()).unwrap();
let mut ip_address = String::new();
if let Some(val) = req.extensions().get::<ConnectInfo<SocketAddr>>().map(|ConnectInfo(addr)| addr.ip()) {
ip_address = val.to_string();
}
let path = req.uri().path().to_owned();
let method = req.method().to_string();
let user_agent = req
.headers()
.get(USER_AGENT)
.map(|x| x.to_string())
.unwrap();
let future = self.inner.call(req);
Box::pin(async move {
let res: Response = future.await?;
let elapsed = now.elapsed().as_millis();
let data = Data::new(
api_key,
hostname,
ip_address,
path,
user_agent,
method,
elapsed.try_into().unwrap(),
res.status().as_u16(),
);
spawn(|| log_request(data));
Ok(res)
})
}
}