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
// 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::{events::error::EventError, identity::ComponentIdentity};
use fidl::endpoints::ServerEnd;
use fidl::prelude::*;
use fidl_fuchsia_component as fcomponent;
use fidl_fuchsia_inspect as finspect;
use fidl_fuchsia_logger as flogger;
use fidl_table_validation::ValidFidlTable;
use fuchsia_zircon as zx;
use moniker::ExtendedMoniker;
use std::sync::Arc;

/// Event types that contain singleton data. When these events are cloned, their singleton data
/// won't be cloned.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum EventType {
    LogSinkRequested,
    InspectSinkRequested,
}

impl AsRef<str> for EventType {
    fn as_ref(&self) -> &str {
        match &self {
            Self::LogSinkRequested => "log_sink_requested",
            Self::InspectSinkRequested => "inspect_sink_requested",
        }
    }
}

/// An event that is emitted and consumed.
#[derive(Debug)]
pub struct Event {
    /// The contents of the event.
    pub payload: EventPayload,
    pub timestamp: zx::Time,
}

impl Event {
    pub fn ty(&self) -> EventType {
        match &self.payload {
            EventPayload::LogSinkRequested(_) => EventType::LogSinkRequested,
            EventPayload::InspectSinkRequested(_) => EventType::InspectSinkRequested,
        }
    }
}

/// The contents of the event depending on the type of event.
#[derive(Debug)]
pub enum EventPayload {
    LogSinkRequested(LogSinkRequestedPayload),
    InspectSinkRequested(InspectSinkRequestedPayload),
}

pub struct InspectSinkRequestedPayload {
    /// The component that is connecting to `InspectSink`.
    pub component: Arc<ComponentIdentity>,
    /// The stream containing requests made on the `InspectSink` channel by the component.
    pub request_stream: finspect::InspectSinkRequestStream,
}

impl std::fmt::Debug for InspectSinkRequestedPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InspectSinkRequestedPayload").field("component", &self.component).finish()
    }
}

/// Payload for a connection to the `LogSink` protocol.
pub struct LogSinkRequestedPayload {
    /// The component that is connecting to `LogSink`.
    pub component: Arc<ComponentIdentity>,
    /// The stream containing requests made on the `LogSink` channel by the component.
    pub request_stream: flogger::LogSinkRequestStream,
}

impl std::fmt::Debug for LogSinkRequestedPayload {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LogSinkRequestedPayload").field("component", &self.component).finish()
    }
}

#[derive(Debug, ValidFidlTable)]
#[fidl_table_src(fcomponent::EventHeader)]
pub struct ValidatedEventHeader {
    pub event_type: fcomponent::EventType,
    pub component_url: String,
    pub moniker: String,
    pub timestamp: i64,
}

#[derive(Debug, ValidFidlTable)]
#[fidl_table_src(fcomponent::Event)]
pub struct ValidatedEvent {
    /// Information about the component for which this event was generated.
    pub header: ValidatedEventHeader,

    pub payload: fcomponent::EventPayload,
}

impl TryFrom<fcomponent::Event> for Event {
    type Error = EventError;

