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
698
699
use tracing_core::{
    metadata::Metadata,
    span,
    subscriber::{Interest, Subscriber},
    Event,
};

use std::{any::TypeId, marker::PhantomData};

/// A composable handler for `tracing` events.
///
/// The [`Subscriber`] trait in `tracing-core` represents the _complete_ set of
/// functionality required to consume `tracing` instrumentation. This means that
/// a single `Subscriber` instance is a self-contained implementation of a
/// complete strategy for collecting traces; but it _also_ means that the
/// `Subscriber` trait cannot easily be composed with other `Subscriber`s.
///
/// In particular, [`Subscriber`]'s are responsible for generating [span IDs] and
/// assigning them to spans. Since these IDs must uniquely identify a span
/// within the context of the current trace, this means that there may only be
/// a single `Subscriber` for a given thread at any point in time —
/// otherwise, there would be no authoritative source of span IDs.
///
/// On the other hand, the majority of the [`Subscriber`] trait's functionality
/// is composable: any number of subscribers may _observe_ events, span entry
/// and exit, and so on, provided that there is a single authoritative source of
/// span IDs. The `Layer` trait represents this composable subset of the
/// [`Subscriber`] behavior; it can _observe_ events and spans, but does not
/// assign IDs.
///
/// ## Recording Traces
///
/// The `Layer` trait defines a set of methods for consuming notifications from
/// tracing instrumentation, which are generally equivalent to the similarly
/// named methods on [`Subscriber`]. Unlike [`Subscriber`], the methods on
/// `Layer` are additionally passed a [`Context`] type, which exposes additional
/// information provided by the wrapped subscriber (such as [the current span])
/// to the layer.
///
/// ## Filtering with `Layer`s
///
/// As well as strategies for handling trace events, the `Layer` trait may also
/// be used to represent composable _filters_. This allows the determination of
/// what spans and events should be recorded to be decoupled from _how_ they are
/// recorded: a filtering layer can be applied to other layers or
/// subscribers. A `Layer` that implements a filtering strategy should override the
/// [`register_callsite`] and/or [`enabled`] methods. It may also choose to implement
/// methods such as [`on_enter`], if it wishes to filter trace events based on
/// the current span context.
///
/// Note that the [`Layer::register_callsite`] and [`Layer::enabled`] methods
/// determine whether a span or event is enabled *globally*. Thus, they should
/// **not** be used to indicate whether an individual layer wishes to record a
/// particular span or event. Instead, if a layer is only interested in a subset
/// of trace data, but does *not* wish to disable other spans and events for the
/// rest of the layer stack should ignore those spans and events in its
/// notification methods.
///
/// The filtering methods on a stack of `Layer`s are evaluated in a top-down
/// order, starting with the outermost `Layer` and ending with the wrapped
/// [`Subscriber`]. If any layer returns `false` from its [`enabled`] method, or
/// [`Interest::never()`] from its [`register_callsite`] method, filter
/// evaluation will short-circuit and the span or event will be disabled.
///
/// [`Subscriber`]: https://docs.rs/tracing-core/0.1.1/tracing_core/subscriber/trait.Subscriber.html
/// [span IDs]: https://docs.rs/tracing-core/0.1.1/tracing_core/span/struct.Id.html
/// [`Context`]: struct.Context.html
/// [the current span]: struct.Context.html#method.current_span
/// [`register_callsite`]: #method.register_callsite
/// [`enabled`]: #method.enabled
/// [`on_enter`]: #method.on_enter
/// [`Layer::register_callsite`]: #method.register_callsite
/// [`Layer::enabled`]: #method.enabled
/// [`Interest::never()`]: https://docs.rs/tracing-core/0.1.1/tracing_core/subscriber/struct.Interest.html#method.never
pub trait Layer<S>
where
    S: Subscriber,
    Self: 'static,
{
    /// Registers a new callsite with this layer, returning whether or not
    /// the layer is interested in being notified about the callsite, similarly
    /// to [`Subscriber::register_callsite`].
    ///
    /// By default, this returns [`Interest::always()`] if [`self.enabled`] returns
    /// true, or [`Interest::never()`] if it returns false.
    ///
    /// **Note:** This method (and [`Layer::enabled`]) determine whether a
    /// span or event is globally enabled, _not_ whether the individual layer
    /// will be notified about that span or event. This is intended to be used
    /// by layers that implement filtering for the entire stack. Layers which do
    /// not wish to be notified about certain spans or events but do not wish to
    /// globally disable them should ignore those spans or events in their
    /// [`on_event`], [`on_enter`], [`on_exit`], and other notification methods.
    ///
    /// See [the trait-level documentation] for more information on filtering
    /// with `Layer`s.
    ///
    /// Layers may also implement this method to perform any behaviour that
    /// should be run once per callsite. If the layer wishes to use
    /// `register_callsite` for per-callsite behaviour, but does not want to
    /// globally enable or disable those callsites, it should always return
    /// [`Interest::always()`].
    ///
    /// [`Interest`]: https://docs.rs/tracing-core/0.1.1/tracing_core/struct.Interest.html
    /// [`Subscriber::register_callsite`]: https://docs.rs/tracing-core/0.1.1/tracing_core/trait.Subscriber.html#method.register_callsite
    /// [`Interest::never()`]: https://docs.rs/tracing-core/0.1.1/tracing_core/subscriber/struct.Interest.html#method.never
    /// [`Interest::never()`]: https://docs.rs/tracing-core/0.1.1/tracing_core/subscriber/struct.Interest.html#method.always
    /// [`self.enabled`]: #method.enabled
    /// [`Layer::enabled`]: #method.enabled
    /// [`on_event`]: #method.on_event
    /// [`on_enter`]: #method.on_enter
    /// [`on_exit`]: #method.on_exit
    /// [the trait-level documentation]: #filtering-with-layers
    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
        if self.enabled(metadata, Context::none()) {
            Interest::always()
        } else {
            Interest::never()
        }
    }

    /// Returns `true` if this layer is interested in a span or event with the
    /// given `metadata` in the current [`Context`], similarly to
    /// [`Subscriber::enabled`].
    ///
    /// By default, this always returns `true`, allowing the wrapped subscriber
    /// to choose to disable the span.
    ///
    /// **Note:** This method (and [`Layer::register_callsite`]) determine whether a
    /// span or event is globally enabled, _not_ whether the individual layer
    /// will be notified about that span or event. This is intended to be used
    /// by layers that implement filtering for the entire stack. Layers which do
    /// not wish to be notified about certain spans or events but do not wish to
    /// globally disable them should ignore those spans or events in their
    /// [`on_event`], [`on_enter`], [`on_exit`], and other notification methods.
    ///
    ///
    /// See [the trait-level documentation] for more information on filtering
    /// with `Layer`s.
    ///
    /// [`Interest`]: https://docs.rs/tracing-core/0.1.1/tracing_core/struct.Interest.html
    /// [`Context`]: ../struct.Context.html
    /// [`Subscriber::enabled`]: https://docs.rs/tracing-core/0.1.1/tracing_core/trait.Subscriber.html#method.enabled
    /// [`Layer::register_callsite`]: #method.reegister_callsite
    /// [`on_event`]: #method.on_event
    /// [`on_enter`]: #method.on_enter
    /// [`on_exit`]: #method.on_exit
    /// [the trait-level documentation]: #filtering-with-layers
    fn enabled(&self, _metadata: &Metadata, _ctx: Context<S>) -> bool {
        true
    }

    /// Notifies this layer that a new span was constructed with the given
    /// `Attributes` and `Id`.
    fn new_span(&self, _attrs: &span::Attributes, _id: &span::Id, _ctx: Context<S>) {}

    /// Notifies this layer that a span with the given `Id` recorded the given
    /// `values`.
    // Note: it's unclear to me why we'd need the current span in `record` (the
    // only thing the `Context` type currently provides), but passing it in anyway
    // seems like a good future-proofing measure as it may grow other methods later...
    fn on_record(&self, _span: &span::Id, _values: &span::Record, _ctx: Context<S>) {}

    /// Notifies this layer that a span with the ID `span` recorded that it
    /// follows from the span with the ID `follows`.
    // Note: it's unclear to me why we'd need the current span in `record` (the
    // only thing the `Context` type currently provides), but passing it in anyway
    // seems like a good future-proofing measure as it may grow other methods later...
    fn on_follows_from(&self, _span: &span::Id, _follows: &span::Id, _ctx: Context<S>) {}

    /// Notifies this layer that an event has occurred.
    fn on_event(&self, _event: &Event, _ctx: Context<S>) {}

    /// Notifies this layer that a span with the given ID was entered.
    fn on_enter(&self, _id: &span::Id, _ctx: Context<S>) {}

    /// Notifies this layer that the span with the given ID was exited.
    fn on_exit(&self, _id: &span::Id, _ctx: Context<S>) {}

    /// Notifies this layer that the span with the given ID has been closed.
    fn on_close(&self, _id: span::Id, _ctx: Context<S>) {}

    /// Notifies this layer that a span ID has been cloned, and that the
    /// subscriber returned a different ID.
    fn on_id_change(&self, _old: &span::Id, _new: &span::Id, _ctx: Context<S>) {}

    /// Composes this layer around the given `Layer`, returning a `Layered`
    /// struct implementing `Layer`.
    ///
    /// The returned `Layer` will call the methods on this `Layer` and then
    /// those of the new `Layer`, before calling the methods on the subscriber
    /// it wraps. For example:
    /// ```rust
    /// # use tracing_subscriber::layer::Layer;
    /// # use tracing_core::Subscriber;
    /// # fn main() {
    /// pub struct FooLayer {
    ///     // ...
    /// }
    ///
    /// pub struct BarLayer {
    ///     // ...
    /// }
    ///
    /// pub struct MySubscriber {
    ///     // ...
    /// }
    ///
    /// impl<S: Subscriber> Layer<S> for FooLayer {
    ///     // ...
    /// }
    ///
    /// impl<S: Subscriber> Layer<S> for BarLayer {
    ///     // ...
    /// }
    ///
    /// # impl FooLayer {
    /// # fn new() -> Self { Self {} }
    /// # }
    /// # impl BarLayer {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # impl MySubscriber {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
    /// # impl tracing_core::Subscriber for MySubscriber {
    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
    /// #   fn record(&self, _: &Id, _: &Record) {}
    /// #   fn event(&self, _: &Event) {}
    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
    /// #   fn enter(&self, _: &Id) {}
    /// #   fn exit(&self, _: &Id) {}
    /// # }
    /// let subscriber = FooLayer::new()
    ///     .and_then(BarLayer::new())
    ///     .with_subscriber(MySubscriber::new());
    /// # }
    /// ```
    ///
    /// Multiple layers may be composed in this manner:
    ///    /// ```rust
    /// # use tracing_subscriber::layer::Layer;
    /// # use tracing_core::Subscriber;
    /// # fn main() {
    /// # pub struct FooLayer {}
    /// # pub struct BarLayer {}
    /// # pub struct MySubscriber {}
    /// # impl<S: Subscriber> Layer<S> for FooLayer {}
    /// # impl<S: Subscriber> Layer<S> for BarLayer {}
    /// # impl FooLayer {
    /// # fn new() -> Self { Self {} }
    /// # }
    /// # impl BarLayer {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # impl MySubscriber {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata, Event};
    /// # impl tracing_core::Subscriber for MySubscriber {
    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(1) }
    /// #   fn record(&self, _: &Id, _: &Record) {}
    /// #   fn event(&self, _: &Event) {}
    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
    /// #   fn enter(&self, _: &Id) {}
    /// #   fn exit(&self, _: &Id) {}
    /// # }
    /// pub struct BazLayer {
    ///     // ...
    /// }
    ///
    /// impl<S: Subscriber> Layer<S> for BazLayer {
    ///     // ...
    /// }
    /// # impl BazLayer { fn new() -> Self { BazLayer } }
    ///
    /// let subscriber = FooLayer::new()
    ///     .and_then(BarLayer::new())
    ///     .and_then(BazLayer::new())
    ///     .with_subscriber(MySubscriber::new());
    /// # }
    /// ```
    fn and_then<L>(self, layer: L) -> Layered<L, Self, S>
    where
        L: Layer<S>,
        Self: Sized,
    {
        Layered {
            layer,
            inner: self,
            _s: PhantomData,
        }
    }

    /// Composes this `Layer` with the given [`Subscriber`], returning a
    /// `Layered` struct that implements [`Subscriber`].
    ///
    /// The returned `Layered` subscriber will call the methods on this `Layer`
    /// and then those of the wrapped subscriber.
    ///
    /// For example:
    /// ```rust
    /// # use tracing_subscriber::layer::Layer;
    /// # use tracing_core::Subscriber;
    /// # fn main() {
    /// pub struct FooLayer {
    ///     // ...
    /// }
    ///
    /// pub struct MySubscriber {
    ///     // ...
    /// }
    ///
    /// impl<S: Subscriber> Layer<S> for FooLayer {
    ///     // ...
    /// }
    ///
    /// # impl FooLayer {
    /// # fn new() -> Self { Self {} }
    /// # }
    /// # impl MySubscriber {
    /// # fn new() -> Self { Self { }}
    /// # }
    /// # use tracing_core::{span::{Id, Attributes, Record}, Metadata};
    /// # impl tracing_core::Subscriber for MySubscriber {
    /// #   fn new_span(&self, _: &Attributes) -> Id { Id::from_u64(0) }
    /// #   fn record(&self, _: &Id, _: &Record) {}
    /// #   fn event(&self, _: &tracing_core::Event) {}
    /// #   fn record_follows_from(&self, _: &Id, _: &Id) {}
    /// #   fn enabled(&self, _: &Metadata) -> bool { false }
    /// #   fn enter(&self, _: &Id) {}
    /// #   fn exit(&self, _: &Id) {}
    /// # }
    /// let subscriber = FooLayer::new()
    ///     .with_subscriber(MySubscriber::new());
    /// # }
    fn with_subscriber(self, inner: S) -> Layered<Self, S>
    where
        Self: Sized,
    {
        Layered {
            layer: self,
            inner,
            _s: PhantomData,
        }
    }

    #[doc(hidden)]
    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
        if id == TypeId::of::<Self>() {
            Some(&self as *const _ as *const ())
        } else {
            None
        }
    }
}

