scientific_workflow/persistence/local/json_payload_decoder.rs
1//! Per-payload decoding contracts and key-based decoder registration.
2//!
3//! A payload decoder receives only one field's borrowed raw JSON and returns
4//! one concrete Rust value. It does not receive record time, sibling fields,
5//! chunk metadata, a destination state, or a series. [`JsonPayloadDecoderRegistry`] matches keys
6//! to these independently reusable conversions and privately adapts their
7//! heterogeneous results for insertion into `SystemState`.
8//!
9//! [`JsonPayloadDecoder::decode_json_payload`] accepts `&str` containing exactly one JSON value.
10//! The reader can obtain this slice from `serde_json::value::RawValue` while
11//! retaining the enclosing line buffer. A tensor decoder can therefore build
12//! its final allocation without an intermediate `serde_json::Value` tree. The
13//! returned payload is owned and cannot retain the temporary input.
14//!
15//! Type erasure occurs only inside the registry adapter. Public decoders still
16//! return their real `T`; the adapter moves that value directly into the state
17//! through `SystemState::insert_payload` and never invokes `T::clone`.
18//!
19//! This module performs no JSON parsing, filesystem access, chunk validation,
20//! record-key validation, state construction, or series collection. The reader
21//! owns those operations and dispatches fields in canonical schema order.
22
23use std::collections::{HashMap, HashSet};
24use std::error::Error;
25use std::fmt;
26use std::marker::PhantomData;
27
28use serde::Serialize;
29use serde::de::DeserializeOwned;
30
31use crate::state::{StateError, SystemState};
32
33use super::error::PersistenceError;
34
35/// Object-safe error boundary for application-defined payload conversion.
36type BoxError = Box<dyn Error + Send + Sync + 'static>;
37
38/// Converts one borrowed raw JSON value into one concrete state payload.
39///
40/// `T` stays explicit at this boundary. Any thread-safe
41/// `Fn(&str) -> Result<T, E>` implements the trait automatically; named decoder
42/// types may implement it directly when they own configuration or shared state.
43pub trait JsonPayloadDecoder<T>: Send + Sync + 'static {
44 /// Decoder-specific failure retained by [`PersistenceError::DecodeField`].
45 type Error: Error + Send + Sync + 'static;
46
47 /// Decodes exactly one complete raw JSON value into an owned payload.
48 fn decode_json_payload(&self, raw_json: &str) -> Result<T, Self::Error>;
49}
50
51impl<T, E, F> JsonPayloadDecoder<T> for F
52where
53 F: Fn(&str) -> Result<T, E> + Send + Sync + 'static,
54 E: Error + Send + Sync + 'static,
55{
56 type Error = E;
57
58 /// Invokes the registered closure without wrapping or copying its output.
59 fn decode_json_payload(&self, raw_json: &str) -> Result<T, Self::Error> {
60 self(raw_json)
61 }
62}
63
64/// Heterogeneous per-key payload decoder registry.
65///
66/// One registry may contain the union of keys used by several output streams.
67/// Coverage therefore requires every selected key but permits additional
68/// registrations. Keys are exact and are not trimmed or case-normalized.
69///
70/// This type is intentionally non-Clone because registered decoders may own
71/// caches, handles, or synchronization state with unknown clone semantics.
72#[derive(Default)]
73pub struct JsonPayloadDecoderRegistry {
74 entries: HashMap<Box<str>, Box<dyn ErasedPayloadDecoder>>,
75}
76
77impl JsonPayloadDecoderRegistry {
78 /// Creates an empty registry.
79 pub fn new() -> Self {
80 Self::default()
81 }
82
83 /// Creates an empty registry with capacity for at least `capacity` keys.
84 pub fn with_capacity(capacity: usize) -> Self {
85 Self {
86 entries: HashMap::with_capacity(capacity),
87 }
88 }
89
90 /// Adds a field decoded directly through Serde JSON into `T`.
91 ///
92 /// This is the concise path for payload types whose JSON representation
93 /// already matches their Rust representation. Specialized decoders remain
94 /// available through [`JsonPayloadDecoderRegistry::register_for_field`]
95 /// when conversion requires configuration, validation, or a different
96 /// wire shape.
97 ///
98 /// # Errors
99 ///
100 /// Returns the same empty-key or duplicate-key errors as
101 /// [`JsonPayloadDecoderRegistry::register_for_field`]. Payload parse
102 /// failures are reported later with their field context by the reader.
103 pub fn with_json_field<T>(mut self, key: impl Into<String>) -> Result<Self, PersistenceError>
104 where
105 T: DeserializeOwned + Serialize + Clone + Send + 'static,
106 {
107 self.register_for_field::<T, _>(key, |raw_json: &str| serde_json::from_str::<T>(raw_json))?;
108 Ok(self)
109 }
110
111 /// Registers one typed decoder under one exact state field key.
112 ///
113 /// Successful decoded values are moved directly into `SystemState`; the
114 /// adapter never invokes `T::clone`.
115 ///
116 /// # Errors
117 ///
118 /// Returns [`PersistenceError::InvalidConfiguration`] for an empty key and
119 /// [`PersistenceError::DuplicateDecoder`] for an existing key. The incoming
120 /// decoder is dropped on either configuration error.
121 pub fn register_for_field<T, D>(
122 &mut self,
123 key: impl Into<String>,
124 decoder: D,
125 ) -> Result<(), PersistenceError>
126 where
127 T: Serialize + Clone + Send + 'static,
128 D: JsonPayloadDecoder<T>,
129 {
130 let key = key.into();
131 if key.is_empty() {
132 return Err(PersistenceError::InvalidConfiguration {
133 setting: "decoder.key",
134 reason: "decoder key must not be empty".to_owned(),
135 });
136 }
137 if self.entries.contains_key(key.as_str()) {
138 return Err(PersistenceError::DuplicateDecoder { field: key });
139 }
140 self.entries.insert(
141 key.into_boxed_str(),
142 Box::new(TypedDecoder {
143 decoder,
144 payload: PhantomData,
145 }),
146 );
147 Ok(())
148 }
149
150 /// Returns the number of registered field keys.
151 pub fn len(&self) -> usize {
152 self.entries.len()
153 }
154
155 /// Reports whether no payload decoder is registered.
156 pub fn is_empty(&self) -> bool {
157 self.entries.is_empty()
158 }
159
160 /// Reports whether an exact field key has a registered decoder.
161 pub fn has_decoder_for_field(&self, key: &str) -> bool {
162 self.entries.contains_key(key)
163 }
164
165 /// Iterates registered keys in unspecified hash-map order.
166 ///
167 /// Reader dispatch never uses this order. Callers needing stable display
168 /// should sort the returned strings.
169 pub fn registered_field_names(&self) -> impl ExactSizeIterator<Item = &str> {
170 self.entries.keys().map(AsRef::as_ref)
171 }
172
173 /// Verifies that every selected stream field has a decoder.
174 ///
175 /// Additional keys remain valid for other streams. Repeated input keys are
176 /// harmless and checked once, though metadata validation rejects them
177 /// before the reader reaches this boundary.
178 pub(crate) fn require<'a>(
179 &self,
180 fields: impl IntoIterator<Item = &'a str>,
181 ) -> Result<(), PersistenceError> {
182 let mut checked = HashSet::new();
183 for field in fields {
184 if checked.insert(field) && !self.has_decoder_for_field(field) {
185 return Err(PersistenceError::MissingDecoder {
186 field: field.to_owned(),
187 });
188 }
189 }
190 Ok(())
191 }
192
193 /// Decodes one matched field and moves it into an empty destination slot.
194 ///
195 /// The reader supplies context after validating record keys. A conversion
196 /// or unexpected insertion failure becomes [`PersistenceError::DecodeField`]
197 /// with its original source chain preserved.
198 pub(crate) fn decode_into(
199 &self,
200 stream: &str,
201 iteration: u64,
202 field: &str,
203 raw_json: &str,
204 state: &mut SystemState,
205 ) -> Result<(), PersistenceError> {
206 let decoder = self
207 .entries
208 .get(field)
209 .ok_or_else(|| PersistenceError::MissingDecoder {
210 field: field.to_owned(),
211 })?;
212 decoder
213 .decode_into(raw_json, field, state)
214 .map_err(|source| PersistenceError::DecodeField {
215 stream: stream.to_owned(),
216 iteration,
217 field: field.to_owned(),
218 source,
219 })
220 }
221}
222
223impl fmt::Debug for JsonPayloadDecoderRegistry {
224 /// Formats sorted keys without exposing decoder internals or payloads.
225 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
226 let mut keys = self.registered_field_names().collect::<Vec<_>>();
227 keys.sort_unstable();
228 formatter
229 .debug_struct("JsonPayloadDecoderRegistry")
230 .field("keys", &keys)
231 .finish_non_exhaustive()
232 }
233}
234
235/// Object-safe insertion adapter stored by [`JsonPayloadDecoderRegistry`].
236trait ErasedPayloadDecoder: Send + Sync {
237 /// Decodes one field and moves its concrete result into `state`.
238 fn decode_into(
239 &self,
240 raw_json: &str,
241 field: &str,
242 state: &mut SystemState,
243 ) -> Result<(), BoxError>;
244}
245
246/// Concrete typed decoder hidden behind [`ErasedPayloadDecoder`].
247struct TypedDecoder<D, T> {
248 decoder: D,
249 /// Associates the adapter with its concrete output without owning a `T`.
250 payload: PhantomData<fn() -> T>,
251}
252
253impl<T, D> ErasedPayloadDecoder for TypedDecoder<D, T>
254where
255 T: Serialize + Clone + Send + 'static,
256 D: JsonPayloadDecoder<T>,
257{
258 /// Preserves `T` through conversion, then transfers it into the state.
259 fn decode_into(
260 &self,
261 raw_json: &str,
262 field: &str,
263 state: &mut SystemState,
264 ) -> Result<(), BoxError> {
265 let payload = self
266 .decoder
267 .decode_json_payload(raw_json)
268 .map_err(|source| Box::new(source) as BoxError)?;
269
270 match state.insert_payload(field, payload) {
271 Ok(None) => Ok(()),
272 Ok(Some(previous)) => {
273 // Restore the pre-existing payload transactionally. Setting an
274 // identical concrete type must succeed and returns the newly
275 // decoded replacement, which is then dropped.
276 let decoded = state
277 .insert_payload(field, previous)
278 .expect("restoring an identical concrete payload type must succeed");
279 drop(decoded);
280 Err(Box::new(DecoderInsertError::Occupied {
281 field: field.to_owned(),
282 }))
283 }
284 Err(rejection) => {
285 let (source, payload) = rejection.into_parts();
286 drop(payload);
287 Err(Box::new(DecoderInsertError::State(source)))
288 }
289 }
290 }
291}
292
293/// Internal state-insertion failure after payload conversion succeeded.
294#[derive(Debug)]
295enum DecoderInsertError {
296 /// Reader attempted to populate the same state field more than once.
297 Occupied { field: String },
298 /// Destination state did not declare the expected field.
299 State(StateError),
300}
301
302impl fmt::Display for DecoderInsertError {
303 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
304 match self {
305 Self::Occupied { field } => {
306 write!(
307 formatter,
308 "decoded state field `{field}` is already populated"
309 )
310 }
311 Self::State(source) => source.fmt(formatter),
312 }
313 }
314}
315
316impl Error for DecoderInsertError {
317 /// Preserves an underlying SystemState insertion failure when present.
318 fn source(&self) -> Option<&(dyn Error + 'static)> {
319 match self {
320 Self::Occupied { .. } => None,
321 Self::State(source) => Some(source),
322 }
323 }
324}