footing 0.4.2

Feature-gated foundations for Rust backend services
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
//! Tracing configuration, context, and subscriber initialization.

use std::fmt;

use serde::{Deserialize, Deserializer, Serialize};
use time::{UtcOffset, format_description::well_known::Rfc3339};
use tracing::{Event, Subscriber};
use tracing_subscriber::{
    EnvFilter,
    fmt::{
        self as tracing_fmt, FmtContext, FormattedFields,
        format::{FormatEvent, JsonFields, Writer},
        time::{FormatTime, OffsetTime},
    },
    layer::SubscriberExt,
    registry::LookupSpan,
    util::SubscriberInitExt,
};

use super::error::ObservabilityError;

const RUST_LOG_ENV: &str = "RUST_LOG";
const MAX_TRACE_CONTEXT_VALUE_LENGTH: usize = 128;
/// Maximum supported tracing service name length.
pub const MAX_TRACING_SERVICE_NAME_LENGTH: usize = 128;

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Runtime configuration for tracing.
///
/// The service name is validated at construction and cannot be changed.
pub struct TracingConfig {
    service_name: String,
    json: bool,
    env_filter: Option<String>,
    time_zone: LogTimeZone,
}

impl TracingConfig {
    /// Creates a configuration with a validated service name.
    pub fn new(service_name: impl Into<String>) -> Result<Self, ObservabilityError> {
        let service_name = service_name.into().trim().to_owned();
        validate_service_name(&service_name)?;
        Ok(Self {
            service_name,
            json: false,
            env_filter: None,
            time_zone: LogTimeZone::Utc,
        })
    }

    #[must_use]
    /// Configures JSON and returns the updated value.
    pub fn with_json(mut self, json: bool) -> Self {
        self.json = json;
        self
    }

    #[must_use]
    /// Configures env filter and returns the updated value.
    pub fn with_env_filter(mut self, env_filter: impl Into<String>) -> Self {
        self.env_filter = Some(env_filter.into().trim().to_owned());
        self
    }

    #[must_use]
    /// Configures time zone and returns the updated value.
    pub const fn with_time_zone(mut self, time_zone: LogTimeZone) -> Self {
        self.time_zone = time_zone;
        self
    }

    #[must_use]
    /// Returns the service name.
    pub fn service_name(&self) -> &str {
        &self.service_name
    }

    #[must_use]
    /// Returns the JSON.
    pub const fn json(&self) -> bool {
        self.json
    }

    #[must_use]
    /// Returns the env filter.
    pub fn env_filter(&self) -> Option<&str> {
        self.env_filter.as_deref()
    }

    #[must_use]
    /// Returns the time zone.
    pub const fn time_zone(&self) -> LogTimeZone {
        self.time_zone
    }
}

/// Timestamp timezone used by tracing output.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum LogTimeZone {
    /// RFC3339 UTC timestamps.
    #[default]
    Utc,
    /// RFC3339 timestamps using the process local UTC offset captured at startup.
    Local,
}

impl LogTimeZone {
    /// Returns the stable configuration.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Utc => "utc",
            Self::Local => "local",
        }
    }
}

/// Both formats use JsonFields' bounded, replace-on-record span cache.
struct ServiceEventFormat<T> {
    service_name: String,
    json: bool,
    timer: T,
}

