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