terracotta 0.4.2

Boilerplate webserver application based on Axum
Documentation
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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#![allow(unused_qualifications,      reason = "False positive")]
#![allow(clippy::exhaustive_structs, reason = "Handlers have auto-generated OpenAPI documentation")]
#![allow(clippy::unused_async,       reason = "Handler functions need to be async")]

//! Endpoint handlers for statistics functionality.



//		Modules																											

#[cfg(test)]
#[path = "tests/handlers.rs"]
mod tests;



//		Packages																										

use super::{
	requests::{GetStatsFeedParams, GetStatsHistoryParams, MeasurementType},
	responses::{StatsHistoryResponse, StatsResponse, StatsResponseForPeriod},
	state::StateProvider,
	worker::StatsForPeriod,
};
use axum::{
	Json,
	extract::{Query, State},
	extract::ws::{Message, WebSocketUpgrade, WebSocket},
	response::Response,
};
use chrono::{NaiveDateTime, SubsecRound as _, Utc};
use core::{
	sync::atomic::Ordering,
	time::Duration,
};
use indexmap::IndexMap;
use itertools::Itertools as _;
use rubedo::{
	std::IteratorExt as _,
	sugar::s,
};
use serde_json::json;
use std::{
	collections::{HashMap, VecDeque},
	sync::Arc,
	time::Instant,
};
use tokio::{
	select,
	time::interval,
};
use tracing::{info, warn};
use velcro::btree_map;



//		Functions																										

//		get_stats																
/// Application statistics overview.
/// 
/// This endpoint produces various statistics about the application. It returns
/// a JSON object containing the following information:
/// 
///   - `started_at`  - The date and time the application was started, in ISO
///                     8601 format.
///   - `last_second` - The latest second period that has been completed.
///   - `uptime`      - The amount of time the application has been running, in
///                     seconds.
///   - `requests`    - The number of requests that have been handled since the
///                     application last started.
///   - `active`      - The number of current open connections.
///   - `codes`       - The counts of responses that have been handled, broken
///                     down by status code, since the application last started.
///   - `times`       - The average, maximum, and minimum response times, plus
///                     sample count, for the [configured periods](super::config::Config#structfield.periods),
///                     and since the application last started.
///   - `endpoints`   - The counts of responses that have been handled, broken
///                     down by endpoint, since the application last started.
///   - `connections` - The average, maximum, and minimum open connections, plus
///                     sample count, for the [configured periods](super::config::Config#structfield.periods),
///                     and since the application last started.
///   - `memory`      - The average, maximum, and minimum memory usage, plus
///                     sample count, for the [configured periods](super::config::Config#structfield.periods),
///                     and since the application last started.
/// 
/// # Parameters
/// 
/// * `state` - The application state.
/// 
#[cfg_attr(feature = "utoipa", utoipa::path(
	get,
	path = "/api/stats",
	tag  = "health",
	responses(
		(status = 200, description = "Application statistics overview", body = StatsResponse),
	)
))]
pub async fn get_stats<SP: StateProvider>(
	State(state): State<Arc<SP>>,
) -> Json<StatsResponse> {
	//		Helper functions													
	/// Initialises a map of stats for each period.
	fn initialize_map(
		periods: &HashMap<String, usize>,
		buffer:  &VecDeque<StatsForPeriod>,
	) -> IndexMap<String, StatsForPeriod> {
		let mut output: IndexMap<String, StatsForPeriod> = periods
			.iter()
			.sorted_by_key(|p| p.1)
			.map(|(name, _)| (name.clone(), StatsForPeriod::default()))
			.collect()
		;
		//	Loop through the circular buffer and calculate the stats
		for (i, stats) in buffer.iter().enumerate() {
			for (name, stats_for_period) in &mut output {
				if i < periods[name] {
					stats_for_period.update(stats);
				}
			}
		}
		output
	}
	
	/// Converts a map of stats for each period into response data.
	fn convert_map(
		input: IndexMap<String, StatsForPeriod>,
		all:   &StatsForPeriod
	) -> IndexMap<String, StatsResponseForPeriod> {
		let mut output: IndexMap<String, StatsResponseForPeriod> = input
			.into_iter()
			.map(|(key, value)| (key, StatsResponseForPeriod::from(&value)))
			.collect()
		;
		_ = output.insert(s!("all"), StatsResponseForPeriod::from(all));
		output
	}
	
	//		Preparation															
	//	Lock source data
	let stats_state  = state.state().read().await;
	let buffers      = stats_state.data.buffers.read();
	
	//	Create pots for each period and process stats buffers
	let timing_input = initialize_map(&state.config().periods, &buffers.responses);
	let conn_input   = initialize_map(&state.config().periods, &buffers.connections);
	let memory_input = initialize_map(&state.config().periods, &buffers.memory);
	
	//	Unlock source data
	drop(buffers);
	
	//		Process stats														
	//	Lock source data
	let totals        = stats_state.data.totals.lock();
	
	//	Convert the input stats data into the output stats data
	let timing_output = convert_map(timing_input, &totals.times);
	let conn_output   = convert_map(conn_input,   &totals.connections);
	let memory_output = convert_map(memory_input, &totals.memory);
	
	//		Build response data													
	let now      = Utc::now().naive_utc();
	#[expect(clippy::arithmetic_side_effects, reason = "Nothing interesting can happen here")]
	#[expect(clippy::cast_sign_loss,          reason = "We don't ever want a negative for uptime")]
	let response = Json(StatsResponse {
		started_at:  stats_state.data.started_at.trunc_subsecs(0),
		last_second: *stats_state.data.last_second.read(),
		uptime:      (now - stats_state.data.started_at).num_seconds() as u64,
		active:      stats_state.data.connections.load(Ordering::Relaxed) as u64,
		requests:    stats_state.data.requests.load(Ordering::Relaxed) as u64,
		codes:       totals.codes.clone(),
		times:       timing_output,
		endpoints:   totals.endpoints.iter()
			.map(|(key, value)| (key.clone(), StatsResponseForPeriod::from(value)))
			.collect()
		,
		connections: conn_output,
		memory:      memory_output,
	});
	//	Unlock source data
	drop(totals);
	drop(stats_state);
	
	//		Response															
	response
}