pub trait SubscriberExt: Subscriber + crate::sealed::Sealed {
    fn with<L>(self, layer: L) -> Layered<L, Self>
    where
        L: Layer<Self>,
        Self: Sized,
    {
        Layered {
            layer,
            inner: self,
            _s: PhantomData,
        }
    }
}

/// Represents information about the current context provided to `Layer`s by the
/// wrapped `Subscriber`.
#[derive(Debug)]
pub struct Context<'a, S> {
    subscriber: Option<&'a S>,
}

#[derive(Clone, Debug)]
pub struct Layered<L, I, S = I> {
    layer: L,
    inner: I,
    _s: PhantomData<fn(S)>,
}

// === impl Layered ===

impl<L, S> Subscriber for Layered<L, S>
where
    L: Layer<S>,
    S: Subscriber,
{
    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
        let outer = self.layer.register_callsite(metadata);
        if outer.is_never() {
            // if the outer layer has disabled the callsite, return now so that
            // the subscriber doesn't get its hopes up.
            return outer;
        }

        let inner = self.inner.register_callsite(metadata);
        if outer.is_sometimes() {
            // if this interest is "sometimes", return "sometimes" to ensure that
            // filters are reevaluated.
            outer
        } else {
            // otherwise, allow the inner subscriber to weigh in.
            inner
        }
    }

    fn enabled(&self, metadata: &Metadata) -> bool {
        if self.layer.enabled(metadata, self.ctx()) {
            // if the outer layer enables the callsite metadata, ask the subscriber.
            self.inner.enabled(metadata)
        } else {
            // otherwise, the callsite is disabled by the layer
            false
        }
    }

    fn new_span(&self, span: &span::Attributes) -> span::Id {
        let id = self.inner.new_span(span);
        self.layer.new_span(span, &id, self.ctx());
        id
    }

    fn record(&self, span: &span::Id, values: &span::Record) {
        self.inner.record(span, values);
        self.layer.on_record(span, values, self.ctx());
    }

    fn record_follows_from(&self, span: &span::Id, follows: &span::Id) {
        self.inner.record_follows_from(span, follows);
        self.layer.on_follows_from(span, follows, self.ctx());
    }

    fn event(&self, event: &Event) {
        self.inner.event(event);
        self.layer.on_event(event, self.ctx());
    }

    fn enter(&self, span: &span::Id) {
        self.inner.enter(span);
        self.layer.on_enter(span, self.ctx());
    }

    fn exit(&self, span: &span::Id) {
        self.inner.exit(span);
        self.layer.on_exit(span, self.ctx());
    }

    fn clone_span(&self, old: &span::Id) -> span::Id {
        let new = self.inner.clone_span(old);
        if &new != old {
            self.layer.on_id_change(old, &new, self.ctx())
        };
        new
    }

    #[inline]
    fn drop_span(&self, id: span::Id) {
        self.try_close(id);
    }

    fn try_close(&self, id: span::Id) -> bool {
        let id2 = id.clone();
        if self.inner.try_close(id) {
            self.layer.on_close(id2, self.ctx());
            true
        } else {
            false
        }
    }

    #[doc(hidden)]
    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
        self.layer
            .downcast_raw(id)
            .or_else(|| self.inner.downcast_raw(id))
    }
}

