river-data-core 0.12.0

Client, sync runner, and shared types for the river-data platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
//! The source audit: everything the source holds, against everything registered here.
//!
//! Per-cycle reconciliation can only speak about streams that exist. A channel the connector
//! declined, a group discovered after the last registration pass, and a stream whose key the source
//! no longer offers are outside every completeness window and named on no receipt, so their absence
//! reads as clean. This is the comparison a sign-off against a retiring source rests on, and it is
//! read per group rather than per pass because that is the question being asked: is this station,
//! whole, here.
//!
//! It writes nothing.

use std::collections::{BTreeMap, BTreeSet};

use crate::models::{DataStream, SourceInventory, StandardCurveUpsert};

/// One source's standing against the store.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SourceAuditReport {
    pub source_system: String,
    pub totals: AuditTotals,
    /// One entry per group, ordered by name. A candidate or stream with no group falls under `""`,
    /// so nothing is dropped for lacking one.
    pub groups: Vec<SourceGroupReport>,
    /// Channels the connector does not carry, source-wide: a source declines by its own rules and
    /// not per group, so listing these once is the whole of it.
    pub declined: Vec<crate::models::DeclinedChannel>,
    pub curves: CurveAudit,
}

#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AuditTotals {
    /// Channels the connector carries.
    pub candidates: usize,
    /// Channels the source holds and the connector does not.
    pub declined: usize,
    pub registered: usize,
    /// Candidates with a registered stream: the healthy case.
    pub matched: usize,
    /// Candidates with no stream here, which no window or receipt can report.
    pub unregistered: usize,
    /// Registered streams the connector no longer offers.
    pub orphaned: usize,
    /// Registered streams with no site parameter, whose readings are attributed to nothing.
    pub unpaired: usize,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SourceGroupReport {
    pub name: String,
    pub candidates: usize,
    pub registered: usize,
    pub matched: usize,
    /// Source keys the connector carries and nothing here holds.
    pub unregistered: Vec<String>,
    /// Registered source keys the connector no longer offers.
    pub orphaned: Vec<String>,
    /// Registered source keys with no pairing.
    pub unpaired: Vec<String>,
}

/// Lab curves replicate by `(source_system, source_key)` and nothing else re-compares the two sets.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct CurveAudit {
    pub at_source: usize,
    pub registered: usize,
    /// Source keys the source holds and the store does not.
    pub unregistered: Vec<String>,
    /// Source keys the store holds and the source no longer offers.
    pub orphaned: Vec<String>,
}

/// The group a registered stream belongs to: its hierarchy path's second segment
/// (`{source_system}/{group}/{channel}`), which is how every backend here builds one.
fn stream_group(stream: &DataStream) -> String {
    stream
        .source_path
        .as_deref()
        .and_then(|p| p.split('/').nth(1))
        .unwrap_or_default()
        .to_string()
}

