footing 0.1.19

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
//! Structured event and trace-field domain types.

use std::{collections::BTreeMap, fmt as std_fmt};

use serde::{Deserialize, Deserializer, Serialize};

use super::{
    error::ObservabilityError,
    schema::{event_names, metric_outcomes, trace_fields},
};

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
/// Represents trace field name.
pub struct TraceFieldName(String);

impl TraceFieldName {
    /// Creates a new instance.
    pub fn new(value: impl Into<String>) -> Result<Self, ObservabilityError> {
        let value = value.into().trim().to_owned();
        validate_trace_field_name(&value)?;
        Ok(Self(value))
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    /// Consumes this value and returns string.
    pub fn into_string(self) -> String {
        self.0
    }
}

impl std_fmt::Display for TraceFieldName {
    fn fmt(&self, formatter: &mut std_fmt::Formatter<'_>) -> std_fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for TraceFieldName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
    }
}

#[derive(Clone, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
/// Represents trace fields.
pub struct TraceFields(Vec<(TraceFieldName, String)>);

impl std_fmt::Debug for TraceFields {
    fn fmt(&self, formatter: &mut std_fmt::Formatter<'_>) -> std_fmt::Result {
        formatter
            .debug_struct("TraceFields")
            .field("field_count", &self.0.len())
            .finish_non_exhaustive()
    }
}

impl TraceFields {
    /// Creates a new instance.
    pub fn new(
        fields: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Result<Self, ObservabilityError> {
        let mut normalized = BTreeMap::<TraceFieldName, String>::new();
        for (key, value) in fields {
            let value = value.into();
            let key = TraceFieldName::new(key)?;
            if !value.trim().is_empty() {
                normalized.insert(key, value);
            }
        }
        Ok(Self(normalized.into_iter().collect()))
    }

    #[must_use]
    /// Creates a value from lossy.
    pub fn from_lossy(
        fields: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        let mut normalized = BTreeMap::<TraceFieldName, String>::new();
        for (key, value) in fields {
            let value = value.into();
            if !value.trim().is_empty()
                && let Ok(key) = TraceFieldName::new(key)
            {
                normalized.insert(key, value);
            }
        }
        Self(normalized.into_iter().collect())
    }

    /// Creates single.
    pub fn single(
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Self, ObservabilityError> {
        Self::new([(key, value)])
    }

    #[must_use]
    /// Adds or replaces a field, ignoring invalid names and blank values.
    pub fn with(mut self, key: &'static str, value: impl Into<String>) -> Self {
        if let Ok(key) = TraceFieldName::new(key) {
            self.insert(key, value.into());
        }
        self
    }

    /// Attempts to append a validated trace field.
    pub fn try_with(
        mut self,
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Self, ObservabilityError> {
        let key = TraceFieldName::new(key)?;
        self.insert(key, value.into());
        Ok(self)
    }

    #[must_use]
    /// Adds the standard request identifier field.
    pub fn request_id(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::REQUEST_ID, value)
    }

    #[must_use]
    /// Adds the standard trace identifier field.
    pub fn trace_id(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::TRACE_ID, value)
    }

    #[must_use]
    /// Adds the standard actor identifier field.
    pub fn actor_id(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::ACTOR_ID, value)
    }

    #[must_use]
    /// Adds the standard user identifier field.
    pub fn user_id(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::USER_ID, value)
    }

