river_data_core/models/backend.rs
1use chrono::{DateTime, Utc};
2use uuid::Uuid;
3
4use crate::models::annotations::AnnotationUpsert;
5use crate::models::replicates::{GroupAudit, ReplicateSpec};
6use crate::models::streams::{IngestReading, IngestStatusEvent};
7
8/// Describes a data stream to register with river-data.
9#[derive(Debug, Clone)]
10pub struct StreamDescriptor {
11 /// Unique key within the source system (ie. a location id or column name).
12 pub source_key: String,
13 /// Human-readable name shown in the dashboard.
14 pub source_name: String,
15 /// Hierarchy path (ie. "cnet/VAD/WTW_DO_mgL_1"), parsed server-side for site discovery.
16 pub source_path: String,
17 pub metadata: serde_json::Value,
18 /// Stream classification ('spot' or 'continuous'); None defers to the API's resolution chain.
19 pub measurement_type: Option<String>,
20 /// Owning sensor; required for streams whose readings carry curve claims.
21 pub sensor_id: Option<Uuid>,
22 /// Replicate-family declaration; requires `measurement_type: "spot"`.
23 pub replicates: Option<ReplicateSpec>,
24 /// The decimal places the source stores or presents this channel at. Pairing writes it onto
25 /// the slot where none is declared, and the public API expresses served values at it. None
26 /// leaves the slot undeclared, which is served unrounded.
27 pub decimal_places: Option<i16>,
28}
29
30/// Asks a backend for readings for one stream since a cursor.
31#[derive(Debug, Clone)]
32pub struct StreamFetchRequest {
33 pub stream_id: Uuid,
34 pub source_key: String,
35 /// Last known reading time. None on a new stream or a full sync.
36 pub since: Option<DateTime<Utc>>,
37}
38
39/// A completeness claim over one stream: the readings sent alongside are the COMPLETE content of
40/// the source for this stream over `[from, to)`, read from `source_rows_read` source rows. The
41/// server diffs stored content against the payload and converges (new / changed / withdrawn);
42/// without a window the request is a bare append, exactly the old semantics.
43#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
44#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
45#[serde(deny_unknown_fields)]
46pub struct SourceWindow {
47 pub from: DateTime<Utc>,
48 pub to: DateTime<Utc>,
49 /// Source rows scanned to produce the payload. An empty payload over a window the store holds
50 /// readings for is refused server-side, so a decode failure cannot read as a source deletion.
51 pub source_rows_read: u64,
52 /// Instants the backend saw but could not carry (cell decode failures). The server retains
53 /// stored rows at these keys rather than withdrawing them.
54 #[serde(default, skip_serializing_if = "Vec::is_empty")]
55 pub dropped_times: Vec<DateTime<Utc>>,
56 /// Digest of the canonical payload, stamped by the driver before send. The server persists
57 /// it on a cleanly-applied pass and echoes it on the stream list, so the next cycle can skip
58 /// re-sending unchanged content. Opaque to the server; never computed server-side.
59 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub content_digest: Option<String>,
61}
62
63/// Readings fetched for one stream, ready to ingest.
64#[derive(Debug)]
65pub struct StreamReadings {
66 pub stream_id: Uuid,
67 pub source_key: String,
68 pub readings: Vec<IngestReading>,
69 /// Portal-precomputed mean/sd per replicate group, for server-side comparison.
70 pub audits: Vec<GroupAudit>,
71 /// Marks the readings as replicate collections; the API groups them per instant.
72 pub collection: bool,
73 /// The completeness claim, when this fetch read the source's full content for the stream.
74 pub window: Option<SourceWindow>,
75 /// Source-authored annotations riding this stream's payload (e.g. the standard curve the
76 /// source applied while producing a stored value). The driver registers them after the
77 /// stream's readings ingest; idempotent per (source_system, source_key).
78 pub annotations: Vec<AnnotationUpsert>,
79}
80
81impl StreamReadings {
82 /// Plain single-series readings: no audits, not a collection, no completeness claim.
83 pub fn new(stream_id: Uuid, source_key: String, readings: Vec<IngestReading>) -> Self {
84 Self {
85 stream_id,
86 source_key,
87 readings,
88 audits: Vec::new(),
89 collection: false,
90 window: None,
91 annotations: Vec::new(),
92 }
93 }
94}
95
96/// Status events fetched for one stream.
97#[derive(Debug)]
98pub struct StreamStatusEvents {
99 pub stream_id: Uuid,
100 pub source_key: String,
101 pub events: Vec<IngestStatusEvent>,
102}
103
104/// Everything the source holds that could become a stream, whether or not the connector takes it.
105///
106/// `discover_streams` reports what a connector accepted, so a column it declined and a group it has
107/// not discovered yet are invisible to every downstream check: no completeness window covers them,
108/// no receipt names them, and reconciliation cannot speak about them at all. This is what a sign-off
109/// against a retiring source has to read.
110///
111/// Taken channels are listed per group because that is the question being asked (is this station,
112/// whole, here); declined channels are listed once, source-wide, because a source declines a
113/// channel by its own rules and not per group.
114#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
115pub struct SourceInventory {
116 /// One entry per channel the connector carries, keyed as it registers.
117 pub candidates: Vec<SourceCandidate>,
118 /// Channels the source holds and the connector does not carry, with the connector's reason.
119 #[serde(default)]
120 pub declined: Vec<DeclinedChannel>,
121 /// Every group the source holds, so one with no channel at all is still named.
122 #[serde(default)]
123 pub groups: Vec<String>,
124 /// The source's own instrument register, where it keeps one. These are instruments no stream
125 /// mints: a portal's `sensor_inventory` is the answer to which probe, which serial, installed
126 /// when, and it goes with the portal unless it is admitted here.
127 #[serde(default)]
128 pub instruments: Vec<crate::models::SensorUpsert>,
129}
130
131/// One channel the connector carries.
132#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
133pub struct SourceCandidate {
134 /// The key it registers under.
135 pub source_key: String,
136 /// The source's own grouping: the station, the location, whatever a report is read by.
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub group: Option<String>,
139}
140
141/// One channel the connector leaves behind, and why.
142#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
143pub struct DeclinedChannel {
144 /// The source's own name for it: a column, a location id.
145 pub channel: String,
146 pub reason: String,
147}
148
149impl SourceInventory {
150 /// The inventory a backend that declines nothing has: every descriptor it discovered.
151 #[must_use]
152 pub fn of_discovered(descriptors: &[StreamDescriptor]) -> Self {
153 let candidates: Vec<SourceCandidate> = descriptors
154 .iter()
155 .map(|d| SourceCandidate {
156 source_key: d.source_key.clone(),
157 group: d.source_path.split('/').nth(1).map(ToString::to_string),
158 })
159 .collect();
160 let mut groups: Vec<String> = candidates
161 .iter()
162 .filter_map(|c| c.group.clone())
163 .collect::<std::collections::BTreeSet<_>>()
164 .into_iter()
165 .collect();
166 groups.sort();
167 Self {
168 candidates,
169 declined: Vec::new(),
170 groups,
171 instruments: Vec::new(),
172 }
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 /// The completeness claim round-trips: the API echoes it back as `accepted_window` and the
181 /// client treats a missing echo as a hard error, so both sides read one shape.
182 #[test]
183 fn source_window_round_trips() {
184 let w = SourceWindow {
185 from: Utc::now(),
186 to: Utc::now(),
187 source_rows_read: 500,
188 dropped_times: vec![Utc::now()],
189 content_digest: Some("fnv:1".into()),
190 };
191 let back: SourceWindow = serde_json::from_value(serde_json::to_value(&w).unwrap()).unwrap();
192 assert_eq!(back.source_rows_read, 500);
193 assert_eq!(back.dropped_times.len(), 1);
194 assert_eq!(back.content_digest.as_deref(), Some("fnv:1"));
195 }
196}