settings/agent/inspect/
external_apis.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
// Copyright 2022 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.

//! The external_apis mod defines the [ExternalApisInspectAgent], which is responsible for recording
//! external API requests and responses to Inspect. Since API usages might happen before agent
//! lifecycle states are communicated (due to agent priority ordering), the
//! [ExternalApisInspectAgent] begins listening to requests immediately after creation.
//!
//! Example Inspect structure:
//!
//! ```text
//! {
//!   "fuchsia.external.FakeAPI": {
//!     "pending_calls": {
//!       "00000000000000000005": {
//!         request: "set_manual_brightness(0.7)",
//!         response: "None",
//!         request_timestamp: "19.002716",
//!         response_timestamp: "None",
//!       },
//!     },
//!     "calls": {
//!       "00000000000000000002": {
//!         request: "set_manual_brightness(0.6)",
//!         response: "Ok(None)",
//!         request_timestamp: "18.293864",
//!         response_timestamp: "18.466811",
//!       },
//!       "00000000000000000004": {
//!         request: "set_manual_brightness(0.8)",
//!         response: "Ok(None)",
//!         request_timestamp: "18.788366",
//!         response_timestamp: "18.915355",
//!       },
//!     },
//!   },
//!   ...
//! }
//! ```

use crate::agent::{Context, Payload};
use crate::event::{Event, Payload as EventPayload};
use crate::message::base::{MessageEvent, MessengerType};
use crate::service::{self as service, TryFromWithClient};
use crate::service_context::ExternalServiceEvent;
use crate::trace;

use fuchsia_async as fasync;
use fuchsia_inspect::{component, Node};
use fuchsia_inspect_derive::{IValue, Inspect, WithInspect};
use futures::StreamExt;
use settings_inspect_utils::managed_inspect_map::ManagedInspectMap;
use settings_inspect_utils::managed_inspect_queue::ManagedInspectQueue;
use std::rc::Rc;

/// The key for the queue for completed calls per protocol.
const COMPLETED_CALLS_KEY: &str = "completed_calls";

/// The key for the queue for pending calls per protocol.
const PENDING_CALLS_KEY: &str = "pending_calls";

/// The maximum number of recently completed calls that will be kept in
/// inspect per protocol.
const MAX_COMPLETED_CALLS: usize = 10;

/// The maximum number of still pending calls that will be kept in
/// inspect per protocol.
const MAX_PENDING_CALLS: usize = 10;

// TODO(https://fxbug.dev/42060063): Explore reducing size of keys in inspect.
#[derive(Debug, Default, Inspect)]
struct ExternalApiCallInfo {
    /// Node of this info.
    inspect_node: Node,

    /// The request sent via the external API.
    request: IValue<String>,

    /// The response received by the external API.
    response: IValue<String>,

    /// The timestamp at which the request was sent.
    request_timestamp: IValue<String>,

    /// The timestamp at which the response was received.
    response_timestamp: IValue<String>,
}

impl ExternalApiCallInfo {
    fn new(
        request: &str,
        response: &str,
        request_timestamp: &str,
        response_timestamp: &str,
    ) -> Self {
        let mut info = Self::default();
        info.request.iset(request.to_string());
        info.response.iset(response.to_string());
        info.request_timestamp.iset(request_timestamp.to_string());
        info.response_timestamp.iset(response_timestamp.to_string());
        info
    }
}

#[derive(Default, Inspect)]
struct ExternalApiCallsWrapper {
    inspect_node: Node,
    /// The number of total calls that have been made on this protocol.
    count: IValue<u64>,
    /// The most recent pending and completed calls per-protocol.
    calls: ManagedInspectMap<ManagedInspectQueue<ExternalApiCallInfo>>,
    /// The external api event counts.
    event_counts: ManagedInspectMap<IValue<u64>>,
}

