1use std::sync::Arc;
40
41use crate::adapter::WrappingDispenser;
42use crate::adapter::{ExecutionError, OpDispenser, OpResult};
43use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
44
45pub const NAME: WrapperName = WrapperName::new("gutter");
46
47#[derive(Debug, Clone, PartialEq)]
51pub enum GutterSpec {
52 Text(String),
55 Bar(f64),
57 Spark(f64),
59 Labeled { name: String, value: String },
65}
66
67fn triggers(s: WrapperSubject) -> bool {
70 let Some(template) = s.op() else {
71 return false;
72 };
73 template
74 .params
75 .get("gutter")
76 .map(|v| v.is_string() || v.is_object())
77 .unwrap_or(false)
78}
79
80fn describe_assignment(s: WrapperSubject) -> Option<String> {
81 let template = s.op()?;
82 let v = template.params.get("gutter")?;
83 if let Some(s) = v.as_str() {
84 if s.is_empty() {
85 return None;
86 }
87 Some(format!("gutter: \"{s}\" (layout)"))
88 } else if let Some(obj) = v.as_object() {
89 let mut parts: Vec<String> = Vec::new();
90 for key in ["bar", "spark", "text"] {
91 if let Some(t) = obj.get(key).and_then(|x| x.as_str()) {
92 parts.push(format!("{key} \"{t}\""));
93 }
94 }
95 match obj.get("final") {
96 Some(f) if f.is_string() => {
97 parts.push(format!("final \"{}\"", f.as_str().unwrap_or("")))
98 }
99 Some(f) if f.is_object() => parts.push("final {…}".to_string()),
100 _ => {}
101 }
102 if parts.is_empty() {
103 None
104 } else {
105 Some(format!("gutter: {}", parts.join(" / ")))
106 }
107 } else {
108 None
109 }
110}
111
112inventory::submit! {
113 WrapperRegistration {
114 name: NAME,
115 owned_fields: &["gutter"],
120 triggers,
121 requires_inner: &[super::traverse::NAME],
122 forbids_outer: &[],
123 mutually_exclusive_with: &[],
124 describe_assignment,
125 levels: &[crate::wrapper_registry::WrapperLevel::Op],
126 }
127}
128
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
131pub enum GutterKind {
132 Text,
133 Bar,
134 Spark,
135 Labeled,
139}
140
141#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct GutterTemplate {
146 pub kind: GutterKind,
147 pub template: String,
148}
149
150impl GutterTemplate {
151 pub fn new(kind: GutterKind, template: impl Into<String>) -> Self {
152 Self {
153 kind,
154 template: template.into(),
155 }
156 }
157}
158
159#[derive(Debug, Clone, Default, PartialEq, Eq)]
162pub struct GutterTemplates {
163 pub during: Option<GutterTemplate>,
164 pub finish: Option<GutterTemplate>,
165}
166
167pub fn parse_templates(v: Option<&serde_json::Value>) -> GutterTemplates {
173 let parse_forms = |obj: &serde_json::Map<String, serde_json::Value>| -> Option<GutterTemplate> {
174 if let Some(m) = obj.get("labeled").and_then(|x| x.as_object()) {
175 let name = m.get("name").and_then(|x| x.as_str()).unwrap_or("");
176 let value = m.get("value").and_then(|x| x.as_str()).unwrap_or("");
177 return Some(GutterTemplate::new(
178 GutterKind::Labeled,
179 format!("{name}{}{value}", '\u{1f}'),
180 ));
181 }
182 if let Some(t) = obj.get("bar").and_then(|x| x.as_str()) {
183 Some(GutterTemplate::new(GutterKind::Bar, t))
184 } else if let Some(t) = obj.get("spark").and_then(|x| x.as_str()) {
185 Some(GutterTemplate::new(GutterKind::Spark, t))
186 } else {
187 obj.get("text")
188 .and_then(|x| x.as_str())
189 .map(|t| GutterTemplate::new(GutterKind::Text, t))
190 }
191 };
192 match v {
193 Some(serde_json::Value::String(s)) if !s.is_empty() => GutterTemplates {
194 during: Some(GutterTemplate::new(GutterKind::Text, s.as_str())),
195 finish: None,
196 },
197 Some(serde_json::Value::Object(obj)) => GutterTemplates {
198 during: parse_forms(obj),
199 finish: match obj.get("final") {
200 Some(serde_json::Value::String(s)) if !s.is_empty() => {
201 Some(GutterTemplate::new(GutterKind::Text, s.as_str()))
202 }
203 Some(serde_json::Value::Object(fobj)) => parse_forms(fobj),
204 _ => None,
205 },
206 },
207 _ => GutterTemplates::default(),
208 }
209}
210
211pub(crate) fn render_spec(
215 declared: &GutterTemplate,
216 wires: &dyn crate::wires::WireSource,
217) -> Option<GutterSpec> {
218 let (kind, template) = (declared.kind, declared.template.as_str());
219 let rendered = match crate::wires::substitute_via_wires(template, wires) {
220 Ok(s) => s,
221 Err(e) => {
222 crate::diag!(
223 crate::observer::LogLevel::Debug,
224 "gutter: substitution failed for '{template}': {e}"
225 );
226 return None;
227 }
228 };
229 match kind {
230 GutterKind::Labeled => {
231 let (name, value) = rendered
232 .split_once('\u{1f}')
233 .unwrap_or(("", rendered.as_str()));
234 Some(GutterSpec::Labeled {
235 name: name.to_string(),
236 value: value.to_string(),
237 })
238 }
239 GutterKind::Text => Some(GutterSpec::Text(rendered)),
240 GutterKind::Bar | GutterKind::Spark => match rendered.trim().parse::<f64>() {
241 Ok(v) if kind == GutterKind::Bar => Some(GutterSpec::Bar(v.clamp(0.0, 1.0))),
242 Ok(v) => Some(GutterSpec::Spark(v)),
243 Err(_) => {
244 crate::diag!(
245 crate::observer::LogLevel::Debug,
246 "gutter: '{template}' rendered to non-numeric '{rendered}'"
247 );
248 None
249 }
250 },
251 }
252}
253
254pub struct GutterDispenser {
263 inner: Arc<dyn OpDispenser>,
264 template: GutterTemplate,
265 gutter_state: Arc<arc_swap::ArcSwapOption<GutterSpec>>,
269}
270
271impl GutterDispenser {
272 pub fn wrap(
273 inner: Arc<dyn OpDispenser>,
274 template: GutterTemplate,
275 gutter_state: Arc<arc_swap::ArcSwapOption<GutterSpec>>,
276 ) -> Arc<dyn OpDispenser> {
277 Arc::new(Self {
278 inner,
279 template,
280 gutter_state,
281 })
282 }
283
284 fn publish(&self, wires: &dyn crate::wires::WireSource) {
285 if let Some(spec) = render_spec(&self.template, wires) {
286 self.gutter_state.store(Some(Arc::new(spec)));
287 }
288 }
289}
290
291impl WrappingDispenser for GutterDispenser {}
292
293impl OpDispenser for GutterDispenser {
294 fn execute<'a>(
295 &'a self,
296 cycle: u64,
297 ctx: &'a crate::fixture::ExecCtx<'a>,
298 ) -> std::pin::Pin<
299 Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
300 > {
301 Box::pin(async move {
302 let result = self.inner.execute(cycle, ctx).await?;
303 self.publish(ctx.wires);
304 Ok(result)
305 })
306 }
307
308 fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
309 Some(self.inner.as_ref())
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316 use crate::adapter::{AdapterError, ExecutionError, OpResult};
317 use crate::fixture::{ExecCtx, ResolvedPulls};
318
319 struct FakeInner {
320 error: Option<&'static str>,
321 }
322
323 impl OpDispenser for FakeInner {
324 fn execute<'a>(
325 &'a self,
326 _cycle: u64,
327 _ctx: &'a ExecCtx<'a>,
328 ) -> std::pin::Pin<
329 Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
330 > {
331 Box::pin(async move {
332 if let Some(msg) = self.error {
333 return Err(ExecutionError::Op(AdapterError {
334 error_name: "test".into(),
335 message: msg.into(),
336 retryable: false,
337 }));
338 }
339 Ok(OpResult {
340 body: None,
341 skipped: false,
342 })
343 })
344 }
345 }
346
347 fn empty_ctx() -> (crate::adapter::ResolvedFields, ResolvedPulls) {
348 let fields = crate::adapter::ResolvedFields::new(vec![], vec![]);
349 let pulls = ResolvedPulls::empty();
350 (fields, pulls)
351 }
352
353 #[tokio::test]
354 async fn text_form_publishes_rendered_layout() {
355 let state = Arc::new(arc_swap::ArcSwapOption::empty());
356 let inner = Arc::new(FakeInner { error: None });
357 let d = GutterDispenser::wrap(
358 inner,
359 GutterTemplate::new(GutterKind::Text, "queue depth ok"),
360 state.clone(),
361 );
362 let (fields, pulls) = empty_ctx();
363 let ctx = ExecCtx::new(&fields, &pulls);
364 let _ = d.execute(0, &ctx).await.expect("inner ok");
365 assert_eq!(
366 state.load().as_deref(),
367 Some(&GutterSpec::Text("queue depth ok".into()))
368 );
369 }
370
371 #[tokio::test]
372 async fn bar_form_parses_and_clamps_fraction() {
373 let state = Arc::new(arc_swap::ArcSwapOption::empty());
374 let inner = Arc::new(FakeInner { error: None });
375 let d = GutterDispenser::wrap(
376 inner,
377 GutterTemplate::new(GutterKind::Bar, "1.7"),
378 state.clone(),
379 );
380 let (fields, pulls) = empty_ctx();
381 let ctx = ExecCtx::new(&fields, &pulls);
382 let _ = d.execute(0, &ctx).await.expect("inner ok");
383 assert_eq!(
384 state.load().as_deref(),
385 Some(&GutterSpec::Bar(1.0)),
386 "fraction must clamp to 0..=1"
387 );
388 }
389
390 #[tokio::test]
391 async fn numeric_parse_failure_leaves_slot_untouched() {
392 let state: Arc<arc_swap::ArcSwapOption<GutterSpec>> =
393 Arc::new(arc_swap::ArcSwapOption::empty());
394 state.store(Some(Arc::new(GutterSpec::Spark(3.0))));
395 let inner = Arc::new(FakeInner { error: None });
396 let d = GutterDispenser::wrap(
397 inner,
398 GutterTemplate::new(GutterKind::Spark, "not-a-number"),
399 state.clone(),
400 );
401 let (fields, pulls) = empty_ctx();
402 let ctx = ExecCtx::new(&fields, &pulls);
403 let _ = d.execute(0, &ctx).await.expect("inner ok");
404 assert_eq!(
405 state.load().as_deref(),
406 Some(&GutterSpec::Spark(3.0)),
407 "unparseable render must not clobber the last good value"
408 );
409 }
410
411 #[tokio::test]
412 async fn does_not_publish_on_inner_error() {
413 let state: Arc<arc_swap::ArcSwapOption<GutterSpec>> =
414 Arc::new(arc_swap::ArcSwapOption::empty());
415 let inner = Arc::new(FakeInner {
416 error: Some("boom"),
417 });
418 let d = GutterDispenser::wrap(
419 inner,
420 GutterTemplate::new(GutterKind::Text, "never"),
421 state.clone(),
422 );
423 let (fields, pulls) = empty_ctx();
424 let ctx = ExecCtx::new(&fields, &pulls);
425 assert!(d.execute(0, &ctx).await.is_err());
426 assert!(
427 state.load().is_none(),
428 "gutter must not publish on inner error"
429 );
430 }
431}