settings/ingress/
fidl.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
// 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 crate::base::{Dependency, Entity, SettingType};
use crate::handler::base::Error;
use crate::ingress::registration::{Registrant, Registrar};
use crate::job::source::Seeder;
use fidl_fuchsia_settings::{
    AccessibilityRequestStream, AudioRequestStream, DisplayRequestStream,
    DoNotDisturbRequestStream, FactoryResetRequestStream, InputRequestStream, IntlRequestStream,
    KeyboardRequestStream, LightRequestStream, NightModeRequestStream, PrivacyRequestStream,
    SetupRequestStream,
};
use fuchsia_component::server::{ServiceFsDir, ServiceObjLocal};
use serde::Deserialize;

impl From<Error> for zx::Status {
    fn from(error: Error) -> zx::Status {
        match error {
            Error::UnhandledType(_) => zx::Status::UNAVAILABLE,
            _ => zx::Status::INTERNAL,
        }
    }
}
/// [Interface] defines the FIDL interfaces supported by the settings service.
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub enum Interface {
    Accessibility,
    Audio,
    Display(display::InterfaceFlags),
    DoNotDisturb,
    FactoryReset,
    Input,
    Intl,
    Keyboard,
    Light,
    NightMode,
    Privacy,
    Setup,
}

/// [InterfaceSpec] is the serializable type that defines the configuration for FIDL interfaces
/// supported by the settings service. It's read in from configuration files to modify what
/// interfaces the settings service provides.
#[derive(Clone, Deserialize, PartialEq, Eq, Hash, Debug)]
pub enum InterfaceSpec {
    Accessibility,
    Audio,
    // Should ideally be a HashSet, but HashSet does not impl Hash.
    Display(Vec<display::InterfaceSpec>),
    DoNotDisturb,
    FactoryReset,
    Input,
    Intl,
    Keyboard,
    Light,
    NightMode,
    Privacy,
    Setup,
}

impl From<InterfaceSpec> for Interface {
    fn from(spec: InterfaceSpec) -> Self {
        match spec {
            InterfaceSpec::Audio => Interface::Audio,
            InterfaceSpec::Accessibility => Interface::Accessibility,
            InterfaceSpec::Display(variants) => Interface::Display(variants.into()),
            InterfaceSpec::DoNotDisturb => Interface::DoNotDisturb,
            InterfaceSpec::FactoryReset => Interface::FactoryReset,
            InterfaceSpec::Input => Interface::Input,
            InterfaceSpec::Intl => Interface::Intl,
            InterfaceSpec::Keyboard => Interface::Keyboard,
            InterfaceSpec::Light => Interface::Light,
            InterfaceSpec::NightMode => Interface::NightMode,
            InterfaceSpec::Privacy => Interface::Privacy,
            InterfaceSpec::Setup => Interface::Setup,
        }
    }
}

pub mod display {
    use bitflags::bitflags;
    use serde::Deserialize;

    bitflags! {
        /// The Display interface covers a number of feature spaces, each handled by a different
        /// entity dependency. The flags below allow the scope of these features to be specified by
        /// the interface.
        #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
        pub struct InterfaceFlags: u64 {
            const BASE = 1 << 0;
        }
    }

    #[derive(Copy, Clone, Deserialize, PartialEq, Eq, Hash, Debug)]
    pub enum InterfaceSpec {
        Base,
    }

    impl From<Vec<InterfaceSpec>> for InterfaceFlags {
        fn from(variants: Vec<InterfaceSpec>) -> Self {
            variants.into_iter().fold(InterfaceFlags::empty(), |flags, variant| {
                flags
                    | match variant {
                        InterfaceSpec::Base => InterfaceFlags::BASE,
                    }
            })
        }
    }
}

/// [Register] defines the closure implemented for interfaces to bring up support. Each interface
/// handler is given access to the MessageHub [Delegate] for communication within the service and
/// [ServiceFsDir] to register as the designated handler for the interface.
pub(crate) type Register =
    Box<dyn for<'a> FnOnce(&Seeder, &mut ServiceFsDir<'_, ServiceObjLocal<'a, ()>>)>;

impl Interface {
    /// Returns the list of [Dependencies](Dependency) that are necessary to provide this Interface.
    fn dependencies(self) -> Vec<Dependency> {
        match self {
            Interface::Accessibility => {
                vec![Dependency::Entity(Entity::Handler(SettingType::Accessibility))]
            }
            Interface::Audio => {
                vec![Dependency::Entity(Entity::Handler(SettingType::Audio))]
            }
            Interface::Display(interfaces) => {
                let mut dependencies = Vec::new();

                if interfaces.contains(display::InterfaceFlags::BASE) {
                    dependencies.push(Dependency::Entity(Entity::Handler(SettingType::Display)));
                }

                if dependencies.is_empty() {
                    panic!("A valid interface flag must be specified with Interface::Display");
                }

                dependencies
            }
            Interface::DoNotDisturb => {
                vec![Dependency::Entity(Entity::Handler(SettingType::DoNotDisturb))]
            }
            Interface::FactoryReset => {
                vec![Dependency::Entity(Entity::Handler(SettingType::FactoryReset))]
            }
            Interface::Input => {
                vec![Dependency::Entity(Entity::Handler(SettingType::Input))]
            }
            Interface::Intl => {
                vec![Dependency::Entity(Entity::Handler(SettingType::Intl))]
            }
            Interface::Keyboard => {
                vec![Dependency::Entity(Entity::Handler(SettingType::Keyboard))]
            }
            Interface::Light => {
                vec![Dependency::Entity(Entity::Handler(SettingType::Light))]
            }
            Interface::NightMode => {
                vec![Dependency::Entity(Entity::Handler(SettingType::NightMode))]
            }
            Interface::Privacy => {
                vec![Dependency::Entity(Entity::Handler(SettingType::Privacy))]
            }
            Interface::Setup => {
                vec![Dependency::Entity(Entity::Handler(SettingType::Setup))]
            }
        }
    }

