archivist_lib/inspect/
container.rs

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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use crate::constants;
use crate::diagnostics::{GlobalConnectionStats, TRACE_CATEGORY};
use crate::identity::ComponentIdentity;
use crate::inspect::collector::{self as collector, InspectData};
use crate::pipeline::ComponentAllowlist;
use diagnostics_data::{self as schema, InspectHandleName};
use diagnostics_hierarchy::DiagnosticsHierarchy;
use fidl::endpoints::Proxy;
use flyweights::FlyStr;
use fuchsia_async::{self as fasync, DurationExt, TimeoutExt};
use fuchsia_inspect::reader::snapshot::{Snapshot, SnapshotTree};
use futures::channel::oneshot;
use futures::{FutureExt, Stream};
use selectors::SelectorExt;
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, Weak};
use std::time::Duration;
use tracing::warn;
use zx::{self as zx, AsHandleRef};
use {
    fidl_fuchsia_diagnostics as fdiagnostics, fidl_fuchsia_inspect as finspect,
    fidl_fuchsia_io as fio, fuchsia_trace as ftrace, inspect_fidl_load as deprecated_inspect,
};

#[derive(Debug)]
pub enum InspectHandle {
    Tree {
        proxy: finspect::TreeProxy,
        name: Option<FlyStr>,
    },
    Directory {
        proxy: fio::DirectoryProxy,
    },
    Escrow {
        vmo: Arc<zx::Vmo>,
        name: Option<FlyStr>,
        token: finspect::EscrowToken,
        related_koid: zx::Koid,
    },
}

impl InspectHandle {
    fn is_closed(&self) -> bool {
        match self {
            Self::Directory { proxy } => proxy.as_channel().is_closed(),
            Self::Tree { proxy, .. } => proxy.as_channel().is_closed(),
            Self::Escrow { .. } => false,
        }
    }

    async fn on_closed(&self) -> Result<zx::Signals, zx::Status> {
        match self {
            Self::Tree { proxy, .. } => proxy.on_closed().await,
            Self::Directory { proxy, .. } => proxy.on_closed().await,
            Self::Escrow { token, .. } => {
                fasync::OnSignals::new(&token.token, fidl::Signals::OBJECT_PEER_CLOSED).await
            }
        }
    }

    pub fn koid(&self) -> zx::Koid {
        match self {
            Self::Directory { proxy } => {
                proxy.as_channel().as_handle_ref().get_koid().expect("DirectoryProxy has koid")
            }
            Self::Tree { proxy, .. } => {
                proxy.as_channel().as_handle_ref().get_koid().expect("TreeProxy has koid")
            }
            // We return the related koid to index based on it so that the retrieval is more
            // efficient.
            Self::Escrow { related_koid, .. } => *related_koid,
        }
    }

    pub fn tree<T: Into<FlyStr>>(proxy: finspect::TreeProxy, name: Option<T>) -> Self {
        InspectHandle::Tree { proxy, name: name.map(|n| n.into()) }
    }

    pub fn escrow<T: Into<FlyStr>>(
        vmo: zx::Vmo,
        token: finspect::EscrowToken,
        name: Option<T>,
    ) -> Self {
        let related_koid = token.token.basic_info().unwrap().related_koid;
        InspectHandle::Escrow {
            vmo: Arc::new(vmo),
            name: name.map(|n| n.into()),
            token,
            related_koid,
        }
    }

    pub fn directory(proxy: fio::DirectoryProxy) -> Self {
        InspectHandle::Directory { proxy }
    }
}

struct StoredInspectHandle {
    handle: Arc<InspectHandle>,
    // Whenever we delete the stored handle from the map, we can leverage dropping this oneshot to
    // trigger completion of the Task listening for related handle peer closed.
    _control: oneshot::Sender<()>,
}

#[derive(Default)]
pub struct InspectArtifactsContainer {
    /// One or more proxies that this container is configured for.
    inspect_handles: HashMap<zx::Koid, StoredInspectHandle>,
}

