fdf_component/incoming.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
// Copyright 2024 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 std::marker::PhantomData;
use anyhow::{anyhow, Context, Error};
use cm_types::{IterablePath, RelativePath};
use fidl::endpoints::{DiscoverableProtocolMarker, Proxy, ServiceMarker, ServiceProxy};
use fidl_fuchsia_io::Flags;
use fuchsia_component::client::{
connect_to_protocol_at_dir_svc, connect_to_service_instance_at_dir_svc,
};
use fuchsia_component::directory::{AsRefDirectory, Directory};
use fuchsia_component::DEFAULT_SERVICE_INSTANCE;
use namespace::{Entry, Namespace};
use tracing::error;
use zx::Status;
/// Implements access to the incoming namespace for a driver. It provides methods
/// for accessing incoming protocols and services by either their marker or proxy
/// types, and can be used as a [`Directory`] with the functions in
/// [`fuchsia_component::client`].
pub struct Incoming(Vec<Entry>);
impl Incoming {
/// Creates a connector to the given protocol by its marker type. This can be convenient when
/// the compiler can't deduce the [`Proxy`] type on its own.
///
/// # Example
///
/// ```ignore
/// let proxy = context.incoming.protocol_marker(fidl_fuchsia_logger::LogSinkMarker).connect()?;
/// ```
pub fn protocol_marker<M: DiscoverableProtocolMarker>(
&self,
_marker: M,
) -> ProtocolConnector<'_, M::Proxy> {
ProtocolConnector(self, PhantomData)
}
/// Creates a connector to the given protocol by its proxy type. This can be convenient when
/// the compiler can deduce the [`Proxy`] type on its own.
///
/// # Example
///
/// ```ignore
/// struct MyProxies {
/// log_sink: fidl_fuchsia_logger::LogSinkProxy,
/// }
/// let proxies = MyProxies {
/// log_sink: context.incoming.protocol().connect()?;
/// };
/// ```
pub fn protocol<P>(&self) -> ProtocolConnector<'_, P> {
ProtocolConnector(self, PhantomData)
}
/// Creates a connector to the given service's default instance by its marker type. This can be
/// convenient when the compiler can't deduce the [`ServiceProxy`] type on its own.
///
/// See [`ServiceConnector`] for more about what you can do with the connector.
///
/// # Example
///
/// ```ignore
/// let service = context.incoming.service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker).connect()?;
/// let device = service.connect_to_device()?;
/// ```
pub fn service_marker<M: ServiceMarker>(&self, _marker: M) -> ServiceConnector<'_, M::Proxy> {
ServiceConnector { incoming: self, instance: DEFAULT_SERVICE_INSTANCE, _p: PhantomData }
}
/// Creates a connector to the given service's default instance by its proxy type. This can be
/// convenient when the compiler can deduce the [`ServiceProxy`] type on its own.
///
/// See [`ServiceConnector`] for more about what you can do with the connector.
///
/// # Example
///
/// ```ignore
/// struct MyProxies {
/// i2c_service: fidl_fuchsia_hardware_i2c::ServiceProxy,
/// }
/// let proxies = MyProxies {
/// i2c_service: context.incoming.service().connect()?;
/// };
/// ```
pub fn service<P>(&self) -> ServiceConnector<'_, P> {
ServiceConnector { incoming: self, instance: DEFAULT_SERVICE_INSTANCE, _p: PhantomData }
}
}
/// A builder for connecting to a protocol in the driver's incoming namespace.
pub struct ProtocolConnector<'incoming, Proxy>(&'incoming Incoming, PhantomData<Proxy>);
impl<'a, P: Proxy> ProtocolConnector<'a, P>
where
P::Protocol: DiscoverableProtocolMarker,
{
/// Connects to the service instance's path in the incoming namespace. Logs and returns
/// a [`Status::CONNECTION_REFUSED`] if the service instance couldn't be opened.
pub fn connect(self) -> Result<P, Status> {
connect_to_protocol_at_dir_svc::<P::Protocol>(&self.0).map_err(|e| {
error!(
"Failed to connect to discoverable protocol `{}`: {e}",
P::Protocol::PROTOCOL_NAME
);
Status::CONNECTION_REFUSED
})
}
}
/// A builder for connecting to an aggregated service instance in the driver's incoming namespace.
/// By default, it will connect to the default instance, named `default`. You can override this
/// by calling [`Self::instance`].
pub struct ServiceConnector<'incoming, ServiceProxy> {
incoming: &'incoming Incoming,
instance: &'incoming str,
_p: PhantomData<ServiceProxy>,
}
impl<'a, S: ServiceProxy> ServiceConnector<'a, S>
where
S::Service: ServiceMarker,
{
/// Overrides the instance name to connect to when [`Self::connect`] is called.
pub fn instance(self, instance: &'a str) -> Self {
let Self { incoming, _p, .. } = self;
Self { incoming, instance, _p }
}
/// Connects to the service instance's path in the incoming namespace. Logs and returns
/// a [`Status::CONNECTION_REFUSED`] if the service instance couldn't be opened.
pub fn connect(self) -> Result<S, Status> {
connect_to_service_instance_at_dir_svc::<S::Service>(self.incoming, self.instance).map_err(
|e| {
error!(
"Failed to connect to aggregated service connector `{}`, instance `{}`: {e}",
S::Service::SERVICE_NAME,
self.instance
);
Status::CONNECTION_REFUSED
},
)
}
}
impl From<Namespace> for Incoming {
fn from(value: Namespace) -> Self {
Incoming(value.flatten())
}
}
/// Returns the remainder of a prefix match of `prefix` against `self` in terms of path segments.
///
/// For example:
/// ```ignore
/// match_prefix("pkg/data", "pkg") == Some("/data")
/// match_prefix("pkg_data", "pkg") == None
/// ```
fn match_prefix(match_in: &impl IterablePath, prefix: &impl IterablePath) -> Option<RelativePath> {
let mut my_segments = match_in.iter_segments();
let mut prefix_segments = prefix.iter_segments();
while let Some(prefix) = prefix_segments.next() {
if prefix != my_segments.next()? {
return None;
}
}
if prefix_segments.next().is_some() {
// did not match all prefix segments
return None;
}
let segments = Vec::from_iter(my_segments.cloned());
Some(RelativePath::from(segments))
}
impl Directory for Incoming {
fn open(&self, path: &str, flags: Flags, server_end: zx::Channel) -> Result<(), Error> {
let path = path.strip_prefix("/").unwrap_or(path);
let path = RelativePath::new(path)?;
for entry in &self.0 {
if let Some(remain) = match_prefix(&path, &entry.path) {
return entry.directory.open(&format!("/{}", remain), flags, server_end);
}
}
Err(Status::NOT_FOUND)
.with_context(|| anyhow!("Path {path} not found in incoming namespace"))
}
}
impl AsRefDirectory for Incoming {
fn as_ref_directory(&self) -> &dyn Directory {
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use cm_types::NamespacePath;
use fuchsia_async::Task;
use fuchsia_component::server::ServiceFs;
use futures::stream::StreamExt;
enum IncomingServices {
I2cDevice(fidl_fuchsia_hardware_i2c::DeviceRequestStream),
I2cDefaultService(fidl_fuchsia_hardware_i2c::ServiceRequest),
I2cOtherService(fidl_fuchsia_hardware_i2c::ServiceRequest),
}
impl IncomingServices {
async fn handle_device_stream(
stream: fidl_fuchsia_hardware_i2c::DeviceRequestStream,
name: &str,
) {
stream
.for_each(|msg| async move {
match msg.unwrap() {
fidl_fuchsia_hardware_i2c::DeviceRequest::GetName { responder } => {
responder.send(Ok(name)).unwrap();
}
_ => unimplemented!(),
}
})
.await
}
async fn handle(self) {
use fidl_fuchsia_hardware_i2c::ServiceRequest::*;
use IncomingServices::*;
match self {
I2cDevice(stream) => Self::handle_device_stream(stream, "device").await,
I2cDefaultService(Device(stream)) => {
Self::handle_device_stream(stream, "default").await
}
I2cOtherService(Device(stream)) => {
Self::handle_device_stream(stream, "other").await
}
}
}
}
async fn make_incoming() -> Incoming {
let (client, server) = fidl::endpoints::create_endpoints();
let mut fs = ServiceFs::new();
fs.dir("svc")
.add_fidl_service(IncomingServices::I2cDevice)
.add_fidl_service_instance("default", IncomingServices::I2cDefaultService)
.add_fidl_service_instance("other", IncomingServices::I2cOtherService);
fs.serve_connection(server).expect("error serving handle");
Task::spawn(fs.for_each_concurrent(100, IncomingServices::handle)).detach_on_drop();
Incoming(vec![Entry { path: NamespacePath::new("/").unwrap(), directory: client }])
}
#[fuchsia::test]
async fn protocol_connect_present() -> anyhow::Result<()> {
let incoming = make_incoming().await;
// try a protocol that we did set up
incoming
.protocol_marker(fidl_fuchsia_hardware_i2c::DeviceMarker)
.connect()?
.get_name()
.await?
.unwrap();
incoming
.protocol::<fidl_fuchsia_hardware_i2c::DeviceProxy>()
.connect()?
.get_name()
.await?
.unwrap();
Ok(())
}
#[fuchsia::test]
async fn protocol_connect_not_present() -> anyhow::Result<()> {
let incoming = make_incoming().await;
// try one we didn't
incoming
.protocol_marker(fidl_fuchsia_hwinfo::DeviceMarker)
.connect()?
.get_info()
.await
.unwrap_err();
incoming
.protocol::<fidl_fuchsia_hwinfo::DeviceProxy>()
.connect()?
.get_info()
.await
.unwrap_err();
Ok(())
}
#[fuchsia::test]
async fn service_connect_default_instance() -> anyhow::Result<()> {
let incoming = make_incoming().await;
// try the default service instance that we did set up
assert_eq!(
"default",
&incoming
.service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
.connect()?
.connect_to_device()?
.get_name()
.await?
.unwrap()
);
assert_eq!(
"default",
&incoming
.service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
.connect()?
.connect_to_device()?
.get_name()
.await?
.unwrap()
);
Ok(())
}
#[fuchsia::test]
async fn service_connect_other_instance() -> anyhow::Result<()> {
let incoming = make_incoming().await;
// try the other service instance that we did set up
assert_eq!(
"other",
&incoming
.service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
.instance("other")
.connect()?
.connect_to_device()?
.get_name()
.await?
.unwrap()
);
assert_eq!(
"other",
&incoming
.service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
.instance("other")
.connect()?
.connect_to_device()?
.get_name()
.await?
.unwrap()
);
Ok(())
}
#[fuchsia::test]
async fn service_connect_invalid_instance() -> anyhow::Result<()> {
let incoming = make_incoming().await;
// try the invalid service instance that we did not set up
incoming
.service_marker(fidl_fuchsia_hardware_i2c::ServiceMarker)
.instance("invalid")
.connect()?
.connect_to_device()?
.get_name()
.await
.unwrap_err();
incoming
.service::<fidl_fuchsia_hardware_i2c::ServiceProxy>()
.instance("invalid")
.connect()?
.connect_to_device()?
.get_name()
.await
.unwrap_err();
Ok(())
}
}