1use std::error::Error;
19use std::future::Future;
20use std::hint::black_box;
21use std::path::Path;
22use std::sync::Arc;
23use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
24use std::time::{Duration, Instant};
25
26use pb_mapper_auth::{
27 ADMIN_KEY_ID, AuthConfig, AuthContext, AuthRuntime, DEFAULT_TEMP_KEY_CAPACITY, KeyId,
28 LegacyProtocolPolicy, MAX_TEMP_KEY_CAPACITY,
29};
30use pb_mapper_core::test_support::{TEST_ADMIN_KEY_BYTES, TempPath};
31use tokio::runtime::{Builder, Runtime};
32use tokio::task::JoinHandle;
33
34type BenchResult<T> = Result<T, Box<dyn Error + Send + Sync>>;
35
36const CALLS: usize = 200_000;
37const SAMPLES: usize = 9;
38const HOUR: Duration = Duration::from_secs(3600);
39const RENEWALS: usize = 200;
41const ROUNDS: usize = 20;
43const KEYS: usize = 100;
45const WORKERS: usize = 4;
47
48fn time(mut call: impl FnMut() -> BenchResult<()>) -> BenchResult<f64> {
50 for _ in 0..CALLS / 10 {
51 call()?;
52 }
53 let mut samples = Vec::with_capacity(SAMPLES);
54 for _ in 0..SAMPLES {
55 let start = Instant::now();
56 for _ in 0..CALLS {
57 call()?;
58 }
59 samples.push(start.elapsed().as_secs_f64() * 1e9 / CALLS as f64);
60 }
61 samples.sort_by(f64::total_cmp);
62 Ok(samples[SAMPLES / 2])
63}
64
65fn config(state_dir: &Path, capacity: usize) -> AuthConfig {
66 AuthConfig {
67 state_dir: state_dir.to_path_buf(),
68 max_temporary_keys: capacity,
69 max_temporary_key_ttl: HOUR,
70 legacy_protocol: LegacyProtocolPolicy::Deny,
71 }
72}
73
74async fn start(state_dir: &Path, capacity: usize) -> BenchResult<(AuthRuntime, AuthContext)> {
75 let runtime = AuthRuntime::start(TEST_ADMIN_KEY_BYTES, config(state_dir, capacity)).await?;
76 let admin = runtime.authenticate_presented(ADMIN_KEY_ID, &TEST_ADMIN_KEY_BYTES)?;
77 Ok((runtime, admin))
78}
79
80async fn hot_path() -> BenchResult<()> {
82 let state_dir = TempPath::new("auth-bench");
83 let (runtime, admin) = start(&state_dir, 16).await?;
84 let issued = runtime.issue(&admin, HOUR, None).await?;
85 let key_id: KeyId = issued.metadata.key_id;
86 let presented = runtime.derive_key(key_id)?;
87
88 let derive = time(|| {
89 black_box(runtime.derive_key(black_box(key_id))?);
90 Ok(())
91 })?;
92 let temporary = time(|| {
93 black_box(runtime.authenticate_presented(black_box(key_id), black_box(&presented))?);
94 Ok(())
95 })?;
96 let administrator =
97 time(|| {
98 black_box(runtime.authenticate_presented(
99 black_box(ADMIN_KEY_ID),
100 black_box(&TEST_ADMIN_KEY_BYTES),
101 )?);
102 Ok(())
103 })?;
104 println!("case=derive_temporary_key ns={derive:.1}");
105 println!("case=authenticate_temporary ns={temporary:.1}");
106 println!("case=authenticate_administrator ns={administrator:.1}");
107
108 drop(admin);
109 runtime.shutdown_actor().await;
110 Ok(())
111}
112
113struct Probes {
115 longest_gap: Arc<AtomicU64>,
117 turns: Vec<Arc<AtomicU64>>,
118 stop: Arc<AtomicBool>,
119 tasks: Vec<JoinHandle<()>>,
120}
121
122impl Probes {
123 fn start(count: usize) -> Self {
124 let longest_gap = Arc::new(AtomicU64::new(0));
125 let stop = Arc::new(AtomicBool::new(false));
126 let turns = (0..count)
127 .map(|_| Arc::new(AtomicU64::new(0)))
128 .collect::<Vec<_>>();
129 let tasks = turns
130 .iter()
131 .map(|turns| {
132 let (longest_gap, turns, stop) = (longest_gap.clone(), turns.clone(), stop.clone());
133 tokio::spawn(async move {
134 let mut last = Instant::now();
135 while !stop.load(Ordering::Relaxed) {
136 tokio::task::yield_now().await;
137 let now = Instant::now();
138 let gap = u64::try_from((now - last).as_nanos()).unwrap_or(u64::MAX);
139 longest_gap.fetch_max(gap, Ordering::Relaxed);
140 turns.fetch_add(1, Ordering::Relaxed);
141 last = now;
142 }
143 })
144 })
145 .collect();
146 Self {
147 longest_gap,
148 turns,
149 stop,
150 tasks,
151 }
152 }
153
154 fn turns(&self) -> Vec<u64> {
155 self.turns
156 .iter()
157 .map(|turns| turns.load(Ordering::Relaxed))
158 .collect()
159 }
160
161 async fn settle(&self) {
164 let before = self.turns();
165 while self
166 .turns()
167 .iter()
168 .zip(&before)
169 .any(|(now, then)| *now < then + 2)
170 {
171 tokio::task::yield_now().await;
172 }
173 }
174
175 async fn measure<T>(&self, operation: impl Future<Output = T>) -> (T, Timing) {
178 self.settle().await;
179 self.longest_gap.store(0, Ordering::Relaxed);
180 let start = Instant::now();
181 let output = operation.await;
182 let latency = start.elapsed();
183 self.settle().await;
184 let hold = Duration::from_nanos(self.longest_gap.load(Ordering::Relaxed));
185 (output, Timing { latency, hold })
186 }
187
188 async fn stop(self) {
189 self.stop.store(true, Ordering::Relaxed);
190 for task in self.tasks {
191 let _ = task.await;
192 }
193 }
194}
195
196struct Timing {
197 latency: Duration,
198 hold: Duration,
199}
200
201#[derive(Default)]
202struct Timings {
203 latency: Vec<Duration>,
204 hold: Vec<Duration>,
205}
206
207impl Timings {
208 fn push(&mut self, Timing { latency, hold }: Timing) {
209 self.latency.push(latency);
210 self.hold.push(hold);
211 }
212
213 fn report(mut self, case: &str) {
214 let micros = |samples: &mut Vec<Duration>, quantile: f64| {
215 samples.sort();
216 let index = ((samples.len() - 1) as f64 * quantile).round() as usize;
217 samples[index].as_secs_f64() * 1e6
218 };
219 println!(
220 "case={case} ops={} latency_p50_us={:.1} latency_p99_us={:.1} hold_p50_us={:.1} hold_p99_us={:.1} hold_max_us={:.1}",
221 self.latency.len(),
222 micros(&mut self.latency, 0.5),
223 micros(&mut self.latency, 0.99),
224 micros(&mut self.hold, 0.5),
225 micros(&mut self.hold, 0.99),
226 micros(&mut self.hold, 1.0),
227 );
228 }
229}
230
231async fn persistence(flavor: &'static str, probes: usize) -> BenchResult<()> {
233 let probes = Probes::start(probes);
234
235 let state_dir = TempPath::new("auth-bench-renew");
236 let (runtime, admin) = start(&state_dir, DEFAULT_TEMP_KEY_CAPACITY).await?;
237 let key_id = runtime.issue(&admin, HOUR, None).await?.metadata.key_id;
238 let mut timings = Timings::default();
239 for round in 0..RENEWALS + RENEWALS / 10 {
240 let (renewed, timing) = probes.measure(runtime.renew(&admin, key_id, HOUR)).await;
241 black_box(renewed?);
242 if round >= RENEWALS / 10 {
243 timings.push(timing);
244 }
245 }
246 timings.report(&format!("renew_{flavor}"));
247 let mut timings = Timings::default();
249 for round in 0..RENEWALS + RENEWALS / 10 {
250 let (status, timing) = probes.measure(runtime.status(&admin)).await;
251 black_box(status?);
252 if round >= RENEWALS / 10 {
253 timings.push(timing);
254 }
255 }
256 timings.report(&format!("status_{flavor}"));
257 drop(admin);
258 runtime.shutdown_actor().await;
259
260 for capacity in [DEFAULT_TEMP_KEY_CAPACITY, MAX_TEMP_KEY_CAPACITY] {
261 let state_dir = TempPath::new("auth-bench-store");
262 let (runtime, admin) = start(&state_dir, capacity).await?;
263 for _ in 0..KEYS {
264 runtime.issue(&admin, HOUR, None).await?;
265 }
266 let mut timings = Timings::default();
267 for _ in 0..ROUNDS {
268 let (removed, timing) = probes.measure(runtime.gc(&admin)).await;
269 black_box(removed?);
270 timings.push(timing);
271 }
272 timings.report(&format!("gc{capacity}_{flavor}"));
273 drop(admin);
274 runtime.shutdown_actor().await;
275 drop(runtime);
277
278 let mut timings = Timings::default();
279 for _ in 0..ROUNDS {
280 let (started, timing) = probes
281 .measure(AuthRuntime::start(
282 TEST_ADMIN_KEY_BYTES,
283 config(&state_dir, capacity),
284 ))
285 .await;
286 timings.push(timing);
287 started?.shutdown_actor().await;
288 }
289 timings.report(&format!("start{capacity}_{flavor}"));
290 }
291
292 probes.stop().await;
293 Ok(())
294}
295
296fn current_thread() -> std::io::Result<Runtime> {
297 Builder::new_current_thread().enable_all().build()
298}
299
300fn multi_thread() -> std::io::Result<Runtime> {
301 Builder::new_multi_thread()
302 .worker_threads(WORKERS)
303 .enable_all()
304 .build()
305}
306
307fn main() -> BenchResult<()> {
308 current_thread()?.block_on(hot_path())?;
309 for (flavor, runtime, probes) in [
310 ("current", current_thread()?, 1),
311 ("multi", multi_thread()?, WORKERS),
312 ] {
313 runtime.block_on(async { tokio::spawn(persistence(flavor, probes)).await })??;
315 }
316 Ok(())
317}