impl InspectArtifactsContainer {
    /// Remove a handle via its `koid` from the set of proxies managed by `self`.
    pub fn remove_handle(&mut self, koid: zx::Koid) -> (Option<Arc<InspectHandle>>, usize) {
        let stored = self.inspect_handles.remove(&koid);
        (stored.map(|stored| stored.handle), self.inspect_handles.len())
    }

    /// Push a new handle into the container.
    ///
    /// Returns `None` if the handle is a DirectoryProxy and there is already one tracked,
    /// as only single handles are supported in the DirectoryProxy case.
    pub fn push_handle(
        &mut self,
        handle: InspectHandle,
        on_closed: impl FnOnce(zx::Koid),
    ) -> Option<impl Future<Output = ()>> {
        if !self.inspect_handles.is_empty() && matches!(handle, InspectHandle::Directory { .. }) {
            return None;
        }
        let (control_snd, control_rcv) = oneshot::channel();
        let handle = Arc::new(handle);
        let stored = StoredInspectHandle { _control: control_snd, handle: Arc::clone(&handle) };
        let koid = handle.koid();
        self.inspect_handles.insert(koid, stored);
        Some(async move {
            if !handle.is_closed() {
                let closed_fut = handle.on_closed();
                futures::pin_mut!(closed_fut);
                let _ = futures::future::select(closed_fut, control_rcv).await;
            }
            on_closed(koid);
        })
    }

    /// Generate an `UnpopulatedInspectDataContainer` from the proxies managed by `self`.
    ///
    /// Returns `None` if there are no valid proxies.
    pub fn create_unpopulated(
        &self,
        identity: &Arc<ComponentIdentity>,
        allowlist: ComponentAllowlist,
        dynamic_selectors: &Option<impl AsRef<[fdiagnostics::Selector]>>,
    ) -> Option<UnpopulatedInspectDataContainer> {
        if self.inspect_handles.is_empty() {
            return None;
        }

        if allowlist.all_filtered_out() {
            return None;
        }

        // Verify that dynamic selectors contain an entry that applies to this moniker
        let mut dynamic_selectors = dynamic_selectors.as_ref().map(|all_components| {
            all_components
                .as_ref()
                .iter()
                .filter(|s| matches!(identity.moniker.matches_selector(s), Ok(true)))
                .peekable()
        });

        if let Some(None) = dynamic_selectors.as_mut().map(|s| s.peek()) {
            return None;
        }

        Some(UnpopulatedInspectDataContainer {
            identity: Arc::clone(identity),
            component_allowlist: allowlist,
            inspect_handles: self
                .inspect_handles
                .values()
                .filter(|s| {
                    // dynamic_selectors.clone() should just be a clone of the iterator, so as to
                    // always start at the beginning
                    Self::name_filters_satisfied(s.handle.as_ref(), dynamic_selectors.clone())
                })
                .map(|s| Arc::downgrade(&s.handle))
                .collect::<Vec<_>>(),
        })
    }

    fn name_filters_satisfied<'a>(
        handle: &InspectHandle,
        mut dynamic_selectors: Option<impl Iterator<Item = &'a fdiagnostics::Selector>>,
    ) -> bool {
        let Some(ref mut selectors) = dynamic_selectors else {
            return true;
        };
        match handle {
            InspectHandle::Tree { name, .. } | InspectHandle::Escrow { name, .. } => {
                selectors.any(|s| {
                    let name = match name.as_ref() {
                        Some(fly) => fly.as_str(),
                        None => finspect::DEFAULT_TREE_NAME,
                    };
                    selectors::match_tree_name_against_selector(name, s)
                })
            }
            InspectHandle::Directory { .. } => selectors.any(|s| {
                matches!(s.tree_names.as_ref(), None | Some(fdiagnostics::TreeNames::All(_)))
            }),
        }
    }
}

#[cfg(test)]
impl InspectArtifactsContainer {
    pub(crate) fn handles(&self) -> impl ExactSizeIterator<Item = &InspectHandle> {
        self.inspect_handles.values().map(|stored| stored.handle.as_ref())
    }
}

static TIMEOUT_MESSAGE: &str = "Exceeded per-component time limit for fetching diagnostics data";

