Skip to main content

xue/
network.rs

1//! Reading the Zarr profile's network store.
2//!
3//! `docs/zarr-profile.md`, "Network store", is normative. A network store
4//! holds one track of a river model — an analysis window or one forecast
5//! cycle — as one `uint8` array `streamflow` of shape `[time, feature]`,
6//! where feature `f` is row `f` of the GeoParquet beside the store, with an
7//! inner chunk of six frames of one GeoParquet row group. Beside it sit the
8//! reach ids, the frame times and each reach's baseflow.
9//!
10//! Like [`crate::zarr`], this module is IO-free: it takes the documents and
11//! the shard's bytes (whole, or one fetched range of it with that range's
12//! offset) and returns codes and values. The shard, its index and the inner
13//! chunk path are the grid store's own; only the dimensions, the chunking and
14//! the attributes are this branch's. Every count that sizes an allocation is
15//! validated first, and every offset is checked against the bytes given.
16
17use serde_json::{Map, Value};
18
19use crate::format::{err, gcd, DecodeError, Predictor, HOUR_SECONDS, MAX_PLANE_LENGTH};
20use crate::zarr::{
21    self, decode_value, parse_iso, IndexLocation, Quantization, ShardIndexEntry, StoreKind,
22    VariableMetadata,
23};
24
25/// The `xue_network` block's version this reader implements.
26pub const NETWORK_VERSION: u64 = 1;
27/// The data array's name, and the one variable's `id`.
28pub const NETWORK_ARRAY: &str = "streamflow";
29/// The data array's one shard object, relative to the store root.
30pub const NETWORK_SHARD_PATH: &str = "streamflow/c/0/0";
31/// Frames per inner chunk, as in a grid store.
32pub const NETWORK_TIME_CHUNK: u32 = 6;
33/// The side arrays' one chunk each, relative to the store root.
34pub const FEATURE_ID_PATH: &str = "feature_id/c/0";
35pub const TIME_PATH: &str = "time/c/0";
36pub const BASEFLOW_PATH: &str = "baseflow/c/0";
37
38const GEOMETRY_KEYS: [&str; 5] = [
39    "path",
40    "byteLength",
41    "crc32",
42    "featureCount",
43    "rowGroupRows",
44];
45const TIME_KEYS: [&str; 5] = [
46    "unitSeconds",
47    "firstFrameOffset",
48    "frameCount",
49    "frameStep",
50    "frameOffsets",
51];
52
53// -- group ---------------------------------------------------------------------
54
55/// The GeoParquet the store's features are the rows of.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct NetworkGeometry {
58    /// Relative to the directory holding the store.
59    pub path: String,
60    pub byte_length: u64,
61    /// The CRC-32 of the file's bytes, eight lowercase hex digits.
62    pub crc32: String,
63    pub feature_count: u32,
64    pub row_group_rows: u32,
65}
66
67/// A network store's group document: its `xue_network` block, validated.
68#[derive(Debug, Clone)]
69pub struct NetworkGroup {
70    pub version: u32,
71    pub model: String,
72    pub product: String,
73    /// The cycle of a forecast, the first frame of an analysis window.
74    pub run_time: String,
75    /// `run_time` in Unix seconds.
76    pub run_time_seconds: i64,
77    pub unit_seconds: u32,
78    /// The materialized frame-offset axis, in `unit_seconds`, strictly
79    /// ascending.
80    pub offsets: Vec<u16>,
81    pub geometry: NetworkGeometry,
82    pub variable: VariableMetadata,
83    /// The variable entry verbatim, which the data array's attributes repeat.
84    variable_json: Value,
85}
86
87impl NetworkGroup {
88    pub fn frame_count(&self) -> u32 {
89        self.offsets.len() as u32
90    }
91
92    /// Every frame's valid time, Unix seconds UTC.
93    pub fn frame_times(&self) -> Vec<i64> {
94        self.offsets
95            .iter()
96            .map(|&offset| self.run_time_seconds + i64::from(offset) * i64::from(self.unit_seconds))
97            .collect()
98    }
99}
100
101/// Parse a store root's `zarr.json` as a network store: a Zarr v3 group whose
102/// attributes carry `xue_network` and neither of the other branches' blocks,
103/// at a version this reader implements.
104pub fn parse_network_group(text: &str) -> Result<NetworkGroup, DecodeError> {
105    let (kind, attributes) = zarr::group_branch(text)?;
106    if kind != StoreKind::Network {
107        return Err(err("group is not a network store"));
108    }
109    let block = attributes
110        .get("xue_network")
111        .and_then(|v| v.as_object())
112        .ok_or_else(|| err("xue_network must be an object"))?;
113    let version = block
114        .get("version")
115        .and_then(|v| v.as_u64())
116        .ok_or_else(|| err("xue_network version missing"))?;
117    if version != NETWORK_VERSION {
118        return Err(err(format!(
119            "network store version {version} is not implemented"
120        )));
121    }
122    let model = nonempty(block, "model")?;
123    let product = nonempty(block, "product")?;
124    let run_time = nonempty(block, "runTime")?;
125    let run_time_ms = parse_iso(&run_time)
126        .ok_or_else(|| err("xue_network runTime is not an ISO 8601 instant"))?;
127    if run_time_ms % 1000.0 != 0.0 {
128        return Err(err("xue_network runTime must fall on a whole second"));
129    }
130    let time = block
131        .get("time")
132        .and_then(|v| v.as_object())
133        .ok_or_else(|| err("xue_network time missing"))?;
134    let (unit_seconds, offsets) = parse_time_block(time)?;
135    let geometry = parse_geometry(block.get("geometry"))?;
136    let variables = block
137        .get("variables")
138        .and_then(|v| v.as_array())
139        .filter(|list| list.len() == 1)
140        .ok_or_else(|| err("xue_network variables must list exactly one variable"))?;
141    let variable_json = variables[0].clone();
142    let variable = parse_variable(&variable_json)?;
143    Ok(NetworkGroup {
144        version: version as u32,
145        model,
146        product,
147        run_time,
148        run_time_seconds: (run_time_ms / 1000.0) as i64,
149        unit_seconds,
150        offsets,
151        geometry,
152        variable,
153        variable_json,
154    })
155}
156
157fn nonempty(block: &Map<String, Value>, key: &str) -> Result<String, DecodeError> {
158    block
159        .get(key)
160        .and_then(|v| v.as_str())
161        .filter(|text| !text.is_empty())
162        .map(str::to_owned)
163        .ok_or_else(|| err(format!("xue_network {key} must be a non-empty string")))
164}
165
166/// The container's time block (`docs/bundle.md`, "Time Axis"): `unitSeconds`
167/// a whole divisor of an hour and the coarsest that fits, exactly one of
168/// `frameStep` (uniform) and `frameOffsets` (listed, strictly increasing,
169/// starting at `firstFrameOffset`, never uniform), offsets below 65535.
170fn parse_time_block(time: &Map<String, Value>) -> Result<(u32, Vec<u16>), DecodeError> {
171    if time.keys().any(|key| !TIME_KEYS.contains(&key.as_str())) {
172        return Err(err("time block has an unknown field"));
173    }
174    let frame_count = time
175        .get("frameCount")
176        .and_then(|v| v.as_u64())
177        .filter(|&count| count > 0 && count <= u64::from(u16::MAX))
178        .ok_or_else(|| err("time frameCount is invalid"))?;
179    let unit_seconds =
180        time.get("unitSeconds")
181            .and_then(|v| v.as_u64())
182            .filter(|&unit| {
183                (1..=u64::from(HOUR_SECONDS)).contains(&unit) && u64::from(HOUR_SECONDS) % unit == 0
184            })
185            .ok_or_else(|| err("time unitSeconds must be a whole divisor of 3600"))? as u32;
186    let first = time
187        .get("firstFrameOffset")
188        .and_then(|v| v.as_u64())
189        .filter(|&offset| offset < u64::from(u16::MAX))
190        .ok_or_else(|| err("time firstFrameOffset is invalid"))?;
191    let offsets = match (time.get("frameStep"), time.get("frameOffsets")) {
192        (Some(step), None) => {
193            let step = step
194                .as_u64()
195                .filter(|&step| step > 0 && step <= u64::from(u16::MAX))
196                .ok_or_else(|| err("time frameStep is invalid"))?;
197            (frame_count - 1)
198                .checked_mul(step)
199                .and_then(|span| span.checked_add(first))
200                .filter(|&last| last < u64::from(u16::MAX))
201                .ok_or_else(|| err("time offsets exceed the u16 range"))?;
202            (0..frame_count)
203                .map(|frame| (first + frame * step) as u16)
204                .collect::<Vec<_>>()
205        }
206        (None, Some(listed)) => {
207            let listed = listed
208                .as_array()
209                .filter(|list| list.len() as u64 == frame_count)
210                .ok_or_else(|| err("time frameOffsets must hold frameCount offsets"))?;
211            let mut offsets: Vec<u16> = Vec::with_capacity(listed.len());
212            for value in listed {
213                let offset = value
214                    .as_u64()
215                    .filter(|&offset| offset < u64::from(u16::MAX))
216                    .ok_or_else(|| err("time frameOffsets entry is invalid"))?
217                    as u16;
218                if offsets.last().is_some_and(|&previous| offset <= previous) {
219                    return Err(err("time frameOffsets must be strictly increasing"));
220                }
221                offsets.push(offset);
222            }
223            if u64::from(offsets[0]) != first {
224                return Err(err("time frameOffsets must begin at firstFrameOffset"));
225            }
226            let mut steps = offsets.windows(2).map(|pair| pair[1] - pair[0]);
227            let first_step = steps.next();
228            if steps.all(|step| Some(step) == first_step) {
229                return Err(err("a uniform time axis must be encoded as a step"));
230            }
231            offsets
232        }
233        _ => {
234            return Err(err(
235                "time must declare exactly one of frameStep and frameOffsets",
236            ))
237        }
238    };
239    let mut divisor = u64::from(HOUR_SECONDS / unit_seconds);
240    for &offset in &offsets {
241        divisor = gcd(divisor, u64::from(offset));
242    }
243    if divisor != 1 {
244        return Err(err("time unitSeconds is finer than the axis needs"));
245    }
246    Ok((unit_seconds, offsets))
247}
248
249fn parse_geometry(value: Option<&Value>) -> Result<NetworkGeometry, DecodeError> {
250    let geometry = value
251        .and_then(|v| v.as_object())
252        .filter(|object| {
253            object.len() == GEOMETRY_KEYS.len()
254                && GEOMETRY_KEYS.iter().all(|key| object.contains_key(*key))
255        })
256        .ok_or_else(|| {
257            err("geometry must be {path, byteLength, crc32, featureCount, rowGroupRows}")
258        })?;
259    let path = geometry
260        .get("path")
261        .and_then(|v| v.as_str())
262        .filter(|path| {
263            !path.is_empty()
264                && !path.starts_with('/')
265                && !path.contains('\\')
266                && path
267                    .split('/')
268                    .all(|part| !part.is_empty() && part != "." && part != "..")
269        })
270        .ok_or_else(|| err("geometry path must be a relative path"))?;
271    let byte_length = geometry
272        .get("byteLength")
273        .and_then(|v| v.as_u64())
274        .filter(|&length| length > 0)
275        .ok_or_else(|| err("geometry byteLength must be a positive integer"))?;
276    let crc32 = geometry
277        .get("crc32")
278        .and_then(|v| v.as_str())
279        .filter(|crc| crc.len() == 8 && crc.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')))
280        .ok_or_else(|| err("geometry crc32 must be eight lowercase hex digits"))?;
281    let feature_count = geometry
282        .get("featureCount")
283        .and_then(|v| v.as_u64())
284        .filter(|&count| count > 0 && count <= u64::from(u32::MAX))
285        .ok_or_else(|| err("geometry featureCount must be a positive integer"))?;
286    let row_group_rows = geometry
287        .get("rowGroupRows")
288        .and_then(|v| v.as_u64())
289        .filter(|&rows| rows > 0 && rows <= u64::from(u32::MAX))
290        .ok_or_else(|| err("geometry rowGroupRows must be a positive integer"))?;
291    // A time chunk across every reach is what a frame read decodes, so it is
292    // held to the decoder's plane limit before anything is sized from it.
293    feature_count
294        .div_ceil(row_group_rows)
295        .checked_mul(row_group_rows)
296        .and_then(|features| features.checked_mul(u64::from(NETWORK_TIME_CHUNK)))
297        .filter(|&cells| cells <= MAX_PLANE_LENGTH)
298        .ok_or_else(|| err("network exceeds the decoded size limit"))?;
299    Ok(NetworkGeometry {
300        path: path.to_owned(),
301        byte_length,
302        crc32: crc32.to_owned(),
303        feature_count: feature_count as u32,
304        row_group_rows: row_group_rows as u32,
305    })
306}
307
308/// The one variable: `streamflow`, `numericId` 1, a `log1p` codebook whose
309/// reserved codes are distinct and whose value codes run between them.
310fn parse_variable(value: &Value) -> Result<VariableMetadata, DecodeError> {
311    let id = value
312        .get("id")
313        .and_then(|v| v.as_str())
314        .ok_or_else(|| err("variable id is invalid"))?;
315    if id != NETWORK_ARRAY {
316        return Err(err(format!("the network variable must be {NETWORK_ARRAY}")));
317    }
318    if value.get("numericId").and_then(|v| v.as_u64()) != Some(1) {
319        return Err(err("the network variable's numericId must be 1"));
320    }
321    let quantization = value
322        .get("quantization")
323        .ok_or_else(|| err("variable quantization missing"))?;
324    if quantization.get("type").and_then(|v| v.as_str()) != Some("log1p") {
325        return Err(err("the network variable must carry a log1p codebook"));
326    }
327    let quantization = zarr::parse_quantization(quantization)?;
328    let Quantization::Log1p {
329        trace,
330        scale,
331        maximum,
332        minimum_code,
333        maximum_code,
334        zero_code,
335        overflow_code,
336        nodata_code,
337    } = quantization
338    else {
339        return Err(err("the network variable must carry a log1p codebook"));
340    };
341    let byte = |code: f64| code.fract() == 0.0 && (0.0..=255.0).contains(&code);
342    let value_codes = minimum_code..=maximum_code;
343    let reserved = [zero_code, overflow_code, nodata_code];
344    let valid = trace > 0.0
345        && scale > 0.0
346        && maximum > trace
347        && [minimum_code, maximum_code]
348            .into_iter()
349            .chain(reserved)
350            .all(byte)
351        && minimum_code < maximum_code
352        && reserved.iter().all(|code| !value_codes.contains(code))
353        && zero_code != overflow_code
354        && zero_code != nodata_code
355        && overflow_code != nodata_code;
356    if !valid {
357        return Err(err("the network variable's log1p codebook is malformed"));
358    }
359    Ok(VariableMetadata {
360        numeric_id: 1,
361        id: id.to_owned(),
362        label: value
363            .get("label")
364            .and_then(|v| v.as_str())
365            .map(str::to_owned),
366        unit: value
367            .get("unit")
368            .and_then(|v| v.as_str())
369            .map(str::to_owned),
370        quantization,
371    })
372}
373
374// -- data array ----------------------------------------------------------------
375
376/// How the `streamflow` array is cut, held to the group: `[frameCount,
377/// featureCount]` in inner chunks of `[6, rowGroupRows]`, one shard of the
378/// whole array rounded up to whole inner chunks.
379#[derive(Debug, Clone, Copy, PartialEq, Eq)]
380pub struct NetworkLayout {
381    pub frame_count: u32,
382    pub feature_count: u32,
383    pub time_chunk: u32,
384    pub row_group_rows: u32,
385    pub time_chunks: u32,
386    pub feature_chunks: u32,
387    /// Inner chunks in the shard, and pairs in its index.
388    pub chunk_count: u32,
389    pub delta: bool,
390    pub index_location: IndexLocation,
391    pub fill_value: u8,
392}
393
394impl NetworkLayout {
395    /// The shard index's byte length: one pair per inner chunk plus the
396    /// CRC-32C.
397    pub fn index_length(&self) -> usize {
398        zarr::shard_index_length(self.chunk_count as usize)
399    }
400
401    /// Bytes of one decoded inner chunk.
402    pub fn chunk_cells(&self) -> usize {
403        self.time_chunk as usize * self.row_group_rows as usize
404    }
405
406    /// The frames of time chunk `t` that lie on the axis.
407    pub fn frames_in_chunk(&self, time_chunk: u32) -> u32 {
408        self.time_chunk.min(
409            self.frame_count
410                .saturating_sub(time_chunk * self.time_chunk),
411        )
412    }
413
414    /// The reaches of feature chunk `g` that lie inside the network.
415    pub fn features_in_chunk(&self, feature_chunk: u32) -> u32 {
416        self.row_group_rows.min(
417            self.feature_count
418                .saturating_sub(feature_chunk * self.row_group_rows),
419        )
420    }
421
422    /// The index position of inner chunk `[time_chunk, feature_chunk]`.
423    pub fn position(&self, time_chunk: u32, feature_chunk: u32) -> usize {
424        time_chunk as usize * self.feature_chunks as usize + feature_chunk as usize
425    }
426
427    fn predictor(&self) -> Predictor {
428        if self.delta {
429            Predictor::Previous
430        } else {
431            Predictor::Raw
432        }
433    }
434}
435
436/// Parse and validate `streamflow/zarr.json` against its group.
437pub fn parse_network_array(text: &str, group: &NetworkGroup) -> Result<NetworkLayout, DecodeError> {
438    let array = zarr::parse_sharded_array(text, 2)?;
439    let frame_count = group.frame_count();
440    let NetworkGeometry {
441        feature_count,
442        row_group_rows,
443        ..
444    } = group.geometry;
445    if array.shape != [u64::from(frame_count), u64::from(feature_count)] {
446        return Err(err("streamflow shape must be [frameCount, featureCount]"));
447    }
448    let dimensions = array
449        .value
450        .get("dimension_names")
451        .and_then(|v| v.as_array());
452    if dimensions.map(|names| names.iter().map(|n| n.as_str()).collect::<Vec<_>>())
453        != Some(vec![Some("time"), Some("feature")])
454    {
455        return Err(err("streamflow dimension_names must be [time, feature]"));
456    }
457    if array.inner_shape != [u64::from(NETWORK_TIME_CHUNK), u64::from(row_group_rows)] {
458        return Err(err("streamflow inner chunk must be [6, rowGroupRows]"));
459    }
460    let time_chunks = frame_count.div_ceil(NETWORK_TIME_CHUNK);
461    let feature_chunks = feature_count.div_ceil(row_group_rows);
462    let outer = [
463        u64::from(time_chunks) * u64::from(NETWORK_TIME_CHUNK),
464        u64::from(feature_chunks) * u64::from(row_group_rows),
465    ];
466    if array.shard_shape != outer {
467        return Err(err(
468            "streamflow shard must be the whole array in whole inner chunks",
469        ));
470    }
471    let Quantization::Log1p { nodata_code, .. } = group.variable.quantization else {
472        return Err(err("the network variable must carry a log1p codebook"));
473    };
474    if f64::from(array.fill_value) != nodata_code {
475        return Err(err(
476            "streamflow fill_value must be the codebook's nodataCode",
477        ));
478    }
479    let repeated = array
480        .value
481        .get("attributes")
482        .and_then(|v| v.get("xue_network"))
483        .and_then(|v| v.get("variable"));
484    if repeated != Some(&group.variable_json) {
485        return Err(err(
486            "streamflow attributes must repeat the group's variable",
487        ));
488    }
489    let chunk_count = u64::from(time_chunks)
490        .checked_mul(u64::from(feature_chunks))
491        .filter(|&count| count.saturating_mul(16) <= MAX_PLANE_LENGTH)
492        .ok_or_else(|| err("streamflow shard index exceeds the size limit"))?;
493    Ok(NetworkLayout {
494        frame_count,
495        feature_count,
496        time_chunk: NETWORK_TIME_CHUNK,
497        row_group_rows,
498        time_chunks,
499        feature_chunks,
500        chunk_count: chunk_count as u32,
501        delta: array.delta,
502        index_location: array.index_location,
503        // A uint8 array (`sharded_array`), so the fill fits a byte.
504        fill_value: array.fill_value as u8,
505    })
506}
507
508/// The `streamflow` document a group carries inline in its consolidated
509/// metadata, as JSON, or `None` where it carries none and the document is the
510/// store's own `streamflow/zarr.json`. A reader holds it to the group with
511/// [`parse_network_array`] like the standalone one. Serialized here rather
512/// than by the caller so its numbers keep the spelling the group gives them:
513/// the array repeats the group's variable, and `1.0` re-written as `1` would
514/// no longer be the same document.
515pub fn consolidated_network_array(group_text: &str) -> Result<Option<String>, DecodeError> {
516    let group: Value =
517        serde_json::from_str(group_text).map_err(|_| err("group metadata is not valid JSON"))?;
518    let Some(array) = group
519        .get("consolidated_metadata")
520        .and_then(|v| v.get("metadata"))
521        .and_then(|v| v.get(NETWORK_ARRAY))
522    else {
523        return Ok(None);
524    };
525    serde_json::to_string(array)
526        .map(Some)
527        .map_err(|_| err("consolidated streamflow document is not serializable"))
528}
529
530// -- shard ---------------------------------------------------------------------
531
532/// The index's span within a shard of `shard_length` bytes, `[start, end)`.
533pub fn index_span(layout: &NetworkLayout, shard_length: u64) -> Result<(u64, u64), DecodeError> {
534    let length = layout.index_length() as u64;
535    if shard_length < length {
536        return Err(err("shard is shorter than its index"));
537    }
538    Ok(match layout.index_location {
539        IndexLocation::Start => (0, length),
540        IndexLocation::End => (shard_length - length, shard_length),
541    })
542}
543
544/// Read the shard index out of the whole shard, CRC-32C verified, every
545/// written chunk lying inside the shard and outside the index.
546pub fn read_network_index(
547    layout: &NetworkLayout,
548    shard: &[u8],
549) -> Result<Vec<Option<ShardIndexEntry>>, DecodeError> {
550    let (start, end) = index_span(layout, shard.len() as u64)?;
551    let index = parse_network_index(layout, &shard[start as usize..end as usize])?;
552    for entry in index.iter().flatten() {
553        let chunk_end = entry
554            .offset
555            .checked_add(entry.length)
556            .ok_or_else(|| err("shard index entry overflows"))?;
557        if chunk_end > shard.len() as u64 || (entry.offset < end && chunk_end > start) {
558            return Err(err("shard index names bytes outside the shard's data"));
559        }
560    }
561    Ok(index)
562}
563
564/// Parse the index bytes alone (a suffix range, or the shard's head), CRC-32C
565/// verified. Spans are checked against the bytes when chunks are read.
566pub fn parse_network_index(
567    layout: &NetworkLayout,
568    bytes: &[u8],
569) -> Result<Vec<Option<ShardIndexEntry>>, DecodeError> {
570    zarr::parse_shard_index(bytes, layout.chunk_count as usize)
571}
572
573/// The byte span `[start, end)` of the shard holding every written chunk of
574/// one frame's time chunk — one range per frame — or `None` when none of them
575/// was written.
576pub fn frame_range(
577    layout: &NetworkLayout,
578    index: &[Option<ShardIndexEntry>],
579    frame: u32,
580) -> Result<Option<(u64, u64)>, DecodeError> {
581    check_index(layout, index)?;
582    if frame >= layout.frame_count {
583        return Err(err("frame is outside the axis"));
584    }
585    let time_chunk = frame / layout.time_chunk;
586    let mut span: Option<(u64, u64)> = None;
587    for group in 0..layout.feature_chunks {
588        if let Some(entry) = index[layout.position(time_chunk, group)] {
589            let end = entry
590                .offset
591                .checked_add(entry.length)
592                .ok_or_else(|| err("shard index entry overflows"))?;
593            span = Some(match span {
594                None => (entry.offset, end),
595                Some((lo, hi)) => (lo.min(entry.offset), hi.max(end)),
596            });
597        }
598    }
599    Ok(span)
600}
601
602/// The chunk spans one reach's series reads: one per time chunk, `None` for a
603/// chunk the shard never held.
604pub fn series_ranges(
605    layout: &NetworkLayout,
606    index: &[Option<ShardIndexEntry>],
607    feature: u32,
608) -> Result<Vec<Option<ShardIndexEntry>>, DecodeError> {
609    check_index(layout, index)?;
610    if feature >= layout.feature_count {
611        return Err(err("feature is outside the network"));
612    }
613    let group = feature / layout.row_group_rows;
614    Ok((0..layout.time_chunks)
615        .map(|chunk| index[layout.position(chunk, group)])
616        .collect())
617}
618
619fn check_index(
620    layout: &NetworkLayout,
621    index: &[Option<ShardIndexEntry>],
622) -> Result<(), DecodeError> {
623    if index.len() != layout.chunk_count as usize {
624        return Err(err("shard index does not match the array's chunk grid"));
625    }
626    Ok(())
627}
628
629/// One inner chunk's compressed bytes out of `data`, which holds the shard's
630/// bytes from `data_offset` on (the whole shard at 0, or one fetched range).
631fn chunk_bytes(
632    data: &[u8],
633    data_offset: u64,
634    entry: ShardIndexEntry,
635) -> Result<&[u8], DecodeError> {
636    let start = entry
637        .offset
638        .checked_sub(data_offset)
639        .ok_or_else(|| err("chunk lies before the bytes given"))?;
640    let end = start
641        .checked_add(entry.length)
642        .filter(|&end| end <= data.len() as u64)
643        .ok_or_else(|| err("chunk lies past the bytes given"))?;
644    Ok(&data[start as usize..end as usize])
645}
646
647/// Decode one inner chunk to its `6 × rowGroupRows` codes, frame-major, the
648/// delta replayed along the frame axis. A never-written chunk is all fill.
649pub fn decode_network_chunk(
650    layout: &NetworkLayout,
651    entry: Option<ShardIndexEntry>,
652    data: &[u8],
653    data_offset: u64,
654) -> Result<Vec<u8>, DecodeError> {
655    match entry {
656        None => Ok(vec![layout.fill_value; layout.chunk_cells()]),
657        Some(entry) => crate::decode_chunk(
658            chunk_bytes(data, data_offset, entry)?,
659            layout.time_chunk,
660            1,
661            layout.row_group_rows,
662            layout.predictor(),
663        ),
664    }
665}
666
667/// Every frame of one time chunk that lies on the axis, `frames × featureCount`
668/// codes, frame-major, padding trimmed: every row group of the chunk decoded
669/// once.
670pub fn decode_time_chunk(
671    layout: &NetworkLayout,
672    index: &[Option<ShardIndexEntry>],
673    time_chunk: u32,
674    data: &[u8],
675    data_offset: u64,
676) -> Result<Vec<u8>, DecodeError> {
677    check_index(layout, index)?;
678    if time_chunk >= layout.time_chunks {
679        return Err(err("time chunk is outside the axis"));
680    }
681    let frames = layout.frames_in_chunk(time_chunk) as usize;
682    let features = layout.feature_count as usize;
683    let rows = layout.row_group_rows as usize;
684    let mut out = vec![layout.fill_value; frames * features];
685    for group in 0..layout.feature_chunks {
686        let chunk = decode_network_chunk(
687            layout,
688            index[layout.position(time_chunk, group)],
689            data,
690            data_offset,
691        )?;
692        let first = group as usize * rows;
693        let width = layout.features_in_chunk(group) as usize;
694        for frame in 0..frames {
695            out[frame * features + first..][..width]
696                .copy_from_slice(&chunk[frame * rows..][..width]);
697        }
698    }
699    Ok(out)
700}
701
702/// One frame's codes, one per reach in GeoParquet row order.
703pub fn decode_network_frame(
704    layout: &NetworkLayout,
705    index: &[Option<ShardIndexEntry>],
706    frame: u32,
707    data: &[u8],
708    data_offset: u64,
709) -> Result<Vec<u8>, DecodeError> {
710    if frame >= layout.frame_count {
711        return Err(err("frame is outside the axis"));
712    }
713    let time_chunk = frame / layout.time_chunk;
714    let within = (frame % layout.time_chunk) as usize;
715    let features = layout.feature_count as usize;
716    let codes = decode_time_chunk(layout, index, time_chunk, data, data_offset)?;
717    Ok(codes[within * features..][..features].to_vec())
718}
719
720/// One reach's codes over the whole axis: one inner chunk per time chunk.
721pub fn decode_network_series(
722    layout: &NetworkLayout,
723    index: &[Option<ShardIndexEntry>],
724    feature: u32,
725    data: &[u8],
726    data_offset: u64,
727) -> Result<Vec<u8>, DecodeError> {
728    let entries = series_ranges(layout, index, feature)?;
729    let column = (feature % layout.row_group_rows) as usize;
730    let rows = layout.row_group_rows as usize;
731    let mut out = Vec::with_capacity(layout.frame_count as usize);
732    for (chunk, entry) in entries.into_iter().enumerate() {
733        let codes = decode_network_chunk(layout, entry, data, data_offset)?;
734        for frame in 0..layout.frames_in_chunk(chunk as u32) as usize {
735            out.push(codes[frame * rows + column]);
736        }
737    }
738    Ok(out)
739}
740
741/// Codes → m³/s through the variable's codebook; `NaN` for no value. Code 0
742/// is no flow, and the overflow code reads as a flow above the codebook's
743/// maximum.
744pub fn dequantize(quantization: &Quantization, codes: &[u8]) -> Vec<f64> {
745    codes
746        .iter()
747        .map(|&code| decode_value(quantization, u16::from(code)).unwrap_or(f64::NAN))
748        .collect()
749}
750
751// -- side arrays ---------------------------------------------------------------
752
753/// A side array's `zarr.json`: one dimension of `length`, one chunk, the
754/// `bytes` codec little-endian, the named dtype and dimension.
755pub fn parse_side_array(
756    text: &str,
757    data_type: &str,
758    dimension: &str,
759    length: u32,
760) -> Result<(), DecodeError> {
761    let value: Value =
762        serde_json::from_str(text).map_err(|_| err("side array metadata is not valid JSON"))?;
763    let length = Value::from(vec![length]);
764    let ok = value.get("zarr_format").and_then(|v| v.as_u64()) == Some(3)
765        && value.get("node_type").and_then(|v| v.as_str()) == Some("array")
766        && value.get("data_type").and_then(|v| v.as_str()) == Some(data_type)
767        && value.get("shape") == Some(&length)
768        && value
769            .get("chunk_grid")
770            .and_then(|v| v.get("name"))
771            .and_then(|v| v.as_str())
772            == Some("regular")
773        && value
774            .get("chunk_grid")
775            .and_then(|v| v.get("configuration"))
776            .and_then(|v| v.get("chunk_shape"))
777            == Some(&length)
778        && value.get("dimension_names") == Some(&Value::from(vec![dimension]))
779        && value
780            .get("codecs")
781            .and_then(|v| v.as_array())
782            .is_some_and(|codecs| {
783                codecs.len() == 1
784                    && codecs[0].get("name").and_then(|v| v.as_str()) == Some("bytes")
785                    && codecs[0]
786                        .get("configuration")
787                        .and_then(|v| v.get("endian"))
788                        .and_then(|v| v.as_str())
789                        .unwrap_or("little")
790                        == "little"
791            });
792    if ok {
793        Ok(())
794    } else {
795        Err(err(format!(
796            "side array must be one {data_type} chunk of [{dimension}] under [bytes]"
797        )))
798    }
799}
800
801fn exact_length(bytes: &[u8], count: u32, width: usize, what: &str) -> Result<(), DecodeError> {
802    if bytes.len() as u64 != u64::from(count) * width as u64 {
803        return Err(err(format!(
804            "{what} holds {} bytes, not {count} values",
805            bytes.len()
806        )));
807    }
808    Ok(())
809}
810
811/// `feature_id/c/0`: each reach's identifier in its source, in row order.
812pub fn read_feature_ids(layout: &NetworkLayout, bytes: &[u8]) -> Result<Vec<i64>, DecodeError> {
813    exact_length(bytes, layout.feature_count, 8, "feature_id")?;
814    Ok(bytes
815        .as_chunks::<8>()
816        .0
817        .iter()
818        .map(|&value| i64::from_le_bytes(value))
819        .collect())
820}
821
822/// `time/c/0`: each frame's valid time in Unix seconds, which must be the
823/// time the group's block gives it.
824pub fn read_frame_times(group: &NetworkGroup, bytes: &[u8]) -> Result<Vec<i64>, DecodeError> {
825    exact_length(bytes, group.frame_count(), 8, "time")?;
826    let times: Vec<i64> = bytes
827        .as_chunks::<8>()
828        .0
829        .iter()
830        .map(|&value| i64::from_le_bytes(value))
831        .collect();
832    if times != group.frame_times() {
833        return Err(err("time array disagrees with the group's time block"));
834    }
835    Ok(times)
836}
837
838/// `baseflow/c/0`: each reach's usual flow before the event, m³/s; `NaN`
839/// where unknown.
840pub fn read_baseflow(layout: &NetworkLayout, bytes: &[u8]) -> Result<Vec<f32>, DecodeError> {
841    exact_length(bytes, layout.feature_count, 4, "baseflow")?;
842    Ok(bytes
843        .as_chunks::<4>()
844        .0
845        .iter()
846        .map(|&value| f32::from_le_bytes(value))
847        .collect())
848}
849
850#[cfg(test)]
851mod tests {
852    use super::*;
853    use serde_json::json;
854
855    fn group_document(edit: impl FnOnce(&mut Value)) -> String {
856        let mut document = json!({
857            "zarr_format": 3, "node_type": "group",
858            "attributes": {"xue_network": {
859                "version": 1, "model": "NWM v3.0", "product": "short_range",
860                "runTime": "2025-07-04T00:00:00Z",
861                "time": {"unitSeconds": 3600, "firstFrameOffset": 1, "frameCount": 8, "frameStep": 1},
862                "geometry": {"path": "reaches.parquet", "byteLength": 35, "crc32": "0123abcd",
863                             "featureCount": 20, "rowGroupRows": 8},
864                "variables": [{"numericId": 1, "id": "streamflow", "label": "Streamflow", "unit": "m3/s",
865                               "quantization": {"type": "log1p", "trace": 0.01, "scale": 1.0, "maximum": 100000.0,
866                                                "minimumCode": 1, "maximumCode": 253, "zeroCode": 0,
867                                                "overflowCode": 254, "nodataCode": 255}}]
868            }}
869        });
870        edit(&mut document);
871        document.to_string()
872    }
873
874    fn array_document(edit: impl FnOnce(&mut Value)) -> String {
875        let group: Value = serde_json::from_str(&group_document(|_| {})).unwrap();
876        let variable = group["attributes"]["xue_network"]["variables"][0].clone();
877        let mut document = json!({
878            "zarr_format": 3, "node_type": "array", "shape": [8, 20], "data_type": "uint8",
879            "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [12, 24]}},
880            "chunk_key_encoding": {"name": "default"}, "fill_value": 255,
881            "codecs": [{"name": "sharding_indexed", "configuration": {
882                "chunk_shape": [6, 8],
883                "codecs": [{"name": "xue.delta", "configuration": {"axis": 0}}, {"name": "bytes"},
884                           {"name": "zstd", "configuration": {"level": 15, "checksum": true}}],
885                "index_codecs": [{"name": "bytes", "configuration": {"endian": "little"}}, {"name": "crc32c"}],
886                "index_location": "end"}}],
887            "attributes": {"xue_network": {"variable": variable}, "_FillValue": 255},
888            "dimension_names": ["time", "feature"]
889        });
890        edit(&mut document);
891        document.to_string()
892    }
893
894    #[test]
895    fn reads_the_block_and_the_layout() {
896        let group = parse_network_group(&group_document(|_| {})).unwrap();
897        assert_eq!(group.model, "NWM v3.0");
898        assert_eq!(group.offsets, (1..=8).collect::<Vec<u16>>());
899        assert_eq!(group.frame_times()[0], 1_751_590_800);
900        assert_eq!(group.geometry.row_group_rows, 8);
901        let layout = parse_network_array(&array_document(|_| {}), &group).unwrap();
902        assert_eq!(layout.time_chunks, 2);
903        assert_eq!(layout.feature_chunks, 3);
904        assert_eq!(layout.chunk_count, 6);
905        assert_eq!(layout.frames_in_chunk(1), 2);
906        assert_eq!(layout.features_in_chunk(2), 4);
907        assert!(layout.delta);
908        assert_eq!(layout.index_length(), 100);
909    }
910
911    #[test]
912    fn reads_the_array_a_group_carries_inline() {
913        let plain = group_document(|_| {});
914        assert_eq!(consolidated_network_array(&plain).unwrap(), None);
915        let array: Value = serde_json::from_str(&array_document(|_| {})).unwrap();
916        let inline = group_document(|d| {
917            d["consolidated_metadata"] = json!({"kind": "inline", "must_understand": false, "metadata": {"streamflow": array}});
918        });
919        let text = consolidated_network_array(&inline)
920            .unwrap()
921            .expect("the group carries the array");
922        let group = parse_network_group(&inline).unwrap();
923        // The codebook's `1.0` and `100000.0` come back as written, so the
924        // array still repeats the group's variable.
925        assert!(text.contains(r#""scale":1.0"#));
926        assert_eq!(
927            parse_network_array(&text, &group).unwrap(),
928            parse_network_array(&array_document(|_| {}), &group).unwrap()
929        );
930        // Written the way a JavaScript caller would re-serialize it, it is
931        // another document.
932        let rewritten = text.replace(r#""scale":1.0"#, r#""scale":1"#);
933        assert!(parse_network_array(&rewritten, &group).is_err());
934        // Consolidated metadata without the data array says nothing.
935        let other = group_document(|d| {
936            d["consolidated_metadata"] = json!({"kind": "inline", "metadata": {"time": {}}});
937        });
938        assert_eq!(consolidated_network_array(&other).unwrap(), None);
939        assert!(consolidated_network_array("{").is_err());
940    }
941
942    #[test]
943    fn tells_the_branches_apart() {
944        assert_eq!(
945            zarr::store_kind(&group_document(|_| {})).unwrap(),
946            StoreKind::Network
947        );
948        assert!(zarr::parse_group_metadata(&group_document(|_| {})).is_err());
949        for other in ["xue", "xue_polar"] {
950            let text = group_document(|d| d["attributes"][other] = json!({"version": 1}));
951            assert!(zarr::store_kind(&text).is_err());
952            assert!(parse_network_group(&text).is_err());
953        }
954        let polar = json!({"zarr_format": 3, "node_type": "group",
955                           "attributes": {"xue_polar": {"version": 1}}});
956        assert_eq!(
957            zarr::store_kind(&polar.to_string()).unwrap(),
958            StoreKind::Polar
959        );
960        assert!(parse_network_group(&polar.to_string()).is_err());
961    }
962
963    #[test]
964    fn rejects_malformed_groups() {
965        let edits: Vec<fn(&mut Value)> = vec![
966            |d| d["attributes"]["xue_network"]["version"] = json!(2),
967            |d| d["attributes"]["xue_network"]["model"] = json!(""),
968            |d| d["attributes"]["xue_network"]["runTime"] = json!("yesterday"),
969            |d| {
970                d["attributes"]["xue_network"]["time"]["frameOffsets"] =
971                    json!([1, 2, 3, 4, 5, 6, 7, 8]);
972            },
973            |d| d["attributes"]["xue_network"]["time"]["unitSeconds"] = json!(7),
974            |d| {
975                // Offsets 2, 4, … in half hours are whole hours: the unit is finer than it needs.
976                let time = &mut d["attributes"]["xue_network"]["time"];
977                time["unitSeconds"] = json!(1800);
978                time["firstFrameOffset"] = json!(2);
979                time["frameStep"] = json!(2);
980            },
981            |d| d["attributes"]["xue_network"]["time"]["frameCount"] = json!(0),
982            |d| d["attributes"]["xue_network"]["time"]["hours"] = json!([1]),
983            |d| {
984                let time = &mut d["attributes"]["xue_network"]["time"];
985                time.as_object_mut().unwrap().remove("frameStep");
986                time["frameOffsets"] = json!([1, 2, 3, 4, 5, 6, 7, 8]);
987            },
988            |d| {
989                let time = &mut d["attributes"]["xue_network"]["time"];
990                time.as_object_mut().unwrap().remove("frameStep");
991                time["frameOffsets"] = json!([1, 2, 2, 4, 5, 6, 7, 9]);
992            },
993            |d| d["attributes"]["xue_network"]["geometry"]["extra"] = json!(1),
994            |d| d["attributes"]["xue_network"]["geometry"]["path"] = json!("../reaches.parquet"),
995            |d| d["attributes"]["xue_network"]["geometry"]["crc32"] = json!("XYZ"),
996            |d| d["attributes"]["xue_network"]["geometry"]["featureCount"] = json!(0),
997            |d| d["attributes"]["xue_network"]["geometry"]["rowGroupRows"] = json!(0),
998            |d| d["attributes"]["xue_network"]["geometry"]["featureCount"] = json!(1u64 << 40),
999            |d| d["attributes"]["xue_network"]["variables"] = json!([]),
1000            |d| d["attributes"]["xue_network"]["variables"][0]["id"] = json!("discharge"),
1001            |d| {
1002                d["attributes"]["xue_network"]["variables"][0]["quantization"]["type"] =
1003                    json!("linear")
1004            },
1005            |d| {
1006                d["attributes"]["xue_network"]["variables"][0]["quantization"]["nodataCode"] =
1007                    json!(100)
1008            },
1009        ];
1010        for (position, edit) in edits.into_iter().enumerate() {
1011            assert!(
1012                parse_network_group(&group_document(edit)).is_err(),
1013                "edit {position} was accepted"
1014            );
1015        }
1016        let listed = group_document(|d| {
1017            let time = &mut d["attributes"]["xue_network"]["time"];
1018            time.as_object_mut().unwrap().remove("frameStep");
1019            time["frameOffsets"] = json!([1, 2, 3, 4, 5, 6, 7, 9]);
1020        });
1021        assert_eq!(parse_network_group(&listed).unwrap().offsets[7], 9);
1022    }
1023
1024    #[test]
1025    fn rejects_malformed_arrays() {
1026        let group = parse_network_group(&group_document(|_| {})).unwrap();
1027        let edits: Vec<fn(&mut Value)> = vec![
1028            |d| d["data_type"] = json!("int16"),
1029            |d| d["shape"] = json!([8, 21]),
1030            |d| d["shape"] = json!([8, 20, 1]),
1031            |d| d["dimension_names"] = json!(["feature", "time"]),
1032            |d| {
1033                d.as_object_mut().unwrap().remove("dimension_names");
1034            },
1035            |d| d["codecs"] = json!([{"name": "bytes"}, {"name": "zstd"}]),
1036            |d| d["codecs"][0]["configuration"]["chunk_shape"] = json!([6, 16]),
1037            |d| d["codecs"][0]["configuration"]["chunk_shape"] = json!([3, 8]),
1038            |d| d["chunk_grid"]["configuration"]["chunk_shape"] = json!([8, 20]),
1039            |d| d["chunk_grid"]["configuration"]["chunk_shape"] = json!([6, 24]),
1040            |d| d["codecs"][0]["configuration"]["index_codecs"] = json!([{"name": "bytes"}]),
1041            |d| {
1042                d["codecs"][0]["configuration"]["index_codecs"][0]["configuration"]["endian"] =
1043                    json!("big");
1044            },
1045            |d| d["codecs"][0]["configuration"]["index_location"] = json!("middle"),
1046            |d| d["fill_value"] = json!(0),
1047            |d| {
1048                d["codecs"][0]["configuration"]["codecs"] = json!([{"name": "xue.delta", "configuration": {"axis": 1}}, {"name": "bytes"}, {"name": "zstd"}]);
1049            },
1050            |d| {
1051                d["codecs"][0]["configuration"]["codecs"] =
1052                    json!([{"name": "bytes"}, {"name": "gzip"}])
1053            },
1054            |d| d["attributes"] = json!({}),
1055        ];
1056        for (position, edit) in edits.into_iter().enumerate() {
1057            assert!(
1058                parse_network_array(&array_document(edit), &group).is_err(),
1059                "edit {position} was accepted"
1060            );
1061        }
1062        let plain = parse_network_array(
1063            &array_document(|d| {
1064                d["codecs"][0]["configuration"]["codecs"] =
1065                    json!([{"name": "bytes"}, {"name": "zstd"}]);
1066                d["codecs"][0]["configuration"]["index_location"] = json!("start");
1067            }),
1068            &group,
1069        )
1070        .unwrap();
1071        assert!(!plain.delta);
1072        assert_eq!(plain.index_location, IndexLocation::Start);
1073    }
1074
1075    #[test]
1076    fn side_arrays_are_held_to_their_length() {
1077        let group = parse_network_group(&group_document(|_| {})).unwrap();
1078        let layout = parse_network_array(&array_document(|_| {}), &group).unwrap();
1079        assert!(read_feature_ids(&layout, &[0u8; 159]).is_err());
1080        assert!(read_baseflow(&layout, &[0u8; 80]).is_ok());
1081        let mut times = Vec::new();
1082        for time in group.frame_times() {
1083            times.extend_from_slice(&time.to_le_bytes());
1084        }
1085        assert_eq!(read_frame_times(&group, &times).unwrap().len(), 8);
1086        times[0] ^= 1;
1087        assert!(read_frame_times(&group, &times).is_err());
1088        let side = json!({"zarr_format": 3, "node_type": "array", "shape": [20], "data_type": "int64",
1089            "chunk_grid": {"name": "regular", "configuration": {"chunk_shape": [20]}},
1090            "chunk_key_encoding": {"name": "default"}, "fill_value": 0,
1091            "codecs": [{"name": "bytes", "configuration": {"endian": "little"}}],
1092            "attributes": {}, "dimension_names": ["feature"]});
1093        assert!(parse_side_array(&side.to_string(), "int64", "feature", 20).is_ok());
1094        assert!(parse_side_array(&side.to_string(), "int64", "feature", 21).is_err());
1095        assert!(parse_side_array(&side.to_string(), "float32", "feature", 20).is_err());
1096    }
1097}