impl<S, T> FormatEvent<S, JsonFields> for ServiceEventFormat<T>
where
    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
    T: FormatTime,
{
    fn format_event(
        &self,
        context: &FmtContext<'_, S, JsonFields>,
        mut writer: Writer<'_>,
        event: &Event<'_>,
    ) -> fmt::Result {
        let mut timestamp = String::new();
        self.timer.format_time(&mut Writer::new(&mut timestamp))?;
        let metadata = event.metadata();
        let mut fields = EventFields::default();
        event.record(&mut fields);
        let mut spans = Vec::new();
        if let Some(scope) = context.event_scope() {
            for span in scope.from_root() {
                let extensions = span.extensions();
                let cached = extensions
                    .get::<FormattedFields<JsonFields>>()
                    .ok_or(fmt::Error)?;
                let mut fields: serde_json::Map<String, serde_json::Value> =
                    serde_json::from_str(&cached.fields).map_err(|_| fmt::Error)?;
                fields.insert("name".into(), span.name().into());
                fields.insert("service_name".into(), self.service_name.clone().into());
                spans.push(fields);
            }
        }
        if self.json {
            #[derive(Serialize)]
            struct JsonEvent<'a> {
                timestamp: &'a str,
                level: &'a str,
                service_name: &'a str,
                target: &'a str,
                fields: &'a serde_json::Map<String, serde_json::Value>,
                #[serde(skip_serializing_if = "Option::is_none")]
                span: Option<&'a serde_json::Map<String, serde_json::Value>>,
                #[serde(skip_serializing_if = "Option::is_none")]
                spans: Option<&'a [serde_json::Map<String, serde_json::Value>]>,
            }
            let output = serde_json::to_string(&JsonEvent {
                timestamp: &timestamp,
                level: metadata.level().as_str(),
                service_name: &self.service_name,
                target: metadata.target(),
                fields: &fields.0,
                span: spans.last(),
                spans: (!spans.is_empty()).then_some(spans.as_slice()),
            })
            .map_err(|_| fmt::Error)?;
            writeln!(writer, "{output}")
        } else {
            if !timestamp.is_empty() {
                write!(writer, "{timestamp} ")?;
            }
            write!(writer, "{:>5} ", metadata.level())?;
            for span in spans {
                write!(writer, "{}{{", span["name"].as_str().ok_or(fmt::Error)?)?;
                write_text_fields(&mut writer, &span, Some("name"))?;
                writer.write_str("}: ")?;
            }
            write!(writer, "{}: ", metadata.target())?;
            write_text_fields(&mut writer, &fields.0, None)?;
            writeln!(writer, " service_name={:?}", self.service_name)
        }
    }
}

fn write_text_fields(
    writer: &mut Writer<'_>,
    fields: &serde_json::Map<String, serde_json::Value>,
    skip: Option<&str>,
) -> fmt::Result {
    let mut separator = "";
    for (key, value) in fields {
        if Some(key.as_str()) == skip {
            continue;
        }
        write!(writer, "{separator}{key}={value}")?;
        separator = " ";
    }
    Ok(())
}

#[derive(Default)]
struct EventFields(serde_json::Map<String, serde_json::Value>);

impl tracing::field::Visit for EventFields {
    fn record_f64(&mut self, field: &tracing::field::Field, value: f64) {
        self.0.insert(field.name().into(), value.into());
    }

    fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
        self.0.insert(field.name().into(), value.into());
    }

    fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
        self.0.insert(field.name().into(), value.into());
    }

    fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
        self.0.insert(field.name().into(), value.into());
    }

    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
        self.0.insert(field.name().into(), value.into());
    }

    fn record_bytes(&mut self, field: &tracing::field::Field, value: &[u8]) {
        self.0.insert(field.name().into(), value.into());
    }

    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn fmt::Debug) {
        let name = field.name().strip_prefix("r#").unwrap_or(field.name());
        self.0.insert(name.into(), format!("{value:?}").into());
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
/// Context associated with trace.
pub struct TraceContext {
    trace_id: Option<String>,
    span_id: Option<String>,
    request_id: Option<String>,
}

impl TraceContext {
    #[must_use]
    /// Creates a new instance.
    pub fn new(
        trace_id: Option<String>,
        span_id: Option<String>,
        request_id: Option<String>,
    ) -> Self {
        Self {
            trace_id: normalize_trace_context_value(trace_id),
            span_id: normalize_trace_context_value(span_id),
            request_id: normalize_trace_context_value(request_id),
        }
    }

    #[must_use]
    /// Returns the trace identifier.
    pub fn trace_id(&self) -> Option<&str> {
        self.trace_id.as_deref()
    }

    #[must_use]
    /// Returns the span identifier.
    pub fn span_id(&self) -> Option<&str> {
        self.span_id.as_deref()
    }

    #[must_use]
    /// Returns the request identifier.
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_deref()
    }

    #[must_use]
    /// Returns whether the collection is empty.
    pub const fn is_empty(&self) -> bool {
        self.trace_id.is_none() && self.span_id.is_none() && self.request_id.is_none()
    }
}

