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("{type_name} router unexpectedly returned debug info for target {moniker}")]
335    RouteUnexpectedDebug { type_name: CapabilityTypeName, moniker: ExtendedMoniker },
336
337    #[error("{type_name} router unexpectedly returned unavailable for target {moniker}")]
338    RouteUnexpectedUnavailable { type_name: CapabilityTypeName, moniker: ExtendedMoniker },
339
340    #[error("{name} at {moniker} is missing porcelain type metadata.")]
341    MissingPorcelainType { name: Name, moniker: Moniker },
342}
343
344impl Explain for RoutingError {
345    /// Convert this error into its approximate `zx::Status` equivalent.
346    fn as_zx_status(&self) -> zx::Status {
347        match self {
348            RoutingError::UseFromRootEnvironmentNotAllowed { .. }
349            | RoutingError::DynamicDictionariesNotAllowed { .. } => zx::Status::ACCESS_DENIED,
350            RoutingError::StorageFromChildExposeNotFound { .. }
351            | RoutingError::ComponentNotInIdIndex { .. }
352            | RoutingError::UseFromComponentManagerNotFound { .. }
353            | RoutingError::RegisterFromComponentManagerNotFound { .. }
354            | RoutingError::OfferFromComponentManagerNotFound { .. }
355            | RoutingError::UseFromParentNotFound { .. }
356            | RoutingError::UseFromSelfNotFound { .. }
357            | RoutingError::UseFromChildInstanceNotFound { .. }
358            | RoutingError::UseFromEnvironmentNotFound { .. }
359            | RoutingError::EnvironmentFromParentNotFound { .. }
360            | RoutingError::EnvironmentFromChildExposeNotFound { .. }
361            | RoutingError::EnvironmentFromChildInstanceNotFound { .. }
362            | RoutingError::OfferFromParentNotFound { .. }
363            | RoutingError::OfferFromSelfNotFound { .. }
364            | RoutingError::StorageFromParentNotFound { .. }
365            | RoutingError::OfferFromChildInstanceNotFound { .. }
366            | RoutingError::OfferFromCollectionNotFound { .. }
367            | RoutingError::OfferFromChildExposeNotFound { .. }
368            | RoutingError::CapabilityFromFrameworkNotFound { .. }
369            | RoutingError::CapabilityFromCapabilityNotFound { .. }
370            | RoutingError::CapabilityFromComponentManagerNotFound { .. }
371            | RoutingError::ExposeFromSelfNotFound { .. }
372            | RoutingError::ExposeFromChildInstanceNotFound { .. }
373            | RoutingError::ExposeFromCollectionNotFound { .. }
374            | RoutingError::ExposeFromChildExposeNotFound { .. }
375            | RoutingError::ExposeFromFrameworkNotFound { .. }
376            | RoutingError::UseFromChildExposeNotFound { .. }
377            | RoutingError::UnsupportedRouteSource { .. }
378            | RoutingError::UnsupportedCapabilityType { .. }
379            | RoutingError::EventsRoutingError(_)
380            | RoutingError::BedrockNotPresentInDictionary { .. }
381            | RoutingError::BedrockSourceDictionaryExposeNotFound { .. }
382            | RoutingError::BedrockSourceDictionaryCollision { .. }
383            | RoutingError::BedrockFailedToSend { .. }
384            | RoutingError::RouteSourceShutdown { .. }
385            | RoutingError::BedrockWrongCapabilityType { .. }
386            | RoutingError::BedrockRemoteCapability { .. }
387            | RoutingError::BedrockNotCloneable { .. }
388            | RoutingError::AvailabilityRoutingError(_) => zx::Status::NOT_FOUND,
389            RoutingError::BedrockMemberAccessUnsupported { .. }
390            | RoutingError::NonDebugRoutesUnsupported { .. }
391            | RoutingError::DictionariesNotSupported { .. } => zx::Status::NOT_SUPPORTED,
392            RoutingError::ComponentInstanceError(err) => err.as_zx_status(),
393            RoutingError::RightsRoutingError(err) => err.as_zx_status(),
394            RoutingError::PolicyError(err) => err.as_zx_status(),
395            RoutingError::SourceCapabilityIsVoid { .. } => zx::Status::NOT_FOUND,
396            RoutingError::RouteUnexpectedDebug { .. }
397            | RoutingError::RouteUnexpectedUnavailable { .. }
398            | RoutingError::MissingPorcelainType { .. } => zx::Status::INTERNAL,
399        }
400    }
401}
402
403impl From<RoutingError> for ExtendedMoniker {
404    fn from(err: RoutingError) -> ExtendedMoniker {
405        match err {
406            RoutingError::BedrockRemoteCapability { moniker, .. }
407            | RoutingError::BedrockSourceDictionaryExposeNotFound { moniker, .. }
408            | RoutingError::CapabilityFromCapabilityNotFound { moniker, .. }
409            | RoutingError::CapabilityFromFrameworkNotFound { moniker, .. }
410            | RoutingError::ComponentNotInIdIndex { source_moniker: moniker, .. }
411            | RoutingError::DictionariesNotSupported { moniker, .. }
412            | RoutingError::EnvironmentFromChildExposeNotFound { moniker, .. }
413            | RoutingError::EnvironmentFromChildInstanceNotFound { moniker, .. }
414            | RoutingError::EnvironmentFromParentNotFound { moniker, .. }
415            | RoutingError::ExposeFromChildExposeNotFound { moniker, .. }
416            | RoutingError::ExposeFromChildInstanceNotFound { moniker, .. }
417            | RoutingError::ExposeFromCollectionNotFound { moniker, .. }
418            | RoutingError::ExposeFromFrameworkNotFound { moniker, .. }
419            | RoutingError::ExposeFromSelfNotFound { moniker, .. }
420            | RoutingError::OfferFromChildExposeNotFound { moniker, .. }
421            | RoutingError::OfferFromChildInstanceNotFound { moniker, .. }
422            | RoutingError::OfferFromCollectionNotFound { moniker, .. }
423            | RoutingError::OfferFromParentNotFound { moniker, .. }
424            | RoutingError::OfferFromSelfNotFound { moniker, .. }
425            | RoutingError::SourceCapabilityIsVoid { moniker, .. }
426            | RoutingError::StorageFromChildExposeNotFound { moniker, .. }
427            | RoutingError::StorageFromParentNotFound { moniker, .. }
428            | RoutingError::UseFromChildExposeNotFound { moniker, .. }
429            | RoutingError::UseFromChildInstanceNotFound { moniker, .. }
430            | RoutingError::UseFromEnvironmentNotFound { moniker, .. }
431            | RoutingError::UseFromParentNotFound { moniker, .. }
432            | RoutingError::UseFromRootEnvironmentNotAllowed { moniker, .. }
433            | RoutingError::DynamicDictionariesNotAllowed { moniker, .. }
434            | RoutingError::RouteSourceShutdown { moniker }
435            | RoutingError::UseFromSelfNotFound { moniker, .. }
436            | RoutingError::MissingPorcelainType { moniker, .. } => moniker.into(),
437
438            RoutingError::BedrockMemberAccessUnsupported { moniker }
439            | RoutingError::BedrockNotPresentInDictionary { moniker, .. }
440            | RoutingError::BedrockNotCloneable { moniker }
441            | RoutingError::BedrockSourceDictionaryCollision { moniker }
442            | RoutingError::BedrockFailedToSend { moniker, .. }
443            | RoutingError::BedrockWrongCapabilityType { moniker, .. }
444            | RoutingError::NonDebugRoutesUnsupported { moniker }
445            | RoutingError::RouteUnexpectedDebug { moniker, .. }
446            | RoutingError::RouteUnexpectedUnavailable { moniker, .. }
447            | RoutingError::UnsupportedCapabilityType { moniker, .. }
448            | RoutingError::UnsupportedRouteSource { moniker, .. } => moniker,
449            RoutingError::AvailabilityRoutingError(err) => err.into(),
450            RoutingError::ComponentInstanceError(err) => err.into(),
451            RoutingError::EventsRoutingError(err) => err.into(),
452            RoutingError::PolicyError(err) => err.into(),
453            RoutingError::RightsRoutingError(err) => err.into(),
454
455            RoutingError::CapabilityFromComponentManagerNotFound { .. }
456            | RoutingError::OfferFromComponentManagerNotFound { .. }
457            | RoutingError::RegisterFromComponentManagerNotFound { .. }
458            | RoutingError::UseFromComponentManagerNotFound { .. } => {
459                ExtendedMoniker::ComponentManager
460            }
461        }
462    }
463}
464
465impl From<RoutingError> for RouterError {
466    fn from(value: RoutingError) -> Self {
467        Self::NotFound(Arc::new(value))
468    }
469}
470
471impl From<RouterError> for RoutingError {
472    fn from(value: RouterError) -> Self {
473        match value {
474            RouterError::NotFound(arc_dyn_explain) => {
475                arc_dyn_explain.downcast_for_test::<Self>().clone()
476            }
477            err => panic!("Cannot downcast {err} to RoutingError!"),
478        }
479    }
480}
481
482impl RoutingError {
483    /// Convert this error into its approximate `fuchsia.component.Error` equivalent.
484    pub fn as_fidl_error(&self) -> fcomponent::Error {
485        fcomponent::Error::ResourceUnavailable
486    }
487
488    pub fn storage_from_child_expose_not_found(
489        child_moniker: &ChildName,
490        moniker: &Moniker,
491        capability_id: impl Into<String>,
492    ) -> Self {
493        Self::StorageFromChildExposeNotFound {
494            child_moniker: child_moniker.clone(),
495            moniker: moniker.clone(),
496            capability_id: capability_id.into(),
497        }
498    }
499
500    pub fn use_from_component_manager_not_found(capability_id: impl Into<String>) -> Self {
501        Self::UseFromComponentManagerNotFound { capability_id: capability_id.into() }
502    }
503
504    pub fn register_from_component_manager_not_found(capability_id: impl Into<String>) -> Self {
505        Self::RegisterFromComponentManagerNotFound { capability_id: capability_id.into() }
506    }
507
508    pub fn offer_from_component_manager_not_found(capability_id: impl Into<String>) -> Self {
509        Self::OfferFromComponentManagerNotFound { capability_id: capability_id.into() }
510    }
511
512    pub fn use_from_parent_not_found(moniker: &Moniker, capability_id: impl Into<String>) -> Self {
513        Self::UseFromParentNotFound {
514            moniker: moniker.clone(),
515            capability_id: capability_id.into(),
516        }
517    }
518
519    pub fn use_from_self_not_found(moniker: &Moniker, capability_id: impl Into<String>) -> Self {
520        Self::UseFromSelfNotFound { moniker: moniker.clone(), capability_id: capability_id.into() }
521    }
522
523    pub fn use_from_child_instance_not_found(
524        child_moniker: &ChildName,
525        moniker: &Moniker,
526        capability_id: impl Into<String>,
527    ) -> Self {
528        Self::UseFromChildInstanceNotFound {
529            child_moniker: child_moniker.clone(),
530            moniker: moniker.clone(),
531            capability_id: capability_id.into(),
532        }
533    }
534
535    pub fn use_from_environment_not_found(
536        moniker: &Moniker,
537        capability_type: impl Into<String>,
538        capability_name: &Name,
539    ) -> Self {
540        Self::UseFromEnvironmentNotFound {
541            moniker: moniker.clone(),
542            capability_type: capability_type.into(),
543            capability_name: capability_name.clone(),
544        }
545    }
546
547    pub fn offer_from_parent_not_found(
548        moniker: &Moniker,
549        capability_id: impl Into<String>,
550    ) -> Self {
551        Self::OfferFromParentNotFound {
552            moniker: moniker.clone(),
553            capability_id: capability_id.into(),
554        }
555    }
556
557    pub fn offer_from_self_not_found(moniker: &Moniker, capability_id: impl Into<String>) -> Self {
558        Self::OfferFromSelfNotFound {
559            moniker: moniker.clone(),
560            capability_id: capability_id.into(),
561        }
562    }
563
564    pub fn storage_from_parent_not_found(
565        moniker: &Moniker,
566        capability_id: impl Into<String>,
567    ) -> Self {
568        Self::StorageFromParentNotFound {
569            moniker: moniker.clone(),
570            capability_id: capability_id.into(),
571        }
572    }
573
574    pub fn offer_from_child_instance_not_found(
575        child_moniker: &ChildName,
576        moniker: &Moniker,
577        capability_id: impl Into<String>,
578    ) -> Self {
579        Self::OfferFromChildInstanceNotFound {
580            child_moniker: child_moniker.clone(),
581            moniker: moniker.clone(),
582            capability_id: capability_id.into(),
583        }
584    }
585
586    pub fn offer_from_child_expose_not_found(
587        child_moniker: &ChildName,
588        moniker: &Moniker,
589        capability_id: impl Into<String>,
590    ) -> Self {
591        Self::OfferFromChildExposeNotFound {
592            child_moniker: child_moniker.clone(),
593            moniker: moniker.clone(),
594            capability_id: capability_id.into(),
595        }
596    }
597
598    pub fn use_from_child_expose_not_found(
599        child_moniker: &ChildName,
600        moniker: &Moniker,
601        capability_id: impl Into<String>,
602    ) -> Self {
603        Self::UseFromChildExposeNotFound {
604            child_moniker: child_moniker.clone(),
605            moniker: moniker.clone(),
606            capability_id: capability_id.into(),
607        }
608    }
609
610    pub fn expose_from_self_not_found(moniker: &Moniker, capability_id: impl Into<String>) -> Self {
611        Self::ExposeFromSelfNotFound {
612            moniker: moniker.clone(),
613            capability_id: capability_id.into(),
614        }
615    }
616
617    pub fn expose_from_child_instance_not_found(
618        child_moniker: &ChildName,
619        moniker: &Moniker,
620        capability_id: impl Into<String>,
621    ) -> Self {
622        Self::ExposeFromChildInstanceNotFound {
623            child_moniker: child_moniker.clone(),
624            moniker: moniker.clone(),
625            capability_id: capability_id.into(),
626        }
627    }
628
629    pub fn expose_from_child_expose_not_found(
630        child_moniker: &ChildName,
631        moniker: &Moniker,
632        capability_id: impl Into<String>,
633    ) -> Self {
634        Self::ExposeFromChildExposeNotFound {
635            child_moniker: child_moniker.clone(),
636            moniker: moniker.clone(),
637            capability_id: capability_id.into(),
638        }
639    }
640
641    pub fn capability_from_framework_not_found(
642        moniker: &Moniker,
643        capability_id: impl Into<String>,
644    ) -> Self {
645        Self::CapabilityFromFrameworkNotFound {
646            moniker: moniker.clone(),
647            capability_id: capability_id.into(),
648        }
649    }
650
651    pub fn capability_from_capability_not_found(
652        moniker: &Moniker,
653        capability_id: impl Into<String>,
654    ) -> Self {
655        Self::CapabilityFromCapabilityNotFound {
656            moniker: moniker.clone(),
657            capability_id: capability_id.into(),
658        }
659    }
660
661    pub fn capability_from_component_manager_not_found(capability_id: impl Into<String>) -> Self {
662        Self::CapabilityFromComponentManagerNotFound { capability_id: capability_id.into() }
663    }
664
665    pub fn expose_from_framework_not_found(
666        moniker: &Moniker,
667        capability_id: impl Into<String>,
668    ) -> Self {
669        Self::ExposeFromFrameworkNotFound {
670            moniker: moniker.clone(),
671            capability_id: capability_id.into(),
672        }
673    }
674
675    pub fn unsupported_route_source(
676        moniker: impl Into<ExtendedMoniker>,
677        source: impl Into<String>,
678    ) -> Self {
679        Self::UnsupportedRouteSource { source_type: source.into(), moniker: moniker.into() }
680    }
681
682    pub fn unsupported_capability_type(
683        moniker: impl Into<ExtendedMoniker>,
684        type_name: impl Into<CapabilityTypeName>,
685    ) -> Self {
686        Self::UnsupportedCapabilityType { type_name: type_name.into(), moniker: moniker.into() }
687    }
688}
689
690/// Errors produced during routing specific to events.
691#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
692#[derive(Error, Debug, Clone, PartialEq)]
693pub enum EventsRoutingError {
694    #[error("filter is not a subset at `{moniker}`")]
695    InvalidFilter { moniker: ExtendedMoniker },
696
697    #[error("event routes must end at source with a filter declaration at `{moniker}`")]
698    MissingFilter { moniker: ExtendedMoniker },
699}
700
701impl From<EventsRoutingError> for ExtendedMoniker {
702    fn from(err: EventsRoutingError) -> ExtendedMoniker {
703        match err {
704            EventsRoutingError::InvalidFilter { moniker }
705            | EventsRoutingError::MissingFilter { moniker } => moniker,
706        }
707    }
708}
709
710#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
711#[derive(Debug, Error, Clone, PartialEq)]
712pub enum RightsRoutingError {
713    #[error(
714        "requested rights ({requested}) greater than provided rights ({provided}) at \"{moniker}\""
715    )]
716    Invalid { moniker: ExtendedMoniker, requested: Rights, provided: Rights },
717
718    #[error("directory routes must end at source with a rights declaration, it's missing at \"{moniker}\"")]
719    MissingRightsSource { moniker: ExtendedMoniker },
720}
721
722impl RightsRoutingError {
723    /// Convert this error into its approximate `zx::Status` equivalent.
724    pub fn as_zx_status(&self) -> zx::Status {
725        match self {
726            RightsRoutingError::Invalid { .. } => zx::Status::ACCESS_DENIED,
727            RightsRoutingError::MissingRightsSource { .. } => zx::Status::NOT_FOUND,
728        }
729    }
730}
731
732impl From<RightsRoutingError> for ExtendedMoniker {
733    fn from(err: RightsRoutingError) -> ExtendedMoniker {
734        match err {
735            RightsRoutingError::Invalid { moniker, .. }
736            | RightsRoutingError::MissingRightsSource { moniker } => moniker,
737        }
738    }
739}
740
741#[cfg_attr(feature = "serde", derive(Deserialize, Serialize), serde(rename_all = "snake_case"))]
742#[derive(Debug, Error, Clone, PartialEq)]
743pub enum AvailabilityRoutingError {
744    #[error(
745        "availability requested by the target has stronger guarantees than what \
746    is being provided at the source at `{moniker}`"
747    )]
748    TargetHasStrongerAvailability { moniker: ExtendedMoniker },
749
750    #[error("offer uses void source, but target requires the capability at `{moniker}`")]
751    OfferFromVoidToRequiredTarget { moniker: ExtendedMoniker },
752
753    #[error("expose uses void source, but target requires the capability at `{moniker}`")]
754    ExposeFromVoidToRequiredTarget { moniker: ExtendedMoniker },
755}
756
757impl From<availability::TargetHasStrongerAvailability> for AvailabilityRoutingError {
758    fn from(value: availability::TargetHasStrongerAvailability) -> Self {
759        let availability::TargetHasStrongerAvailability { moniker } = value;
760        AvailabilityRoutingError::TargetHasStrongerAvailability { moniker }
761    }
762}
763
764impl From<AvailabilityRoutingError> for ExtendedMoniker {
765    fn from(err: AvailabilityRoutingError) -> ExtendedMoniker {
766        match err {
767            AvailabilityRoutingError::ExposeFromVoidToRequiredTarget { moniker }
768            | AvailabilityRoutingError::OfferFromVoidToRequiredTarget { moniker }
769            | AvailabilityRoutingError::TargetHasStrongerAvailability { moniker } => moniker,
770        }
771    }
772}
773
774// Implements error reporting upon routing failure. For example, component
775// manager logs the error.
776#[async_trait]
777pub trait ErrorReporter: Clone + Send + Sync + 'static {
778    async fn report(&self, request: &RouteRequestErrorInfo, err: &RouterError);
779}
780
781/// What to print in an error if a route request fails.
782pub struct RouteRequestErrorInfo {
783    capability_type: cm_rust::CapabilityTypeName,
784    name: cm_types::Name,
785    availability: cm_rust::Availability,
786}
787
788impl RouteRequestErrorInfo {
789    pub fn availability(&self) -> cm_rust::Availability {
790        self.availability.clone()
791    }
792}
793
794impl From<&cm_rust::UseDecl> for RouteRequestErrorInfo {
795    fn from(value: &cm_rust::UseDecl) -> Self {
796        RouteRequestErrorInfo {
797            capability_type: value.into(),
798            name: value.source_name().clone(),
799            availability: value.availability().clone(),
800        }
801    }
802}
803
804impl From<&cm_rust::UseConfigurationDecl> for RouteRequestErrorInfo {
805    fn from(value: &cm_rust::UseConfigurationDecl) -> Self {
806        RouteRequestErrorInfo {
807            capability_type: CapabilityTypeName::Config,
808            name: value.source_name().clone(),
809            availability: value.availability().clone(),
810        }
811    }
812}
813
814impl From<&cm_rust::ExposeDecl> for RouteRequestErrorInfo {
815    fn from(value: &cm_rust::ExposeDecl) -> Self {
816        RouteRequestErrorInfo {
817            capability_type: value.into(),
818            name: value.target_name().clone(),
819            availability: value.availability().clone(),
820        }
821    }
822}
823
824impl From<&cm_rust::OfferDecl> for RouteRequestErrorInfo {
825    fn from(value: &cm_rust::OfferDecl) -> Self {
826        RouteRequestErrorInfo {
827            capability_type: value.into(),
828            name: value.target_name().clone(),
829            availability: value.availability().clone(),
830        }
831    }
832}
833
834impl std::fmt::Display for RouteRequestErrorInfo {
835    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
836        write!(f, "{} `{}`", self.capability_type, self.name)
837    }
838}