larust_live/registry.rs
1use crate::component::WireComponent;
2use axum::http::StatusCode;
3use larust_core::AppError;
4use larust_http::session::Session;
5use serde_json::Value;
6use std::collections::HashMap;
7use std::future::Future;
8use std::pin::Pin;
9use std::sync::OnceLock;
10
11type BoxedFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
12
13type MountFn = Box<
14 dyn for<'a> Fn(
15 &'a Session,
16 &'a HashMap<String, Value>,
17 ) -> BoxedFuture<'a, Result<Value, AppError>>
18 + Send
19 + Sync,
20>;
21type RenderFn =
22 Box<dyn for<'a> Fn(&'a Value) -> BoxedFuture<'a, Result<String, AppError>> + Send + Sync>;
23type SetManyFn =
24 Box<dyn Fn(Value, &HashMap<String, Value>) -> Result<Value, AppError> + Send + Sync>;
25/// The `Option<String>` alongside the new state is `call`'s optional
26/// redirect path (see `WireComponent::call`'s own doc comment) - carried
27/// out of the type-erasure boundary as a plain tuple element rather than a
28/// second closure, since it's produced by the same one dispatch.
29type CallFn = Box<
30 dyn for<'a> Fn(
31 Value,
32 &'a Session,
33 &'a str,
34 &'a Value,
35 ) -> BoxedFuture<'a, Result<(Value, Option<String>), AppError>>
36 + Send
37 + Sync,
38>;
39
40/// The type-erasure boundary: given only a component *name* string (read
41/// back out of session storage) and no compile-time type, this is how
42/// `mount()`/`update()` get back to a concrete, statically-typed `C`.
43/// State is carried as `serde_json::Value` between calls - `mount`/`call`
44/// round-trip it through `C` (via `serde_json::from_value`/`to_value`) so
45/// every operation is still fully type-checked against `C`'s own `Serialize`/
46/// `Deserialize` impl, just monomorphized once at `register::<C>()` time
47/// instead of at every call site. `mount`/`render`/`call` return boxed
48/// futures (`WireComponent`'s own methods are `async`, and a `Box<dyn Fn>`
49/// can't return `impl Future` directly) - `set_many` stays synchronous, since
50/// merging a props object and round-tripping it through `C` purely as a type
51/// check needs no async work at all.
52pub(crate) struct ComponentEntry {
53 pub(crate) mount: MountFn,
54 pub(crate) render: RenderFn,
55 pub(crate) set_many: SetManyFn,
56 pub(crate) call: CallFn,
57}
58
59static REGISTRY: OnceLock<HashMap<&'static str, ComponentEntry>> = OnceLock::new();
60
61/// Starts building the process-wide wire-component registry. Call
62/// `.register::<C>()` for each component, then `.publish()` once, typically
63/// right before `Application::serve()` - same "build via fluent chain, then
64/// publish once" shape as `larust_events::listeners()`/`ListenerRegistry`.
65pub fn components() -> LiveRegistry {
66 LiveRegistry {
67 map: HashMap::new(),
68 }
69}
70
71#[must_use]
72pub struct LiveRegistry {
73 map: HashMap<&'static str, ComponentEntry>,
74}
75
76impl LiveRegistry {
77 /// Registers `C` under its own `WireComponent::NAME`. Panics if the same
78 /// name is registered twice in one process - a genuine app-author bug
79 /// (two components fighting over one `@wire(...)` name), not a
80 /// recoverable runtime condition, so this fails loudly at startup rather
81 /// than silently letting the second registration shadow the first.
82 pub fn register<C: WireComponent>(mut self) -> Self {
83 let entry = ComponentEntry {
84 mount: Box::new(|session, props| {
85 Box::pin(async move {
86 serde_json::to_value(C::mount(session, props).await)
87 .map_err(|source| AppError::Internal(Box::new(source)))
88 })
89 }),
90 render: Box::new(|state| {
91 Box::pin(async move {
92 let component = decode::<C>(state.clone())?;
93 Ok(component.render().await.into_html())
94 })
95 }),
96 set_many: Box::new(|state, props| {
97 if props.is_empty() {
98 // Nothing to merge - skip the object round-trip
99 // entirely. This matters for a `wire:click`-only
100 // component with no `wire:model` fields at all: such a
101 // `WireComponent` is naturally written as a unit
102 // struct, which `serde_json::to_value` serializes as
103 // `Value::Null`, not `Value::Object` - `as_object`
104 // would otherwise reject every action dispatch on it,
105 // even though there was never anything to merge.
106 return Ok(state);
107 }
108 let mut merged = as_object(state)?;
109 for (key, value) in props {
110 merged.insert(key.clone(), value.clone());
111 }
112 let merged = Value::Object(merged);
113 // Round-tripped through `C` purely as a type check - an
114 // update payload with a prop of the wrong shape (a string
115 // where `C` expects a number, say) is rejected as a 422
116 // here, rather than silently stored malformed.
117 let component = decode::<C>(merged)?;
118 serde_json::to_value(component)
119 .map_err(|source| AppError::Internal(Box::new(source)))
120 }),
121 call: Box::new(|state, session, action, args| {
122 Box::pin(async move {
123 let mut component = decode::<C>(state)?;
124 let redirect = component.call(session, action, args).await?;
125 let new_state = serde_json::to_value(component)
126 .map_err(|source| AppError::Internal(Box::new(source)))?;
127 Ok((new_state, redirect))
128 })
129 }),
130 };
131
132 let existing = self.map.insert(C::NAME, entry);
133 assert!(
134 existing.is_none(),
135 "duplicate LiveRegistry::register for component NAME {:?} - each wire component \
136 must be registered exactly once",
137 C::NAME
138 );
139 self
140 }
141
142 /// Publishes this registry process-wide - `mount()`/`update()` read from
143 /// it afterward. Same "second call warns, doesn't panic, first writer
144 /// wins" shape as `larust_events::ListenerRegistry::publish`.
145 pub fn publish(self) {
146 if REGISTRY.set(self.map).is_err() {
147 tracing::warn!(
148 "wire component registry published more than once in this process; \
149 mount()/update() still use the first registry's components"
150 );
151 }
152 }
153}
154
155pub(crate) fn lookup(name: &str) -> Option<&'static ComponentEntry> {
156 REGISTRY.get().and_then(|map| map.get(name))
157}
158
159fn decode<C: WireComponent>(state: Value) -> Result<C, AppError> {
160 serde_json::from_value(state).map_err(|source| AppError::Http {
161 status: StatusCode::UNPROCESSABLE_ENTITY,
162 message: format!("invalid component state: {source}"),
163 })
164}
165
166/// Rejected as a 422, not an internal error: a client sending non-empty
167/// `props` for a component whose state doesn't serialize to a JSON object
168/// (a unit-struct component with no `wire:model` fields at all - see
169/// `set_many`'s empty-props fast path above, which is what normal usage
170/// hits instead) is a client-shaped mismatch, the same category as any
171/// other type-mismatched prop, not an internal invariant violation.
172fn as_object(state: Value) -> Result<serde_json::Map<String, Value>, AppError> {
173 match state {
174 Value::Object(map) => Ok(map),
175 other => Err(AppError::Http {
176 status: StatusCode::UNPROCESSABLE_ENTITY,
177 message: format!(
178 "cannot apply props to this component's state - expected a JSON object, found: {other}"
179 ),
180 }),
181 }
182}