impl<'de> Deserialize<'de> for TraceContext {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct TraceContextWire {
            #[serde(default)]
            trace_id: Option<String>,
            #[serde(default)]
            span_id: Option<String>,
            #[serde(default)]
            request_id: Option<String>,
        }

        let wire = TraceContextWire::deserialize(deserializer)?;
        Ok(Self::new(wire.trace_id, wire.span_id, wire.request_id))
    }
}

/// Builds a formatting layer without installing a subscriber or a filter.
///
/// The layer owns its configuration. Customize its writer with `with_writer`,
/// then combine it with application tracing layers. Apply [`tracing_filter`]
/// to this layer when other layers need independent filtering, or to the
/// subscriber for a global filter. Neither function installs a subscriber.
///
/// ```rust
/// use footing::observability::{TracingConfig, tracing_filter, tracing_layer};
/// use tracing_subscriber::prelude::*;
///
/// let config = TracingConfig::new("inventory")?.with_json(true);
/// let logs = tracing_layer(&config)?
///     .with_writer(std::io::stderr)
///     .with_filter(tracing_filter(&config)?);
/// let subscriber = tracing_subscriber::registry().with(logs);
/// // Add application layers here, then install the subscriber once at startup.
/// # let _ = subscriber;
/// # Ok::<(), footing::observability::ObservabilityError>(())
/// ```
pub fn tracing_layer<S>(
    config: &TracingConfig,
) -> Result<
    tracing_fmt::Layer<
        S,
        JsonFields,
        impl FormatEvent<S, JsonFields> + Send + Sync + 'static + use<S>,
    >,
    ObservabilityError,
>
where
    S: Subscriber + for<'lookup> LookupSpan<'lookup>,
{
    let timer = match config.time_zone {
        LogTimeZone::Utc => OffsetTime::new(UtcOffset::UTC, Rfc3339),
        LogTimeZone::Local => {
            OffsetTime::local_rfc_3339().map_err(ObservabilityError::LocalTimeOffset)?
        }
    };

    Ok(tracing_fmt::layer()
        .with_ansi(false)
        .fmt_fields(JsonFields::new())
        .event_format(ServiceEventFormat {
            service_name: config.service_name.clone(),
            json: config.json,
            timer,
        }))
}

/// Builds the tracing filter, using nonempty `RUST_LOG` before the configured
/// filter, then falling back to `info,tower_http=info`.
///
/// Invalid filters return an error. Use the returned native `EnvFilter` globally
/// or on an individual layer; building it does not install a subscriber.
pub fn tracing_filter(config: &TracingConfig) -> Result<EnvFilter, ObservabilityError> {
    env_filter_from(config, std::env::var(RUST_LOG_ENV).ok())
}

/// Installs Footing's formatting layer and filter as the global subscriber.
///
/// Applications composing multiple layers should use [`tracing_layer`] and
/// [`tracing_filter`] and install their completed subscriber themselves.
///
/// ```no_run
/// use footing::observability::{TracingConfig, init};
///
/// let config = TracingConfig::new("inventory")?.with_json(true);
/// init(&config)?;
/// # Ok::<(), footing::observability::ObservabilityError>(())
/// ```
pub fn init(config: &TracingConfig) -> Result<(), ObservabilityError> {
    tracing_subscriber::registry()
        .with(tracing_filter(config)?)
        .with(tracing_layer(config)?)
        .try_init()?;

    Ok(())
}

pub(super) fn env_filter_from(
    config: &TracingConfig,
    env_value: Option<String>,
) -> Result<EnvFilter, ObservabilityError> {
    if let Some(value) = env_value
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        return Ok(EnvFilter::try_new(value)?);
    }

    if let Some(value) = config
        .env_filter
        .as_deref()
        .map(str::trim)
        .filter(|value| !value.is_empty())
    {
        return Ok(EnvFilter::try_new(value)?);
    }

    Ok(EnvFilter::try_new("info,tower_http=info")?)
}

