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
/*!
The [`Emitter`] type.

Emitters are the receivers of diagnostic data in the form of [`Event`]s. A typical emitter will translate and forward those events to some outside observer. That could be a file containing newline JSON, a remote observability system via OTLP, or anything else.

Emitters are asynchronous, so emitted diagnostics are not guaranteed to have been fully processed until a call to [`Emitter::blocking_flush`].
*/

use core::time::Duration;

use crate::{
    and::And,
    empty::Empty,
    event::{Event, ToEvent},
    props::ErasedProps,
};

/**
An asynchronous destination for diagnostic data.

Once [`Event`]s are emitted through [`Emitter::emit`], a call to [`Emitter::blocking_flush`] must be made to ensure they're fully processed. This should be done once before the emitter is disposed, but may be more frequent for auditing.
*/
pub trait Emitter {
    /**
    Emit an [`Event`].
    */
    fn emit<E: ToEvent>(&self, evt: E);

    /**
    Block for up to `timeout`, waiting for all diagnostic data emitted up to this point to be fully processed.

    This method returns `true` if the flush completed, and `false` if it timed out.

    If an emitter doesn't need to flush, this method should immediately return `true`. If an emitted doesn't support flushing, this method should immediately return `false`.
    */
    fn blocking_flush(&self, timeout: Duration) -> bool;

    /**
    Emit events to both `self` and `other`.
    */
    fn and_to<U>(self, other: U) -> And<Self, U>
    where
        Self: Sized,
    {
        And::new(self, other)
    }

    /**
    Wrap the emitter, transforming or filtering [`Event`]s before it receives them.

    Flushing defers to the wrapped emitter.
    */
    fn wrap_emitter<W: wrapping::Wrapping>(self, wrapping: W) -> Wrap<Self, W>
    where
        Self: Sized,
    {
        Wrap {
            emitter: self,
            wrapping,
        }
    }
}

impl<'a, T: Emitter + ?Sized> Emitter for &'a T {
    fn emit<E: ToEvent>(&self, evt: E) {
        (**self).emit(evt)
    }

    fn blocking_flush(&self, timeout: Duration) -> bool {
        (**self).blocking_flush(timeout)
    }
}

#[cfg(feature = "alloc")]
impl<'a, T: Emitter + ?Sized + 'a> Emitter for alloc::boxed::Box<T> {
    fn emit<E: ToEvent>(&self, evt: E) {
        (**self).emit(evt)
    }

    fn blocking_flush(&self, timeout: Duration) -> bool {
        (**self).blocking_flush(timeout)
    }
}

#[cfg(feature = "alloc")]
impl<'a, T: Emitter + ?Sized + 'a> Emitter for alloc::sync::Arc<T> {
    fn emit<E: ToEvent>(&self, evt: E) {
        (**self).emit(evt)
    }

    fn blocking_flush(&self, timeout: Duration) -> bool {
        (**self).blocking_flush(timeout)
    }
}

impl<T: Emitter> Emitter for Option<T> {
    fn emit<E: ToEvent>(&self, evt: E) {
        match self {
            Some(target) => target.emit(evt),
            None => Empty.emit(evt),
        }
    }

    fn blocking_flush(&self, timeout: Duration) -> bool {
        match self {
            Some(target) => target.blocking_flush(timeout),
            None => Empty.blocking_flush(timeout),
        }
    }
}

impl Emitter for Empty {
    fn emit<E: ToEvent>(&self, _: E) {}

    fn blocking_flush(&self, _: Duration) -> bool {
        true
    }
}

impl Emitter for fn(&Event<&dyn ErasedProps>) {
    fn emit<E: ToEvent>(&self, evt: E) {
        (self)(&evt.to_event().erase())
    }

    fn blocking_flush(&self, _: Duration) -> bool {
        true
    }
}

/**
An [`Emitter`] from a function.

This type can be created directly, or via [`from_fn`].
*/
pub struct FromFn<F = fn(&Event<&dyn ErasedProps>)>(F);

impl<F> FromFn<F> {
    /**
    Wrap the given emitter function.
    */
    pub const fn new(emitter: F) -> FromFn<F> {
        FromFn(emitter)
    }
}

impl<F: Fn(&Event<&dyn ErasedProps>)> Emitter for FromFn<F> {
    fn emit<E: ToEvent>(&self, evt: E) {
        (self.0)(&evt.to_event().erase())
    }

