wireframe/app/builder/push.rs
1//! Push-queue and session-registry configuration for `WireframeApp`.
2
3use std::sync::Arc;
4
5use tokio::sync::mpsc;
6
7use super::WireframeApp;
8use crate::{
9 app::{Packet, PrepareError},
10 codec::FrameCodec,
11 push::{FrameLike, PushQueuesBuilder},
12 serializer::Serializer,
13 session::SessionRegistry,
14};
15
16/// Reject a stored push-queue template before any connection exists.
17///
18/// Validating during preparation turns a misconfigured capacity or rate into a
19/// preparation error rather than a failure repeated by every accepted
20/// connection.
21///
22/// # Errors
23///
24/// Returns [`PrepareError::InvalidPushConfig`] when the template is unusable.
25pub(in crate::app) fn validate_push_queues<Fr>(
26 push_queues: Option<&PushQueuesBuilder<Fr>>,
27) -> Result<(), PrepareError>
28where
29 Fr: FrameLike,
30{
31 let Some(template) = push_queues else {
32 return Ok(());
33 };
34 template
35 .validate()
36 .map_err(|source| PrepareError::InvalidPushConfig { source })
37}
38
39/// Bound a push template by the codec that will encode its frames.
40///
41/// A server connection writes queued pushes straight to the transport, so a
42/// frame the codec cannot encode would fail after the producer had been told
43/// the push succeeded, ending the connection. The codec's limit is applied to
44/// the template as a ceiling, so a template that already limits frames more
45/// tightly keeps its own bound and the connection's handle rejects such a push
46/// at enqueue.
47pub(in crate::app) fn with_codec_frame_limit<C>(
48 template: PushQueuesBuilder<C::Frame>,
49 codec: &C,
50) -> PushQueuesBuilder<C::Frame>
51where
52 C: FrameCodec,
53{
54 template.capped_by_codec(codec.max_frame_length(), payload_len::<C>)
55}
56
57/// Report the payload size a codec would encode for `frame`.
58fn payload_len<C: FrameCodec>(frame: &C::Frame) -> usize { C::frame_payload(frame).len() }
59
60/// Warn once when an application still configures the legacy DLQ.
61///
62/// The legacy sink is not wired to connection queues, so silently ignoring it
63/// would hide dropped frames from the operator.
64pub(in crate::app) fn warn_about_legacy_push_dlq(push_dlq: Option<&mpsc::Sender<Vec<u8>>>) {
65 if push_dlq.is_some() {
66 tracing::warn!(
67 "with_push_dlq configures an unused legacy sink; use with_push_queues to receive \
68 dropped frames as codec frames"
69 );
70 }
71}
72
73impl<S, C, E, F> WireframeApp<S, C, E, F>
74where
75 S: Serializer + Send + Sync,
76 C: Send + 'static,
77 E: Packet,
78 F: FrameCodec,
79{
80 /// Provide the template used to build every connection's push queues.
81 ///
82 /// The template is cloned once per accepted connection, so each connection
83 /// gets independent queues, rate limiter state, and dead-letter routing
84 /// derived from the same configuration. A dead-letter queue configured
85 /// here receives codec frames, matching ADR 009.
86 ///
87 /// The template is validated when the application is prepared, so an
88 /// invalid capacity or rate fails before any connection is accepted.
89 ///
90 /// # Examples
91 ///
92 /// ```rust,no_run
93 /// use bytes::Bytes;
94 /// use tokio::sync::mpsc;
95 /// use wireframe::{app::WireframeApp, push::PushQueues};
96 ///
97 /// # fn build() -> WireframeApp {
98 /// # WireframeApp::new().expect("builder creation should not fail")
99 /// # }
100 /// # fn main() {
101 /// let (dlq_tx, _dlq_rx) = mpsc::channel(16);
102 /// let templates = PushQueues::<Bytes>::builder()
103 /// .high_capacity(8)
104 /// .low_capacity(8)
105 /// .dlq(Some(dlq_tx));
106 /// let app = build().with_push_queues(templates);
107 /// # let _ = app;
108 /// # }
109 /// ```
110 #[must_use]
111 pub fn with_push_queues(mut self, push_queues: PushQueuesBuilder<F::Frame>) -> Self {
112 self.push_queues = Some(push_queues);
113 self
114 }
115
116 /// Share a session registry across every connection.
117 ///
118 /// Connections register their push handle with this registry on setup and
119 /// deregister it on close, so application code holding the same `Arc` can
120 /// address individual connections. Without this call the application
121 /// creates its own registry, which [`Self::session_registry`] returns, so
122 /// call that before handing the application to a server if application
123 /// code needs to address its connections.
124 ///
125 /// # Examples
126 ///
127 /// ```rust,no_run
128 /// use std::sync::Arc;
129 ///
130 /// use bytes::Bytes;
131 /// use wireframe::{app::WireframeApp, session::SessionRegistry};
132 ///
133 /// let registry = Arc::new(SessionRegistry::<Bytes>::new());
134 /// let app: WireframeApp = WireframeApp::new()
135 /// .expect("builder creation should not fail")
136 /// .with_session_registry(Arc::clone(®istry));
137 /// # let _ = app;
138 /// ```
139 #[must_use]
140 pub fn with_session_registry(mut self, registry: Arc<SessionRegistry<F::Frame>>) -> Self {
141 self.session_registry = registry;
142 self
143 }
144
145 /// Return the registry every connection built from this application uses.
146 ///
147 /// # Examples
148 ///
149 /// ```rust,no_run
150 /// use std::sync::Arc;
151 ///
152 /// use bytes::Bytes;
153 /// use wireframe::{app::WireframeApp, session::SessionRegistry};
154 ///
155 /// let registry = Arc::new(SessionRegistry::<Bytes>::new());
156 /// let app: WireframeApp = WireframeApp::new()
157 /// .expect("builder creation should not fail")
158 /// .with_session_registry(Arc::clone(®istry));
159 /// assert!(Arc::ptr_eq(&app.session_registry(), ®istry));
160 /// ```
161 #[must_use]
162 pub fn session_registry(&self) -> Arc<SessionRegistry<F::Frame>> {
163 Arc::clone(&self.session_registry)
164 }
165
166 /// Configure a legacy Dead Letter Queue for dropped push frames.
167 ///
168 /// # Deprecated
169 ///
170 /// This sink receives serialized payloads and is no longer consulted when
171 /// building connection queues. Use
172 /// [`with_push_queues`][Self::with_push_queues] with
173 /// [`PushQueues::builder`][crate::push::PushQueues::builder] and its
174 /// `dlq` method so dropped frames arrive as codec frames, as required by
175 /// ADR 009.
176 ///
177 /// ```rust,no_run
178 /// use tokio::sync::mpsc;
179 /// use wireframe::app::WireframeApp;
180 ///
181 /// # fn build() -> WireframeApp {
182 /// # WireframeApp::new().expect("builder creation should not fail")
183 /// # }
184 /// # fn main() {
185 /// let (tx, _rx) = mpsc::channel(16);
186 /// let app = build().with_push_dlq(tx);
187 /// # let _ = app;
188 /// # }
189 /// ```
190 #[must_use]
191 #[deprecated(
192 since = "0.4.0",
193 note = "use with_push_queues(PushQueues::builder().dlq(sender)) so dropped frames arrive \
194 as codec frames"
195 )]
196 pub fn with_push_dlq(mut self, dlq: tokio::sync::mpsc::Sender<Vec<u8>>) -> Self {
197 self.push_dlq = Some(dlq);
198 self
199 }
200}
201
202#[cfg(test)]
203#[path = "push_tests.rs"]
204mod tests;