Skip to main content

ulo/transport/
metadata.rs

1use std::any::{Any, TypeId, type_name};
2use std::sync::Arc;
3
4use crate::transport::Transport;
5
6/// A metadata type that means something on one transport alone, naming it (transports DESIGN
7/// §2.5, X24): `ulo_http::Timeout` and `ulo_http::MaxBody` name `Http`.
8///
9/// Every transport's handler attribute probes each `#[meta(..)]` value at the concrete site, so a
10/// value naming another transport fails to compile where it is written, E0308 at the value with
11/// both transports in the message: `#[meta(Timeout::after(..))]` on an RPC handler is refused in
12/// an application that binds no HTTP server too. A type implementing no `TransportMetadata` is
13/// valid on every transport, so a user's own metadata needs no impl.
14pub trait TransportMetadata: Send + Sync + 'static {
15    type Transport: Transport;
16}
17
18/// The metadata declared on one handler with `#[meta(..)]`, on the method and on its controller
19/// impl (transports DESIGN §2.5).
20///
21/// Values are plain `Send + Sync + 'static` values, built once when the handler mounts. A guard or
22/// interceptor reads them through `cx.exec().handler()`; [`HandlerInfo::meta`](crate::HandlerInfo::meta)
23/// answers the method's declaration when there is one and the controller's otherwise.
24///
25/// The type lives in the core because the core's `HandlerSpec` and `HandlerInfo` carry it;
26/// `ulo-transport` re-exports it.
27#[derive(Clone, Default)]
28pub struct Metadata {
29    entries: Vec<MetaValue>,
30}
31
32/// Which tier declared a metadata value.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum MetaTier {
35    /// `#[meta(..)]` on the `#[handlers]` impl, applying to every handler in it.
36    Controller,
37    /// `#[meta(..)]` on the handler method.
38    Method,
39}
40
41#[derive(Clone)]
42struct MetaValue {
43    ty: TypeId,
44    name: &'static str,
45    tier: MetaTier,
46    value: Arc<dyn Any + Send + Sync>,
47}
48
49impl Metadata {
50    pub fn new() -> Self {
51        Metadata::default()
52    }
53
54    /// A value declared on the controller impl.
55    pub fn controller<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
56        self.push(MetaTier::Controller, value)
57    }
58
59    /// A value declared on the handler method.
60    pub fn method<T: Send + Sync + 'static>(&mut self, value: T) -> &mut Self {
61        self.push(MetaTier::Method, value)
62    }
63
64    /// The most specific declaration of `T`: the method's if it has one, otherwise the
65    /// controller's. Within one tier the first written answers.
66    pub fn get<T: 'static>(&self) -> Option<&T> {
67        self.tier::<T>(MetaTier::Method).next().or_else(|| self.tier::<T>(MetaTier::Controller).next())
68    }
69
70    /// Every declaration of `T`, the method's first, each tier in the order written.
71    pub fn get_all<T: 'static>(&self) -> impl Iterator<Item = &T> + '_ {
72        self.tier::<T>(MetaTier::Method).chain(self.tier::<T>(MetaTier::Controller))
73    }
74
75    /// Every declaration, as its type's name and the tier that declared it, the method's first.
76    pub fn entries(&self) -> impl Iterator<Item = (&'static str, MetaTier)> + '_ {
77        let method = self.entries.iter().filter(|e| e.tier == MetaTier::Method);
78        let controller = self.entries.iter().filter(|e| e.tier == MetaTier::Controller);
79        method.chain(controller).map(|e| (e.name, e.tier))
80    }
81
82    pub fn is_empty(&self) -> bool {
83        self.entries.is_empty()
84    }
85
86    fn push<T: Send + Sync + 'static>(&mut self, tier: MetaTier, value: T) -> &mut Self {
87        self.entries.push(MetaValue { ty: TypeId::of::<T>(), name: type_name::<T>(), tier, value: Arc::new(value) });
88        self
89    }
90
91    fn tier<T: 'static>(&self, tier: MetaTier) -> impl Iterator<Item = &T> + '_ {
92        self.entries
93            .iter()
94            .filter(move |e| e.tier == tier && e.ty == TypeId::of::<T>())
95            .filter_map(|e| e.value.downcast_ref::<T>())
96    }
97}