/// The [SettingTypeUsageInspectAgent] is responsible for listening to requests to external
/// APIs and recording their requests and responses to Inspect.
pub(crate) struct ExternalApiInspectAgent {
    /// Map from the API call type to its most recent calls.
    ///
    /// Example structure:
    /// ```text
    /// {
    ///   "fuchsia.ui.brightness.Control": {
    ///     "count": 6,
    ///     "calls": {
    ///       "pending_calls": {
    ///         "00000000000000000006": {
    ///           request: "set_manual_brightness(0.7)",
    ///           response: "None",
    ///           request_timestamp: "19.002716",
    ///           response_timestamp: "None",
    ///         },
    ///       }],
    ///       "completed_calls": [{
    ///         "00000000000000000003": {
    ///           request: "set_manual_brightness(0.6)",
    ///           response: "Ok(None)",
    ///           request_timestamp: "18.293864",
    ///           response_timestamp: "18.466811",
    ///         },
    ///         "00000000000000000005": {
    ///           request: "set_manual_brightness(0.8)",
    ///           response: "Ok(None)",
    ///           request_timestamp: "18.788366",
    ///           response_timestamp: "18.915355",
    ///         },
    ///       },
    ///     },
    ///     "event_counts": {
    ///       "Connect": 1,
    ///       "ApiCall": 3,
    ///       "ApiResponse": 2,
    ///     }
    ///   },
    ///   ...
    /// }
    /// ```
    api_calls: ManagedInspectMap<ExternalApiCallsWrapper>,
}

impl ExternalApiInspectAgent {
    /// Creates the `ExternalApiInspectAgent` with the given `context`.
    pub(crate) async fn create(context: Context) {
        Self::create_with_node(
            context,
            component::inspector().root().create_child("external_apis"),
        )
        .await;
    }

    /// Creates the `ExternalApiInspectAgent` with the given `context` and Inspect `node`.
    async fn create_with_node(context: Context, node: Node) {
        let (_, message_rx) = context
            .delegate
            .create(MessengerType::Broker(Rc::new(move |message| {
                // Only catch external api requests.
                matches!(
                    message.payload(),
                    service::Payload::Event(EventPayload::Event(Event::ExternalServiceEvent(_)))
                )
            })))
            .await
            .expect("should receive client");

        let mut agent = ExternalApiInspectAgent {
            api_calls: ManagedInspectMap::<ExternalApiCallsWrapper>::with_node(node),
        };

        fasync::Task::local({
            async move {
                let _ = &context;
                let id = fuchsia_trace::Id::new();
                trace!(id, c"external_api_inspect_agent");
                let event = message_rx.fuse();
                let agent_event = context.receptor.fuse();
                futures::pin_mut!(agent_event, event);

                let mut message_event_fut = event.select_next_some();
                let mut agent_message_fut = agent_event.select_next_some();
                loop {
                    futures::select! {
                        message_event = message_event_fut => {
                            trace!(
                                id,
                                c"message_event"
                            );
                            agent.process_message_event(message_event);
                            message_event_fut = event.select_next_some();
                        },
                        agent_message = agent_message_fut => {
                            trace!(
                                id,
                                c"agent_event"
                            );
                            if let MessageEvent::Message(
                                    service::Payload::Agent(Payload::Invocation(_)), client)
                                    = agent_message {
                                // Since the agent runs at creation, there is no
                                // need to handle state here.
                                let _ = client.reply(Payload::Complete(Ok(())).into());
                            }
                            agent_message_fut = agent_event.select_next_some();
                        },
                    }
                }
            }
        })
        .detach();
    }