fn validate_service_name(value: &str) -> Result<(), ObservabilityError> {
    if value.is_empty()
        || value.len() > MAX_TRACING_SERVICE_NAME_LENGTH
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return Err(ObservabilityError::InvalidServiceName);
    }

    Ok(())
}

fn normalize_trace_context_value(value: Option<String>) -> Option<String> {
    let value = value?.trim().to_owned();
    if value.is_empty()
        || value.len() > MAX_TRACE_CONTEXT_VALUE_LENGTH
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
    {
        return None;
    }

    Some(value)
}

#[cfg(test)]
mod tests {
    use std::{
        io,
        sync::{Arc, Mutex},
    };

    use tracing_subscriber::{fmt::MakeWriter, layer::SubscriberExt};

    use super::{JsonFields, ServiceEventFormat, tracing_fmt};

    #[derive(Clone, Default)]
    struct Buffer(Arc<Mutex<Vec<u8>>>);

    struct BufferWriter(Arc<Mutex<Vec<u8>>>);

    impl io::Write for BufferWriter {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            self.0
                .lock()
                .map_err(|_| io::Error::other("test output lock poisoned"))?
                .extend_from_slice(bytes);
            Ok(bytes.len())
        }

        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    impl<'writer> MakeWriter<'writer> for Buffer {
        type Writer = BufferWriter;

        fn make_writer(&'writer self) -> Self::Writer {
            BufferWriter(Arc::clone(&self.0))
        }
    }

    impl Buffer {
        fn output(&self) -> String {
            let bytes = self
                .0
                .lock()
                .expect("test output lock should not be poisoned")
                .clone();
            String::from_utf8(bytes).expect("tracing output should be UTF-8")
        }
    }

    fn emit_events() {
        tracing::info!(
            event_field = 1,
            bytes = &[0u8, 127, 255][..],
            flag = true,
            ratio = 1.5,
            "outside span"
        );
        let span = tracing::info_span!("request", span_field = 2);
        let _entered = span.enter();
        tracing::info!(event_field = 3, "inside span");
    }

    #[test]
    fn public_layer_owns_config_and_composes_with_independent_filters_and_writers() {
        use std::sync::atomic::{AtomicUsize, Ordering};

        use crate::observability::{TracingConfig, tracing_layer};
        use tracing_subscriber::{EnvFilter, Layer, layer::Context};

        struct CountEvents(Arc<AtomicUsize>);
        impl<S: tracing::Subscriber> Layer<S> for CountEvents {
            fn on_event(&self, _: &tracing::Event<'_>, _: Context<'_, S>) {
                self.0.fetch_add(1, Ordering::Relaxed);
            }
        }

        for json in [false, true] {
            let output = Buffer::default();
            let events = Arc::new(AtomicUsize::new(0));
            let config = TracingConfig::new("composed_service")
                .unwrap()
                .with_json(json);
            let logs = tracing_layer(&config)
                .unwrap()
                .with_writer(output.clone())
                .with_filter(EnvFilter::new("warn"));
            drop(config);
            let subscriber = tracing_subscriber::registry()
                .with(logs)
                .with(CountEvents(events.clone()));
            tracing::subscriber::with_default(subscriber, || {
                tracing::info!("other layer only");
                tracing::warn!("both layers");
            });
            assert_eq!(events.load(Ordering::Relaxed), 2);
            let text = output.output();
            assert_eq!(text.lines().count(), 1);
            assert!(text.contains("both layers"));
            assert!(text.contains("composed_service"));
            if json {
                let event: serde_json::Value = serde_json::from_str(&text).unwrap();
                assert_eq!(event["service_name"], "composed_service");
                assert_eq!(event["level"], "WARN");
            }
        }
    }