    #[must_use]
    /// Adds the standard client identifier field.
    pub fn client_id(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::CLIENT_ID, value)
    }

    #[must_use]
    /// Adds the standard source IP field.
    pub fn source_ip(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::SOURCE_IP, value)
    }

    #[must_use]
    /// Adds the standard operation field.
    pub fn operation(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::OPERATION, value)
    }

    #[must_use]
    /// Adds the standard outcome field.
    pub fn outcome(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::OUTCOME, value)
    }

    #[must_use]
    /// Adds the standard reason code field.
    pub fn reason_code(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::REASON_CODE, value)
    }

    #[must_use]
    /// Adds the standard subject identifier field.
    pub fn subject_id(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::SUBJECT_ID, value)
    }

    #[must_use]
    /// Adds the standard subject kind field.
    pub fn subject_kind(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::SUBJECT_KIND, value)
    }

    #[must_use]
    /// Adds the standard method field.
    pub fn method(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::METHOD, value)
    }

    #[must_use]
    /// Adds the standard route field.
    pub fn route(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::ROUTE, value)
    }

    #[must_use]
    /// Adds the standard path field.
    pub fn path(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::PATH, value)
    }

    #[must_use]
    /// Adds the standard error kind field.
    pub fn error_kind(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::ERROR_KIND, value)
    }

    #[must_use]
    /// Adds the standard error code field.
    pub fn error_code(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::ERROR_CODE, value)
    }

    #[must_use]
    /// Adds the standard worker field.
    pub fn worker(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::WORKER, value)
    }

    #[must_use]
    /// Adds the standard job field.
    pub fn job(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::JOB, value)
    }

    #[must_use]
    /// Adds the standard latency ms field.
    pub fn latency_ms(self, value: impl Into<String>) -> Self {
        self.with(trace_fields::LATENCY_MS, value)
    }

    #[must_use]
    /// Returns the trace field value associated with a key.
    pub fn get(&self, key: &str) -> Option<&str> {
        self.0
            .iter()
            .find(|(name, _)| name.as_str() == key)
            .map(|(_, value)| value.as_str())
    }

    #[must_use]
    /// Returns this value as slice.
    pub fn as_slice(&self) -> &[(TraceFieldName, String)] {
        &self.0
    }

    #[must_use]
    /// Converts this value to btree map.
    pub fn to_btree_map(&self) -> BTreeMap<String, String> {
        self.0
            .iter()
            .map(|(name, value)| (name.as_str().to_owned(), value.clone()))
            .collect()
    }

    #[must_use]
    /// Consumes this value and returns vec.
    pub fn into_vec(self) -> Vec<(String, String)> {
        self.0
            .into_iter()
            .map(|(name, value)| (name.into_string(), value))
            .collect()
    }

    fn insert(&mut self, key: TraceFieldName, value: String) {
        if value.trim().is_empty() {
            return;
        }
        match self.0.binary_search_by(|(name, _)| name.cmp(&key)) {
            Ok(index) => self.0[index].1 = value,
            Err(index) => self.0.insert(index, (key, value)),
        }
    }

    fn from_valid_fields(fields: impl IntoIterator<Item = (TraceFieldName, String)>) -> Self {
        let mut normalized = BTreeMap::<TraceFieldName, String>::new();
        for (key, value) in fields {
            if !value.trim().is_empty() {
                normalized.insert(key, value);
            }
        }
        Self(normalized.into_iter().collect())
    }
}

impl<'de> Deserialize<'de> for TraceFields {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let fields = Vec::<(TraceFieldName, String)>::deserialize(deserializer)?;
        Ok(Self::from_valid_fields(fields))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Classification of event.
pub enum EventKind {
    /// Indicates HTTP.
    Http,
    /// Indicates worker.
    Worker,
    /// Indicates audit.
    Audit,
    /// Indicates security.
    Security,
    /// Indicates domain.
    Domain,
}

impl EventKind {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Http => "http",
            Self::Worker => "worker",
            Self::Audit => "audit",
            Self::Security => "security",
            Self::Domain => "domain",
        }
    }
}

impl std_fmt::Display for EventKind {
    fn fmt(&self, formatter: &mut std_fmt::Formatter<'_>) -> std_fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
/// Outcome of event.
pub enum EventOutcome {
    /// The operation succeeded.
    Success,
    /// The operation failed.
    Failure,
    /// Indicates denied.
    Denied,
    /// Indicates skipped.
    Skipped,
    /// Indicates retry.
    Retry,
}

impl EventOutcome {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Success => metric_outcomes::SUCCESS,
            Self::Failure => metric_outcomes::FAILURE,
            Self::Denied => metric_outcomes::DENIED,
            Self::Skipped => "skipped",
            Self::Retry => "retry",
        }
    }
}

impl std_fmt::Display for EventOutcome {
    fn fmt(&self, formatter: &mut std_fmt::Formatter<'_>) -> std_fmt::Result {
        formatter.write_str(self.as_str())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
/// Represents structured event.
pub struct StructuredEvent {
    name: String,
    kind: EventKind,
    fields: TraceFields,
}

impl<'de> Deserialize<'de> for StructuredEvent {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct StructuredEventWire {
            name: String,
            kind: EventKind,
            #[serde(default)]
            fields: TraceFields,
        }

        let wire = StructuredEventWire::deserialize(deserializer)?;
        Ok(Self::new(wire.name, wire.kind)
            .map_err(serde::de::Error::custom)?
            .with_fields(wire.fields))
    }
}

impl StructuredEvent {
    /// Creates a new instance.
    pub fn new(name: impl Into<String>, kind: EventKind) -> Result<Self, ObservabilityError> {
        let name = name.into().trim().to_owned();
        validate_event_name(&name)?;
        Ok(Self::from_valid_parts(name, kind))
    }

    fn from_valid_parts(name: String, kind: EventKind) -> Self {
        Self {
            name,
            kind,
            fields: TraceFields::default(),
        }
    }

    #[must_use]
    /// Creates HTTP request.
    pub fn http_request() -> Self {
        Self::from_valid_parts(event_names::HTTP_REQUEST.to_owned(), EventKind::Http)
    }

    #[must_use]
    /// Creates worker tick.
    pub fn worker_tick(worker: impl Into<String>) -> Self {
        Self::from_valid_parts(event_names::WORKER_TICK.to_owned(), EventKind::Worker)
            .worker(worker)
    }

    #[must_use]
    /// Creates security decision.
    pub fn security_decision() -> Self {
        Self::from_valid_parts(
            event_names::SECURITY_DECISION.to_owned(),
            EventKind::Security,
        )
    }