#[derive(Debug)]
pub enum ReadSnapshot {
    Single(Snapshot),
    Tree(SnapshotTree),
    Finished(DiagnosticsHierarchy),
}

/// Packet containing a snapshot and all the metadata needed to
/// populate a diagnostics schema for that snapshot.
#[derive(Debug)]
pub struct SnapshotData {
    /// Optional name of the file or InspectSink proxy that created this snapshot.
    pub name: Option<InspectHandleName>,
    /// Timestamp at which this snapshot resolved or failed.
    pub timestamp: zx::BootInstant,
    /// Errors encountered when processing this snapshot.
    pub errors: Vec<schema::InspectError>,
    /// Optional snapshot of the inspect hierarchy, in case reading fails
    /// and we have errors to share with client.
    pub snapshot: Option<ReadSnapshot>,
    /// Whether or not the data was escrowed.
    pub escrowed: bool,
}

impl SnapshotData {
    async fn new(
        name: Option<InspectHandleName>,
        data: InspectData,
        lazy_child_timeout: zx::MonotonicDuration,
        identity: &ComponentIdentity,
        parent_trace_id: ftrace::Id,
    ) -> SnapshotData {
        let trace_id = ftrace::Id::random();
        let _trace_guard = ftrace::async_enter!(
            trace_id,
            TRACE_CATEGORY,
            c"SnapshotData::new",
            // An async duration cannot have multiple concurrent child async durations
            // so we include the nonce as metadata to manually determine relationship.
            "parent_trace_id" => u64::from(parent_trace_id),
            "trace_id" => u64::from(trace_id),
            "moniker" => identity.to_string().as_ref(),
            "filename" => name
                    .as_ref()
                    .and_then(InspectHandleName::as_filename)
                    .unwrap_or(""),
            "name" => name
                    .as_ref()
                    .and_then(InspectHandleName::as_name)
                    .unwrap_or("")
        );
        match data {
            InspectData::Tree(tree) => {
                let lazy_child_timeout =
                    Duration::from_nanos(lazy_child_timeout.into_nanos() as u64);
                match SnapshotTree::try_from_with_timeout(&tree, lazy_child_timeout).await {
                    Ok(snapshot_tree) => {
                        SnapshotData::successful(ReadSnapshot::Tree(snapshot_tree), name, false)
                    }
                    Err(e) => SnapshotData::failed(
                        schema::InspectError { message: format!("{e:?}") },
                        name,
                        false,
                    ),
                }
            }
            InspectData::DeprecatedFidl(inspect_proxy) => {
                match deprecated_inspect::load_hierarchy(inspect_proxy).await {
                    Ok(hierarchy) => {
                        SnapshotData::successful(ReadSnapshot::Finished(hierarchy), name, false)
                    }
                    Err(e) => SnapshotData::failed(
                        schema::InspectError { message: format!("{e:?}") },
                        name,
                        false,
                    ),
                }
            }
            InspectData::Vmo { data: vmo, escrowed } => match Snapshot::try_from(vmo.as_ref()) {
                Ok(snapshot) => {
                    SnapshotData::successful(ReadSnapshot::Single(snapshot), name, escrowed)
                }
                Err(e) => SnapshotData::failed(
                    schema::InspectError { message: format!("{e:?}") },
                    name,
                    escrowed,
                ),
            },
            InspectData::File(contents) => match Snapshot::try_from(contents) {
                Ok(snapshot) => {
                    SnapshotData::successful(ReadSnapshot::Single(snapshot), name, false)
                }
                Err(e) => SnapshotData::failed(
                    schema::InspectError { message: format!("{e:?}") },
                    name,
                    false,
                ),
            },
        }
    }

    // Constructs packet that timestamps and packages inspect snapshot for exfiltration.
    fn successful(
        snapshot: ReadSnapshot,
        name: Option<InspectHandleName>,
        escrowed: bool,
    ) -> SnapshotData {
        SnapshotData {
            name,
            timestamp: zx::BootInstant::get(),
            errors: Vec::new(),
            snapshot: Some(snapshot),
            escrowed,
        }
    }

