component_events/
events.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
// Copyright 2019 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::{format_err, Error};
use fidl::endpoints::{ProtocolMarker, ServerEnd};
use fuchsia_component::client::connect_to_protocol_at_path;
use lazy_static::lazy_static;
use std::collections::VecDeque;
use thiserror::Error;
use {fidl_fuchsia_component as fcomponent, fidl_fuchsia_io as fio};

lazy_static! {
    /// The path of the static event stream that, by convention, synchronously listens for
    /// Resolved events.
    pub static ref START_COMPONENT_TREE_STREAM: String = "StartComponentTree".into();
}

/// Returns the string name for the given `event_type`
pub fn event_name(event_type: &fcomponent::EventType) -> String {
    match event_type {
        fcomponent::EventType::CapabilityRequested => "capability_requested",
        fcomponent::EventType::Discovered => unreachable!("This isn't used anymore"),
        fcomponent::EventType::Destroyed => "destroyed",
        fcomponent::EventType::Resolved => "resolved",
        fcomponent::EventType::Unresolved => "unresolved",
        fcomponent::EventType::Started => "started",
        fcomponent::EventType::Stopped => "stopped",
        fcomponent::EventType::DebugStarted => "debug_started",
        #[cfg(fuchsia_api_level_at_least = "HEAD")]
        fcomponent::EventType::DirectoryReady => unreachable!("This isn't used anymore"),
    }
    .to_string()
}

enum InternalStream {
    New(fcomponent::EventStreamProxy),
}

pub struct EventStream {
    stream: InternalStream,
    buffer: VecDeque<fcomponent::Event>,
}

#[derive(Debug, Error, Clone)]
pub enum EventStreamError {
    #[error("Stream terminated unexpectedly")]
    StreamClosed,
}

impl EventStream {
    pub fn new(stream: fcomponent::EventStreamProxy) -> Self {
        Self { stream: InternalStream::New(stream), buffer: VecDeque::new() }
    }

    pub fn open_at_path_pipelined(path: impl Into<String>) -> Result<Self, Error> {
        Ok(Self::new(connect_to_protocol_at_path::<fcomponent::EventStreamMarker>(&path.into())?))
    }

    pub async fn open_at_path(path: impl Into<String>) -> Result<Self, Error> {
        let event_stream =
            connect_to_protocol_at_path::<fcomponent::EventStreamMarker>(&path.into())?;
        event_stream.wait_for_ready().await?;
        Ok(Self::new(event_stream))
    }

    pub async fn open() -> Result<Self, Error> {
        let event_stream = connect_to_protocol_at_path::<fcomponent::EventStreamMarker>(
            "/svc/fuchsia.component.EventStream",
        )?;
        event_stream.wait_for_ready().await?;
        Ok(Self::new(event_stream))
    }

    pub fn open_pipelined() -> Result<Self, Error> {
        Ok(Self::new(connect_to_protocol_at_path::<fcomponent::EventStreamMarker>(
            "/svc/fuchsia.component.EventStream",
        )?))
    }

    pub async fn next(&mut self) -> Result<fcomponent::Event, EventStreamError> {
        if let Some(event) = self.buffer.pop_front() {
            return Ok(event);
        }
        match &mut self.stream {
            InternalStream::New(stream) => {
                match stream.get_next().await {
                    Ok(events) => {
                        let mut iter = events.into_iter();
                        if let Some(real_event) = iter.next() {
                            let ret = real_event;
                            while let Some(value) = iter.next() {
                                self.buffer.push_back(value);
                            }
                            return Ok(ret);
                        } else {
                            // This should never happen, we should always
                            // have at least one event.
                            Err(EventStreamError::StreamClosed)
                        }
                    }
                    Err(_) => Err(EventStreamError::StreamClosed),
                }
            }
        }
    }
}

/// Common features of any event - event type, target moniker, conversion function
pub trait Event: TryFrom<fcomponent::Event, Error = anyhow::Error> {
    const TYPE: fcomponent::EventType;
    const NAME: &'static str;

    fn target_moniker(&self) -> &str;
    fn component_url(&self) -> &str;
    fn timestamp(&self) -> zx::BootInstant;
    fn is_ok(&self) -> bool;
    fn is_err(&self) -> bool;
}

#[derive(Copy, Debug, PartialEq, Eq, Clone, Ord, PartialOrd)]
/// Simplifies the exit status represented by an Event. All stop status values
/// that indicate failure are crushed into `Crash`.
pub enum ExitStatus {
    Clean,
    Crash(i32),
}

