Skip to main content

nmbrs_runtime/wrappers/
fields.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Fields wrapper — prints the rendered op text per cycle.
5//!
6//! Two modes, distinguished by whether op_fields are attached at
7//! wrap time:
8//! - **Adapter-agnostic field render** (`fields: true` on op template):
9//!   resolves the op_fields the template carries via the
10//!   per-fiber wires, prints each value verbatim, then forwards
11//!   the call to inner. This is the canonical "render what the
12//!   adapter would send" surface — under `dryrun=fields` the
13//!   DRYRUN wrapper short-circuits inner, so this wrapper is the
14//!   only surface that prints.
15//! - **Body+wire dump** (no op_fields at wrap): falls back to
16//!   the inner result body + wire snapshot. Kept as the
17//!   historical surface for callers that want post-execute
18//!   introspection rather than pre-execute rendering.
19
20use std::sync::Arc;
21
22use crate::adapter::WrappingDispenser;
23use crate::adapter::{ExecutionError, OpDispenser, OpResult};
24use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
25
26/// SRD-32a wrapper name.
27pub const NAME: WrapperName = WrapperName::new("fields");
28
29/// Trigger: op carries `fields:` with any value but `false`. A
30/// value that isn't a boolean triggers too, so the wrap step
31/// ([`check_fields_value`]) rejects it instead of it quietly reading
32/// as off.
33fn triggers(s: WrapperSubject) -> bool {
34    let Some(template) = s.op() else {
35        return false;
36    };
37    template
38        .params
39        .get("fields")
40        .is_some_and(|v| nmbrs_workload::boolean::json_bool("fields", v) != Ok(false))
41}
42
43/// The op's `fields:` value must be `true` / `false`
44/// ([`nmbrs_workload::boolean`]); absent is fine.
45pub fn check_fields_value(
46    params: &std::collections::HashMap<String, serde_json::Value>,
47) -> Result<(), String> {
48    params.get("fields").map_or(Ok(()), |v| {
49        nmbrs_workload::boolean::json_bool("fields", v).map(|_| ())
50    })
51}
52
53fn describe_assignment(_: WrapperSubject) -> Option<String> {
54    Some("fields: rendered op text to stdout".into())
55}
56
57inventory::submit! {
58    WrapperRegistration {
59        name: NAME,
60        owned_fields: &["fields"],
61        triggers,
62        // SRD-32a's table lists `fields.requires_inner = [result]`,
63        // but the cascade composes `result` OUTSIDE `fields`
64        // (innermost-first list ends `..., fields, result,
65        // metrics`). Declaring `requires_inner = [result]` would
66        // make `result` innermore than `fields`, which contradicts
67        // the cascade and breaks the byte-identical-output test
68        // bar in §"Migration".
69        requires_inner: &[],
70        forbids_outer: &[],
71        mutually_exclusive_with: &[],
72        describe_assignment,
73        levels: &[crate::wrapper_registry::WrapperLevel::Op],
74    }
75}
76
77/// Wraps any adapter's dispenser and prints the result body to stdout
78/// as JSON after each execution. Adapter-agnostic — works with CQL,
79/// HTTP, stdout, or any adapter that returns a ResultBody.
80///
81/// Enabled by wrapping at init time when `dryrun=fields` is active
82/// or when the op has `fields: true`.
83pub struct FieldsDispenser {
84    inner: Arc<dyn OpDispenser>,
85    op_name: String,
86    /// Op-field key/value pairs cloned from the op template at
87    /// wrap time. When non-empty, this wrapper resolves them via wires
88    /// at each cycle and prints the value strings — that's the
89    /// pre-execute "render what would have been sent" surface.
90    /// When empty, falls back to the post-execute body
91    /// + wires dump for callers that want introspection only.
92    op_fields: Vec<(String, serde_json::Value)>,
93}
94
95impl FieldsDispenser {
96    pub fn wrap(inner: Arc<dyn OpDispenser>, op_name: &str) -> Arc<dyn OpDispenser> {
97        Arc::new(Self {
98            inner,
99            op_name: op_name.to_string(),
100            op_fields: Vec::new(),
101        })
102    }
103
104    /// Same as [`Self::wrap`], but seeds the dispenser with the
105    /// op_fields it should resolve + print on each cycle. Used
106    /// at activity init when the op template's `op:` map is
107    /// known and we want the rendered op text on stdout (e.g.
108    /// under `dryrun=fields`).
109    pub fn wrap_with_op_fields(
110        inner: Arc<dyn OpDispenser>,
111        op_name: &str,
112        op_fields: Vec<(String, serde_json::Value)>,
113    ) -> Arc<dyn OpDispenser> {
114        Arc::new(Self {
115            inner,
116            op_name: op_name.to_string(),
117            op_fields,
118        })
119    }
120}
121
122impl WrappingDispenser for FieldsDispenser {}
123
124impl OpDispenser for FieldsDispenser {
125    fn execute<'a>(
126        &'a self,
127        cycle: u64,
128        ctx: &'a crate::fixture::ExecCtx<'a>,
129    ) -> std::pin::Pin<
130        Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
131    > {
132        Box::pin(async move {
133            // Pre-execute rendering mode — resolve the
134            // captured op_fields and print their rendered
135            // values. This runs BEFORE inner.execute so the
136            // surface lands the rendered op text whether or
137            // not inner short-circuits (DRYRUN under
138            // dryrun=fields, etc).
139            if !self.op_fields.is_empty() {
140                match crate::wires::resolve_op_fields_via_wires(&self.op_fields, ctx.wires) {
141                    Ok(resolved) => {
142                        for s in resolved.strings().iter() {
143                            println!("{s}");
144                        }
145                    }
146                    Err(msg) => {
147                        eprintln!("[{}@{}] fields-render failed: {msg}", self.op_name, cycle);
148                    }
149                }
150            }
151
152            let result = self.inner.execute(cycle, ctx).await?;
153
154            // Post-execute introspection — only fires when
155            // this wrapper was wrapped without op_fields (the
156            // body+wires fallback surface). With op_fields the
157            // pre-execute render is the authoritative surface
158            // and the post-execute dump is omitted to keep
159            // stdout terse.
160            if self.op_fields.is_empty() {
161                if let Some(ref body) = result.body {
162                    let json = body.to_json();
163                    println!(
164                        "[{}@{}] {} rows: {}",
165                        self.op_name,
166                        cycle,
167                        body.element_count(),
168                        serde_json::to_string_pretty(&json).unwrap_or_else(|_| json.to_string())
169                    );
170                } else {
171                    println!("[{}@{}] (no result body)", self.op_name, cycle);
172                }
173                for name in ctx.wires.names() {
174                    if let Some(value) = ctx.wires.get(&name) {
175                        println!("  wire {name} = {}", value.to_display_string());
176                    }
177                }
178            }
179
180            Ok(result)
181        })
182    }
183    fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
184        Some(self.inner.as_ref())
185    }
186}