impl<S, A, B> Layer<S> for Layered<A, B, S>
where
    A: Layer<S>,
    B: Layer<S>,
    S: Subscriber,
{
    fn register_callsite(&self, metadata: &'static Metadata<'static>) -> Interest {
        let outer = self.layer.register_callsite(metadata);
        if outer.is_never() {
            // if the outer layer has disabled the callsite, return now so that
            // inner layers  don't get their hopes up.
            return outer;
        }

        let inner = self.inner.register_callsite(metadata);
        if outer.is_sometimes() {
            // if this interest is "sometimes", return "sometimes" to ensure that
            // filters are reevaluated.
            outer
        } else {
            // otherwise, allow the inner layer to weigh in.
            inner
        }
    }

    fn enabled(&self, metadata: &Metadata, ctx: Context<S>) -> bool {
        if self.layer.enabled(metadata, ctx.clone()) {
            // if the outer layer enables the callsite metadata, ask the inner layer.
            self.inner.enabled(metadata, ctx)
        } else {
            // otherwise, the callsite is disabled by this layer
            false
        }
    }

    #[inline]
    fn new_span(&self, attrs: &span::Attributes, id: &span::Id, ctx: Context<S>) {
        self.inner.new_span(attrs, id, ctx.clone());
        self.layer.new_span(attrs, id, ctx);
    }

    #[inline]
    fn on_record(&self, span: &span::Id, values: &span::Record, ctx: Context<S>) {
        self.inner.on_record(span, values, ctx.clone());
        self.layer.on_record(span, values, ctx);
    }

    #[inline]
    fn on_follows_from(&self, span: &span::Id, follows: &span::Id, ctx: Context<S>) {
        self.inner.on_follows_from(span, follows, ctx.clone());
        self.layer.on_follows_from(span, follows, ctx);
    }

    #[inline]
    fn on_event(&self, event: &Event, ctx: Context<S>) {
        self.inner.on_event(event, ctx.clone());
        self.layer.on_event(event, ctx);
    }

    #[inline]
    fn on_enter(&self, id: &span::Id, ctx: Context<S>) {
        self.inner.on_enter(id, ctx.clone());
        self.layer.on_enter(id, ctx);
    }

    #[inline]
    fn on_exit(&self, id: &span::Id, ctx: Context<S>) {
        self.inner.on_exit(id, ctx.clone());
        self.layer.on_exit(id, ctx);
    }

    #[inline]
    fn on_close(&self, id: span::Id, ctx: Context<S>) {
        self.inner.on_close(id.clone(), ctx.clone());
        self.layer.on_close(id, ctx);
    }

    #[inline]
    fn on_id_change(&self, old: &span::Id, new: &span::Id, ctx: Context<S>) {
        self.inner.on_id_change(old, new, ctx.clone());
        self.layer.on_id_change(old, new, ctx);
    }

    #[doc(hidden)]
    unsafe fn downcast_raw(&self, id: TypeId) -> Option<*const ()> {
        self.layer
            .downcast_raw(id)
            .or_else(|| self.inner.downcast_raw(id))
    }
}