impl From<i32> for ExitStatus {
    fn from(exit_status: i32) -> Self {
        match exit_status {
            0 => ExitStatus::Clean,
            _ => ExitStatus::Crash(exit_status),
        }
    }
}

#[derive(Debug)]
struct EventHeader {
    event_type: fcomponent::EventType,
    component_url: String,
    moniker: String,
    timestamp: zx::BootInstant,
}

impl TryFrom<fcomponent::EventHeader> for EventHeader {
    type Error = anyhow::Error;

    fn try_from(header: fcomponent::EventHeader) -> Result<Self, Self::Error> {
        let event_type = header.event_type.ok_or_else(|| format_err!("No event type"))?;
        let component_url = header.component_url.ok_or_else(|| format_err!("No component url"))?;
        let moniker = header.moniker.ok_or_else(|| format_err!("No moniker"))?;
        let timestamp = header
            .timestamp
            .ok_or_else(|| format_err!("Missing timestamp from the Event object"))?;
        Ok(EventHeader { event_type, component_url, moniker, timestamp })
    }
}

#[derive(Debug, PartialEq, Eq)]
pub struct EventError {
    pub description: String,
}

/// The macro defined below will automatically create event classes corresponding
/// to their events.fidl and hooks.rs counterparts. Every event class implements
/// the Event and Handler traits. These minimum requirements allow every event to
/// be handled by the events client library.

/// Creates an event class based on event type and an optional payload
/// * event_type -> FIDL name for event type
/// * payload -> If an event has a payload, describe the additional params:
///   * name -> FIDL name for the payload
///   * data -> If a payload contains data items, describe the additional params:
///     * name -> FIDL name for the data item
///     * ty -> Rust type for the data item
///   * client_protocols -> If a payload contains client-side protocols, describe
///     the additional params:
///     * name -> FIDL name for the protocol
///     * ty -> Rust type for the protocol proxy
///   * server_protocols -> If a payload contains server-side protocols, describe
///     the additional params:
///     * name -> FIDL name for the protocol
// TODO(https://fxbug.dev/42131403): This marco is getting complicated. Consider replacing it
//                  with a procedural macro.
macro_rules! create_event {
    // Entry points
    (
        event_type: $event_type:ident,
        event_name: $event_name:ident,
        payload: {
            data: {$(
                {
                    name: $data_name:ident,
                    ty: $data_ty:ty,
                }
            )*},
            client_protocols: {$(
                {
                    name: $client_protocol_name:ident,
                    ty: $client_protocol_ty:ty,
                }
            )*},
            server_protocols: {$(
                {
                    name: $server_protocol_name:ident,
                }
            )*},
        },
        error_payload: {
            $(
                {
                    name: $error_data_name:ident,
                    ty: $error_data_ty:ty,
                }
            )*
        }
    ) => {
        paste::paste! {
            #[derive(Debug)]
            pub struct [<$event_type Payload>] {
                $(pub $client_protocol_name: $client_protocol_ty,)*
                $(pub $server_protocol_name: Option<zx::Channel>,)*
                $(pub $data_name: $data_ty,)*
            }

            #[derive(Debug)]
            pub struct [<$event_type Error>] {
                $(pub $error_data_name: $error_data_ty,)*
                pub description: String,
            }

            #[derive(Debug)]
            pub struct $event_type {
                header: EventHeader,
                result: Result<[<$event_type Payload>], [<$event_type Error>]>,
            }

            impl $event_type {
                pub fn result<'a>(&'a self) -> Result<&'a [<$event_type Payload>], &'a [<$event_type Error>]> {
                    self.result.as_ref()
                }

                $(
                    pub fn [<take_ $server_protocol_name>]<T: ProtocolMarker>(&mut self)
                            -> Option<T::RequestStream> {
                        self.result.as_mut()
                            .ok()
                            .and_then(|payload| payload.$server_protocol_name.take())
                            .map(|channel| {
                                let server_end = ServerEnd::<T>::new(channel);
                                server_end.into_stream()
                            })
                    }
                )*
            }

            impl Event for $event_type {
                const TYPE: fcomponent::EventType = fcomponent::EventType::$event_type;
                const NAME: &'static str = stringify!($event_name);

                fn target_moniker(&self) -> &str {
                    &self.header.moniker
                }

                fn component_url(&self) -> &str {
                    &self.header.component_url
                }

                fn timestamp(&self) -> zx::BootInstant {
                    self.header.timestamp
                }

                fn is_ok(&self) -> bool {
                    self.result.is_ok()
                }

                fn is_err(&self) -> bool {
                    self.result.is_err()
                }
            }

            impl TryFrom<fcomponent::Event> for $event_type {
                type Error = anyhow::Error;

                fn try_from(event: fcomponent::Event) -> Result<Self, Self::Error> {
                    // Extract the payload from the Event object.
                    let result = match event.payload {
                        Some(payload) => {
                            // This payload will be unused for event types that have no additional
                            // fields.
                            #[allow(unused)]
                            let payload = match payload {
                                fcomponent::EventPayload::$event_type(payload) => Ok(payload),
                                _ => Err(format_err!("Incorrect payload type, {:?}", payload)),
                            }?;

                            // Extract the additional data from the Payload object.
                            $(
                                let $data_name: $data_ty = payload.$data_name.coerce().ok_or(
                                    format_err!("Missing {} from {} object",
                                        stringify!($data_name), stringify!($event_type))
                                )?;
                            )*

                            // Extract the additional protocols from the Payload object.
                            $(
                                let $client_protocol_name: $client_protocol_ty = payload.$client_protocol_name.ok_or(
                                    format_err!("Missing {} from {} object",
                                        stringify!($client_protocol_name), stringify!($event_type))
                                )?.into_proxy();
                            )*
                            $(
                                let $server_protocol_name: Option<zx::Channel> =
                                    Some(payload.$server_protocol_name.ok_or(
                                        format_err!("Missing {} from {} object",
                                            stringify!($server_protocol_name), stringify!($event_type))
                                    )?);
                            )*

                            #[allow(dead_code)]
                            let payload = paste::paste! {
                                [<$event_type Payload>] {
                                    $($data_name,)*
                                    $($client_protocol_name,)*
                                    $($server_protocol_name,)*
                                }
                            };

                            Ok(Ok(payload))
                        },
                        None => Err(format_err!("Missing event_result from Event object")),
                    }?;

                    let event = {
                        let header = event.header
                            .ok_or(format_err!("Missing Event header"))
                            .and_then(|header| EventHeader::try_from(header))?;

                        if header.event_type != Self::TYPE {
                            return Err(format_err!("Incorrect event type"));
                        }

                        $event_type { header, result }
                    };
                    Ok(event)
                }
            }
        }
    };
    ($event_type:ident, $event_name:ident) => {
        create_event!(event_type: $event_type, event_name: $event_name,
                      payload: {
                          data: {},
                          client_protocols: {},
                          server_protocols: {},
                      },
                      error_payload: {});
    };
}

