1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
//! Core traits for the Armature framework
use async_trait::async_trait;
use std::any::TypeId;
// Re-export DI traits from dependency-injector
pub use dependency_injector::{Injectable, Provider};
/// Trait for HTTP controllers
#[async_trait]
pub trait Controller: Send + Sync + 'static {
/// Returns the base path for this controller
fn base_path(&self) -> &'static str;
/// Returns the routes registered on this controller
fn routes(&self) -> Vec<RouteDefinition>;
}
/// Trait for modules that organize components
pub trait Module: Send + Sync + 'static {
/// Returns the `TypeId` of the concrete type implementing this trait.
///
/// Do not override this: the default implementation is monomorphized
/// per concrete `Self` (the same technique `std::any::Any::type_id`
/// uses), so its vtable entry always reports the *concrete* module
/// type, even when called through a `&dyn Module` trait object.
///
/// This exists so callers that only hold a `&dyn Module` (e.g.
/// [`crate::Application`]'s module-tree walk) can still deduplicate
/// modules by concrete identity. `std::any::type_name_of_val`/
/// `TypeId::of` cannot do this from outside the trait: both resolve
/// their type parameter from the *static* type of the reference
/// (`dyn Module`), not the concrete type behind the vtable, so every
/// module would compare equal to every other module.
fn module_type_id(&self) -> std::any::TypeId {
std::any::TypeId::of::<Self>()
}
/// Returns the type name of the concrete type implementing this trait.
///
/// Like [`Module::module_type_id`], this is monomorphized per concrete
/// `Self`, so it reports the real module type name (useful for
/// diagnostics/logging) even through a `&dyn Module` reference — unlike
/// `std::any::type_name_of_val(&dyn Module)`, which always returns the
/// trait object's own type name.
fn module_type_name(&self) -> &'static str {
std::any::type_name::<Self>()
}
/// Returns the list of provider types to register
fn providers(&self) -> Vec<ProviderRegistration>;
/// Returns the list of controller types to register
fn controllers(&self) -> Vec<ControllerRegistration>;
/// Returns the list of guard types to register
fn guards(&self) -> Vec<crate::module::GuardRegistration> {
vec![]
}
/// Returns the list of imported modules
fn imports(&self) -> Vec<Box<dyn Module>>;
/// Returns the list of exported provider types
fn exports(&self) -> Vec<TypeId>;
/// Returns the list of re-exported modules
///
/// Re-exported modules have their exports forwarded to any module
/// that imports this module.
fn re_exports(&self) -> Vec<Box<dyn Module>> {
vec![]
}
}
/// Trait for request handlers (route methods)
#[async_trait]
pub trait RequestHandler: Send + Sync {
/// Handle an HTTP request and return a response
async fn handle(
&self,
request: crate::HttpRequest,
) -> Result<crate::HttpResponse, crate::Error>;
}
/// Trait for validators
pub trait Validator: Send + Sync {
/// Validate a value
fn validate(&self, value: &str) -> Result<(), String>;
}
/// Definition of a route
#[derive(Clone, Debug)]
pub struct RouteDefinition {
pub method: HttpMethod,
pub path: String,
pub handler_name: String,
}
/// HTTP methods
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum HttpMethod {
GET,
POST,
PUT,
DELETE,
PATCH,
HEAD,
OPTIONS,
/// Safe, idempotent query with a request body
/// (draft-ietf-httpbis-safe-method-w-body).
QUERY,
}
impl HttpMethod {
#[allow(clippy::should_implement_trait)]
pub fn from_str(s: &str) -> Option<Self> {
match s.to_uppercase().as_str() {
"GET" => Some(HttpMethod::GET),
"POST" => Some(HttpMethod::POST),
"PUT" => Some(HttpMethod::PUT),
"DELETE" => Some(HttpMethod::DELETE),
"PATCH" => Some(HttpMethod::PATCH),
"HEAD" => Some(HttpMethod::HEAD),
"OPTIONS" => Some(HttpMethod::OPTIONS),
"QUERY" => Some(HttpMethod::QUERY),
_ => None,
}
}
pub fn as_str(&self) -> &'static str {
match self {
HttpMethod::GET => "GET",
HttpMethod::POST => "POST",
HttpMethod::PUT => "PUT",
HttpMethod::DELETE => "DELETE",
HttpMethod::PATCH => "PATCH",
HttpMethod::HEAD => "HEAD",
HttpMethod::OPTIONS => "OPTIONS",
HttpMethod::QUERY => "QUERY",
}
}
}
/// Registration information for a provider
#[derive(Clone)]
pub struct ProviderRegistration {
pub type_id: TypeId,
pub type_name: &'static str,
/// Function that registers the provider in the container.
/// Uses the Container wrapper type from armature-core.
pub register_fn: fn(&crate::container::Container),
}
impl std::fmt::Debug for ProviderRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ProviderRegistration")
.field("type_id", &self.type_id)
.field("type_name", &self.type_name)
.finish()
}
}
/// Registration information for a controller
#[derive(Clone)]
pub struct ControllerRegistration {
pub type_id: TypeId,
pub type_name: &'static str,
pub base_path: &'static str,
pub factory:
fn(&crate::Container) -> Result<Box<dyn std::any::Any + Send + Sync>, crate::Error>,
#[allow(clippy::type_complexity)]
pub route_registrar: fn(
&crate::Container,
&mut crate::Router,
Box<dyn std::any::Any + Send + Sync>,
) -> Result<(), crate::Error>,
}
impl std::fmt::Debug for ControllerRegistration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ControllerRegistration")
.field("type_id", &self.type_id)
.field("type_name", &self.type_name)
.field("base_path", &self.base_path)
.finish()
}
}
impl From<HttpMethod> for crate::Method {
#[inline]
fn from(m: HttpMethod) -> Self {
match m {
HttpMethod::GET => crate::Method::Get,
HttpMethod::POST => crate::Method::Post,
HttpMethod::PUT => crate::Method::Put,
HttpMethod::DELETE => crate::Method::Delete,
HttpMethod::PATCH => crate::Method::Patch,
HttpMethod::HEAD => crate::Method::Head,
HttpMethod::OPTIONS => crate::Method::Options,
HttpMethod::QUERY => crate::Method::Query,
// Deliberately exhaustive with no catch-all. `HttpMethod` is
// #[non_exhaustive] for downstream crates, but this match is inside
// the defining crate, so a variant added later fails to compile here
// rather than silently mapping onto something wrong.
}
}
}
/// The method has no `HttpMethod` counterpart, so it is not routable.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnroutableMethod(pub String);
impl std::fmt::Display for UnroutableMethod {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "method `{}` has no HttpMethod counterpart", self.0)
}
}
impl std::error::Error for UnroutableMethod {}
impl TryFrom<&crate::Method> for HttpMethod {
type Error = UnroutableMethod;
#[inline]
fn try_from(m: &crate::Method) -> Result<Self, Self::Error> {
match m {
crate::Method::Get => Ok(HttpMethod::GET),
crate::Method::Post => Ok(HttpMethod::POST),
crate::Method::Put => Ok(HttpMethod::PUT),
crate::Method::Delete => Ok(HttpMethod::DELETE),
crate::Method::Patch => Ok(HttpMethod::PATCH),
crate::Method::Head => Ok(HttpMethod::HEAD),
crate::Method::Options => Ok(HttpMethod::OPTIONS),
crate::Method::Query => Ok(HttpMethod::QUERY),
crate::Method::Connect => Err(UnroutableMethod("CONNECT".into())),
crate::Method::Trace => Err(UnroutableMethod("TRACE".into())),
crate::Method::Other(t) => Err(UnroutableMethod(t.into_owned())),
}
}
}
#[cfg(test)]
mod method_conversion_tests {
use super::HttpMethod;
use crate::Method;
#[test]
fn every_http_method_round_trips_through_method() {
for m in [
HttpMethod::GET,
HttpMethod::POST,
HttpMethod::PUT,
HttpMethod::DELETE,
HttpMethod::PATCH,
HttpMethod::HEAD,
HttpMethod::OPTIONS,
HttpMethod::QUERY,
] {
let converted = Method::from(m.clone());
assert_eq!(
HttpMethod::try_from(&converted).ok(),
Some(m.clone()),
"{m:?} did not round-trip"
);
}
}
#[test]
fn methods_with_no_http_method_counterpart_fail_conversion() {
// CONNECT, TRACE, and Other exist in armature-h1 because the wire has
// them; HttpMethod is the *routable* set, which is deliberately smaller.
// A router that silently mapped CONNECT onto GET would be a security bug.
assert!(HttpMethod::try_from(&Method::Connect).is_err());
assert!(HttpMethod::try_from(&Method::Trace).is_err());
assert!(HttpMethod::try_from(&Method::from("PURGE")).is_err());
}
}