    fn try_from(event: fcomponent::Event) -> Result<Event, Self::Error> {
        if let Ok(event) = ValidatedEvent::try_from(event) {
            let identity = ComponentIdentity::new(
                ExtendedMoniker::parse_str(&event.header.moniker)?,
                &event.header.component_url,
            );

            match event.header.event_type {
                fcomponent::EventType::CapabilityRequested => match event.payload {
                    fcomponent::EventPayload::CapabilityRequested(capability_requested) => {
                        let name =
                            capability_requested.name.ok_or(EventError::MissingField("name"))?;

                        if name == flogger::LogSinkMarker::PROTOCOL_NAME {
                            let capability = capability_requested
                                .capability
                                .ok_or(EventError::MissingField("capability"))?;
                            let request_stream =
                                ServerEnd::<flogger::LogSinkMarker>::new(capability)
                                    .into_stream()?;
                            Ok(Event {
                                timestamp: zx::Time::from_nanos(event.header.timestamp),
                                payload: EventPayload::LogSinkRequested(LogSinkRequestedPayload {
                                    component: Arc::new(identity),
                                    request_stream,
                                }),
                            })
                        } else if name == finspect::InspectSinkMarker::PROTOCOL_NAME {
                            let capability = capability_requested
                                .capability
                                .ok_or(EventError::MissingField("capability"))?;
                            let request_stream =
                                ServerEnd::<finspect::InspectSinkMarker>::new(capability)
                                    .into_stream()?;
                            Ok(Event {
                                timestamp: zx::Time::from_nanos(event.header.timestamp),
                                payload: EventPayload::InspectSinkRequested(
                                    InspectSinkRequestedPayload {
                                        component: Arc::new(identity),
                                        request_stream,
                                    },
                                ),
                            })
                        } else {
                            Err(EventError::IncorrectName {
                                received: name,
                                expected: flogger::LogSinkMarker::PROTOCOL_NAME,
                            })
                        }
                    }
                    _ => Err(EventError::UnknownResult(event.payload)),
                },
                _ => Err(EventError::InvalidEventType(event.header.event_type)),
            }
        } else {
            Err(EventError::MissingField("Payload or header is missing"))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::logs::testing::create_log_sink_requested_event;
    use assert_matches::assert_matches;
    use fidl_fuchsia_component as fcomponent;
    use fidl_fuchsia_inspect as finspect;
    use fidl_fuchsia_logger::LogSinkMarker;
    use fuchsia_zircon as zx;

    fn create_inspect_sink_requested_event(
        target_moniker: String,
        target_url: String,
        capability: zx::Channel,
    ) -> fcomponent::Event {
        fcomponent::Event {
            header: Some(fcomponent::EventHeader {
                event_type: Some(fcomponent::EventType::CapabilityRequested),
                moniker: Some(target_moniker),
                component_url: Some(target_url),
                timestamp: Some(zx::Time::get_monotonic().into_nanos()),
                ..Default::default()
            }),
            payload: Some(fcomponent::EventPayload::CapabilityRequested(
                fcomponent::CapabilityRequestedPayload {
                    name: Some(finspect::InspectSinkMarker::PROTOCOL_NAME.into()),
                    capability: Some(capability),
                    ..Default::default()
                },
            )),
            ..Default::default()
        }
    }

    #[fuchsia::test]
    fn inspect_sink_capability_requested() {
        let _exec = fuchsia_async::LocalExecutor::new();
        let (_, inspect_sink_server_end) =
            fidl::endpoints::create_endpoints::<finspect::InspectSinkMarker>();
        let event = create_inspect_sink_requested_event(
            "a/b".into(),
            "".into(),
            inspect_sink_server_end.into_channel(),
        );
        let actual = event.try_into().unwrap();

        assert_matches!(actual, Event { payload, .. } => {
            assert_matches!(payload,
                EventPayload::InspectSinkRequested(InspectSinkRequestedPayload {
                    component, ..
                }) => {
                    assert_eq!(component, ComponentIdentity::from(vec!["a", "b"]).into());
                })
        });
    }

    #[fuchsia::test]
    fn log_sink_capability_requested() {
        let _exec = fuchsia_async::LocalExecutor::new();
        let (_, log_sink_server_end) = fidl::endpoints::create_endpoints::<LogSinkMarker>();
        let event = create_log_sink_requested_event(
            "a/b".into(),
            "".into(),
            log_sink_server_end.into_channel(),
        );
        let actual = event.try_into().unwrap();

        assert_matches!(actual, Event { payload, .. } => {
            assert_matches!(payload,
                EventPayload::LogSinkRequested(LogSinkRequestedPayload {
                    component, ..
                }) => {
                    assert_eq!(component, ComponentIdentity::from(vec!["a", "b"]).into());
                })
        });
    }
}