/// Compare one source's inventory and curves against what is registered here.
///
/// `registered_curve_keys` is the store's `(source_system, source_key)` set for this source; an API
/// that cannot list them passes `None`, and the curve arms then report only what the source holds
/// rather than declaring every curve missing.
#[must_use]
pub fn compare(
    source_system: &str,
    inventory: &SourceInventory,
    registered: &[DataStream],
    source_curves: &[StandardCurveUpsert],
    registered_curve_keys: Option<&[String]>,
) -> SourceAuditReport {
    let registered_keys: BTreeSet<&str> =
        registered.iter().map(|s| s.source_key.as_str()).collect();
    let candidate_keys: BTreeSet<&str> = inventory
        .candidates
        .iter()
        .map(|c| c.source_key.as_str())
        .collect();

    let mut groups: BTreeMap<String, SourceGroupReport> = inventory
        .groups
        .iter()
        .map(|g| (g.clone(), SourceGroupReport::empty(g)))
        .collect();

    let mut totals = AuditTotals {
        candidates: inventory.candidates.len(),
        declined: inventory.declined.len(),
        registered: registered.len(),
        ..AuditTotals::default()
    };

    for candidate in &inventory.candidates {
        let name = candidate.group.clone().unwrap_or_default();
        let entry = groups
            .entry(name.clone())
            .or_insert_with(|| SourceGroupReport::empty(&name));
        entry.candidates += 1;
        if registered_keys.contains(candidate.source_key.as_str()) {
            totals.matched += 1;
            entry.matched += 1;
        } else {
            totals.unregistered += 1;
            entry.unregistered.push(candidate.source_key.clone());
        }
    }

    for stream in registered {
        let name = stream_group(stream);
        let entry = groups
            .entry(name.clone())
            .or_insert_with(|| SourceGroupReport::empty(&name));
        entry.registered += 1;
        if !candidate_keys.contains(stream.source_key.as_str()) {
            totals.orphaned += 1;
            entry.orphaned.push(stream.source_key.clone());
        }
        if stream.site_parameter_id.is_none() {
            totals.unpaired += 1;
            entry.unpaired.push(stream.source_key.clone());
        }
    }

    let source_curve_keys: BTreeSet<&str> = source_curves
        .iter()
        .map(|c| c.source_key.as_str())
        .collect();
    let curves = match registered_curve_keys {
        None => CurveAudit {
            at_source: source_curve_keys.len(),
            ..CurveAudit::default()
        },
        Some(stored) => {
            let stored_set: BTreeSet<&str> = stored.iter().map(String::as_str).collect();
            CurveAudit {
                at_source: source_curve_keys.len(),
                registered: stored_set.len(),
                unregistered: source_curve_keys
                    .difference(&stored_set)
                    .map(|k| (*k).to_string())
                    .collect(),
                orphaned: stored_set
                    .difference(&source_curve_keys)
                    .map(|k| (*k).to_string())
                    .collect(),
            }
        }
    };

    let mut declined = inventory.declined.clone();
    declined.sort_by(|a, b| a.channel.cmp(&b.channel));

    SourceAuditReport {
        source_system: source_system.to_string(),
        totals,
        groups: groups
            .into_values()
            .map(|mut group| {
                group.unregistered.sort();
                group.orphaned.sort();
                group.unpaired.sort();
                group
            })
            .collect(),
        declined,
        curves,
    }
}