    /// Processes the given `event` and writes it to Inspect if it is an
    /// `ExternalServiceEvent`.
    fn process_message_event(&mut self, event: service::message::MessageEvent) {
        if let Ok((EventPayload::Event(Event::ExternalServiceEvent(external_service_event)), _)) =
            EventPayload::try_from_with_client(event)
        {
            match external_service_event {
                ExternalServiceEvent::Created(protocol, timestamp) => {
                    let count = self.get_count(protocol) + 1;
                    let info = ExternalApiCallInfo::new("connect", "none", "none", &timestamp);
                    self.add_info(protocol, COMPLETED_CALLS_KEY, "Created", info, count);
                }
                ExternalServiceEvent::ApiCall(protocol, request, timestamp) => {
                    let count = self.get_count(protocol) + 1;
                    let info = ExternalApiCallInfo::new(&request, "none", &timestamp, "none");
                    self.add_info(protocol, PENDING_CALLS_KEY, "ApiCall", info, count);
                }
                ExternalServiceEvent::ApiResponse(
                    protocol,
                    response,
                    request,
                    request_timestamp,
                    response_timestamp,
                ) => {
                    let count = self.get_count(protocol) + 1;
                    let info = ExternalApiCallInfo::new(
                        &request,
                        &response,
                        &request_timestamp,
                        &response_timestamp,
                    );
                    self.remove_pending(protocol, &info);
                    self.add_info(protocol, COMPLETED_CALLS_KEY, "ApiResponse", info, count);
                }
                ExternalServiceEvent::ApiError(
                    protocol,
                    error,
                    request,
                    request_timestamp,
                    error_timestamp,
                ) => {
                    let count = self.get_count(protocol) + 1;
                    let info = ExternalApiCallInfo::new(
                        &request,
                        &error,
                        &request_timestamp,
                        &error_timestamp,
                    );
                    self.remove_pending(protocol, &info);
                    self.add_info(protocol, COMPLETED_CALLS_KEY, "ApiError", info, count);
                }
                ExternalServiceEvent::Closed(
                    protocol,
                    request,
                    request_timestamp,
                    response_timestamp,
                ) => {
                    let count = self.get_count(protocol) + 1;
                    let info = ExternalApiCallInfo::new(
                        &request,
                        "closed",
                        &request_timestamp,
                        &response_timestamp,
                    );
                    self.remove_pending(protocol, &info);
                    self.add_info(protocol, COMPLETED_CALLS_KEY, "Closed", info, count);
                }
            }
        }
    }

    /// Retrieves the total call count for the given `protocol`. Implicitly
    /// calls `ensure_protocol_exists`.
    fn get_count(&mut self, protocol: &str) -> u64 {
        self.ensure_protocol_exists(protocol);
        *self.api_calls.get(protocol).expect("Wrapper should exist").count
    }

    /// Ensures that an entry exists for the given `protocol`, adding a new one if
    /// it does not yet exist.
    fn ensure_protocol_exists(&mut self, protocol: &str) {
        let _ = self
            .api_calls
            .get_or_insert_with(protocol.to_string(), ExternalApiCallsWrapper::default);
    }

    /// Ensures that an entry exists for the given `protocol`, and `queue_key` adding a
    /// new queue of max size `queue_size` if one does not yet exist. Implicitly calls
    /// `ensure_protocol_exists`.
    fn ensure_queue_exists(&mut self, protocol: &str, queue_key: &'static str, queue_size: usize) {
        self.ensure_protocol_exists(protocol);

        let protocol_map = self.api_calls.get_mut(protocol).expect("Protocol entry should exist");
        let _ = protocol_map.calls.get_or_insert_with(queue_key.to_string(), || {
            ManagedInspectQueue::<ExternalApiCallInfo>::new(queue_size)
        });
    }

    /// Inserts the given `info` into the entry at `protocol` and `queue_key`, incrementing
    /// the total call count to the protocol's wrapper entry.
    fn add_info(
        &mut self,
        protocol: &str,
        queue_key: &'static str,
        event_type: &str,
        info: ExternalApiCallInfo,
        count: u64,
    ) {
        self.ensure_queue_exists(
            protocol,
            queue_key,
            if queue_key == COMPLETED_CALLS_KEY { MAX_COMPLETED_CALLS } else { MAX_PENDING_CALLS },
        );
        let wrapper = self.api_calls.get_mut(protocol).expect("Protocol entry should exist");
        {
            let mut wrapper_guard = wrapper.count.as_mut();
            *wrapper_guard += 1;
        }
        let event_count =
            wrapper.event_counts.get_or_insert_with(event_type.to_string(), || IValue::new(0));
        {
            let mut event_count_guard = event_count.as_mut();
            *event_count_guard += 1;
        }

        let queue = wrapper.calls.get_mut(queue_key).expect("Queue should exist");
        let key = format!("{count:020}");
        queue.push(
            &key,
            info.with_inspect(queue.inspect_node(), &key)
                .expect("Failed to create ExternalApiCallInfo node"),
        );
    }