    // Constructs packet that timestamps and packages inspect snapshot failure for exfiltration.
    fn failed(
        error: schema::InspectError,
        name: Option<InspectHandleName>,
        escrowed: bool,
    ) -> SnapshotData {
        SnapshotData {
            name,
            timestamp: zx::BootInstant::get(),
            errors: vec![error],
            snapshot: None,
            escrowed,
        }
    }
}

/// PopulatedInspectDataContainer is the container that
/// holds the actual Inspect data for a given component,
/// along with all information needed to transform that data
/// to be returned to the client.
pub struct PopulatedInspectDataContainer {
    pub identity: Arc<ComponentIdentity>,
    /// Vector of all the snapshots of inspect hierarchies under
    /// the diagnostics directory of the component identified by
    /// moniker, along with the metadata needed to populate
    /// this snapshot's diagnostics schema.
    pub snapshot: SnapshotData,
    pub component_allowlist: ComponentAllowlist,
}

enum Status {
    Begin,
    Pending(collector::InspectHandleDeque),
}

struct State {
    status: Status,
    unpopulated: Arc<UnpopulatedInspectDataContainer>,
    batch_timeout: zx::MonotonicDuration,
    elapsed_time: zx::MonotonicDuration,
    global_stats: Arc<GlobalConnectionStats>,
    trace_guard: Arc<Option<ftrace::AsyncScope>>,
    trace_id: ftrace::Id,
}

impl State {
    fn into_pending(
        self,
        pending: collector::InspectHandleDeque,
        start_time: zx::MonotonicInstant,
    ) -> Self {
        Self {
            unpopulated: self.unpopulated,
            status: Status::Pending(pending),
            batch_timeout: self.batch_timeout,
            global_stats: self.global_stats,
            elapsed_time: self.elapsed_time + (zx::MonotonicInstant::get() - start_time),
            trace_guard: self.trace_guard,
            trace_id: self.trace_id,
        }
    }

    fn add_elapsed_time(&mut self, start_time: zx::MonotonicInstant) {
        self.elapsed_time += zx::MonotonicInstant::get() - start_time
    }

    async fn iterate(
        mut self,
        start_time: zx::MonotonicInstant,
    ) -> Option<(PopulatedInspectDataContainer, State)> {
        loop {
            match &mut self.status {
                Status::Begin => {
                    let data_map =
                        collector::populate_data_map(&self.unpopulated.inspect_handles).await;
                    self = self.into_pending(data_map, start_time);
                }
                Status::Pending(ref mut pending) => match pending.pop_front() {
                    None => {
                        self.global_stats.record_component_duration(
                            self.unpopulated.identity.moniker.to_string(),
                            self.elapsed_time + (zx::MonotonicInstant::get() - start_time),
                        );
                        return None;
                    }
                    Some((name, data)) => {
                        let snapshot = SnapshotData::new(
                            name,
                            data,
                            self.batch_timeout / constants::LAZY_NODE_TIMEOUT_PROPORTION,
                            &self.unpopulated.identity,
                            self.trace_id,
                        )
                        .await;
                        let result = PopulatedInspectDataContainer {
                            identity: Arc::clone(&self.unpopulated.identity),
                            snapshot,
                            component_allowlist: self.unpopulated.component_allowlist.clone(),
                        };
                        self.add_elapsed_time(start_time);
                        return Some((result, self));
                    }
                },
            }
        }
    }
}

/// UnpopulatedInspectDataContainer is the container that holds
/// all information needed to retrieve Inspect data
/// for a given component, when requested.
#[derive(Debug)]
pub struct UnpopulatedInspectDataContainer {
    pub identity: Arc<ComponentIdentity>,
    /// Proxies configured for container. It is an invariant that if any value is an
    /// InspectHandle::Directory, then there is exactly one value.
    pub inspect_handles: Vec<Weak<InspectHandle>>,
    /// Optional hierarchy matcher. If unset, the reader is running
    /// in all-access mode, meaning no matching or filtering is required.
    pub component_allowlist: ComponentAllowlist,
}