    fn blocking_flush(&self, _: Duration) -> bool {
        true
    }
}

/**
Create an [`Emitter`] from a function.

The input function is assumed not to perform any background work that needs flushing.
*/
pub fn from_fn<F: Fn(&Event<&dyn ErasedProps>)>(f: F) -> FromFn<F> {
    FromFn::new(f)
}

impl<T: Emitter, U: Emitter> Emitter for And<T, U> {
    fn emit<E: ToEvent>(&self, evt: E) {
        let evt = evt.to_event();

        self.left().emit(&evt);
        self.right().emit(&evt);
    }

    fn blocking_flush(&self, timeout: Duration) -> bool {
        // Approximate; give each target an equal
        // time to flush. With a monotonic clock
        // we could measure the time each takes
        // to flush and track in our timeout
        let timeout = timeout / 2;

        let lhs = self.left().blocking_flush(timeout);
        let rhs = self.right().blocking_flush(timeout);

        lhs && rhs
    }
}

/**
An [`Emitter`] that can transform or filter events before forwarding them through.

This type is returned by [`Emitter::wrap_emitter`].
*/
pub struct Wrap<E, W> {
    emitter: E,
    wrapping: W,
}

impl<E, W> Wrap<E, W> {
    /**
    Get a reference to the underlying [`Emitter`].
    */
    pub const fn emitter(&self) -> &E {
        &self.emitter
    }

    /**
    Get a reference to the underlying [`Wrapping`].
    */
    pub const fn wrapping(&self) -> &W {
        &self.wrapping
    }
}

impl<E: Emitter, W: wrapping::Wrapping> Emitter for Wrap<E, W> {
    fn emit<T: ToEvent>(&self, evt: T) {
        self.wrapping.wrap(&self.emitter, evt.to_event())
    }

    fn blocking_flush(&self, timeout: Duration) -> bool {
        self.emitter.blocking_flush(timeout)
    }
}

/**
Wrap the [`Emitter`] in a [`Wrapping`], transforming or filtering [`Event`]s before it receives them.

Flushing defers to the wrapped emitter.
*/
pub fn wrap<E: Emitter, W: wrapping::Wrapping>(emitter: E, wrapping: W) -> Wrap<E, W> {
    emitter.wrap_emitter(wrapping)
}

pub mod wrapping {
    /*!
    The [`Wrapping`] type.
    */

    use super::*;

    use crate::filter::Filter;

    /**
    A transformation or filter applied to an [`Event`] before emitting it through an [`Emitter`].
    */
    pub trait Wrapping {
        /**
        Wrap the given emitter.
        */
        fn wrap<O: Emitter, E: ToEvent>(&self, output: O, evt: E);
    }

    impl<'a, T: Wrapping + ?Sized> Wrapping for &'a T {
        fn wrap<O: Emitter, E: ToEvent>(&self, output: O, evt: E) {
            (**self).wrap(output, evt)
        }
    }

    /**
    A [`Wrapping`] from a function.

    This type can be created directly, or via [`from_fn`].
    */
    pub struct FromFn<F = fn(&dyn ErasedEmitter, Event<&dyn ErasedProps>)>(F);

    impl<F> FromFn<F> {
        /**
        Wrap the given function.
        */
        pub const fn new(wrapping: F) -> FromFn<F> {
            FromFn(wrapping)
        }
    }

    impl<F: Fn(&dyn ErasedEmitter, Event<&dyn ErasedProps>)> Wrapping for FromFn<F> {
        fn wrap<O: Emitter, E: ToEvent>(&self, output: O, evt: E) {
            (self.0)(&output, evt.to_event().erase())
        }
    }

    /**
    Create a [`Wrapping`] from a function.
    */
    pub fn from_fn<F: Fn(&dyn ErasedEmitter, Event<&dyn ErasedProps>)>(f: F) -> FromFn<F> {
        FromFn::new(f)
    }

    /**
    A [`Wrapping`] from a filter.

    The filter will be applied to incoming [`Event`]s and only passed to the output [`Emitter`] when they match.
    */
    pub struct FromFilter<F>(F);

    impl<F> FromFilter<F> {
        /**
        Wrap the given filter.
        */
        pub const fn new(filter: F) -> FromFilter<F> {
            FromFilter(filter)
        }
    }

    impl<F: Filter> Wrapping for FromFilter<F> {
        fn wrap<O: Emitter, E: ToEvent>(&self, output: O, evt: E) {
            if self.0.matches(&evt) {
                output.emit(evt);
            }
        }
    }