    /// Removes the call with the same request timestamp from the `protocol`'s pending
    /// call queue, indicating that the call has completed. Should be called along with
    /// `add_info` to add the completed call.
    fn remove_pending(&mut self, protocol: &str, info: &ExternalApiCallInfo) {
        let wrapper = self.api_calls.get_mut(protocol).expect("Protocol entry should exist");
        let pending_queue =
            wrapper.calls.get_mut(PENDING_CALLS_KEY).expect("Pending queue should exist");
        let req_timestamp = &*info.request_timestamp;
        pending_queue.retain(|pending| &*pending.request_timestamp != req_timestamp);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::message::base::Audience;

    use diagnostics_assertions::assert_data_tree;
    use fuchsia_inspect::Inspector;
    use std::collections::HashSet;

    const MOCK_PROTOCOL_NAME: &str = "fuchsia.external.FakeAPI";

    /// The `RequestProcessor` handles sending a request through a MessageHub
    /// From caller to recipient. This is useful when testing brokers in
    /// between.
    struct RequestProcessor {
        delegate: service::message::Delegate,
    }

    impl RequestProcessor {
        fn new(delegate: service::message::Delegate) -> Self {
            RequestProcessor { delegate }
        }

        async fn send_and_receive(&self, external_api_event: ExternalServiceEvent) {
            let (messenger, _) =
                self.delegate.create(MessengerType::Unbound).await.expect("should be created");

            let (_, mut receptor) =
                self.delegate.create(MessengerType::Unbound).await.expect("should be created");

            let _ = messenger.message(
                service::Payload::Event(EventPayload::Event(Event::ExternalServiceEvent(
                    external_api_event,
                ))),
                Audience::Broadcast,
            );

            let _ = receptor.next_payload().await;
        }
    }

    async fn create_context() -> Context {
        Context::new(
            service::MessageHub::create_hub()
                .create(MessengerType::Unbound)
                .await
                .expect("should be present")
                .1,
            service::MessageHub::create_hub(),
            HashSet::new(),
        )
        .await
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_inspect_create_connection() {
        let inspector = Inspector::default();
        let inspect_node = inspector.root().create_child("external_apis");
        let context = create_context().await;

        let request_processor = RequestProcessor::new(context.delegate.clone());

        ExternalApiInspectAgent::create_with_node(context, inspect_node).await;

        let connection_created_event =
            ExternalServiceEvent::Created(MOCK_PROTOCOL_NAME, "0.000000".into());

        request_processor.send_and_receive(connection_created_event.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "completed_calls": {
                            "00000000000000000001": {
                                request: "connect",
                                response: "none",
                                request_timestamp: "none",
                                response_timestamp: "0.000000",
                            },
                        },
                    },
                    "count": 1u64,
                    "event_counts": {
                        "Created": 1u64,
                    },
                },
            },
        });
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_inspect_pending() {
        let inspector = Inspector::default();
        let inspect_node = inspector.root().create_child("external_apis");
        let context = create_context().await;

        let request_processor = RequestProcessor::new(context.delegate.clone());

        ExternalApiInspectAgent::create_with_node(context, inspect_node).await;

        let api_call_event = ExternalServiceEvent::ApiCall(
            MOCK_PROTOCOL_NAME,
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
        );

        request_processor.send_and_receive(api_call_event.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {
                            "00000000000000000001": {
                                request: "set_manual_brightness(0.6)",
                                response: "none",
                                request_timestamp: "0.000000",
                                response_timestamp: "none",
                            },
                        },
                    },
                    "count": 1u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                    },
                },
            },
        });
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_inspect_success_response() {
        let inspector = Inspector::default();
        let inspect_node = inspector.root().create_child("external_apis");
        let context = create_context().await;

        let request_processor = RequestProcessor::new(context.delegate.clone());

        ExternalApiInspectAgent::create_with_node(context, inspect_node).await;

        let api_call_event = ExternalServiceEvent::ApiCall(
            MOCK_PROTOCOL_NAME,
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
        );
        let api_response_event = ExternalServiceEvent::ApiResponse(
            MOCK_PROTOCOL_NAME,
            "Ok(None)".into(),
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
            "0.129987".into(),
        );

        request_processor.send_and_receive(api_call_event.clone()).await;
        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {
                            "00000000000000000001": {
                                request: "set_manual_brightness(0.6)",
                                response: "none",
                                request_timestamp: "0.000000",
                                response_timestamp: "none",
                            },
                        },
                    },
                    "count": 1u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                    },
                },
            },
        });

        request_processor.send_and_receive(api_response_event.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {},
                        "completed_calls": {
                            "00000000000000000002": {
                                request: "set_manual_brightness(0.6)",
                                response: "Ok(None)",
                                request_timestamp: "0.000000",
                                response_timestamp: "0.129987",
                            },
                        },
                    },
                    "count": 2u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                        "ApiResponse": 1u64,
                    },
                },
            },
        });
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_inspect_error() {
        let inspector = Inspector::default();
        let inspect_node = inspector.root().create_child("external_apis");
        let context = create_context().await;

        let request_processor = RequestProcessor::new(context.delegate.clone());

        ExternalApiInspectAgent::create_with_node(context, inspect_node).await;

        let api_call_event = ExternalServiceEvent::ApiCall(
            MOCK_PROTOCOL_NAME,
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
        );
        let error_event = ExternalServiceEvent::ApiError(
            MOCK_PROTOCOL_NAME,
            "Err(INTERNAL_ERROR)".into(),
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
            "0.129987".into(),
        );

        request_processor.send_and_receive(api_call_event.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {
                            "00000000000000000001": {
                                request: "set_manual_brightness(0.6)",
                                response: "none",
                                request_timestamp: "0.000000",
                                response_timestamp: "none",
                            },
                        },
                    },
                    "count": 1u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                    },
                },
            },
        });

        request_processor.send_and_receive(error_event.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {},
                        "completed_calls": {
                            "00000000000000000002": {
                                request: "set_manual_brightness(0.6)",
                                response: "Err(INTERNAL_ERROR)",
                                request_timestamp: "0.000000",
                                response_timestamp: "0.129987",
                            },
                        },
                    },
                    "count": 2u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                        "ApiError": 1u64,
                    },
                },
            },
        });
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_inspect_channel_closed() {
        let inspector = Inspector::default();
        let inspect_node = inspector.root().create_child("external_apis");
        let context = create_context().await;

        let request_processor = RequestProcessor::new(context.delegate.clone());

        ExternalApiInspectAgent::create_with_node(context, inspect_node).await;

        let api_call_event = ExternalServiceEvent::ApiCall(
            MOCK_PROTOCOL_NAME,
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
        );
        let closed_event = ExternalServiceEvent::Closed(
            MOCK_PROTOCOL_NAME,
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
            "0.129987".into(),
        );

        request_processor.send_and_receive(api_call_event.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {
                            "00000000000000000001": {
                                request: "set_manual_brightness(0.6)",
                                response: "none",
                                request_timestamp: "0.000000",
                                response_timestamp: "none",
                            },
                        },
                    },
                    "count": 1u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                    },
                },
            },
        });

        request_processor.send_and_receive(closed_event.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {},
                        "completed_calls": {
                            "00000000000000000002": {
                                request: "set_manual_brightness(0.6)",
                                response: "closed",
                                request_timestamp: "0.000000",
                                response_timestamp: "0.129987",
                            },
                        },
                    },
                    "count": 2u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                        "Closed": 1u64,
                    },
                },
            },
        });
    }

    #[fuchsia::test(allow_stalls = false)]
    async fn test_inspect_multiple_requests() {
        let inspector = Inspector::default();
        let inspect_node = inspector.root().create_child("external_apis");
        let context = create_context().await;

        let request_processor = RequestProcessor::new(context.delegate.clone());

        ExternalApiInspectAgent::create_with_node(context, inspect_node).await;

        let api_call_event = ExternalServiceEvent::ApiCall(
            MOCK_PROTOCOL_NAME,
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
        );
        let api_response_event = ExternalServiceEvent::ApiResponse(
            MOCK_PROTOCOL_NAME,
            "Ok(None)".into(),
            "set_manual_brightness(0.6)".into(),
            "0.000000".into(),
            "0.129987".into(),
        );

        let api_call_event_2 = ExternalServiceEvent::ApiCall(
            MOCK_PROTOCOL_NAME,
            "set_manual_brightness(0.7)".into(),
            "0.139816".into(),
        );
        let api_response_event_2 = ExternalServiceEvent::ApiResponse(
            MOCK_PROTOCOL_NAME,
            "Ok(None)".into(),
            "set_manual_brightness(0.7)".into(),
            "0.139816".into(),
            "0.141235".into(),
        );

        request_processor.send_and_receive(api_call_event.clone()).await;
        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {
                            "00000000000000000001": {
                                request: "set_manual_brightness(0.6)",
                                response: "none",
                                request_timestamp: "0.000000",
                                response_timestamp: "none",
                            },
                        },
                    },
                    "count": 1u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                    },
                },
            },
        });

        request_processor.send_and_receive(api_response_event.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {},
                        "completed_calls": {
                            "00000000000000000002": {
                                request: "set_manual_brightness(0.6)",
                                response: "Ok(None)",
                                request_timestamp: "0.000000",
                                response_timestamp: "0.129987",
                            },
                        },
                    },
                    "count": 2u64,
                    "event_counts": {
                        "ApiCall": 1u64,
                        "ApiResponse": 1u64,
                    },
                },
            },
        });

        request_processor.send_and_receive(api_call_event_2.clone()).await;
        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {
                            "00000000000000000003": {
                                request: "set_manual_brightness(0.7)",
                                response: "none",
                                request_timestamp: "0.139816",
                                response_timestamp: "none",
                            },
                        },
                        "completed_calls": {
                            "00000000000000000002": {
                                request: "set_manual_brightness(0.6)",
                                response: "Ok(None)",
                                request_timestamp: "0.000000",
                                response_timestamp: "0.129987",
                            },
                        },
                    },
                    "count": 3u64,
                    "event_counts": {
                        "ApiCall": 2u64,
                        "ApiResponse": 1u64,
                    },
                },
            },
        });

        request_processor.send_and_receive(api_response_event_2.clone()).await;

        assert_data_tree!(inspector, root: {
            external_apis: {
                "fuchsia.external.FakeAPI": {
                    "calls": {
                        "pending_calls": {},
                        "completed_calls": {
                            "00000000000000000002": {
                                request: "set_manual_brightness(0.6)",
                                response: "Ok(None)",
                                request_timestamp: "0.000000",
                                response_timestamp: "0.129987",
                            },
                            "00000000000000000004": {
                                request: "set_manual_brightness(0.7)",
                                response: "Ok(None)",
                                request_timestamp: "0.139816",
                                response_timestamp: "0.141235",
                            },
                        },
                    },
                    "count": 4u64,
                    "event_counts": {
                        "ApiCall": 2u64,
                        "ApiResponse": 2u64,
                    },
                },
            },
        });
    }
}