routing/
error.rs

1// Copyright 2021 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use crate::policy::PolicyError;
6use crate::rights::Rights;
7use async_trait::async_trait;
8use clonable_error::ClonableError;
9use cm_rust::{CapabilityTypeName, ExposeDeclCommon, OfferDeclCommon, SourceName, UseDeclCommon};
10use cm_types::Name;
11use moniker::{ChildName, ExtendedMoniker, Moniker};
12use router_error::{DowncastErrorForTest, Explain, RouterError};
13use std::sync::Arc;
14use thiserror::Error;
15use {fidl_fuchsia_component as fcomponent, zx_status as zx};
16
17#[cfg(feature = "serde")]
18use serde::{Deserialize, Serialize};
19
20/// Errors produced by `ComponentInstanceInterface`.
21#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
22#[derive(Debug, Error, Clone)]
23pub enum ComponentInstanceError {
24    #[error("could not find `{moniker}`")]
25    InstanceNotFound { moniker: Moniker },
26    #[error("component manager instance unavailable")]
27    ComponentManagerInstanceUnavailable {},
28    #[error("expected a component instance, but got component manager's instance")]
29    ComponentManagerInstanceUnexpected {},
30    #[error("malformed url `{url}` for `{moniker}`")]
31    MalformedUrl { url: String, moniker: Moniker },
32    #[error("url `{url}` for `{moniker}` does not resolve to an absolute url")]
33    NoAbsoluteUrl { url: String, moniker: Moniker },
34    // The capability routing static analyzer never produces this error subtype, so we don't need
35    // to serialize it.
36    #[cfg_attr(feature = "serde", serde(skip))]
37    #[error("failed to resolve `{moniker}`:\n\t{err}")]
38    ResolveFailed {
39        moniker: Moniker,
40        #[source]
41        err: ClonableError,
42    },
43}
44
45impl ComponentInstanceError {
46    pub fn as_zx_status(&self) -> zx::Status {
47        match self {
48            ComponentInstanceError::ResolveFailed { .. }
49            | ComponentInstanceError::InstanceNotFound { .. }
50            | ComponentInstanceError::ComponentManagerInstanceUnavailable {}
51            | ComponentInstanceError::NoAbsoluteUrl { .. } => zx::Status::NOT_FOUND,
52            ComponentInstanceError::MalformedUrl { .. }
53            | ComponentInstanceError::ComponentManagerInstanceUnexpected { .. } => {
54                zx::Status::INTERNAL
55            }
56        }
57    }
58
59    pub fn instance_not_found(moniker: Moniker) -> ComponentInstanceError {
60        ComponentInstanceError::InstanceNotFound { moniker }
61    }
62
63    pub fn cm_instance_unavailable() -> ComponentInstanceError {
64        ComponentInstanceError::ComponentManagerInstanceUnavailable {}
65    }
66
67    pub fn resolve_failed(moniker: Moniker, err: impl Into<anyhow::Error>) -> Self {
68        Self::ResolveFailed { moniker, err: err.into().into() }
69    }
70}
71
72impl Explain for ComponentInstanceError {
73    fn as_zx_status(&self) -> zx::Status {
74        self.as_zx_status()
75    }
76}
77
78impl From<ComponentInstanceError> for ExtendedMoniker {
79    fn from(err: ComponentInstanceError) -> ExtendedMoniker {
80        match err {
81            ComponentInstanceError::InstanceNotFound { moniker }
82            | ComponentInstanceError::MalformedUrl { moniker, .. }
83            | ComponentInstanceError::NoAbsoluteUrl { moniker, .. }
84            | ComponentInstanceError::ResolveFailed { moniker, .. } => {
85                ExtendedMoniker::ComponentInstance(moniker)
86            }
87            ComponentInstanceError::ComponentManagerInstanceUnavailable {}
88            | ComponentInstanceError::ComponentManagerInstanceUnexpected {} => {
89                ExtendedMoniker::ComponentManager
90            }
91        }
92    }
93}
94
95// Custom implementation of PartialEq in which two ComponentInstanceError::ResolveFailed errors are
96// never equal.
97impl PartialEq for ComponentInstanceError {
98    fn eq(&self, other: &Self) -> bool {
99        match (self, other) {
100            (
101                Self::InstanceNotFound { moniker: self_moniker },
102                Self::InstanceNotFound { moniker: other_moniker },
103            ) => self_moniker.eq(other_moniker),
104            (
105                Self::ComponentManagerInstanceUnavailable {},
106                Self::ComponentManagerInstanceUnavailable {},
107            ) => true,
108            (Self::ResolveFailed { .. }, Self::ResolveFailed { .. }) => false,
109            _ => false,
110        }
111    }
112}
113
114/// Errors produced during routing.
115#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
116#[derive(Debug, Error, Clone, PartialEq)]
117pub enum RoutingError {
118    #[error(
119        "backing directory `{capability_id}` was not exposed to `{moniker}` from `#{child_moniker}`"
120    )]
121    StorageFromChildExposeNotFound {
122        child_moniker: ChildName,
123        moniker: Moniker,
124        capability_id: String,
125    },
126
127    #[error(
128        "`{target_name:?}` tried to use a storage capability from `{source_moniker}` but it is \
129        not in the component id index. https://fuchsia.dev/go/components/instance-id"
130    )]
131    ComponentNotInIdIndex { source_moniker: Moniker, target_name: Option<ChildName> },
132
133    #[error("`{capability_id}` is not a built-in capability")]
134    UseFromComponentManagerNotFound { capability_id: String },
135
136    #[error("`{capability_id}` is not a built-in capability")]
137    RegisterFromComponentManagerNotFound { capability_id: String },
138
139    #[error("`{capability_id}` is not a built-in capability")]
140    OfferFromComponentManagerNotFound { capability_id: String },
141
142    #[error("`{capability_id}` was not offered to `{moniker}` by parent")]
143    UseFromParentNotFound { moniker: Moniker, capability_id: String },
144
145    #[error("`{capability_id}` was not declared as a capability by `{moniker}`")]
146    UseFromSelfNotFound { moniker: Moniker, capability_id: String },
147
148    #[error("`{moniker}` does not have child `#{child_moniker}`")]
149    UseFromChildInstanceNotFound {
150        child_moniker: ChildName,
151        moniker: Moniker,
152        capability_id: String,
153    },
154
155    #[error(
156        "{capability_type} `{capability_name}` was not registered in environment of `{moniker}`"
157    )]
158    UseFromEnvironmentNotFound { moniker: Moniker, capability_type: String, capability_name: Name },
159
160    #[error(
161        "`{moniker}` tried to use {capability_type} `{capability_name}` from the root environment"
162    )]
163    UseFromRootEnvironmentNotAllowed {
164        moniker: Moniker,
165        capability_type: String,
166        capability_name: Name,
167    },
168
169    #[error("{capability_type} `{capability_name}` was not offered to `{moniker}` by parent")]
170    EnvironmentFromParentNotFound {
171        moniker: Moniker,
172        capability_type: String,
173        capability_name: Name,
174    },
175
176    #[error("`{capability_name}` was not exposed to `{moniker}` from `#{child_moniker}`")]
177    EnvironmentFromChildExposeNotFound {
178        child_moniker: ChildName,
179        moniker: Moniker,
180        capability_type: String,
181        capability_name: Name,
182    },
183
184    #[error("`{moniker}` does not have child `#{child_moniker}`")]
185    EnvironmentFromChildInstanceNotFound {
186        child_moniker: ChildName,
187        moniker: Moniker,
188        capability_name: Name,
189        capability_type: String,
190    },
191
192    #[error("`{capability_id}` was not offered to `{moniker}` by parent")]
193    OfferFromParentNotFound { moniker: Moniker, capability_id: String },
194
195    #[error(
196        "cannot offer `{capability_id}` because was not declared as a capability by `{moniker}`"
197    )]
198    OfferFromSelfNotFound { moniker: Moniker, capability_id: String },
199
200    #[error("`{capability_id}` was not offered to `{moniker}` by parent")]
201    StorageFromParentNotFound { moniker: Moniker, capability_id: String },
202
203    #[error("`{moniker}` does not have child `#{child_moniker}`")]
204    OfferFromChildInstanceNotFound {
205        child_moniker: ChildName,
206        moniker: Moniker,
207        capability_id: String,
208    },
209
210    #[error("`{moniker}` does not have collection `#{collection}`")]
211    OfferFromCollectionNotFound { collection: String, moniker: Moniker, capability: Name },
212
213    #[error("`{capability_id}` was not exposed to `{moniker}` from `#{child_moniker}`")]
214    OfferFromChildExposeNotFound {
215        child_moniker: ChildName,
216        moniker: Moniker,
217        capability_id: String,
218    },
219
220    // TODO: Could this be distinguished by use/offer/expose?
221    #[error("`{capability_id}` is not a framework capability (at component `{moniker}`)")]
222    CapabilityFromFrameworkNotFound { moniker: Moniker, capability_id: String },
223
224    #[error(
225        "A capability was sourced to a base capability `{capability_id}` from `{moniker}`, but this is unsupported",
226    )]
227    CapabilityFromCapabilityNotFound { moniker: Moniker, capability_id: String },
228
229    // TODO: Could this be distinguished by use/offer/expose?
230    #[error("`{capability_id}` is not a framework capability")]
231    CapabilityFromComponentManagerNotFound { capability_id: String },
232
233    #[error(
234        "unable to expose `{capability_id}` because it was not declared as a capability by `{moniker}`"
235    )]
236    ExposeFromSelfNotFound { moniker: Moniker, capability_id: String },
237
238    #[error("`{moniker}` does not have child `#{child_moniker}`")]
239    ExposeFromChildInstanceNotFound {
240        child_moniker: ChildName,
241        moniker: Moniker,
242        capability_id: String,
243    },
244
245    #[error("`{moniker}` does not have collection `#{collection}`")]
246    ExposeFromCollectionNotFound { collection: String, moniker: Moniker, capability: Name },
247
248    #[error("`{capability_id}` was not exposed to `{moniker}` from `#{child_moniker}`")]
249    ExposeFromChildExposeNotFound {
250        child_moniker: ChildName,
251        moniker: Moniker,
252        capability_id: String,
253    },
254
255    #[error(
256        "`{moniker}` tried to expose `{capability_id}` from the framework, but no such framework capability was found"
257    )]
258    ExposeFromFrameworkNotFound { moniker: Moniker, capability_id: String },
259
260    #[error("`{capability_id}` was not exposed to `{moniker}` from `#{child_moniker}`")]
261    UseFromChildExposeNotFound { child_moniker: ChildName, moniker: Moniker, capability_id: String },
262
263    #[error("routing a capability from an unsupported source type `{source_type}` at `{moniker}`")]
264    UnsupportedRouteSource { source_type: String, moniker: ExtendedMoniker },
265
266    #[error("routing a capability of an unsupported type `{type_name}` at `{moniker}`")]
267    UnsupportedCapabilityType { type_name: CapabilityTypeName, moniker: ExtendedMoniker },
268
269    #[error(
270        "dictionaries are not yet supported for {cap_type} capabilities at component `{moniker}`"
271    )]
272    DictionariesNotSupported { moniker: Moniker, cap_type: CapabilityTypeName },
273
274    #[error("dynamic dictionaries are not allowed at component `{moniker}`")]
275    DynamicDictionariesNotAllowed { moniker: Moniker },
276
277    #[error("the capability does not support member access at `{moniker}`")]
278    BedrockMemberAccessUnsupported { moniker: ExtendedMoniker },
279
280    #[error("item `{name}` is not present in dictionary at component `{moniker}`")]
281    BedrockNotPresentInDictionary { name: String, moniker: ExtendedMoniker },
282
283    #[error("routed capability was the wrong type at component `{moniker}`. Was: {actual}, expected: {expected}")]
284    BedrockWrongCapabilityType { actual: String, expected: String, moniker: ExtendedMoniker },
285
286    #[error("there was an error remoting a capability at component `{moniker}`")]
287    BedrockRemoteCapability { moniker: Moniker },
288
289    #[error("source dictionary was not found in child's exposes at component `{moniker}`")]
290    BedrockSourceDictionaryExposeNotFound { moniker: Moniker },
291
292    #[error("Some capability in the routing chain could not be cloned at `{moniker}`.")]
293    BedrockNotCloneable { moniker: ExtendedMoniker },
294
295    #[error(
296        "a capability in a dictionary extended from a source dictionary collides with \
297        a capability in the source dictionary that has the same key at `{moniker}`"
298    )]
299    BedrockSourceDictionaryCollision { moniker: ExtendedMoniker },
300
301    #[error("failed to send message for capability `{capability_id}` from component `{moniker}`")]
302    BedrockFailedToSend { moniker: ExtendedMoniker, capability_id: String },
303
304    #[error("failed to route capability because the route source has been shutdown and possibly destroyed")]
305    RouteSourceShutdown { moniker: Moniker },
306
307    #[error(transparent)]
308    ComponentInstanceError(#[from] ComponentInstanceError),
309
310    #[error(transparent)]
311    EventsRoutingError(#[from] EventsRoutingError),
312
313    #[error(transparent)]
314    RightsRoutingError(#[from] RightsRoutingError),
315
316    #[error(transparent)]
317    AvailabilityRoutingError(#[from] AvailabilityRoutingError),
318
319    #[error(transparent)]
320    PolicyError(#[from] PolicyError),
321
322    #[error(
323        "source capability at component {moniker} is void. \
324        If the offer/expose declaration has `source_availability` set to `unknown`, \
325        the source component instance likely isn't defined in the component declaration"
326    )]
327    SourceCapabilityIsVoid { moniker: Moniker },
328
329    #[error(
330        "routes that do not set the `debug` flag are unsupported in the current configuration (at `{moniker}`)."
331    )]
332    NonDebugRoutesUnsupported { moniker: ExtendedMoniker },
333
334    #[error("debug routes are unsupported for external routers (at `{moniker}`).")]
335    DebugRoutesUnsupported { moniker: ExtendedMoniker },
336
337    #[error("{type_name} router unexpectedly returned debug info for target {moniker}")]
338    RouteUnexpectedDebug { type_name: CapabilityTypeName, moniker: ExtendedMoniker },
339
340    #[error("{type_name} router unexpectedly returned unavailable for target {moniker}")]
341    RouteUnexpectedUnavailable { type_name: CapabilityTypeName, moniker: ExtendedMoniker },
342
343    #[error("{name} at {moniker} is missing porcelain type metadata.")]
344    MissingPorcelainType { name: Name, moniker: Moniker },
345
346    #[error("path at `{moniker}` was too long for `{keyword}`: {path}")]
347    PathTooLong { moniker: ExtendedMoniker, path: String, keyword: String },
348}
349
350impl Explain for RoutingError {
351    /// Convert this error into its approximate `zx::Status` equivalent.
352    fn as_zx_status(&self) -> zx::Status {
353        match self {
354            RoutingError::UseFromRootEnvironmentNotAllowed { .. }
355            | RoutingError::DynamicDictionariesNotAllowed { .. } => zx::Status::ACCESS_DENIED,
356            RoutingError::StorageFromChildExposeNotFound { .. }
357            | RoutingError::ComponentNotInIdIndex { .. }
358            | RoutingError::UseFromComponentManagerNotFound { .. }
359            | RoutingError::RegisterFromComponentManagerNotFound { .. }
360            | RoutingError::OfferFromComponentManagerNotFound { .. }
361            | RoutingError::UseFromParentNotFound { .. }
362            | RoutingError::UseFromSelfNotFound { .. }
363            | RoutingError::UseFromChildInstanceNotFound { .. }
364            | RoutingError::UseFromEnvironmentNotFound { .. }
365            | RoutingError::EnvironmentFromParentNotFound { .. }
366            | RoutingError::EnvironmentFromChildExposeNotFound { .. }
367            | RoutingError::EnvironmentFromChildInstanceNotFound { .. }
368            | RoutingError::OfferFromParentNotFound { .. }
369            | RoutingError::OfferFromSelfNotFound { .. }
370            | RoutingError::StorageFromParentNotFound { .. }
371            | RoutingError::OfferFromChildInstanceNotFound { .. }
372            | RoutingError::OfferFromCollectionNotFound { .. }
373            | RoutingError::OfferFromChildExposeNotFound { .. }
374            | RoutingError::CapabilityFromFrameworkNotFound { .. }
375            | RoutingError::CapabilityFromCapabilityNotFound { .. }
376            | RoutingError::CapabilityFromComponentManagerNotFound { .. }
377            | RoutingError::ExposeFromSelfNotFound { .. }
378            | RoutingError::ExposeFromChildInstanceNotFound { .. }
379            | RoutingError::ExposeFromCollectionNotFound { .. }
380            | RoutingError::ExposeFromChildExposeNotFound { .. }
381            | RoutingError::ExposeFromFrameworkNotFound { .. }
382            | RoutingError::UseFromChildExposeNotFound { .. }
383            | RoutingError::UnsupportedRouteSource { .. }
384            | RoutingError::UnsupportedCapabilityType { .. }
385            | RoutingError::EventsRoutingError(_)
386            | RoutingError::BedrockNotPresentInDictionary { .. }
387            | RoutingError::BedrockSourceDictionaryExposeNotFound { .. }
388            | RoutingError::BedrockSourceDictionaryCollision { .. }
389            | RoutingError::BedrockFailedToSend { .. }
390            | RoutingError::RouteSourceShutdown { .. }
391            | RoutingError::BedrockWrongCapabilityType { .. }
392            | RoutingError::BedrockRemoteCapability { .. }
393            | RoutingError::BedrockNotCloneable { .. }
394            | RoutingError::AvailabilityRoutingError(_)
395            | RoutingError::PathTooLong { .. } => zx::Status::NOT_FOUND,
396            RoutingError::BedrockMemberAccessUnsupported { .. }
397            | RoutingError::NonDebugRoutesUnsupported { .. }
398            | RoutingError::DebugRoutesUnsupported { .. }
399            | RoutingError::DictionariesNotSupported { .. } => zx::Status::NOT_SUPPORTED,
400            RoutingError::ComponentInstanceError(err) => err.as_zx_status(),
401            RoutingError::RightsRoutingError(err) => err.as_zx_status(),
402            RoutingError::PolicyError(err) => err.as_zx_status(),
403            RoutingError::SourceCapabilityIsVoid { .. } => zx::Status::NOT_FOUND,
404            RoutingError::RouteUnexpectedDebug { .. }
405            | RoutingError::RouteUnexpectedUnavailable { .. }
406            | RoutingError::MissingPorcelainType { .. } => zx::Status::INTERNAL,
407        }
408    }
409}
410
411impl From<RoutingError> for ExtendedMoniker {
412    fn from(err: RoutingError) -> ExtendedMoniker {
413        match err {
414            RoutingError::BedrockRemoteCapability { moniker, .. }
415            | RoutingError::BedrockSourceDictionaryExposeNotFound { moniker, .. }
416            | RoutingError::CapabilityFromCapabilityNotFound { moniker, .. }
417            | RoutingError::CapabilityFromFrameworkNotFound { moniker, .. }
418            | RoutingError::ComponentNotInIdIndex { source_moniker: moniker, .. }
419            | RoutingError::DictionariesNotSupported { moniker, .. }
420            | RoutingError::EnvironmentFromChildExposeNotFound { moniker, .. }
421            | RoutingError::EnvironmentFromChildInstanceNotFound { moniker, .. }
422            | RoutingError::EnvironmentFromParentNotFound { moniker, .. }
423            | RoutingError::ExposeFromChildExposeNotFound { moniker, .. }
424            | RoutingError::ExposeFromChildInstanceNotFound { moniker, .. }
425            | RoutingError::ExposeFromCollectionNotFound { moniker, .. }
426            | RoutingError::ExposeFromFrameworkNotFound { moniker, .. }
427            | RoutingError::ExposeFromSelfNotFound { moniker, .. }
428            | RoutingError::OfferFromChildExposeNotFound { moniker, .. }
429            | RoutingError::OfferFromChildInstanceNotFound { moniker, .. }
430            | RoutingError::OfferFromCollectionNotFound { moniker, .. }
431            | RoutingError::OfferFromParentNotFound { moniker, .. }
432            | RoutingError::OfferFromSelfNotFound { moniker, .. }
433            | RoutingError::SourceCapabilityIsVoid { moniker, .. }
434            | RoutingError::StorageFromChildExposeNotFound { moniker, .. }
435            | RoutingError::StorageFromParentNotFound { moniker, .. }
436            | RoutingError::UseFromChildExposeNotFound { moniker, .. }
437            | RoutingError::UseFromChildInstanceNotFound { moniker, .. }
438            | RoutingError::UseFromEnvironmentNotFound { moniker, .. }
439            | RoutingError::UseFromParentNotFound { moniker, .. }
440            | RoutingError::UseFromRootEnvironmentNotAllowed { moniker, .. }
441            | RoutingError::DynamicDictionariesNotAllowed { moniker, .. }
442            | RoutingError::RouteSourceShutdown { moniker }
443            | RoutingError::UseFromSelfNotFound { moniker, .. }
444            | RoutingError::MissingPorcelainType { moniker, .. } => moniker.into(),
445            RoutingError::PathTooLong { moniker, .. } => moniker,
446
447            RoutingError::BedrockMemberAccessUnsupported { moniker }
448            | RoutingError::BedrockNotPresentInDictionary { moniker, .. }
449            | RoutingError::BedrockNotCloneable { moniker }
450            | RoutingError::BedrockSourceDictionaryCollision { moniker }
451            | RoutingError::BedrockFailedToSend { moniker, .. }
452            | RoutingError::BedrockWrongCapabilityType { moniker, .. }
453            | RoutingError::NonDebugRoutesUnsupported { moniker }
454            | RoutingError::DebugRoutesUnsupported { moniker }
455            | RoutingError::RouteUnexpectedDebug { moniker, .. }
456            | RoutingError::RouteUnexpectedUnavailable { moniker, .. }
457            | RoutingError::UnsupportedCapabilityType { moniker, .. }
458            | RoutingError::UnsupportedRouteSource { moniker, .. } => moniker,
459            RoutingError::AvailabilityRoutingError(err) => err.into(),
460            RoutingError::ComponentInstanceError(err) => err.into(),
461            RoutingError::EventsRoutingError(err) => err.into(),
462            RoutingError::PolicyError(err) => err.into(),
463            RoutingError::RightsRoutingError(err) => err.into(),
464
465            RoutingError::CapabilityFromComponentManagerNotFound { .. }
466            | RoutingError::OfferFromComponentManagerNotFound { .. }
467            | RoutingError::RegisterFromComponentManagerNotFound { .. }
468            | RoutingError::UseFromComponentManagerNotFound { .. } => {
469                ExtendedMoniker::ComponentManager
470            }
471        }
472    }
473}
474
475impl From<RoutingError> for RouterError {
476    fn from(value: RoutingError) -> Self {
477        Self::NotFound(Arc::new(value))
478    }
479}
480
481impl From<RouterError> for RoutingError {
482    fn from(value: RouterError) -> Self {
483        match value {
484            RouterError::NotFound(arc_dyn_explain) => {
485                arc_dyn_explain.downcast_for_test::<Self>().clone()
486            }
487            err => panic!("Cannot downcast {err} to RoutingError!"),
488        }
489    }
490}
491
492impl RoutingError {
493    /// Convert this error into its approximate `fuchsia.component.Error` equivalent.
494    pub fn as_fidl_error(&self) -> fcomponent::Error {
495        fcomponent::Error::ResourceUnavailable
496    }
497
498    pub fn storage_from_child_expose_not_found(
499        child_moniker: &ChildName,
500        moniker: &Moniker,
501        capability_id: impl Into<String>,
502    ) -> Self {
503        Self::StorageFromChildExposeNotFound {
504            child_moniker: child_moniker.clone(),
505            moniker: moniker.clone(),
506            capability_id: capability_id.into(),
507        }
508    }
509
510    pub fn use_from_component_manager_not_found(capability_id: impl Into<String>) -> Self {
511        Self::UseFromComponentManagerNotFound { capability_id: capability_id.into() }
512    }
513
514    pub fn register_from_component_manager_not_found(capability_id: impl Into<String>) -> Self {
515        Self::RegisterFromComponentManagerNotFound { capability_id: capability_id.into() }
516    }
517
518    pub fn offer_from_component_manager_not_found(capability_id: impl Into<String>) -> Self {
519        Self::OfferFromComponentManagerNotFound { capability_id: capability_id.into() }
520    }
521
522    pub fn use_from_parent_not_found(moniker: &Moniker, capability_id: impl Into<String>) -> Self {
523        Self::UseFromParentNotFound {
524            moniker: moniker.clone(),
525            capability_id: capability_id.into(),
526        }
527    }
528
529    pub fn use_from_self_not_found(moniker: &Moniker, capability_id: impl Into<String>) -> Self {
530        Self::UseFromSelfNotFound { moniker: moniker.clone(), capability_id: capability_id.into() }
531    }
532
533    pub fn use_from_child_instance_not_found(
534        child_moniker: &ChildName,
535        moniker: &Moniker,
536        capability_id: impl Into<String>,
537    ) -> Self {
538        Self::UseFromChildInstanceNotFound {
539            child_moniker: child_moniker.clone(),
540            moniker: moniker.clone(),
541            capability_id: capability_id.into(),
542        }
543    }
544
545    pub fn use_from_environment_not_found(
546        moniker: &Moniker,
547        capability_type: impl Into<String>,
548        capability_name: &Name,
549    ) -> Self {
550        Self::UseFromEnvironmentNotFound {
551            moniker: moniker.clone(),
552            capability_type: capability_type.into(),
553            capability_name: capability_name.clone(),
554        }
555    }
556
557    pub fn offer_from_parent_not_found(
558        moniker: &Moniker,
559        capability_id: impl Into<String>,
560    ) -> Self {
561        Self::OfferFromParentNotFound {
562            moniker: moniker.clone(),
563            capability_id: capability_id.into(),
564        }
565    }
566
567    pub fn offer_from_self_not_found(moniker: &Moniker, capability_id: impl Into<String>) -> Self {
568        Self::OfferFromSelfNotFound {
569            moniker: moniker.clone(),
570            capability_id: capability_id.into(),
571        }
572    }
573
574    pub fn storage_from_parent_not_found(
575        moniker: &Moniker,
576        capability_id: impl Into<String>,
577    ) -> Self {
578        Self::StorageFromParentNotFound {
579            moniker: moniker.clone(),
580            capability_id: capability_id.into(),
581        }
582    }
583
584    pub fn offer_from_child_instance_not_found(
585        child_moniker: &ChildName,
586        moniker: &Moniker,
587        capability_id: impl Into<String>,
588    ) -> Self {
589        Self::OfferFromChildInstanceNotFound {
590            child_moniker: child_moniker.clone(),
591            moniker: moniker.clone(),
592            capability_id: capability_id.into(),
593        }
594    }
595
596    pub fn offer_from_child_expose_not_found(
597        child_moniker: &ChildName,
598        moniker: &Moniker,
599        capability_id: impl Into<String>,
600    ) -> Self {
601        Self::OfferFromChildExposeNotFound {
602            child_moniker: child_moniker.clone(),
603            moniker: moniker.clone(),
604            capability_id: capability_id.into(),
605        }
606    }
607
608    pub fn use_from_child_expose_not_found(
609        child_moniker: &ChildName,
610        moniker: &Moniker,
611        capability_id: impl Into<String>,
612    ) -> Self {
613        Self::UseFromChildExposeNotFound {
614            child_moniker: child_moniker.clone(),
615            moniker: moniker.clone(),
616            capability_id: capability_id.into(),
617        }
618    }
619
620    pub fn expose_from_self_not_found(moniker: &Moniker, capability_id: impl Into<String>) -> Self {
621        Self::ExposeFromSelfNotFound {
622            moniker: moniker.clone(),
623            capability_id: capability_id.into(),
624        }
625    }
626
627    pub fn expose_from_child_instance_not_found(
628        child_moniker: &ChildName,
629        moniker: &Moniker,
630        capability_id: impl Into<String>,
631    ) -> Self {
632        Self::ExposeFromChildInstanceNotFound {
633            child_moniker: child_moniker.clone(),
634            moniker: moniker.clone(),
635            capability_id: capability_id.into(),
636        }
637    }
638
639    pub fn expose_from_child_expose_not_found(
640        child_moniker: &ChildName,
641        moniker: &Moniker,
642        capability_id: impl Into<String>,
643    ) -> Self {
644        Self::ExposeFromChildExposeNotFound {
645            child_moniker: child_moniker.clone(),
646            moniker: moniker.clone(),
647            capability_id: capability_id.into(),
648        }
649    }
650
651    pub fn capability_from_framework_not_found(
652        moniker: &Moniker,
653        capability_id: impl Into<String>,
654    ) -> Self {
655        Self::CapabilityFromFrameworkNotFound {
656            moniker: moniker.clone(),
657            capability_id: capability_id.into(),
658        }
659    }
660
661    pub fn capability_from_capability_not_found(
662        moniker: &Moniker,
663        capability_id: impl Into<String>,
664    ) -> Self {
665        Self::CapabilityFromCapabilityNotFound {
666            moniker: moniker.clone(),
667            capability_id: capability_id.into(),
668        }
669    }
670
671    pub fn capability_from_component_manager_not_found(capability_id: impl Into<String>) -> Self {
672        Self::CapabilityFromComponentManagerNotFound { capability_id: capability_id.into() }
673    }
674
675    pub fn expose_from_framework_not_found(
676        moniker: &Moniker,
677        capability_id: impl Into<String>,
678    ) -> Self {
679        Self::ExposeFromFrameworkNotFound {
680            moniker: moniker.clone(),
681            capability_id: capability_id.into(),
682        }
683    }
684
685    pub fn unsupported_route_source(
686        moniker: impl Into<ExtendedMoniker>,
687        source: impl Into<String>,
688    ) -> Self {
689        Self::UnsupportedRouteSource { source_type: source.into(), moniker: moniker.into() }
690    }
691
692    pub fn unsupported_capability_type(
693        moniker: impl Into<ExtendedMoniker>,
694        type_name: impl Into<CapabilityTypeName>,
695    ) -> Self {
696        Self::UnsupportedCapabilityType { type_name: type_name.into(), moniker: moniker.into() }
697    }
698}
699
700/// Errors produced during routing specific to events.
701#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
702#[derive(Error, Debug, Clone, PartialEq)]
703pub enum EventsRoutingError {
704    #[error("filter is not a subset at `{moniker}`")]
705    InvalidFilter { moniker: ExtendedMoniker },
706
707    #[error("event routes must end at source with a filter declaration at `{moniker}`")]
708    MissingFilter { moniker: ExtendedMoniker },
709}
710
711impl From<EventsRoutingError> for ExtendedMoniker {
712    fn from(err: EventsRoutingError) -> ExtendedMoniker {
713        match err {
714            EventsRoutingError::InvalidFilter { moniker }
715            | EventsRoutingError::MissingFilter { moniker } => moniker,
716        }
717    }
718}
719
720#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
721#[derive(Debug, Error, Clone, PartialEq)]
722pub enum RightsRoutingError {
723    #[error(
724        "requested rights ({requested}) greater than provided rights ({provided}) at \"{moniker}\""
725    )]
726    Invalid { moniker: ExtendedMoniker, requested: Rights, provided: Rights },
727
728    #[error("directory routes must end at source with a rights declaration, it's missing at \"{moniker}\"")]
729    MissingRightsSource { moniker: ExtendedMoniker },
730}
731
732impl RightsRoutingError {
733    /// Convert this error into its approximate `zx::Status` equivalent.
734    pub fn as_zx_status(&self) -> zx::Status {
735        match self {
736            RightsRoutingError::Invalid { .. } => zx::Status::ACCESS_DENIED,
737            RightsRoutingError::MissingRightsSource { .. } => zx::Status::NOT_FOUND,
738        }
739    }
740}
741
742impl From<RightsRoutingError> for ExtendedMoniker {
743    fn from(err: RightsRoutingError) -> ExtendedMoniker {
744        match err {
745            RightsRoutingError::Invalid { moniker, .. }
746            | RightsRoutingError::MissingRightsSource { moniker } => moniker,
747        }
748    }
749}
750
751#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
752#[derive(Debug, Error, Clone, PartialEq)]
753pub enum AvailabilityRoutingError {
754    #[error(
755        "availability requested by the target has stronger guarantees than what \
756    is being provided at the source at `{moniker}`"
757    )]
758    TargetHasStrongerAvailability { moniker: ExtendedMoniker },
759
760    #[error("offer uses void source, but target requires the capability at `{moniker}`")]
761    OfferFromVoidToRequiredTarget { moniker: ExtendedMoniker },
762
763    #[error("expose uses void source, but target requires the capability at `{moniker}`")]
764    ExposeFromVoidToRequiredTarget { moniker: ExtendedMoniker },
765}
766
767impl From<availability::TargetHasStrongerAvailability> for AvailabilityRoutingError {
768    fn from(value: availability::TargetHasStrongerAvailability) -> Self {
769        let availability::TargetHasStrongerAvailability { moniker } = value;
770        AvailabilityRoutingError::TargetHasStrongerAvailability { moniker }
771    }
772}
773
774impl From<AvailabilityRoutingError> for ExtendedMoniker {
775    fn from(err: AvailabilityRoutingError) -> ExtendedMoniker {
776        match err {
777            AvailabilityRoutingError::ExposeFromVoidToRequiredTarget { moniker }
778            | AvailabilityRoutingError::OfferFromVoidToRequiredTarget { moniker }
779            | AvailabilityRoutingError::TargetHasStrongerAvailability { moniker } => moniker,
780        }
781    }
782}
783
784// Implements error reporting upon routing failure. For example, component
785// manager logs the error.
786#[async_trait]
787pub trait ErrorReporter: Clone + Send + Sync + 'static {
788    async fn report(
789        &self,
790        request: &RouteRequestErrorInfo,
791        err: &RouterError,
792        route_target: Option<sandbox::WeakInstanceToken>,
793    );
794}
795
796/// What to print in an error if a route request fails.
797pub struct RouteRequestErrorInfo {
798    capability_type: cm_rust::CapabilityTypeName,
799    name: cm_types::Name,
800    availability: cm_rust::Availability,
801}
802
803impl RouteRequestErrorInfo {
804    pub fn availability(&self) -> cm_rust::Availability {
805        self.availability.clone()
806    }
807}
808
809impl From<&cm_rust::UseDecl> for RouteRequestErrorInfo {
810    fn from(value: &cm_rust::UseDecl) -> Self {
811        RouteRequestErrorInfo {
812            capability_type: value.into(),
813            name: value.source_name().clone(),
814            availability: value.availability().clone(),
815        }
816    }
817}
818
819impl From<&cm_rust::UseConfigurationDecl> for RouteRequestErrorInfo {
820    fn from(value: &cm_rust::UseConfigurationDecl) -> Self {
821        RouteRequestErrorInfo {
822            capability_type: CapabilityTypeName::Config,
823            name: value.source_name().clone(),
824            availability: value.availability().clone(),
825        }
826    }
827}
828
829impl From<&cm_rust::ExposeDecl> for RouteRequestErrorInfo {
830    fn from(value: &cm_rust::ExposeDecl) -> Self {
831        RouteRequestErrorInfo {
832            capability_type: value.into(),
833            name: value.target_name().clone(),
834            availability: value.availability().clone(),
835        }
836    }
837}
838
839impl From<&cm_rust::OfferDecl> for RouteRequestErrorInfo {
840    fn from(value: &cm_rust::OfferDecl) -> Self {
841        RouteRequestErrorInfo {
842            capability_type: value.into(),
843            name: value.target_name().clone(),
844            availability: value.availability().clone(),
845        }
846    }
847}
848
849impl std::fmt::Display for RouteRequestErrorInfo {
850    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
851        write!(f, "{} `{}`", self.capability_type, self.name)
852    }
853}