Macros
The core attributes of ulo-macros and the derives of ulo-transport-macros, with the arguments each takes, what it lowers to and what it refuses.
Every macro is sugar over the value API in Core types: an attribute lowers to calls on ModuleDef, Construct and Mount, and an integration crate calls those directly. The handler attributes of the four transports (get, message, gateway, method and the rest) are on Handler attributes.
ulo re-exports injectable, controller, construct, module, handlers, guards, interceptors, error_handlers and meta. The compile-time diagnostics each macro raises are collected, with the other refusals, on Errors and diagnostics.
| Macro | Kind | Goes on | Crate |
|---|---|---|---|
#[injectable] | attribute | a struct, or an inherent impl containing the constructor | ulo-macros |
#[controller] | attribute | a struct, or an inherent impl containing the constructor | ulo-macros |
#[construct] | attribute | one fn inside an #[injectable] or #[controller] impl | ulo-macros |
#[module] | attribute | a struct | ulo-macros |
#[handlers] | attribute | a controller's inherent impl of handlers | ulo-macros |
#[guards], #[interceptors], #[error_handlers] | attribute | a #[handlers] impl, or a method of one | ulo-macros |
#[meta] | attribute | a #[handlers] impl, or a method of one | ulo-macros |
#[derive(Classify)] | derive | an error struct or enum | ulo-transport-macros |
#[derive(Validate)] | derive | a struct with named fields | ulo-transport-macros |
#[injectable]
A type the container builds and injects into others. It writes impl Construct for T: the dependencies declaration, the construct body, the Scope and the hooks list.
On a struct, every field is an injection point (a type that implements FromContainer: Dep, Many, Ext, Option of those, ModuleRef, ExecutionRef) except a field marked #[injectable(default)], which is set from Default::default().
On an impl block, the constructor is the fn named new, or the one marked #[construct]. Its parameters are injection points. It may be async, and it may return Self or Result<Self, E>. An Err(e) is mapped through ConstructError::failed, so the error is redacted and reported as FailureReason::Errored.
Arguments, written in any order, each at most once:
| Argument | Meaning |
|---|---|
singleton | Scope = Singleton. Refused at wire() when anything below the type reads execution data. |
execution | Scope = PerExecution. Built once per execution, shared inside it. |
transient | Scope = Transient. Built at every injection point. |
timeout = <Duration expression> | Writes CONSTRUCT_TIMEOUT as Bound::After(..). Combines with a scope. |
No scope word means Auto: a provider is a singleton, and an enhancer is a singleton unless something below it needs an execution, in which case it is built per execution. See Scopes.
Construct::hooks is filled by probing the five lifecycle traits at the concrete type, so implementing OnModuleInit (and the others) is all a type does to register a hook. The probes are named with a __ulo_ prefix, which keeps a user trait with a method every type has from colliding with them.
A type whose handlers a transport calls is a controller and takes #[controller] instead. An #[injectable] type is not a Controller, so #[handlers] on it and #[module]'s controllers both refuse it.
Struct form and impl form, from examples/05-scopes:
#[injectable]
pub struct Ids {
#[injectable(default)]
next: AtomicU64,
}
#[injectable(execution)]
impl PerCall {
fn new(ids: Dep<Ids>) -> Self {
PerCall(ids.next.fetch_add(1, Ordering::SeqCst) + 1)
}
}Refused:
| Input | Diagnostic |
|---|---|
| anything but a struct or an inherent impl | #[injectable] goes on a struct, whose fields are injected, or on an impl block holding its constructor |
| a trait impl | #[injectable] goes on the type's inherent impl block holding its constructor, not on a trait impl |
| an unknown argument | expected `singleton`, `execution`, `transient` or `timeout = <Duration>` |
| two scopes | a scope is written once |
timeout twice | `timeout` is written once |
a field attribute other than #[injectable(default)] | a field takes `#[injectable(default)]` alone, which sets it from `Default`; every other field is injected |
#[injectable(default)] twice on a field | `#[injectable(default)]` is written once |
an impl with no new and no #[construct] | no constructor: name it `new`, or mark the fn that builds the type #[construct] |
two #[construct] fns | a second #[construct] fn; a type has one constructor, so mark one fn only |
a constructor with a self receiver | a constructor takes no `self`: it builds the instance from its parameters, each an injection point |
| a constructor parameter that is not a plain identifier | a constructor parameter is named by a plain identifier, which diagnostics print as the parameter's name |
| a field or parameter that is not an injection point | rustc E0277 `String` cannot be obtained from the container, with the notes write `Dep<String>` to share the container's instance and or set it inside the #[construct] fn / mark the field #[injectable(default)] |
Ext<T> or ExecutionRef in a type declared singleton | rustc E0277 a `ulo::scope::Singleton` type cannot read `Ext<CurrentUser>`, with the note declare the type #[injectable(execution)] or #[injectable(transient)] |
a lifecycle hook on a type declared execution or transient | rustc E0277 lifecycle hooks are only allowed on singletons, with the note remove the scope argument from #[injectable], or move the hook to a singleton |
Dep<T> where T is not Send + Sync | rustc's own cannot be sent between threads safely or cannot be shared between threads safely, with no Ulo note |
a constructor whose future is not Send | rustc E0277 future cannot be sent between threads safely, pointing at the constructor |
The macro emits one quote_spanned! assertion per field and parameter, so each E0277 diagnostic points at the offending field or parameter and not at the attribute.
#[controller]
A controller: a type the container builds and its transports reach through the handlers of its #[handlers] impl. Only another controller injects one, and wire() refuses a read of a controller by any other binding.
It writes what #[injectable] writes, from a struct or from an impl block's new or #[construct] fn, and takes the same arguments: a scope and timeout = <Duration expression>. With no scope it is Auto. On a struct, a field set from Default is marked #[controller(default)], and every other field is an injection point.
It also writes impl Controller for T, the mark that makes a type a controller. The impl carries the bound T: Handlers, so a concrete #[controller] type with no #[handlers] impl fails to compile at the attribute. A WebSocket gateway is a controller and takes #[controller] too.
A controller takes no route prefix. The module mounts it under one with m.controller::<T>().at(prefix).
On an impl block, #[controller] and #[handlers] stack in either order, so the constructor and the handlers can share one impl.
A controller whose handlers are mounted by hand implements Handlers itself. Controller is then the mark, with no methods, and Handlers::mount registers the handlers. See Without macros.
From examples/01-hello:
#[controller]
pub struct HelloController;
#[handlers]
impl HelloController {
#[ulo_http::get("/")]
fn hello(&self) -> &'static str {
"Hello, ulo!"
}
}Refused:
| Input | Diagnostic |
|---|---|
a route prefix, #[controller("/checkout")] | #[controller] takes no route prefix: the module mounts the controller under one, `m.controller::<T>().at("/prefix")` |
#[injectable(default)] on a field of a #[controller] struct | this struct is #[controller]: a field set from `Default` is marked `#[controller(default)]` |
a controller with no #[handlers] impl | rustc E0277 `Checkout` is not a controller with handlers, with the note that #[handlers] on the impl holding the handlers writes the Handlers impl |
a controller under providers, by type or by value | rustc E0277 `Checkout` is a controller, listed under `providers`, labelled a controller goes under `controllers` |
the other argument forms, as for #[injectable] | the #[injectable] rows above, with #[controller] as the name |
#[construct]
Marks the constructor inside an #[injectable] or #[controller] impl when it is not named new. It takes no arguments and is written once per fn.
| Input | Diagnostic |
|---|---|
outside an #[injectable] or #[controller] impl | #[construct] marks the constructor inside an #[injectable] or #[controller] impl block |
| with arguments | #[construct] takes no arguments |
| twice on one fn | #[construct] is written once on a fn |
#[module]
A module, written on a struct. It lowers to impl Module whose register calls the ModuleDef API in a fixed order: global, the secrets, the imports, the providers, the controllers, the exports. Imports and providers keep the order written, which is part of collection order.
A unit struct is identified by type (ModuleIdentity::of_type::<Self>()). A struct with fields is a configured module, identified by value (ModuleIdentity::of_value(self)), so it must be Clone + Eq + Hash. Every field whose type is named Secret is registered with m.secret(..) for redaction.
Arguments, in any order, each at most once:
| Argument | Value | Lowers to |
|---|---|---|
global | a bare flag | m.global() |
imports = [..] | expressions that evaluate to a Module | m.import(expr) |
providers = [..] | provider entries, below | provide, value, with, contribute and the rest |
controllers = [..] | types that implement Handlers, and through it Controller | m.controller::<C>() |
exports = [..] | Type, Type @ Q, reexport Type, reexport Type @ Q | export, export_qualified, reexport, reexport_qualified |
Provider entries:
| Entry | Lowers to |
|---|---|
Type | m.provide::<Type>() |
Type as dyn Trait | m.provide::<Type>() then .also_as::<dyn Trait>(|a| a); the concrete type stays bound too |
expr | m.value(expr) |
expr? | m.try_value(expr); an Err is reported by wire() beside the other wiring errors |
{ CONST } | m.value(CONST); the braces tell a constant from a type |
with = closure | m.with(closure), or m.try_with(..) when the closure answers a Result |
with(singleton) = closure, with(execution) = .., with(transient) = .. | m.singleton(..), m.execution(..), m.transient(..), or the try_ form |
| a bare closure | shorthand for with = closure |
dyn Trait: with = closure | the same binding, also bound under the trait key with also_as |
into dyn Trait: [..] | one m.contribute::<dyn Trait>() call per item |
Type, Type as dyn Trait, expr or expr?, then @ Q | the same call followed by .qualified::<Q>() |
An into K: [..] list takes a type, value = expr, value = expr?, with = closure and with(scope) = closure. A global enhancer is a contribution under a role key: into AnyGuard<Http>: [AuthGuard]. A K that implements Meta, such as ulo_http::PreDispatch, is module metadata and not a contribution key.
A closure's body extends as far as it can, which is why the key comes first in dyn Trait: with = closure: in with = |cfg| RedisCache::new(cfg) as dyn Cache the as would parse as a cast inside the body.
with says how a binding is built and nothing about how long it lives. with = .. is Auto. Inference reads what the closure takes, not what it does, so a closure that creates per-call state but reads nothing per call is written with(execution) = || RequestTimer::start().
#[module] has no spelling for a readiness check (.ready(..)), a closure hook (.on_init(..), .on_destroy(..)), a qualified closure binding, the enhancer mark or module metadata. A module that needs one implements Module by hand. It imports and is imported by attribute-written modules like any other. See Without macros.
Unit module, qualified values and exports, from examples/03-traits-and-qualifiers:
#[module(
providers = [Db("primary") @ Primary, Db("replica") @ Replica],
exports = [Db @ Primary, Db @ Replica],
)]
pub struct DbModule;
#[module(
imports = [DbModule],
providers = [PgUserRepo as dyn UserRepo],
controllers = [UserController],
)]
pub struct AppModule;Global flag and keyed instances of a configured module, from examples/07-configured-modules:
#[module(global, providers = [AppConfig { name: "ledger" }], exports = [AppConfig])]
pub struct ConfigModule;
#[derive(Clone, PartialEq, Eq, Hash)]
#[module(providers = [Store { url: self.url }], exports = [Store])]
pub struct StoreModule {
url: &'static str,
}
#[module(imports = [ConfigModule, primary(), replica()], controllers = [LedgerController])]
pub struct AppModule;Collection contributions from two modules, from examples/04-collections-and-optional:
#[module(providers = [into dyn Plugin: [ExtraPlugin]])]
pub struct ExtrasModule;
#[module(
imports = [ExtrasModule],
providers = [Host, into dyn Plugin: [MetricsPlugin, TracingPlugin]],
controllers = [HostController],
)]
pub struct AppModule;Refused:
| Input | Diagnostic |
|---|---|
| an unknown argument | expected `global`, `imports`, `providers`, `controllers` or `exports` |
| an argument twice | `providers` is written once (the name varies) |
a second @ on an entry | an entry takes one `@` qualifier |
@ after a closure binding | a closure binding takes no `@` qualifier; write the binding in a `ModuleDef` with `.qualified::<Q>()`, or bind a value, `Db(..) @ Primary` |
@ after an into item | an `into` item takes no `@` qualifier; a qualified collection is written in a `ModuleDef`, `m.contribute::<K>().qualified::<Q>()` |
| a qualifier naming no type | rustc E0425 on the qualifier: cannot find type `Primary` in this scope |
X as AnyGuard<Http> in providers | a role key takes contributions, and `as` binds a single instance; a global enhancer is written `into AnyGuard<Http>: [AuthGuard]` |
AnyGuard<Http>: with = .. | a role key takes contributions, and `K: with = ..` binds a single instance; a global enhancer is written `into AnyGuard<Http>: [with = ..]` |
an into item that is none of the four forms | an `into` entry is a type, `value = expr`, `with = |..| ..` or `with(<scope>) = |..| ..` , followed, when the item parses as an expression, by ; an expression is contributed with `value = ..` |
with whose right side is not a closure | `with` takes a closure whose parameters are injection points, as in `with = |cfg: Dep<MetricsConfig>| MetricsPlugin::new(cfg)` |
a scope on a value | a `value` is built once and shared, so it takes no scope; write `value = ..` |
into over a Meta type | rustc E0277 `ulo_http::PreDispatch` is module metadata, not a contribution key, with the note write this module with `ModuleDef` and configure `ulo_http::PreDispatch` through `m.meta::<ulo_http::PreDispatch>()` |
a provider type that is not Construct | rustc E0277 `X` is not a type the container can construct, with the note add #[injectable] to the type, or bind it with a factory |
X as dyn Trait where X does not implement the trait | rustc E0277 the trait bound `Memory: Repo` is not satisfied, noting the cast from Arc<Memory> to Arc<dyn Repo> |
The wiring errors a module can produce (DuplicateBinding, Missing, Ambiguous and the rest) are on Errors and diagnostics.
#[handlers]
Goes on a controller's inherent impl of handlers, on every transport. It writes impl Handlers for T, whose mount registers each handler, and leaves every other item as written. The type itself is declared with #[controller], which writes impl Controller for T and no mount. Handlers requires Controller, so #[handlers] on a type that is not a controller, an #[injectable] one among them, is a compile error naming Controller. It runs before the transport attributes on the methods and hands them each handler's enhancers and metadata through a doc-hidden __handler attribute.
Takes no arguments.
A method is a handler when it carries an attribute outside the language's own (doc, allow, warn, deny, expect, cfg, cfg_attr, inline, must_use, deprecated, track_caller) and the enhancer and #[meta] attributes. A helper carrying #[tracing::instrument] is read as a handler and fails. Helpers go in a separate impl block. Attributes are read through cfg_attr at any depth. A handler behind #[cfg] is mounted, and its transport key counted, only in a build that compiles it.
The enhancer attributes and #[meta] are read as markers by name. A marker is written bare, #[guards], or as ulo::guards or ::ulo::guards. Any other qualifier is a compile error at the attribute: write the marker bare, or as `ulo::guards`; under a renamed dependency, alias it at the crate root, `extern crate <name> as ulo;` . The same holds for the construct marker and a field's injectable(default) and controller(default). The attributes #[injectable], #[controller] and #[handlers] are resolved by rustc, so any path that reaches one is accepted. The generated code names ::ulo, so a crate that depends on ulo under another name aliases it at its root with extern crate <name> as ulo;.
A handler takes &self, or self: Arc<Self> for a reply that outlives the call, and declares no type or const parameter. The controller itself may be generic.
The impl's #[guards], #[interceptors], #[error_handlers] and #[meta] are the controller tier and each method's are the method tier. An impl-level value = expr is built once, when the controller mounts, and shared by every handler it applies to, so a rate limiter declared on the impl limits the controller as a whole.
Refused:
| Input | Diagnostic |
|---|---|
| arguments | #[handlers] takes no arguments |
| a trait impl | #[handlers] goes on the controller's inherent impl block holding its handlers, not on a trait impl |
| a type that is not a controller | rustc E0277 `Checkout` is not a controller, labelled a controller is declared with `#[controller]` |
a controller-level transport key that no handler's transport carries, as in #[guards(htpp = AuthGuard)] | `htpp` is not the key of any handler's transport in this impl (handlers: get, get_rpc), a const-evaluation error (E0080) spanned on the key; a gated handler is listed apart, as behind `cfg`: get_rpc |
| an entry for a transport the method does not belong to | `get` is a `http` handler, so an entry for `rpc` applies to nothing; write it for every transport, or on the handler it belongs to |
a method-level #[guards], #[interceptors], #[error_handlers] or #[meta] on a method with no transport attribute | #[guards] on `helper`, which carries no transport attribute and so is not a handler |
| a handler with no receiver | a handler is a method: it takes `&self`, or `self: Arc<Self>` for a reply that outlives the call |
a handler with &mut self or self | a handler takes `&self`, or `self: Arc<Self>` for a reply that outlives the call |
| two parameters that consume the body | `user` and `login` both consume the body; a handler reads the body once |
| a controller-level enhancer that lacks the role for one handler's transport | rustc E0277 per handler, `HttpOnly` is not a guard for `Rpc`, with the note implement `Guard<Rpc>` for `HttpOnly` |
a transport attribute that finds no __handler | names the rule #[handlers] applied: a method has one transport attribute, and when every attribute macro on it sits inside cfg_attr the first is taken |
a __handler no transport attribute consumed | no transport attribute read this handler's enhancers: #[handlers] took this method for a handler because of an attribute macro on it, ..; a helper goes in a separate impl block |
#[guards], #[interceptors], #[error_handlers]
Declare the enhancers of a controller or of one handler. Each is read by #[handlers]: on the impl it goes below #[handlers], on a method it may be written inside cfg_attr, and anywhere else it is an error.
Each takes a comma list of entries:
| Entry | Meaning |
|---|---|
Type | By type, resolved from the container. Must hold the role for the transport of every handler it applies to. |
key = Type | By type, for the handlers of the transport whose Transport::KEY is key: http, ws, ws_connect, rpc or grpc. |
value = expr | By value, built once and shared. On a method, by that handler's calls; on the impl, by every handler. |
with = |param: Ty, ..| expr | By closure, scope Auto. The parameters are injection points. |
with(singleton) = .., with(execution) = .., with(transient) = .. | By closure, in the scope written. |
key(value = expr), key(with = ..), key(with(scope) = ..) | The last three, for one transport's handlers. |
Stacking is global, then controller, then method, and within a tier the order written. Which contributions are enhancers is decided by TypeId at freeze, so the role comes from the trait the type implements: Guard<Http>, Interceptor<Rpc>, ErrorHandler<Grpc>.
A controller-level entry is strict. #[guards(AuthGuard)] on an impl that mounts an HTTP and an RPC handler requires Guard<Http> and Guard<Rpc> for AuthGuard. A guard that guards three of four handlers is the bug the check exists to prevent. http = AuthGuard limits the entry to the HTTP handlers and checks only their role.
One guard serving two transports, from examples/41-one-guard-two-transports:
impl<T: Transport> Guard<T> for Maintenance
where
T::Cx: AsRef<ExecutionRef>,
{
async fn can_activate(&self, cx: &T::Cx) -> Result<bool, BoxError> {
let exec: &ExecutionRef = cx.as_ref();
Ok(exec.handler().and_then(|handler| handler.meta::<Shut>()).is_none())
}
}
#[handlers]
#[guards(Maintenance)]
impl ShopHttp {
#[ulo_http::get("/shop")]
fn open(&self) -> &'static str {
"open"
}
}Transport-scoped entry, from examples/29-grpc-service:
#[handlers]
#[guards(grpc = TokenGuard)]
impl CatalogService {A closure is written synchronously, and the macro wraps a synchronous body in async move. with = .. is built once unless what its parameters read needs an execution, then per execution. A closure that creates per-call state but reads nothing per call must be written with(execution) = ...
Refused:
| Input | Diagnostic |
|---|---|
outside a #[handlers] impl, or above #[handlers] | #[guards] is read by #[handlers]: it goes on a #[handlers] impl block, below #[handlers], or on a method of one; no #[handlers] read this one, so it is outside a #[handlers] impl or above #[handlers], which expands after it |
a scope word in a transport key's place, execution = AuthGuard | `execution` is a scope, not a transport key; a type declares its scope on the type, `#[injectable(execution)]`, and a closure is written `with(execution) = ..` |
a scope on a value | a `value` is built once and shared, so it takes no scope; write `value = ..`, or `<transport>(value = ..)` for one transport's handlers |
| a scope other than the three | `with(..)` takes a scope: `singleton`, `execution` or `transient` |
with whose right side is not a closure | `with` takes a closure whose parameters are injection points, as in `with = |u: Ext<CurrentUser>| RoleGuard::require(u)` |
| a closure parameter without a type | a factory parameter needs its type written, as in `cfg: Dep<DbConfig>` |
| a type without the role | rustc E0277 `NotAGuard` is not a guard for `Http`, with the note implement `Guard<Http>` for `NotAGuard` |
an explicit singleton closure that reads execution data | the wiring error ClosureScopeViolation, at wire() |
#[meta]
Declares metadata on a handler or on its #[handlers] impl: plain Send + Sync + 'static values, built once when the handler mounts. Guards and interceptors read them through exec.handler(), as the Maintenance guard above does with handler.meta::<Shut>(). Metadata::get returns the most specific declaration of a type: the method's if it has one and otherwise the controller's. get_all returns every declaration, the method's first.
A metadata type that implements TransportMetadata is valid on that transport only. ulo_http::Timeout on an RPC handler fails at the value, because every transport's handler attribute probes each #[meta(..)] value at the concrete site. A type that implements no TransportMetadata is valid on every transport.
| Input | Diagnostic |
|---|---|
outside a #[handlers] impl | the text of the enhancer attributes, with #[meta] as the name |
| on a method with no transport attribute | #[meta] on `helper`, which carries no transport attribute and so is not a handler |
| a value naming another transport | rustc E0308: expected `()`, found `MetaMismatch<Rpc, Http>` |
#[derive(Classify)]
From ulo-transport-macros, re-exported by ulo-transport and by each transport crate. Writes impl Classify from #[classify(<kind>)]. The kind is a snake-case ErrorKind variant:
bad_request, unauthorized, forbidden, not_found, conflict, unprocessable, too_many_requests, timeout, unavailable, unimplemented, internal.
On a struct, one #[classify(..)] on the type. On an enum, one on each variant, or one on the enum as the default for variants that carry none. The generated impl names the first of ulo-transport, ulo-rpc, ulo-http, ulo-ws and ulo-grpc that the deriving crate depends on, so a crate needs no dependency beyond the transport it already uses.
From examples/25-rpc-basics:
#[derive(Debug, Classify)]
pub enum CalcError {
#[classify(unprocessable)]
DivideByZero,
}| Input | Diagnostic |
|---|---|
| a struct with no kind | `Classify` needs a kind: add `#[classify(<kind>)]` to the struct, e.g. `#[classify(not_found)]` |
| an enum variant with no kind and no default | variant `X` has no kind: add `#[classify(<kind>)]` to it, or one to the enum as the default |
a second #[classify(..)] | a second `#[classify(..)]`: an item takes one kind |
| a malformed attribute | `#[classify(..)]` takes one kind word: followed by the eleven kinds |
| an unknown kind | unknown kind `x`; expected one of followed by the eleven kinds |
| a union | `Classify` derives on a struct or an enum, not a union |
#[derive(Validate)]
Writes impl Validate from #[validate(..)] on the fields of a struct with named fields.
| Rule | Applies to | Counts |
|---|---|---|
length(min = .., max = ..) | text or a collection | characters for text, items for a collection |
email | a string | a shape check, not RFC 5322 |
range(min = .., max = ..) | an ordered value | the value |
Bounds are inclusive and either may be left out. A bound's value is written into the violation's description, so it implements Display. Several rules go in one attribute or in several: #[validate(length(max = 254), email)].
Every failing rule is one FieldViolation, so a value is checked whole rather than to its first failure. The violation names the field as the request does: serde's rename, or the container's rename_all, when present. A field with no #[validate] is not checked. Valid<P> runs the rules after P extracts and turns violations into ExtractError::Invalid.
| Input | Diagnostic |
|---|---|
| a tuple struct, unit struct, enum or union | `Validate` derives on a struct with named fields |