//		get_stats_history														
/// Historical application statistics interval data.
/// 
/// This endpoint provides access to historical application statistics interval
/// data available from the statistics buffers. It returns a JSON object
/// containing the following information:
/// 
///   - `last_second` - The latest second period that has been completed.
///   - `times`       - The average, maximum, and minimum response times, plus
///                     sample count, per second for every second since the
///                     application last started, or up until the end of the
///                     [configured buffer](super::config::Config#structfield.timing_buffer_size).
///   - `connections` - The average, maximum, and minimum open connections, plus
///                     sample count, per second for every second since the
///                     application last started, or up until the end of the
///                     [configured buffer](super::config::Config#structfield.connection_buffer_size).
///   - `memory`      - The average, maximum, and minimum memory usage, plus
///                     sample count, per second for every second since the
///                     application last started, or up until the end of the
///                     [configured buffer](super::config::Config#structfield.memory_buffer_size).
/// 
/// # Parameters
/// 
/// * `state`  - The application state.
/// * `params` - The parameters for the request.
/// 
#[cfg_attr(feature = "utoipa", utoipa::path(
	get,
	path = "/api/stats/history",
	tag  = "health",
	params(
		GetStatsHistoryParams,
	),
	responses(
		(status = 200, description = "Historical application statistics interval data", body = StatsHistoryResponse),
	)
))]
pub async fn get_stats_history<SP: StateProvider>(
	State(state):  State<Arc<SP>>,
	Query(params): Query<GetStatsHistoryParams>,
) -> Json<StatsHistoryResponse> {
	//		Helper function														
	/// Processes a buffer of statistics data.
	fn process_buffer(
		buffer: &VecDeque<StatsForPeriod>,
		from:   Option<NaiveDateTime>,
		limit:  Option<usize>,
	) -> Vec<StatsResponseForPeriod> {
		buffer.iter()
			.take_while(|entry| from.is_none_or(|time| entry.started_at >= time))
			.limit(limit)
			.map(StatsResponseForPeriod::from)
			.collect()
	}
	
	//		Prepare response data												
	//	Lock source data
	let stats_state  = state.state().read().await;
	let buffers      = stats_state.data.buffers.read();
	let mut response = StatsHistoryResponse {
		last_second:   *stats_state.data.last_second.read(),
		..Default::default()
	};
	//	Convert the statistics buffers
	match params.buffer {
		Some(MeasurementType::Times) => {
			response.times       = process_buffer(&buffers.responses,   params.from, params.limit);
		},
		Some(MeasurementType::Connections) => {
			response.connections = process_buffer(&buffers.connections, params.from, params.limit);
		},
		Some(MeasurementType::Memory) => {
			response.memory      = process_buffer(&buffers.memory,      params.from, params.limit);
		},
		None => {
			response.times       = process_buffer(&buffers.responses,   params.from, params.limit);
			response.connections = process_buffer(&buffers.connections, params.from, params.limit);
			response.memory      = process_buffer(&buffers.memory,      params.from, params.limit);
		},
	}
	//	Unlock source data
	drop(buffers);
	drop(stats_state);
	Json(response)
}

