Debian Codegraph @

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

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Demonstrates how to wire an `AggregatedMetricsSubscriber` into an s2n-tls
5 //! config, perform handshakes, and export the aggregated metrics as JSON.
6 //!
7 //! The subscriber is tagged with an `Attribution` so that the exported record
8 //! identifies which service and resource produced the metrics.
9 //!
10 //! The `TelemetrySink` receives a `MetricRecord` which implements
11 //! `serde::Serialize`, so the sink decides the serialization format.
12
13 use std::{
14 io::{self, Write},
15 time::Duration,
16 };
17
18 use s2n_tls::{
19 security::DEFAULT_TLS13,
20 testing::{TestPair, build_config, config_builder},
21 };
22
23 use s2n_tls_metrics_subscriber::{
24 AggregatedMetricsSubscriber, Attribution, MetricRecord, TelemetrySink,
25 };
26
27 /// Example TelemetrySink that serializes each record as JSON and writes it
28 /// to stdout. Applications can implement TelemetrySink to route records to
29 /// any destination and serialize in any format (JSON, CBOR, etc.).
30 #[derive(Clone)]
31 struct StdoutJsonSink;
32
33 impl TelemetrySink for StdoutJsonSink {
34 fn export_record(&self, record: &MetricRecord) {
35 let stdout = io::stdout();
36 let mut handle = stdout.lock();
37 // MetricRecord implements serde::Serialize, so we can use serde_json
38 if let Err(e) = serde_json::to_writer(&mut handle, record) {
39 eprintln!("failed to serialize metric record: {e}");
40 return;
41 }
42 let _ = handle.write_all(b"\n");
43 let _ = handle.flush();
44 }
45 }
46
47 fn main() {
48 let attribution = Attribution {
49 service: "my-service".to_owned(),
50 resource: "test-resource".to_owned(),
51 component: "frontend".to_owned(),
52 };
53
54 // Passive periodic export: the subscriber will automatically export
55 // the aggregated record during handshake processing once 60 seconds
56 // have elapsed since the last export. No background thread needed.
57 let subscriber = AggregatedMetricsSubscriber::with_periodic_export(
58 StdoutJsonSink,
59 attribution,
60 Duration::from_secs(60),
61 );
62
63 // Wire the subscriber into a server config so handshake events flow into it.
64 let server_config = {
65 let mut builder = config_builder(&DEFAULT_TLS13).unwrap();
66 builder.set_event_subscriber(subscriber.clone()).unwrap();
67 builder.build().unwrap()
68 };
69 let client_config = build_config(&DEFAULT_TLS13).unwrap();
70
71 // Perform a few handshakes so there is real data to export.
72 for _ in 0..3 {
73 let mut pair = TestPair::from_configs(&client_config, &server_config);
74 pair.handshake().unwrap();
75 }
76
77 // Final flush — export any remaining accumulated metrics.
78 subscriber.finish_record();
79 }