// To create a class for an event, use the above macro here.
create_event!(Destroyed, destroyed);
create_event!(Resolved, resolved);
create_event!(Unresolved, unresolved);
create_event!(Started, started);
create_event!(
    event_type: Stopped,
    event_name: stopped,
    payload: {
        data: {
            {
                name: status,
                ty: ExitStatus,
            }
            {
                name: exit_code,
                ty: Option<i64>,
            }
        },
        client_protocols: {},
        server_protocols: {},
    },
    error_payload: {}
);
create_event!(
    event_type: CapabilityRequested,
    event_name: capability_requested,
    payload: {
        data: {
            {
                name: name,
                ty: String,
            }
        },
        client_protocols: {},
        server_protocols: {
            {
                name: capability,
            }
        },
    },
    error_payload: {
        {
            name: name,
            ty: String,
        }
    }
);
create_event!(
    event_type: DebugStarted,
    event_name: debug_started,
    payload: {
        data: {
            {
                name: break_on_start,
                ty: zx::EventPair,
            }
        },
        client_protocols: {
            {
                name: runtime_dir,
                ty: fio::DirectoryProxy,
            }
        },
        server_protocols: {},
    },
    error_payload: {}
);

trait Coerce<T> {
    fn coerce(self) -> Option<T>;
}

impl<T> Coerce<T> for Option<T> {
    fn coerce(self) -> Option<T> {
        self
    }
}

impl<T> Coerce<Option<T>> for Option<T> {
    fn coerce(self) -> Option<Option<T>> {
        Some(self)
    }
}

impl Coerce<ExitStatus> for Option<i32> {
    fn coerce(self) -> Option<ExitStatus> {
        self.map(Into::into)
    }
}