//		get_stats_feed															
/// Application statistics event feed.
/// 
/// This endpoint returns an open WebSocket connection for a feed of statistics
/// events. It will establish a handshake with the [`WebSocket`] and then pass
/// over to [`ws_stats_feed()`] to handle the connection. This function will
/// then return a [`Response`] with a status code of `101 Switching Protocols`
/// and the `Connection` header set to `Upgrade`.
/// 
/// # Parameters
/// 
/// * `state`  - The application state.
/// * `params` - The parameters for the request.
/// * `ws_req` - The websocket request.
/// 
#[cfg_attr(feature = "utoipa", utoipa::path(
	get,
	path = "/api/stats/feed",
	tag  = "health",
	params(
		GetStatsFeedParams,
	),
	responses(
		(status = 200, description = "Application statistics event feed"),
	),
))]
pub async fn get_stats_feed<SP: StateProvider>(
	State(state):  State<Arc<SP>>,
	Query(params): Query<GetStatsFeedParams>,
	ws_req:        WebSocketUpgrade,
) -> Response {
	//	Establish a handshake with the WebSocket
	ws_req.on_upgrade(move |socket| ws_stats_feed(Arc::clone(&state), socket, params.r#type))
}

//		ws_stats_feed															
/// WebSocket feed of application statistics events.
/// 
/// This endpoint returns a feed of application statistics over a WebSocket
/// connection established by [`get_stats_feed()`]. Statistics events are sent
/// as they are received from the broadcast channel. The events are
/// [`StatsForPeriod`] instances, sent as JSON objects.
/// 
/// Notably, if not filtered by measurement type, all measurement types will
/// have their statistics returned in a JSON object, with the type names as keys
/// and the statistics data in sub-objects. However, when filtered by type, only
/// the statistics object for that one type will be returned. This is in order
/// to keep the transmitted data as efficient as possible.
/// 
/// # Parameters
/// 
/// * `state` - The application state.
/// * `ws`    - The websocket stream.
/// * `scope` - The type of measurement statistics to send.
/// 
#[expect(clippy::similar_names, reason = "Clearly different")]
pub async fn ws_stats_feed<SP: StateProvider>(
	state:  Arc<SP>,
	mut ws: WebSocket,
	scope:  Option<MeasurementType>,
) {
	//		Preparation															
	info!("WebSocket connection established");
	//	Subscribe to the broadcast channel
	let mut rx = if let Some(ref broadcaster) = state.state().read().await.broadcaster {
		broadcaster.subscribe()
	} else {
		warn!("Broadcast channel not available");
		return;
	};
	//	Set up a timer to send pings at regular intervals
	let mut timer     = interval(Duration::from_secs(state.config().ws_ping_interval as u64));
	let mut timeout   = interval(Duration::from_secs(state.config().ws_ping_timeout  as u64));
	let mut last_ping = None;
	let mut last_pong = Instant::now();
	
	//	Message processing loop
	#[expect(clippy::pattern_type_mismatch, reason = "Tokio code")]
	loop { select! {
		//		Ping															
		//	Send a ping at regular intervals
		_ = timer.tick() => {
			if let Err(err) = ws.send(Message::Ping(Vec::new().into())).await {
				warn!("Failed to send ping over WebSocket: {err}");
				break;
			}
			last_ping = Some(Instant::now());
		},
		
		//		Ping/pong timeout												
		//	Check for ping timeout (X seconds since the last ping without a pong)
		_ = timeout.tick() => {
			if let Some(ping_time) = last_ping {
				let limit = Duration::from_secs(state.config().ws_ping_timeout as u64);
				if last_pong < ping_time && ping_time.elapsed() > limit {
					warn!("WebSocket ping timed out");
					break;
				}
			}
		},
		
		//		Incoming message												
		//	Handle incoming messages from the WebSocket
		Some(msg) = ws.recv() => {
			match msg {
				Ok(Message::Ping(ping)) => {
					if let Err(err) = ws.send(Message::Pong(ping)).await {
						warn!("Failed to send pong over WebSocket: {err}");
						break;
					}
				}
				Ok(Message::Pong(_)) => {
					last_pong = Instant::now();
				}
				Ok(Message::Close(_)) => {
					info!("WebSocket connection closed");
					break;
				}
				Ok(Message::Text(_)) => {
					warn!("Unexpected WebSocket text message");
				}
				Ok(Message::Binary(_)) => {
					warn!("Unexpected WebSocket binary message");
				}
				Err(err) => {
					warn!("WebSocket error: {err}");
					break;
				}
				#[expect(unreachable_patterns, reason = "Future-proofing")]
				_ => {
					//	At present there are no other message types, but this is here to catch
					//	any future additions.
					warn!("Unknown WebSocket message type");
				}
			}	
		}
		
		//		Send stats data													
		//	Handle new data from the broadcast channel
		Ok(data) = rx.recv() => {
			let response = match scope {
				Some(MeasurementType::Times)  => {
					json!{StatsResponseForPeriod::from(&data.times)}
				},
				Some(MeasurementType::Connections) => {
					json!{StatsResponseForPeriod::from(&data.connections)}
				},
				Some(MeasurementType::Memory) => {
					json!{StatsResponseForPeriod::from(&data.memory)}
				},
				None => {
					json!{btree_map!{
						"times":       StatsResponseForPeriod::from(&data.times),
						"connections": StatsResponseForPeriod::from(&data.connections),
						"memory":      StatsResponseForPeriod::from(&data.memory),
					}}
				},
			};
			if let Err(err) = ws.send(Message::Text(response.to_string().into())).await {
				warn!("Failed to send data over WebSocket: {err}");
				break;
			}
		}
	}}
}