    /// Converts an [Interface] into the closure to bring up the interface in the service environment
    /// as defined by [Register].
    fn registration_fn(self) -> Register {
        Box::new(
            move |seeder: &Seeder, service_dir: &mut ServiceFsDir<'_, ServiceObjLocal<'_, ()>>| {
                match self {
                    Interface::Audio => {
                        let seeder = seeder.clone();
                        let _ = service_dir.add_fidl_service(move |stream: AudioRequestStream| {
                            seeder.seed(stream);
                        });
                    }
                    Interface::Accessibility => {
                        let seeder = seeder.clone();
                        let _ = service_dir.add_fidl_service(
                            move |stream: AccessibilityRequestStream| {
                                seeder.seed(stream);
                            },
                        );
                    }
                    Interface::Display(_) => {
                        let seeder = seeder.clone();
                        let _ =
                            service_dir.add_fidl_service(move |stream: DisplayRequestStream| {
                                seeder.seed(stream);
                            });
                    }
                    Interface::DoNotDisturb => {
                        let seeder = seeder.clone();
                        let _ = service_dir.add_fidl_service(
                            move |stream: DoNotDisturbRequestStream| {
                                seeder.seed(stream);
                            },
                        );
                    }
                    Interface::FactoryReset => {
                        let seeder = seeder.clone();
                        let _ = service_dir.add_fidl_service(
                            move |stream: FactoryResetRequestStream| {
                                seeder.seed(stream);
                            },
                        );
                    }
                    Interface::Input => {
                        let seeder = seeder.clone();
                        let _ = service_dir.add_fidl_service(move |stream: InputRequestStream| {
                            seeder.seed(stream);
                        });
                    }
                    Interface::Intl => {
                        let seeder = seeder.clone();
                        let _ = service_dir.add_fidl_service(move |stream: IntlRequestStream| {
                            seeder.seed(stream);
                        });
                    }
                    Interface::Keyboard => {
                        let seeder = seeder.clone();
                        let _ =
                            service_dir.add_fidl_service(move |stream: KeyboardRequestStream| {
                                seeder.seed(stream);
                            });
                    }
                    Interface::Light => {
                        let seeder = seeder.clone();
                        let _ = service_dir.add_fidl_service(move |stream: LightRequestStream| {
                            seeder.seed(stream);
                        });
                    }
                    Interface::NightMode => {
                        let seeder = seeder.clone();
                        let _ =
                            service_dir.add_fidl_service(move |stream: NightModeRequestStream| {
                                seeder.seed(stream);
                            });
                    }
                    Interface::Privacy => {
                        let seeder = seeder.clone();
                        let _ =
                            service_dir.add_fidl_service(move |stream: PrivacyRequestStream| {
                                seeder.seed(stream);
                            });
                    }
                    Interface::Setup => {
                        let seeder = seeder.clone();
                        let _ = service_dir.add_fidl_service(move |stream: SetupRequestStream| {
                            seeder.seed(stream);
                        });
                    }
                }
            },
        )
    }

    /// Derives a [Registrant] from this [Interface]. This is used convert a list of Interfaces
    /// specified in a configuration into actionable Registrants that can be used in the setting
    /// service.
    pub(crate) fn registrant(self) -> Registrant {
        Registrant::new(
            format!("{self:?}"),
            Registrar::Fidl(self.registration_fn()),
            self.dependencies().into_iter().collect(),
        )
    }
}

#[cfg(test)]
mod tests {
    use fidl_fuchsia_settings::PrivacyMarker;
    use fuchsia_async as fasync;
    use fuchsia_component::server::ServiceFs;
    use futures::StreamExt;

    use assert_matches::assert_matches;

    use crate::base::{Dependency, Entity, SettingType};
    use crate::handler::base::{Payload, Request};
    use crate::ingress::registration::Registrant;
    use crate::job::manager::Manager;
    use crate::job::source::Seeder;
    use crate::message::base::MessengerType;
    use crate::service;

    use super::Interface;

    #[fuchsia::test(allow_stalls = false)]
    async fn test_fidl_seeder_bringup() {
        let mut fs = ServiceFs::new_local();
        let delegate = service::MessageHub::create_hub();
        let job_manager_signature = Manager::spawn(&delegate).await;
        let job_seeder = Seeder::new(&delegate, job_manager_signature).await;

        // Using privacy since it uses a seeder for its fidl registration.
        let setting_type = SettingType::Privacy;

        let registrant: Registrant = Interface::Privacy.registrant();

        // Verify dependencies properly derived from the interface.
        assert!(registrant
            .get_dependencies()
            .contains(&Dependency::Entity(Entity::Handler(setting_type))));

        // Create handler to intercept messages.
        let mut rx = delegate
            .create(MessengerType::Addressable(service::Address::Handler(setting_type)))
            .await
            .expect("messenger should be created")
            .1;

        // Register and consume Registrant.
        registrant.register(&job_seeder, &mut fs.root_dir());

        // Spawn nested environment.
        let connector = fs.create_protocol_connector().expect("should create connector");
        fasync::Task::local(fs.collect()).detach();

        // Connect to the Privacy interface and request watching.
        let privacy_proxy =
            connector.connect_to_protocol::<PrivacyMarker>().expect("should connect to protocol");
        fasync::Task::local(async move {
            let _ = privacy_proxy.watch().await;
        })
        .detach();

        // Ensure handler receives request.
        assert_matches!(rx.next_of::<Payload>().await, Ok((Payload::Request(Request::Listen), _)));
    }
}