Debian Codegraph @

crt/s2n/bindings/rust/standard/s2n-tls-metrics-subscriber/src/subscriber.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use s2n_tls_metrics_schema::record::FrozenHandshakeRecord;
5
6 use crate::{
7 Attribution, MetricRecord, detector::SyntheticTrafficDetector,
8 record::HandshakeRecordInProgress, telemetry_sink::TelemetrySink,
9 };
10 use arc_swap::ArcSwap;
11 use s2n_tls::events::EventSubscriber;
12 use std::{
13 sync::{
14 Arc, Mutex, OnceLock,
15 atomic::{AtomicU64, Ordering},
16 mpsc::{self, Receiver, Sender},
17 },
18 time::{Duration, SystemTime},
19 };
20
21 #[derive(Debug)]
22 struct ExportPipeline<S: TelemetrySink> {
23 metric_receiver: Receiver<FrozenHandshakeRecord>,
24 sink: S,
25 }
26
27 /// The AggregatedMetricSubscriber can be used to aggregate events over some period
28 /// of time, and then export them using a [`TelemetrySink`].
29 #[derive(Debug, Clone)]
30 pub struct AggregatedMetricsSubscriber<S: TelemetrySink> {
31 inner: Arc<MetricSubscriberInner<S>>,
32 }
33
34 /// The [`s2n_tls::events::EventSubscriber`] may be invoked concurrently, which
35 /// means that multiple threads might be incrementing the current record. To handle
36 /// this and ensure that the `HandshakeRecordInProgress` is never flushed while
37 /// an update is in progress we use an [`arc_swap::ArcSwap`].
38 ///
39 /// ArcSwap is basically an `Atomic<Arc<HandshakeRecordInProgress>>`
40 ///
41 /// We use this as a relatively intuitive form of synchronization. Once there
42 /// are no references to the HandshakeRecordInProgress (e.g. no threads updating
43 /// it) then its `drop` implementation will write it to the channel, where it can
44 /// then be read by the export pipeline.
45 #[derive(Debug)]
46 struct MetricSubscriberInner<S: TelemetrySink> {
47 current_record: ArcSwap<HandshakeRecordInProgress>,
48 /// This handle is not directly used, but is used when constructing new
49 /// HandshakeRecordInProgress items.
50 tx_handle: Sender<FrozenHandshakeRecord>,
51
52 // the mutex is necessary because s2n-tls callbacks must be Send + Sync
53 export_pipeline: Mutex<ExportPipeline<S>>,
54 attribution: Attribution,
55
56 /// If set, the subscriber will passively export the record when at least
57 /// this much time has elapsed since the last export. The check happens
58 /// inside `on_handshake_event`, so export is piggy-backed on handshake
59 /// traffic rather than requiring a background thread.
60 export_interval: Option<Duration>,
61 /// Epoch millis of the last successful export (or construction time).
62 /// Using an AtomicU64 so the fast-path check in `on_handshake_event`
63 /// doesn't need to acquire the export_pipeline mutex.
64 last_export_epoch_ms: AtomicU64,
65
66 /// Optional plug-in for marking handshakes as synthetic traffic.
67 /// Installed once via `with_synthetic_traffic_detector`; the hot path
68 /// reads it lock-free.
69 synthetic_detector: OnceLock<Box<dyn SyntheticTrafficDetector>>,
70 }
71
72 fn epoch_ms_now() -> u64 {
73 SystemTime::now()
74 .duration_since(SystemTime::UNIX_EPOCH)
75 .unwrap_or_default()
76 .as_millis() as u64
77 }
78
79 impl<S: TelemetrySink> AggregatedMetricsSubscriber<S> {
80 pub fn new(sink: S, attribution: Attribution) -> Self {
81 Self::build(sink, attribution, None)
82 }
83
84 /// Create a subscriber that passively exports the aggregated record
85 /// whenever at least `interval` has elapsed since the last export.
86 ///
87 /// The check is performed inside `on_handshake_event`, so no background
88 /// thread is needed — export is driven by handshake traffic. If there
89 /// are no handshakes for a long period, no export will occur until the
90 /// next handshake (or an explicit `finish_record()` call).
91 pub fn with_periodic_export(sink: S, attribution: Attribution, interval: Duration) -> Self {
92 Self::build(sink, attribution, Some(interval))
93 }
94
95 fn build(sink: S, attribution: Attribution, export_interval: Option<Duration>) -> Self {
96 let (tx, rx) = mpsc::channel();
97
98 let record = HandshakeRecordInProgress::new(tx.clone());
99
100 let export_pipe = ExportPipeline {
101 metric_receiver: rx,
102 sink,
103 };
104 let inner = MetricSubscriberInner {
105 current_record: ArcSwap::new(Arc::new(record)),
106 tx_handle: tx,
107 export_pipeline: Mutex::new(export_pipe),
108 attribution,
109 export_interval,
110 last_export_epoch_ms: AtomicU64::new(epoch_ms_now()),
111 synthetic_detector: OnceLock::new(),
112 };
113 Self {
114 inner: Arc::new(inner),
115 }
116 }
117
118 /// Install a detector that flags certain handshakes as synthetic traffic
119 /// (e.g. scanners, health-checks, load tests). When it returns `true`, the
120 /// subscriber bumps `synthetic_traffic_count` on the record and skips
121 /// every other counter for that handshake.
122 ///
123 /// Must be called before any handshake traffic begins. Subsequent calls
124 /// are silently ignored.
125 pub fn with_synthetic_traffic_detector(
126 self,
127 detector: Box<dyn SyntheticTrafficDetector>,
128 ) -> Self {
129 let _ = self.inner.synthetic_detector.set(detector);
130 self
131 }
132
133 /// Finish aggregation of the record and export it.
134 ///
135 /// Note that this method will block until all other in-flight updates of the
136 /// metric record are complete. This is generally very fast because updates
137 /// only consist of atomic integer updates, but latency-sensitive applications
138 /// should avoid calling this method in a tokio runtime, and using `spawn_blocking`
139 /// instead.
140 pub fn finish_record(&self) {
141 let export_pipeline = self.inner.export_pipeline.lock().unwrap();
142 self.finish_record_with_pipeline(&export_pipeline);
143 }
144
145 /// Shared export logic used by both `finish_record` and the passive export
146 /// path. The caller must already hold the pipeline lock.
147 fn finish_record_with_pipeline(&self, export_pipeline: &ExportPipeline<S>) {
148 let new_record = Arc::new(HandshakeRecordInProgress::new(self.inner.tx_handle.clone()));
149
150 let old_record = self.inner.current_record.swap(new_record);
151 // On drop, the record will be "frozen" and written to the channel
152 // This might not happen immediately because other threads might also hold
153 // a reference to the metric record
154 drop(old_record);
155
156 // This will block the thread until the record is received.
157 let handshake = export_pipeline.metric_receiver.recv().unwrap();
158 let record = MetricRecord::new(s2n_tls_metrics_schema::record::MetricRecord {
159 attribution: self.inner.attribution.clone().into_schema(),
160 handshake,
161 });
162 export_pipeline.sink.export_record(&record);
163 self.inner
164 .last_export_epoch_ms
165 .store(epoch_ms_now(), Ordering::Relaxed);
166 }
167
168 /// Check whether the export interval has elapsed and, if so, try to export.
169 ///
170 /// Uses `try_lock` so that the handshake thread is never blocked waiting
171 /// for an export that is already in progress on another thread.
172 fn try_periodic_export(&self) {
173 let interval = match self.inner.export_interval {
174 Some(d) => d,
175 None => return,
176 };
177
178 let last = self.inner.last_export_epoch_ms.load(Ordering::Relaxed);
179 let now = epoch_ms_now();
180 if now.saturating_sub(last) < interval.as_millis() as u64 {
181 return;
182 }
183
184 // try_lock: if another thread is already exporting, skip this attempt
185 if let Ok(pipeline) = self.inner.export_pipeline.try_lock() {
186 // Re-check after acquiring the lock — another thread may have
187 // exported between our check and the lock acquisition.
188 let last = self.inner.last_export_epoch_ms.load(Ordering::Relaxed);
189 if epoch_ms_now().saturating_sub(last) >= interval.as_millis() as u64 {
190 self.finish_record_with_pipeline(&pipeline);
191 }
192 }
193 }
194 }
195
196 impl<S: TelemetrySink> EventSubscriber for AggregatedMetricsSubscriber<S> {
197 fn on_handshake_event(
198 &self,
199 connection: &s2n_tls::connection::Connection,
200 event: &s2n_tls::events::HandshakeEvent,
201 ) {
202 let current_record = self.inner.current_record.load_full();
203 let detector = self
204 .inner
205 .synthetic_detector
206 .get()
207 .map(|boxed| boxed.as_ref());
208 let res = current_record.update(connection, event, detector);
209 // we never expect this to fail, but if it fails in production there is
210 // no meaningful way to handle the failure
211 debug_assert!(res.is_ok());
212 if let Err(e) = res {
213 tracing::error!("failed to update handshake record: {e}");
214 }
215 // Drop the Arc before attempting export so that finish_record can
216 // observe the final reference count drop.
217 drop(current_record);
218
219 self.try_periodic_export();
220 }
221 }
222
223 #[cfg(test)]
224 mod tests {
225 use crate::test_utils::{ARBITRARY_POLICY_1, TestEndpoint};
226
227 /// Verify that after a handshake and finish_record, the sink contains a record.
228 #[test]
229 fn record_is_exported() {
230 let endpoint = TestEndpoint::new();
231
232 endpoint.client_handshake(&ARBITRARY_POLICY_1);
233 endpoint.subscriber.finish_record();
234
235 let records = endpoint.sink.records.lock().unwrap();
236 assert_eq!(records.len(), 1);
237 }
238
239 /// Verify that finish_record blocks while another thread holds a reference
240 /// to the current record (via ArcSwap load_full).
241 #[test]
242 fn export_blocking() {
243 let endpoint = TestEndpoint::new();
244
245 endpoint.client_handshake(&ARBITRARY_POLICY_1);
246
247 // Load a reference to the current record, preventing it from being dropped
248 let held_record = endpoint.subscriber.inner.current_record.load_full();
249
250 let subscriber = endpoint.subscriber.clone();
251 let handle = std::thread::spawn(move || {
252 subscriber.finish_record();
253 });
254
255 // The finish_record call should be blocked because we hold a reference
256 // Give it a moment to ensure it's actually blocked
257 std::thread::sleep(std::time::Duration::from_millis(100));
258 assert!(
259 !handle.is_finished(),
260 "finish_record should block while record reference is held"
261 );
262
263 // Drop the held reference to unblock finish_record
264 drop(held_record);
265 handle.join().unwrap();
266
267 let records = endpoint.sink.records.lock().unwrap();
268 assert_eq!(records.len(), 1);
269 }
270
271 /// Multiple finish_record() calls should each produce a separate record
272 /// in the sink, and records should accumulate in order.
273 #[test]
274 fn multiple_finish_record_buffering() {
275 let endpoint = TestEndpoint::new();
276
277 // First batch: 2 handshakes
278 endpoint.client_handshake(&ARBITRARY_POLICY_1);
279 endpoint.client_handshake(&ARBITRARY_POLICY_1);
280 endpoint.subscriber.finish_record();
281
282 // Second batch: 1 handshake
283 endpoint.client_handshake(&ARBITRARY_POLICY_1);
284 endpoint.subscriber.finish_record();
285
286 // Third: empty record (no handshakes)
287 endpoint.subscriber.finish_record();
288
289 let records = endpoint.sink.records.lock().unwrap();
290 assert_eq!(
291 records.len(),
292 3,
293 "expected 3 records from 3 finish_record calls"
294 );
295
296 // Verify handshake counts
297 assert_eq!(records[0].as_schema().handshake.handshake_success_count, 2);
298 assert_eq!(records[1].as_schema().handshake.handshake_success_count, 1);
299 assert_eq!(records[2].as_schema().handshake.handshake_success_count, 0);
300 }
301
302 /// Passive export: when the interval has elapsed, the next handshake
303 /// triggers an automatic export without an explicit finish_record call.
304 #[test]
305 fn passive_export_triggers_on_handshake() {
306 use crate::{AggregatedMetricsSubscriber, Attribution, test_utils::VecSink};
307 use s2n_tls::{
308 security::DEFAULT_TLS13,
309 testing::{build_config, config_builder},
310 };
311 use std::time::Duration;
312
313 let sink = VecSink::new();
314 let attribution = Attribution {
315 service: "test_server".to_owned(),
316 resource: "test_resource".to_owned(),
317 component: "test_component".to_owned(),
318 };
319 // Use a zero-duration interval so every handshake triggers an export
320 let subscriber = AggregatedMetricsSubscriber::with_periodic_export(
321 sink.clone(),
322 attribution,
323 Duration::ZERO,
324 );
325 let server_config = {
326 let mut config = config_builder(&DEFAULT_TLS13).unwrap();
327 config.set_event_subscriber(subscriber.clone()).unwrap();
328 config.build().unwrap()
329 };
330
331 let client_config = build_config(&ARBITRARY_POLICY_1).unwrap();
332 let mut pair = s2n_tls::testing::TestPair::from_configs(&client_config, &server_config);
333 pair.handshake().unwrap();
334
335 // The handshake itself should have triggered a passive export
336 let records = sink.records.lock().unwrap();
337 assert_eq!(
338 records.len(),
339 1,
340 "passive export should have produced a record"
341 );
342 }
343
344 /// When a synthetic-traffic detector is configured and matches, only
345 /// `synthetic_traffic_count` is bumped.
346 #[test]
347 fn synthetic_traffic_detector_increments_count() {
348 use crate::{
349 AggregatedMetricsSubscriber, Attribution, SyntheticTrafficDetector, test_utils::VecSink,
350 };
351 use s2n_tls::{
352 client_hello::ClientHello,
353 security::DEFAULT_TLS13,
354 testing::{TestPair, build_config, config_builder},
355 };
356 use std::sync::{
357 Arc,
358 atomic::{AtomicBool, Ordering},
359 };
360
361 #[derive(Debug)]
362 struct ToggleDetector(Arc<AtomicBool>);
363 impl SyntheticTrafficDetector for ToggleDetector {
364 fn is_synthetic(&self, _ch: &ClientHello) -> bool {
365 self.0.load(Ordering::Relaxed)
366 }
367 }
368
369 let toggle = Arc::new(AtomicBool::new(false));
370 let sink = VecSink::new();
371 let attribution = Attribution {
372 service: "test_server".to_owned(),
373 resource: "test_resource".to_owned(),
374 component: "test_component".to_owned(),
375 };
376 let subscriber = AggregatedMetricsSubscriber::new(sink.clone(), attribution)
377 .with_synthetic_traffic_detector(Box::new(ToggleDetector(toggle.clone())));
378 let server_config = {
379 let mut cfg = config_builder(&DEFAULT_TLS13).unwrap();
380 cfg.set_event_subscriber(subscriber.clone()).unwrap();
381 cfg.build().unwrap()
382 };
383 let client_config = build_config(&ARBITRARY_POLICY_1).unwrap();
384
385 // 2 "real" handshakes, then 3 "synthetic" ones.
386 for _ in 0..2 {
387 TestPair::from_configs(&client_config, &server_config)
388 .handshake()
389 .unwrap();
390 }
391 toggle.store(true, Ordering::Relaxed);
392 for _ in 0..3 {
393 TestPair::from_configs(&client_config, &server_config)
394 .handshake()
395 .unwrap();
396 }
397
398 subscriber.finish_record();
399 let records = sink.records.lock().unwrap();
400 assert_eq!(records.len(), 1);
401 let record = &records[0].as_schema().handshake;
402
403 assert_eq!(record.handshake_success_count, 2);
404 assert_eq!(record.synthetic_traffic_count, 3);
405 assert_eq!(record.negotiated_protocols.total(), 2);
406 assert_eq!(record.negotiated_ciphers.total(), 2);
407 }
408
409 /// With no detector installed, `synthetic_traffic_count` stays at zero
410 /// regardless of handshake volume.
411 #[test]
412 fn synthetic_traffic_count_zero_when_no_detector() {
413 let endpoint = TestEndpoint::new();
414 endpoint.client_handshake(&ARBITRARY_POLICY_1);
415 endpoint.client_handshake(&ARBITRARY_POLICY_1);
416 endpoint.subscriber.finish_record();
417
418 let records = endpoint.sink.records.lock().unwrap();
419 assert_eq!(records[0].as_schema().handshake.handshake_success_count, 2);
420 assert_eq!(records[0].as_schema().handshake.synthetic_traffic_count, 0);
421 }
422 }