    #[test]
    fn configured_service_name_is_present_on_text_events_and_spans() {
        let output = Buffer::default();
        let subscriber = tracing_subscriber::registry().with(
            tracing_fmt::layer()
                .without_time()
                .with_ansi(false)
                .with_target(false)
                .with_writer(output.clone())
                .fmt_fields(JsonFields::new())
                .event_format(ServiceEventFormat {
                    service_name: "example_service".to_owned(),
                    json: false,
                    timer: (),
                }),
        );

        tracing::subscriber::with_default(subscriber, emit_events);
        let lines = output
            .output()
            .lines()
            .map(str::to_owned)
            .collect::<Vec<_>>();
        assert_eq!(lines.len(), 2);
        assert!(
            lines
                .iter()
                .all(|line| line.contains("service_name=\"example_service\""))
        );
        assert!(lines[1].matches("service_name=\"example_service\"").count() >= 2);
    }

    #[test]
    fn configured_service_name_is_present_on_json_events_and_spans() {
        let output = Buffer::default();
        let event_format = ServiceEventFormat {
            service_name: "example_service".to_owned(),
            json: true,
            timer: (),
        };
        let subscriber = tracing_subscriber::registry().with(
            tracing_fmt::layer()
                .with_ansi(false)
                .with_target(false)
                .with_writer(output.clone())
                .fmt_fields(JsonFields::new())
                .event_format(event_format),
        );

        tracing::subscriber::with_default(subscriber, emit_events);
        let lines = output
            .output()
            .lines()
            .map(str::to_owned)
            .collect::<Vec<_>>();
        assert_eq!(lines.len(), 2);
        let event: serde_json::Value = serde_json::from_str(&lines[0]).unwrap();
        assert_eq!(event["fields"]["bytes"], serde_json::json!([0, 127, 255]));
        assert_eq!(event["fields"]["flag"], true);
        assert_eq!(event["fields"]["ratio"], 1.5);
        assert!(
            lines
                .iter()
                .all(|line| line.contains(r#""service_name":"example_service""#))
        );
        assert!(
            lines[1]
                .matches(r#""service_name":"example_service""#)
                .count()
                >= 2
        );
    }

    #[test]
    fn span_updates_replace_fields_without_growing_the_buffer_in_both_formats() {
        use tracing_subscriber::{fmt::FormattedFields, registry::LookupSpan};

        for json in [false, true] {
            let output = Buffer::default();
            let subscriber = tracing_subscriber::registry().with(
                tracing_fmt::layer()
                    .with_writer(output.clone())
                    .fmt_fields(JsonFields::new())
                    .event_format(ServiceEventFormat {
                        service_name: "configured_service".to_owned(),
                        json,
                        timer: (),
                    }),
            );
            let subscriber = Arc::new(subscriber);
            tracing::subscriber::with_default(subscriber.clone(), || {
                let parent = tracing::info_span!("parent", service_name = "incorrect");
                let _parent = parent.enter();
                let span = tracing::info_span!(
                    "child",
                    counter = 0,
                    service_name = "incorrect",
                    note = tracing::field::Empty
                );
                for counter in 1..=10_000 {
                    span.record("counter", counter);
                }
                span.record("note", "quoted\"\n中文");
                span.record("service_name", "still_incorrect");
                let stored = subscriber.span(&span.id().unwrap()).unwrap();
                let extensions = stored.extensions();
                let fields = &extensions
                    .get::<FormattedFields<JsonFields>>()
                    .unwrap()
                    .fields;
                assert!(
                    fields.len() < 150,
                    "span fields must hold only current values"
                );
                assert_eq!(fields.matches("\"counter\"").count(), 1);
                drop(extensions);
                let _entered = span.enter();
                tracing::info!("updated");
            });
            let text = output.output();
            if !json {
                assert_eq!(text.matches("counter=").count(), 1);
                assert!(text.contains("counter=10000"));
                assert!(!text.contains("incorrect"));
                assert_eq!(text.lines().count(), 1);
                continue;
            }
            let event: serde_json::Value = serde_json::from_str(&text).unwrap();
            assert_eq!(event["service_name"], "configured_service");
            assert_eq!(event["span"]["counter"], 10_000);
            assert_eq!(event["span"]["note"], "quoted\"\n中文");
            assert_eq!(event["span"]["service_name"], "configured_service");
            assert!(
                event["spans"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .all(|span| span["service_name"] == "configured_service")
            );
        }
    }
}