    /**
    Create a [`Wrapping`] from a filter.
    */
    pub fn from_filter<F: Filter>(filter: F) -> FromFilter<F> {
        FromFilter::new(filter)
    }

    mod internal {
        use crate::{emitter::ErasedEmitter, event::Event, props::ErasedProps};

        pub trait DispatchWrapping {
            fn dispatch_wrap(&self, emitter: &dyn ErasedEmitter, evt: Event<&dyn ErasedProps>);
        }

        pub trait SealedWrapping {
            fn erase_wrapping(&self) -> crate::internal::Erased<&dyn DispatchWrapping>;
        }
    }

    /**
    An object-safe [`Wrapping`].

    A `dyn ErasedWrapping` can be treated as `impl Wrapping`.
    */
    pub trait ErasedWrapping: internal::SealedWrapping {}

    impl<T: Wrapping> ErasedWrapping for T {}

    impl<T: Wrapping> internal::SealedWrapping for T {
        fn erase_wrapping(&self) -> crate::internal::Erased<&dyn internal::DispatchWrapping> {
            crate::internal::Erased(self)
        }
    }

    impl<T: Wrapping> internal::DispatchWrapping for T {
        fn dispatch_wrap(&self, emitter: &dyn ErasedEmitter, evt: Event<&dyn ErasedProps>) {
            self.wrap(emitter, evt)
        }
    }

    impl<'a> Wrapping for dyn ErasedWrapping + 'a {
        fn wrap<O: Emitter, E: ToEvent>(&self, output: O, evt: E) {
            self.erase_wrapping()
                .0
                .dispatch_wrap(&output, evt.to_event().erase())
        }
    }

