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
// Copyright 2021 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 {
    anyhow::Error,
    fidl::endpoints::{DiscoverableProtocolMarker, ProtocolMarker, Proxy},
    fidl_fuchsia_device::{NameProviderMarker, NameProviderRequestStream},
    fidl_fuchsia_stash::SecureStoreMarker,
    fuchsia_async as fasync,
    fuchsia_component::server::{ServiceFs, ServiceObj},
    fuchsia_component_test::LocalComponentHandles,
    futures::{channel::mpsc, SinkExt, StreamExt, TryStream, TryStreamExt},
    std::sync::Arc,
    tracing::info,
    vfs::directory::{entry_container::Directory, spawn_directory},
};

// #! Library for common utilities (mocks, definitions) for the manifest integration tests.

/// Process requests received in the `stream` and relay them to the provided `sender`.
/// Logs incoming requests prefixed with the `tag`.
pub async fn process_request_stream<S, Event>(
    mut stream: S::RequestStream,
    mut sender: mpsc::Sender<Event>,
) where
    S: DiscoverableProtocolMarker,
    Event: std::convert::From<<S::RequestStream as TryStream>::Ok>,
    <S::RequestStream as TryStream>::Ok: std::fmt::Debug,
{
    while let Some(request) = stream.try_next().await.expect("serving request stream failed") {
        info!("Received {} service request: {:?}", S::PROTOCOL_NAME, request);
        sender.send(request.into()).await.expect("should send");
    }
}

/// Adds a handler for the FIDL service `S` which relays the ServerEnd of the service
/// connection request to the provided `sender`.
/// Note: This method does not process requests from the service connection. It only relays
/// the stream to the `sender.
pub fn add_fidl_service_handler<S, Event: 'static>(
    fs: &mut ServiceFs<ServiceObj<'_, ()>>,
    sender: mpsc::Sender<Event>,
) where
    S: DiscoverableProtocolMarker,
    Event: std::convert::From<S::RequestStream> + std::marker::Send,
{
    let _ = fs.dir("svc").add_fidl_service(move |req_stream: S::RequestStream| {
        let mut s = sender.clone();
        fasync::Task::local(async move {
            info!("Received connection for {}", S::PROTOCOL_NAME);
            s.send(req_stream.into()).await.expect("should send");
        })
        .detach()
    });
}

/// A mock component that provides the generic service `S`. The request stream
/// of the service is processed and any requests relayed to the provided `sender`.
pub async fn mock_component<S, Event: 'static>(
    sender: mpsc::Sender<Event>,
    handles: LocalComponentHandles,
) -> Result<(), Error>
where
    S: DiscoverableProtocolMarker,
    Event: std::convert::From<<<S as ProtocolMarker>::RequestStream as TryStream>::Ok>
        + std::marker::Send,
    <<S as ProtocolMarker>::RequestStream as TryStream>::Ok: std::fmt::Debug,
{
    let mut fs = ServiceFs::new();
    let _ = fs.dir("svc").add_fidl_service(move |req_stream: S::RequestStream| {
        let sender_clone = sender.clone();
        info!("Received connection for {}", S::PROTOCOL_NAME);
        fasync::Task::local(process_request_stream::<S, _>(req_stream, sender_clone)).detach();
    });

    let _ = fs.serve_connection(handles.outgoing_dir)?;
    fs.collect::<()>().await;
    Ok(())
}

/// Sets up a mock dev/ directory with the provided `dev_directory` topology.
pub async fn mock_dev(
    handles: LocalComponentHandles,
    dev_directory: Arc<dyn Directory>,
) -> Result<(), Error> {
    let mut fs = ServiceFs::new();
    let _ = fs.add_remote("dev", spawn_directory(dev_directory));
    let _ = fs.serve_connection(handles.outgoing_dir)?;
    fs.collect::<()>().await;
    Ok(())
}

/// A mock component serving a protocol `S` on `handles`. Specifically, this services S by calling
/// `responder` for every request of every client connection to S.
pub async fn stateless_mock_responder<S, F>(
    handles: LocalComponentHandles,
    responder: F,
) -> Result<(), anyhow::Error>
where
    S: DiscoverableProtocolMarker,
    <<S as ProtocolMarker>::RequestStream as TryStream>::Ok: std::fmt::Debug,
    F: Fn(<<S as ProtocolMarker>::RequestStream as TryStream>::Ok) -> Result<(), Error>
        + Copy
        + Send
        + 'static,
{
    let mut fs = ServiceFs::new();
    // The FIDL service's task is generated for every client connection, hence the `F: Copy` bound
    // in order to use `responder` inside the task. F's bound could be changed to `Clone` in the
    // future, but we chose not to do so for now to avoid unexpected implicit `clone`s.
    let _ = fs.dir("svc").add_fidl_service(
        move |mut req_stream: <S as ProtocolMarker>::RequestStream| {
            fasync::Task::local(async move {
                let failure_msg = format!("serving {} request stream failed", S::DEBUG_NAME);
                while let Some(req) = req_stream.try_next().await.expect(&failure_msg) {
                    let failed_to_respond = format!("failed to respond to req {:?}", req);
                    responder(req).expect(&failed_to_respond);
                }
            })
            .detach()
        },
    );
    let _ = fs.serve_connection(handles.outgoing_dir)?;
    fs.collect::<()>().await;
    Ok(())
}

/// Exposes implementations of the the services used by bt-gap in the provided `ServiceFs`.
pub fn provide_bt_gap_uses<Event>(
    fs: &mut ServiceFs<ServiceObj<'_, ()>>,
    sender: &mpsc::Sender<Event>,
    handles: &LocalComponentHandles,
) -> Result<(), Error>
where
    Event: From<SecureStoreMarker> + From<NameProviderRequestStream> + Send + 'static,
{
    let svc_dir = handles.clone_from_namespace("svc")?;
    let sender_clone = Some(sender.clone());
    let _ = fs.dir("svc").add_service_at(SecureStoreMarker::PROTOCOL_NAME, move |chan| {
        let mut s = sender_clone.clone();
        let svc_dir = Clone::clone(&svc_dir);
        fasync::Task::local(async move {
            info!(
                "Proxying {} connection to real implementation",
                SecureStoreMarker::PROTOCOL_NAME
            );
            fdio::service_connect_at(
                svc_dir.as_channel().as_ref(),
                SecureStoreMarker::PROTOCOL_NAME,
                chan,
            )
            .expect("unable to forward secure store");
            // We only care that the Secure Store is routed correctly, so if a client connects
            // to it more than once, we only want to report it the first time.
            if let Some(mut sender) = s.take() {
                sender.send(Event::from(SecureStoreMarker)).await.expect("should send");
            }
        })
        .detach();
        None
    });
    add_fidl_service_handler::<NameProviderMarker, _>(fs, sender.clone());
    Ok(())
}