    #[must_use]
    /// Creates audit event.
    pub fn audit_event() -> Self {
        Self::from_valid_parts(event_names::AUDIT_EVENT.to_owned(), EventKind::Audit)
    }

    #[must_use]
    /// Configures fields and returns the updated value.
    pub fn with_fields(mut self, fields: TraceFields) -> Self {
        self.fields = fields;
        self
    }

    #[must_use]
    /// Adds a structured-event field.
    pub fn with_field(mut self, key: &'static str, value: impl Into<String>) -> Self {
        self.fields = self.fields.with(key, value);
        self
    }

    /// Attempts to append a validated structured-event field.
    pub fn try_with_field(
        mut self,
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Self, ObservabilityError> {
        self.fields = self.fields.try_with(key, value)?;
        Ok(self)
    }

    #[must_use]
    /// Merges fields, replacing matching names and preserving other fields.
    pub fn merge_fields(mut self, fields: TraceFields) -> Self {
        for (key, value) in fields.0 {
            self.fields.insert(key, value);
        }
        self
    }

    #[must_use]
    /// Adds the standard outcome field.
    pub fn outcome(self, outcome: EventOutcome) -> Self {
        self.with_field(trace_fields::OUTCOME, outcome.as_str())
    }

    #[must_use]
    /// Adds the standard request identifier field.
    pub fn request_id(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::REQUEST_ID, value)
    }

    #[must_use]
    /// Adds the standard actor identifier field.
    pub fn actor_id(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::ACTOR_ID, value)
    }

    #[must_use]
    /// Adds the standard subject identifier field.
    pub fn subject_id(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::SUBJECT_ID, value)
    }

    #[must_use]
    /// Adds the standard subject kind field.
    pub fn subject_kind(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::SUBJECT_KIND, value)
    }

    #[must_use]
    /// Adds the standard user identifier field.
    pub fn user_id(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::USER_ID, value)
    }

    #[must_use]
    /// Adds the standard client identifier field.
    pub fn client_id(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::CLIENT_ID, value)
    }

    #[must_use]
    /// Adds the standard source IP field.
    pub fn source_ip(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::SOURCE_IP, value)
    }

    #[must_use]
    /// Adds the standard operation field.
    pub fn operation(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::OPERATION, value)
    }

    #[must_use]
    /// Adds the standard reason code field.
    pub fn reason_code(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::REASON_CODE, value)
    }

    #[must_use]
    /// Adds the standard method field.
    pub fn method(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::METHOD, value)
    }

    #[must_use]
    /// Adds the standard route field.
    pub fn route(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::ROUTE, value)
    }

    #[must_use]
    /// Adds the standard path field.
    pub fn path(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::PATH, value)
    }

    #[must_use]
    /// Adds the standard error kind field.
    pub fn error_kind(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::ERROR_KIND, value)
    }

    #[must_use]
    /// Adds the standard error code field.
    pub fn error_code(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::ERROR_CODE, value)
    }

    #[must_use]
    /// Adds the standard worker field.
    pub fn worker(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::WORKER, value)
    }

    #[must_use]
    /// Adds the standard job field.
    pub fn job(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::JOB, value)
    }

    #[must_use]
    /// Adds the standard latency ms field.
    pub fn latency_ms(self, value: impl Into<String>) -> Self {
        self.with_field(trace_fields::LATENCY_MS, value)
    }

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

    #[must_use]
    /// Returns the kind.
    pub const fn kind(&self) -> EventKind {
        self.kind
    }

    #[must_use]
    /// Returns the fields.
    pub const fn fields(&self) -> &TraceFields {
        &self.fields
    }

    #[must_use]
    /// Returns the trace fields.
    pub fn trace_fields(&self) -> TraceFields {
        self.fields
            .clone()
            .with(trace_fields::EVENT_NAME, self.name.clone())
            .with(trace_fields::EVENT_KIND, self.kind.as_str())
    }

    #[must_use]
    /// Consumes this value and returns trace fields.
    pub fn into_trace_fields(self) -> TraceFields {
        self.fields
            .with(trace_fields::EVENT_NAME, self.name)
            .with(trace_fields::EVENT_KIND, self.kind.as_str())
    }

    #[must_use]
    /// Converts this value to btree map.
    pub fn to_btree_map(&self) -> BTreeMap<String, String> {
        self.trace_fields().to_btree_map()
    }
}

fn validate_trace_field_name(value: &str) -> Result<(), ObservabilityError> {
    if value.is_empty()
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
    {
        return Err(ObservabilityError::InvalidTraceFieldName);
    }

    Ok(())
}

fn validate_event_name(value: &str) -> Result<(), ObservabilityError> {
    if value.is_empty()
        || !value.bytes().all(|byte| {
            byte.is_ascii_lowercase()
                || byte.is_ascii_digit()
                || matches!(byte, b'-' | b'_' | b'.' | b':')
        })
    {
        return Err(ObservabilityError::InvalidEventName);
    }

    Ok(())
}