    impl<'a> Wrapping for dyn ErasedWrapping + Send + Sync + 'a {
        fn wrap<O: Emitter, E: ToEvent>(&self, output: O, evt: E) {
            (self as &(dyn ErasedWrapping + 'a)).wrap(output, evt)
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        use crate::{path::Path, template::Template};

        use std::cell::Cell;

        struct MyWrapping(Cell<usize>);

        impl Wrapping for MyWrapping {
            fn wrap<O: Emitter, E: ToEvent>(&self, _: O, _: E) {
                self.0.set(self.0.get() + 1);
            }
        }

        #[test]
        fn erased_wrapping() {
            let wrapping = MyWrapping(Cell::new(0));

            {
                let wrapping = &wrapping as &dyn ErasedWrapping;

                wrapping.wrap(
                    Empty,
                    Event::new(
                        Path::new_unchecked("a"),
                        Template::literal("test"),
                        Empty,
                        Empty,
                    ),
                );
            }

            assert_eq!(1, wrapping.0.get());
        }

        #[test]
        fn from_fn_wrapping() {
            let calls = Cell::new(0);

            let wrapping = from_fn(|_, _| {
                calls.set(calls.get() + 1);
            });

            wrapping.wrap(
                Empty,
                Event::new(
                    Path::new_unchecked("a"),
                    Template::literal("test"),
                    Empty,
                    Empty,
                ),
            );

            assert_eq!(1, calls.get());
        }
    }
}

mod internal {
    use core::time::Duration;

    use crate::{event::Event, props::ErasedProps};

    pub trait DispatchEmitter {
        fn dispatch_emit(&self, evt: &Event<&dyn ErasedProps>);
        fn dispatch_blocking_flush(&self, timeout: Duration) -> bool;
    }

    pub trait SealedEmitter {
        fn erase_emitter(&self) -> crate::internal::Erased<&dyn DispatchEmitter>;
    }
}

/**
An object-safe [`Emitter`].

A `dyn ErasedEmitter` can be treated as `impl Emitter`.
*/
pub trait ErasedEmitter: internal::SealedEmitter {}

impl<T: Emitter> ErasedEmitter for T {}

impl<T: Emitter> internal::SealedEmitter for T {
    fn erase_emitter(&self) -> crate::internal::Erased<&dyn internal::DispatchEmitter> {
        crate::internal::Erased(self)
    }
}

impl<T: Emitter> internal::DispatchEmitter for T {
    fn dispatch_emit(&self, evt: &Event<&dyn ErasedProps>) {
        self.emit(evt)
    }

    fn dispatch_blocking_flush(&self, timeout: Duration) -> bool {
        self.blocking_flush(timeout)
    }
}

impl<'a> Emitter for dyn ErasedEmitter + 'a {
    fn emit<E: ToEvent>(&self, evt: E) {
        self.erase_emitter()
            .0
            .dispatch_emit(&evt.to_event().erase())
    }

    fn blocking_flush(&self, timeout: Duration) -> bool {
        self.erase_emitter().0.dispatch_blocking_flush(timeout)
    }
}

impl<'a> Emitter for dyn ErasedEmitter + Send + Sync + 'a {
    fn emit<E: ToEvent>(&self, evt: E) {
        (self as &(dyn ErasedEmitter + 'a)).emit(evt)
    }

    fn blocking_flush(&self, timeout: Duration) -> bool {
        (self as &(dyn ErasedEmitter + 'a)).blocking_flush(timeout)
    }
}

#[cfg(test)]
mod tests {
    use crate::{path::Path, props::Props, template::Template};

    use super::*;

    use std::{cell::Cell, sync::Mutex};

    struct MyEmitter {
        pending: Mutex<Vec<String>>,
        emitted: Mutex<Vec<String>>,
    }

    impl MyEmitter {
        fn new() -> Self {
            MyEmitter {
                pending: Mutex::new(Vec::new()),
                emitted: Mutex::new(Vec::new()),
            }
        }

        fn emitted(&self) -> Vec<String> {
            (*self.emitted.lock().unwrap()).clone()
        }
    }

    impl Emitter for MyEmitter {
        fn emit<E: ToEvent>(&self, evt: E) {
            let rendered = evt.to_event().msg().to_string();
            self.pending.lock().unwrap().push(rendered);
        }

        fn blocking_flush(&self, _: Duration) -> bool {
            let mut pending = self.pending.lock().unwrap();
            let mut emitted = self.emitted.lock().unwrap();

            emitted.extend(pending.drain(..));

            true
        }
    }

    #[test]
    fn erased_emitter() {
        let emitter = MyEmitter::new();

        {
            let emitter = &emitter as &dyn ErasedEmitter;

            emitter.emit(Event::new(
                Path::new_unchecked("a"),
                Template::literal("event 1"),
                Empty,
                Empty,
            ));
            emitter.blocking_flush(Duration::from_secs(0));
        }

        assert_eq!(vec![String::from("event 1")], emitter.emitted());
    }

    #[test]
    fn option_emitter() {
        for (emitter, expected) in [
            (Some(MyEmitter::new()), vec![String::from("event 1")]),
            (None, vec![]),
        ] {
            emitter.emit(Event::new(
                Path::new_unchecked("a"),
                Template::literal("event 1"),
                Empty,
                Empty,
            ));
            emitter.blocking_flush(Duration::from_secs(0));

            let emitted = emitter.map(|emitter| emitter.emitted()).unwrap_or_default();

            assert_eq!(expected, emitted);
        }
    }

    #[test]
    fn from_fn_emitter() {
        let count = Cell::new(0);

        let emitter = from_fn(|evt| {
            assert_eq!(Path::new_unchecked("a"), evt.mdl());

            count.set(count.get() + 1);
        });

        emitter.emit(Event::new(
            Path::new_unchecked("a"),
            Template::literal("event 1"),
            Empty,
            Empty,
        ));

        assert_eq!(1, count.get());
    }

    #[test]
    fn and_emitter() {
        let emitter = MyEmitter::new().and_to(MyEmitter::new());

        emitter.emit(Event::new(
            Path::new_unchecked("a"),
            Template::literal("event 1"),
            Empty,
            Empty,
        ));
        emitter.blocking_flush(Duration::from_secs(0));

        assert_eq!(vec![String::from("event 1")], emitter.left().emitted());
        assert_eq!(vec![String::from("event 1")], emitter.right().emitted());
    }

    #[test]
    fn wrap_emitter() {
        let count = Cell::new(0);
        let emitter = from_fn(|evt| {
            assert_eq!(1, evt.props().pull::<i32, _>("appended").unwrap());

            count.set(count.get() + 1);
        })
        .wrap_emitter(wrapping::from_fn(|output, evt| {
            output.emit(evt.map_props(|props| props.and_props(("appended", 1))));
        }));

        emitter.emit(Event::new(
            Path::new_unchecked("a"),
            Template::literal("event 1"),
            Empty,
            Empty,
        ));

        assert_eq!(1, count.get());
    }
}