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))]
45pub struct SourceWindow {
46 pub from: DateTime<Utc>,
47 pub to: DateTime<Utc>,
48 /// Source rows scanned to produce the payload. An empty payload over a window the store holds
49 /// readings for is refused server-side, so a decode failure cannot read as a source deletion.
50 pub source_rows_read: u64,
51 /// Instants the backend saw but could not carry (cell decode failures). The server retains
52 /// stored rows at these keys rather than withdrawing them.
53 #[serde(default, skip_serializing_if = "Vec::is_empty")]
54 pub dropped_times: Vec<DateTime<Utc>>,
55 /// Digest of the canonical payload, stamped by the driver before send. The server persists
56 /// it on a cleanly-applied pass and echoes it on the stream list, so the next cycle can skip
57 /// re-sending unchanged content. Opaque to the server; never computed server-side.
58 #[serde(default, skip_serializing_if = "Option::is_none")]
59 pub content_digest: Option<String>,
60}
61
62/// Readings fetched for one stream, ready to ingest.
63#[derive(Debug)]
64pub struct StreamReadings {
65 pub stream_id: Uuid,
66 pub source_key: String,
67 pub readings: Vec<IngestReading>,
68 /// Portal-precomputed mean/sd per replicate group, for server-side comparison.
69 pub audits: Vec<GroupAudit>,
70 /// Marks the readings as replicate collections; the API groups them per instant.
71 pub collection: bool,
72 /// The completeness claim, when this fetch read the source's full content for the stream.
73 pub window: Option<SourceWindow>,
74 /// Source-authored annotations riding this stream's payload (e.g. the standard curve the
75 /// source applied while producing a stored value). The driver registers them after the
76 /// stream's readings ingest; idempotent per (source_system, source_key).
77 pub annotations: Vec<AnnotationUpsert>,
78}
79
80impl StreamReadings {
81 /// Plain single-series readings: no audits, not a collection, no completeness claim.
82 pub fn new(stream_id: Uuid, source_key: String, readings: Vec<IngestReading>) -> Self {
83 Self {
84 stream_id,
85 source_key,
86 readings,
87 audits: Vec::new(),
88 collection: false,
89 window: None,
90 annotations: Vec::new(),
91 }
92 }
93}
94
95/// Status events fetched for one stream.
96#[derive(Debug)]
97pub struct StreamStatusEvents {
98 pub stream_id: Uuid,
99 pub source_key: String,
100 pub events: Vec<IngestStatusEvent>,
101}
102
103/// Everything the source holds that could become a stream, whether or not the connector takes it.
104///
105/// `discover_streams` reports what a connector accepted, so a column it declined and a group it has
106/// not discovered yet are invisible to every downstream check: no completeness window covers them,
107/// no receipt names them, and reconciliation cannot speak about them at all. This is what a sign-off
108/// against a retiring source has to read.
109///
110/// Taken channels are listed per group because that is the question being asked (is this station,
111/// whole, here); declined channels are listed once, source-wide, because a source declines a
112/// channel by its own rules and not per group.
113#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
114pub struct SourceInventory {
115 /// One entry per channel the connector carries, keyed as it registers.
116 pub candidates: Vec<SourceCandidate>,
117 /// Channels the source holds and the connector does not carry, with the connector's reason.
118 #[serde(default)]
119 pub declined: Vec<DeclinedChannel>,
120 /// Every group the source holds, so one with no channel at all is still named.
121 #[serde(default)]
122 pub groups: Vec<String>,
123}
124
125/// One channel the connector carries.
126#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
127pub struct SourceCandidate {
128 /// The key it registers under.
129 pub source_key: String,
130 /// The source's own grouping: the station, the location, whatever a report is read by.
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub group: Option<String>,
133}
134
135/// One channel the connector leaves behind, and why.
136#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
137pub struct DeclinedChannel {
138 /// The source's own name for it: a column, a location id.
139 pub channel: String,
140 pub reason: String,
141}
142
143impl SourceInventory {
144 /// The inventory a backend that declines nothing has: every descriptor it discovered.
145 #[must_use]
146 pub fn of_discovered(descriptors: &[StreamDescriptor]) -> Self {
147 let candidates: Vec<SourceCandidate> = descriptors
148 .iter()
149 .map(|d| SourceCandidate {
150 source_key: d.source_key.clone(),
151 group: d.source_path.split('/').nth(1).map(ToString::to_string),
152 })
153 .collect();
154 let mut groups: Vec<String> = candidates
155 .iter()
156 .filter_map(|c| c.group.clone())
157 .collect::<std::collections::BTreeSet<_>>()
158 .into_iter()
159 .collect();
160 groups.sort();
161 Self {
162 candidates,
163 declined: Vec::new(),
164 groups,
165 }
166 }
167}
168
169#[cfg(test)]
170mod tests {
171 use super::*;
172
173 /// The completeness claim round-trips: the API echoes it back as `accepted_window` and the
174 /// client treats a missing echo as a hard error, so both sides read one shape.
175 #[test]
176 fn source_window_round_trips() {
177 let w = SourceWindow {
178 from: Utc::now(),
179 to: Utc::now(),
180 source_rows_read: 500,
181 dropped_times: vec![Utc::now()],
182 content_digest: Some("fnv:1".into()),
183 };
184 let back: SourceWindow = serde_json::from_value(serde_json::to_value(&w).unwrap()).unwrap();
185 assert_eq!(back.source_rows_read, 500);
186 assert_eq!(back.dropped_times.len(), 1);
187 assert_eq!(back.content_digest.as_deref(), Some("fnv:1"));
188 }
189}