impl<L, S> Layered<L, S>
where
    S: Subscriber,
{
    fn ctx(&self) -> Context<S> {
        Context {
            subscriber: Some(&self.inner),
        }
    }
}

// === impl SubscriberExt ===

impl<S: Subscriber> crate::sealed::Sealed for S {}
impl<S: Subscriber> SubscriberExt for S {}

// === impl Context ===

impl<'a, S: Subscriber> Context<'a, S> {
    /// Returns the wrapped subscriber's view of the current span.
    #[inline]
    pub fn current_span(&self) -> span::Current {
        self.subscriber
            .map(Subscriber::current_span)
            // TODO: this would be more correct as "unknown", so perhaps
            // `tracing-core` should make `Current::unknown()` public?
            .unwrap_or_else(span::Current::none)
    }
}

impl<'a, S> Context<'a, S> {
    pub(crate) fn none() -> Self {
        Self { subscriber: None }
    }
}

impl<'a, S> Clone for Context<'a, S> {
    #[inline]
    fn clone(&self) -> Self {
        let subscriber = if let Some(ref subscriber) = self.subscriber {
            Some(*subscriber)
        } else {
            None
        };
        Context { subscriber }
    }
}

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

    struct NopSubscriber;

    impl Subscriber for NopSubscriber {
        fn register_callsite(&self, _: &'static Metadata<'static>) -> Interest {
            Interest::never()
        }

        fn enabled(&self, _: &Metadata) -> bool {
            false
        }

        fn new_span(&self, _: &span::Attributes) -> span::Id {
            span::Id::from_u64(1)
        }

        fn record(&self, _: &span::Id, _: &span::Record) {}
        fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
        fn event(&self, _: &Event) {}
        fn enter(&self, _: &span::Id) {}
        fn exit(&self, _: &span::Id) {}
    }

    struct NopLayer;
    impl<S: Subscriber> Layer<S> for NopLayer {}

    struct NopLayer2;
    impl<S: Subscriber> Layer<S> for NopLayer2 {}

    fn assert_subscriber(_s: impl Subscriber) {}

    #[test]
    fn layer_is_subscriber() {
        let s = NopLayer.with_subscriber(NopSubscriber);
        assert_subscriber(s)
    }

    #[test]
    fn two_layers_are_subscriber() {
        let s = NopLayer.and_then(NopLayer).with_subscriber(NopSubscriber);
        assert_subscriber(s)
    }

    #[test]
    fn three_layers_are_subscriber() {
        let s = NopLayer
            .and_then(NopLayer)
            .and_then(NopLayer)
            .with_subscriber(NopSubscriber);
        assert_subscriber(s)
    }

    #[test]
    fn downcasts_to_subscriber() {
        let s = NopLayer
            .and_then(NopLayer)
            .and_then(NopLayer)
            .with_subscriber(NopSubscriber);
        assert!(Subscriber::downcast_ref::<NopSubscriber>(&s).is_some());
    }

    #[test]
    fn downcasts_to_layer() {
        let s = NopLayer
            .and_then(NopLayer)
            .and_then(NopLayer2)
            .with_subscriber(NopSubscriber);
        assert!(Subscriber::downcast_ref::<NopLayer>(&s).is_some());
        assert!(Subscriber::downcast_ref::<NopLayer2>(&s).is_some());
    }
}