impl SourceGroupReport {
    fn empty(name: &str) -> Self {
        Self {
            name: name.to_string(),
            candidates: 0,
            registered: 0,
            matched: 0,
            unregistered: Vec::new(),
            orphaned: Vec::new(),
            unpaired: Vec::new(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{CurveAudit, compare};
    use crate::models::{
        DataStream, DeclinedChannel, SourceCandidate, SourceInventory, StandardCurveUpsert,
    };
    use uuid::Uuid;

    fn candidate(key: &str, group: &str) -> SourceCandidate {
        SourceCandidate {
            source_key: key.to_string(),
            group: Some(group.to_string()),
        }
    }

    fn stream(key: &str, group: &str, paired: bool) -> DataStream {
        DataStream {
            id: Uuid::new_v4(),
            source_system: "cnet".to_string(),
            source_key: key.to_string(),
            source_name: None,
            source_path: Some(format!("cnet/{group}/{key}")),
            metadata: serde_json::json!({}),
            site_parameter_id: paired.then(Uuid::new_v4),
            measurement_type: Some(crate::models::MeasurementType::Spot.to_string()),
            is_active: true,
            last_data_time: None,
            last_window_digest: None,
            replicates: None,
        }
    }

    fn curve(key: &str) -> StandardCurveUpsert {
        StandardCurveUpsert {
            source_key: key.to_string(),
            instrument_label: "DOC".to_string(),
            slope: 1.0,
            intercept: 0.0,
            r_squared: None,
            name: None,
            fitted_on: None,
            notes: None,
        }
    }

    fn inventory(candidates: Vec<SourceCandidate>) -> SourceInventory {
        let groups = candidates
            .iter()
            .filter_map(|c| c.group.clone())
            .collect::<std::collections::BTreeSet<_>>()
            .into_iter()
            .collect();
        SourceInventory {
            candidates,
            declined: Vec::new(),
            groups,
            instruments: Vec::new(),
        }
    }

    #[test]
    fn test_compare_matches_a_source_that_is_fully_registered() {
        let report = compare(
            "cnet",
            &inventory(vec![
                candidate("VAD:pH", "VAD"),
                candidate("VAD:DOC", "VAD"),
            ]),
            &[
                stream("VAD:pH", "VAD", true),
                stream("VAD:DOC", "VAD", true),
            ],
            &[],
            Some(&[]),
        );
        assert_eq!(report.totals.matched, 2);
        assert_eq!(report.totals.unregistered, 0);
        assert_eq!(report.totals.orphaned, 0);
        assert_eq!(report.totals.unpaired, 0);
        assert_eq!(report.groups.len(), 1);
        assert_eq!(report.groups[0].name, "VAD");
    }

    /// A station added at the portal after the last registration pass is the case the per-cycle
    /// reconciliation structurally cannot see: no stream, so no window and no receipt.
    #[test]
    fn test_compare_reports_a_candidate_with_no_stream() {
        let report = compare(
            "cnet",
            &inventory(vec![candidate("VAD:pH", "VAD"), candidate("FP3:pH", "FP3")]),
            &[stream("VAD:pH", "VAD", true)],
            &[],
            Some(&[]),
        );
        assert_eq!(report.totals.unregistered, 1);
        let fp3 = report.groups.iter().find(|g| g.name == "FP3").unwrap();
        assert_eq!(fp3.unregistered, vec!["FP3:pH".to_string()]);
        assert_eq!(fp3.matched, 0);
    }

    /// A group the source holds and the connector took nothing from is still named, or a station
    /// whose every column was declined would read as a station that does not exist.
    #[test]
    fn test_compare_names_a_group_with_no_candidates() {
        let mut inv = inventory(vec![candidate("VAD:pH", "VAD")]);
        inv.groups.push("EMPTY".to_string());
        let report = compare("cnet", &inv, &[], &[], Some(&[]));
        let empty = report.groups.iter().find(|g| g.name == "EMPTY").unwrap();
        assert_eq!(empty.candidates, 0);
        assert_eq!(empty.registered, 0);
    }

    #[test]
    fn test_compare_carries_the_declined_channels_source_wide() {
        let mut inv = inventory(vec![candidate("VAD:pH", "VAD")]);
        inv.declined = vec![
            DeclinedChannel {
                channel: "row_id".to_string(),
                reason: "bookkeeping column".to_string(),
            },
            DeclinedChannel {
                channel: "Field_BP".to_string(),
                reason: "not plotted and in no calculation".to_string(),
            },
        ];
        let report = compare("cnet", &inv, &[], &[], Some(&[]));
        assert_eq!(report.totals.declined, 2);
        // Sorted, so two runs of the same source produce the same report.
        assert_eq!(report.declined[0].channel, "Field_BP");
        assert_eq!(report.declined[1].channel, "row_id");
    }

    #[test]
    fn test_compare_reports_an_orphaned_and_an_unpaired_stream() {
        let report = compare(
            "cnet",
            &inventory(vec![candidate("VAD:pH", "VAD")]),
            &[
                stream("VAD:pH", "VAD", false),
                stream("VAD:gone", "VAD", true),
            ],
            &[],
            Some(&[]),
        );
        assert_eq!(report.totals.orphaned, 1);
        assert_eq!(report.totals.unpaired, 1);
        let vad = &report.groups[0];
        assert_eq!(vad.orphaned, vec!["VAD:gone".to_string()]);
        assert_eq!(vad.unpaired, vec!["VAD:pH".to_string()]);
    }

    #[test]
    fn test_compare_reconciles_the_curve_sets_both_ways() {
        let report = compare(
            "cnet",
            &inventory(vec![]),
            &[],
            &[curve("12"), curve("13")],
            Some(&["13".to_string(), "99".to_string()]),
        );
        assert_eq!(
            report.curves,
            CurveAudit {
                at_source: 2,
                registered: 2,
                unregistered: vec!["12".to_string()],
                orphaned: vec!["99".to_string()],
            }
        );
    }

    /// An API that cannot list curves must not report every source curve as missing.
    #[test]
    fn test_compare_reports_no_curve_difference_when_the_store_cannot_be_listed() {
        let report = compare("cnet", &inventory(vec![]), &[], &[curve("12")], None);
        assert_eq!(report.curves.at_source, 1);
        assert!(report.curves.unregistered.is_empty());
        assert!(report.curves.orphaned.is_empty());
    }

    /// A candidate and a stream with no group still have to land somewhere.
    #[test]
    fn test_compare_groups_ungrouped_entries_under_one_empty_name() {
        let inv = SourceInventory {
            candidates: vec![SourceCandidate {
                source_key: "bare".to_string(),
                group: None,
            }],
            declined: Vec::new(),
            groups: Vec::new(),
            instruments: Vec::new(),
        };
        let mut bare = stream("bare", "", true);
        bare.source_path = None;
        let report = compare("cnet", &inv, &[bare], &[], Some(&[]));
        assert_eq!(report.groups.len(), 1);
        assert_eq!(report.groups[0].name, "");
        assert_eq!(report.groups[0].matched, 1);
    }
}