impl UnpopulatedInspectDataContainer {
    /// Populates this data container with a timeout. On the timeout firing returns a
    /// container suitable to return to clients, but with timeout error information recorded.
    pub fn populate(
        self,
        timeout: i64,
        global_stats: Arc<GlobalConnectionStats>,
        parent_trace_id: ftrace::Id,
    ) -> impl Stream<Item = PopulatedInspectDataContainer> {
        let trace_id = ftrace::Id::random();
        let trace_guard = ftrace::async_enter!(
            trace_id,
            TRACE_CATEGORY,
            c"ReaderServer::stream.populate",
            // An async duration cannot have multiple concurrent child async durations
            // so we include the nonce as metadata to manually determine relationship.
            "parent_trace_id" => u64::from(parent_trace_id),
            "trace_id" => u64::from(trace_id),
            "moniker" => self.identity.to_string().as_ref()
        );
        let this = Arc::new(self);
        let state = State {
            status: Status::Begin,
            unpopulated: this,
            batch_timeout: zx::MonotonicDuration::from_seconds(timeout),
            global_stats,
            elapsed_time: zx::MonotonicDuration::ZERO,
            trace_guard: Arc::new(trace_guard),
            trace_id,
        };

        futures::stream::unfold(state, |state| {
            let unpopulated_for_timeout = Arc::clone(&state.unpopulated);
            let timeout = state.batch_timeout;
            let elapsed_time = state.elapsed_time;
            let global_stats = Arc::clone(&state.global_stats);
            let start_time = zx::MonotonicInstant::get();
            let trace_guard = Arc::clone(&state.trace_guard);
            let trace_id = state.trace_id;

            state
                .iterate(start_time)
                .on_timeout((timeout - elapsed_time).after_now(), move || {
                    warn!(identity = ?unpopulated_for_timeout.identity.moniker, "{TIMEOUT_MESSAGE}");
                    global_stats.add_timeout();
                    let result = PopulatedInspectDataContainer {
                        identity: Arc::clone(&unpopulated_for_timeout.identity),
                        component_allowlist: unpopulated_for_timeout.component_allowlist.clone(),
                        snapshot: SnapshotData::failed(
                            schema::InspectError { message: TIMEOUT_MESSAGE.to_string() },
                            None,
                            false,
                        ),
                    };
                    Some((
                        result,
                        State {
                            status: Status::Pending(collector::InspectHandleDeque::new()),
                            unpopulated: unpopulated_for_timeout,
                            batch_timeout: timeout,
                            global_stats,
                            elapsed_time: elapsed_time + (zx::MonotonicInstant::get() - start_time),
                            trace_guard,
                            trace_id,
                        },
                    ))
                })
                .boxed()
        })
    }
}

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

    use futures::StreamExt;
    use std::sync::LazyLock;

    static EMPTY_IDENTITY: LazyLock<Arc<ComponentIdentity>> =
        LazyLock::new(|| Arc::new(ComponentIdentity::unknown()));

    static O_K_IDENTITY: LazyLock<Arc<ComponentIdentity>> =
        LazyLock::new(|| Arc::new(ComponentIdentity::from(vec!["o", "k"])));

    #[fuchsia::test]
    async fn population_times_out() {
        // Simulate a directory that hangs indefinitely in any request so that we consistently
        // trigger the 0 timeout.
        let (directory, mut stream) =
            fidl::endpoints::create_proxy_and_stream::<fio::DirectoryMarker>();
        fasync::Task::spawn(async move {
            while stream.next().await.is_some() {
                fasync::Timer::new(fasync::MonotonicInstant::after(
                    zx::MonotonicDuration::from_seconds(100000),
                ))
                .await;
            }
        })
        .detach();

        let handle = Arc::new(InspectHandle::directory(directory));
        let container = UnpopulatedInspectDataContainer {
            identity: EMPTY_IDENTITY.clone(),
            inspect_handles: vec![Arc::downgrade(&handle)],
            component_allowlist: ComponentAllowlist::new_disabled(),
        };
        let mut stream = container.populate(
            0,
            Arc::new(GlobalConnectionStats::new(Node::default())),
            ftrace::Id::random(),
        );
        let res = stream.next().await.unwrap();
        assert_eq!(res.snapshot.name, None);
        assert_eq!(
            res.snapshot.errors,
            vec![schema::InspectError { message: TIMEOUT_MESSAGE.to_string() }]
        );
    }

    #[fuchsia::test]
    async fn no_inspect_files_do_not_give_an_error_response() {
        let directory = Arc::new(InspectHandle::directory(
            fuchsia_fs::directory::open_in_namespace("/tmp", fio::PERM_READABLE).unwrap(),
        ));
        let container = UnpopulatedInspectDataContainer {
            identity: EMPTY_IDENTITY.clone(),
            inspect_handles: vec![Arc::downgrade(&directory)],
            component_allowlist: ComponentAllowlist::new_disabled(),
        };
        let mut stream = container.populate(
            1000000,
            Arc::new(GlobalConnectionStats::new(Node::default())),
            ftrace::Id::random(),
        );
        assert!(stream.next().await.is_none());
    }

    #[fuchsia::test]
    fn only_one_directory_proxy_is_populated() {
        let _executor = fuchsia_async::LocalExecutor::new();
        let (directory, _) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
        let mut container = InspectArtifactsContainer::default();
        let _rx = container.push_handle(InspectHandle::directory(directory), |_| {});
        let (directory2, _) = fidl::endpoints::create_proxy::<fio::DirectoryMarker>();
        assert!(container.push_handle(InspectHandle::directory(directory2), |_| {}).is_none());
    }

    fn inspect_artifacts_container_with_one_dir() -> InspectArtifactsContainer {
        let (directory, _) = fidl::endpoints::create_proxy_and_stream::<fio::DirectoryMarker>();
        let handle = InspectHandle::directory(directory);
        let mut container = InspectArtifactsContainer::default();
        container.push_handle(handle, |_| {});
        container
    }

    #[fuchsia::test]
    fn prefilter_on_names_for_directories() {
        let _executor = fuchsia_async::LocalExecutor::new();
        let all_selector = fdiagnostics::Selector {
            tree_names: Some(fdiagnostics::TreeNames::All(fdiagnostics::All {})),
            component_selector: Some(fdiagnostics::ComponentSelector {
                moniker_segments: Some(vec![
                    fdiagnostics::StringSelector::ExactMatch("o".to_string()),
                    fdiagnostics::StringSelector::ExactMatch("k".to_string()),
                ]),
                ..Default::default()
            }),
            tree_selector: Some(fdiagnostics::TreeSelector::SubtreeSelector(
                fdiagnostics::SubtreeSelector {
                    node_path: vec![fdiagnostics::StringSelector::ExactMatch("root".to_string())],
                },
            )),
            ..Default::default()
        };
        let selectors = Some(vec![all_selector]);

        let iac = inspect_artifacts_container_with_one_dir();
        let container = iac
            .create_unpopulated(&O_K_IDENTITY, ComponentAllowlist::new_disabled(), &selectors)
            .unwrap();

        assert_eq!(1, container.inspect_handles.len());

        let selector_with_wrong_tree_name = fdiagnostics::Selector {
            tree_names: Some(fdiagnostics::TreeNames::Some(vec!["a".to_string()])),
            component_selector: Some(fdiagnostics::ComponentSelector {
                moniker_segments: Some(vec![
                    fdiagnostics::StringSelector::ExactMatch("o".to_string()),
                    fdiagnostics::StringSelector::ExactMatch("k".to_string()),
                ]),
                ..Default::default()
            }),
            tree_selector: Some(fdiagnostics::TreeSelector::SubtreeSelector(
                fdiagnostics::SubtreeSelector {
                    node_path: vec![fdiagnostics::StringSelector::ExactMatch("root".to_string())],
                },
            )),
            ..Default::default()
        };
        let selectors = Some(vec![selector_with_wrong_tree_name]);

        let iac = inspect_artifacts_container_with_one_dir();
        let container = iac
            .create_unpopulated(&O_K_IDENTITY, ComponentAllowlist::new_disabled(), &selectors)
            .unwrap();

        assert_eq!(0, container.inspect_handles.len());

        let selector_with_no_tree_names = fdiagnostics::Selector {
            tree_names: None,
            component_selector: Some(fdiagnostics::ComponentSelector {
                moniker_segments: Some(vec![
                    fdiagnostics::StringSelector::ExactMatch("o".to_string()),
                    fdiagnostics::StringSelector::ExactMatch("k".to_string()),
                ]),
                ..Default::default()
            }),
            tree_selector: Some(fdiagnostics::TreeSelector::SubtreeSelector(
                fdiagnostics::SubtreeSelector {
                    node_path: vec![fdiagnostics::StringSelector::ExactMatch("root".to_string())],
                },
            )),
            ..Default::default()
        };

        let selectors = Some(vec![selector_with_no_tree_names]);

        let iac = inspect_artifacts_container_with_one_dir();
        let container = iac
            .create_unpopulated(&O_K_IDENTITY, ComponentAllowlist::new_disabled(), &selectors)
            .unwrap();
        assert_eq!(1, container.inspect_handles.len());
    }

    fn inspect_artifacts_container_with_n_trees<'a>(
        tree_names: impl IntoIterator<Item = &'a str>,
    ) -> InspectArtifactsContainer {
        let mut container = InspectArtifactsContainer::default();
        for name in tree_names {
            let (proxy, _) = fidl::endpoints::create_proxy::<finspect::TreeMarker>();
            let handle = InspectHandle::tree(proxy, Some(name));
            container.push_handle(handle, |_| {});
        }
        container
    }

    #[fuchsia::test]
    fn name_filter_with_no_matches() {
        let _executor = fuchsia_async::LocalExecutor::new();

        let b_only = fdiagnostics::Selector {
            tree_names: Some(fdiagnostics::TreeNames::Some(vec!["b".to_string()])),
            component_selector: Some(fdiagnostics::ComponentSelector {
                moniker_segments: Some(vec![
                    fdiagnostics::StringSelector::ExactMatch("o".to_string()),
                    fdiagnostics::StringSelector::ExactMatch("k".to_string()),
                ]),
                ..Default::default()
            }),
            tree_selector: Some(fdiagnostics::TreeSelector::SubtreeSelector(
                fdiagnostics::SubtreeSelector {
                    node_path: vec![fdiagnostics::StringSelector::ExactMatch("root".to_string())],
                },
            )),
            ..Default::default()
        };
        let selectors = Some(vec![b_only]);

        let iac = inspect_artifacts_container_with_n_trees(["a"]);
        let container = iac
            .create_unpopulated(&O_K_IDENTITY, ComponentAllowlist::new_disabled(), &selectors)
            .unwrap();
        assert_eq!(0, container.inspect_handles.len());
    }

    #[fuchsia::test]
    fn all_name_filter_matches_everything() {
        let _executor = fuchsia_async::LocalExecutor::new();

        let iac = inspect_artifacts_container_with_n_trees(["a", "b"]);
        let container = iac
            .create_unpopulated(
                &O_K_IDENTITY,
                ComponentAllowlist::new_disabled(),
                &None::<&[fdiagnostics::Selector]>,
            )
            .unwrap();
        assert_eq!(2, container.inspect_handles.len());

        let all_selector = fdiagnostics::Selector {
            tree_names: Some(fdiagnostics::TreeNames::All(fdiagnostics::All {})),
            component_selector: Some(fdiagnostics::ComponentSelector {
                moniker_segments: Some(vec![
                    fdiagnostics::StringSelector::ExactMatch("o".to_string()),
                    fdiagnostics::StringSelector::ExactMatch("k".to_string()),
                ]),
                ..Default::default()
            }),
            tree_selector: Some(fdiagnostics::TreeSelector::SubtreeSelector(
                fdiagnostics::SubtreeSelector {
                    node_path: vec![fdiagnostics::StringSelector::ExactMatch("root".to_string())],
                },
            )),
            ..Default::default()
        };
        let selectors = Some(vec![all_selector]);

        let iac = inspect_artifacts_container_with_n_trees(["a", "b"]);
        let container = iac
            .create_unpopulated(&O_K_IDENTITY, ComponentAllowlist::new_disabled(), &selectors)
            .unwrap();
        assert_eq!(2, container.inspect_handles.len());
    }

    // TODO(https://fxbug.dev/355732696): Not specifying a name filter list should implicitly mean
    // selecting for the root Inspect tree
    #[fuchsia::test]
    fn none_name_filter_matches_everything() {
        let _executor = fuchsia_async::LocalExecutor::new();

        let lists_each_name = fdiagnostics::Selector {
            tree_names: Some(fdiagnostics::TreeNames::Some(vec!["a".to_string(), "b".to_string()])),
            component_selector: Some(fdiagnostics::ComponentSelector {
                moniker_segments: Some(vec![
                    fdiagnostics::StringSelector::ExactMatch("o".to_string()),
                    fdiagnostics::StringSelector::ExactMatch("k".to_string()),
                ]),
                ..Default::default()
            }),
            tree_selector: Some(fdiagnostics::TreeSelector::SubtreeSelector(
                fdiagnostics::SubtreeSelector {
                    node_path: vec![fdiagnostics::StringSelector::ExactMatch("root".to_string())],
                },
            )),
            ..Default::default()
        };
        let selectors = Some(vec![lists_each_name]);

        let iac = inspect_artifacts_container_with_n_trees(["a", "b"]);
        let container = iac
            .create_unpopulated(&O_K_IDENTITY, ComponentAllowlist::new_disabled(), &selectors)
            .unwrap();
        assert_eq!(2, container.inspect_handles.len());
    }

    #[fuchsia::test]
    fn select_subset_of_names() {
        let _executor = fuchsia_async::LocalExecutor::new();

        let a_only = fdiagnostics::Selector {
            tree_names: Some(fdiagnostics::TreeNames::Some(vec!["a".to_string()])),
            component_selector: Some(fdiagnostics::ComponentSelector {
                moniker_segments: Some(vec![
                    fdiagnostics::StringSelector::ExactMatch("o".to_string()),
                    fdiagnostics::StringSelector::ExactMatch("k".to_string()),
                ]),
                ..Default::default()
            }),
            tree_selector: Some(fdiagnostics::TreeSelector::SubtreeSelector(
                fdiagnostics::SubtreeSelector {
                    node_path: vec![fdiagnostics::StringSelector::ExactMatch("root".to_string())],
                },
            )),
            ..Default::default()
        };
        let selectors = Some(vec![a_only]);

        let iac = inspect_artifacts_container_with_n_trees(["a", "b"]);
        let container = iac
            .create_unpopulated(&O_K_IDENTITY, ComponentAllowlist::new_disabled(), &selectors)
            .unwrap();
        assert_eq!(1, container.inspect_handles.len());

        match container.inspect_handles[0].upgrade().unwrap().as_ref() {
            InspectHandle::Tree { name: Some(n), .. } => assert_eq!(n.as_str(), "a"),
            bad_handle => {
                panic!("filtering failed, got {bad_handle:?}");
            }
        };
    }

    #[fuchsia::test]
    fn names_are_case_sensitive() {
        let _executor = fuchsia_async::LocalExecutor::new();

        let a_but_wrong_case = fdiagnostics::Selector {
            tree_names: Some(fdiagnostics::TreeNames::Some(vec!["A".to_string()])),
            component_selector: Some(fdiagnostics::ComponentSelector {
                moniker_segments: Some(vec![
                    fdiagnostics::StringSelector::ExactMatch("o".to_string()),
                    fdiagnostics::StringSelector::ExactMatch("k".to_string()),
                ]),
                ..Default::default()
            }),
            tree_selector: Some(fdiagnostics::TreeSelector::SubtreeSelector(
                fdiagnostics::SubtreeSelector {
                    node_path: vec![fdiagnostics::StringSelector::ExactMatch("root".to_string())],
                },
            )),
            ..Default::default()
        };
        let selectors = Some(vec![a_but_wrong_case]);

        let iac = inspect_artifacts_container_with_n_trees(["a", "b"]);
        let container = iac
            .create_unpopulated(&O_K_IDENTITY, ComponentAllowlist::new_disabled(), &selectors)
            .unwrap();
        assert_eq!(0, container.inspect_handles.len());
    }
}