Skip to main content

opcua_kit/client/
history.rs

1//! Bounded forward raw history for one configured measurement.
2
3use super::ua;
4use super::{Client, FixedScalar, ReadError, ReadSession, Sample};
5use crate::NodeId;
6use time::OffsetDateTime;
7use ua::{HistoryReadResponse as Response, ReadRawModifiedDetails as Details};
8
9/// Historical values returned in server order, with the raw per-page operation statuses.
10#[derive(Clone, Debug, PartialEq)]
11pub struct HistoricalRead<T> {
12    /// Samples as reported. Present source clocks are ordered and inside the requested window.
13    pub samples: Vec<Sample<T>>,
14    /// One OPC UA operation status per successful response page.
15    pub page_statuses: Vec<u32>,
16}
17
18/// A raw history request could not be completed.
19#[derive(Debug, thiserror::Error)]
20#[non_exhaustive]
21pub enum HistoryError {
22    /// Time or requested row count is outside the supported bounds.
23    #[error("expected an increasing UTC window on 100 ns boundaries and a limit of 1–4096 samples")]
24    Window,
25    /// Service failure or stale session.
26    #[error(transparent)]
27    Read(#[from] ReadError),
28    /// The server returned a non-Good per-node history operation status.
29    #[error("history operation status 0x{0:08X}")]
30    Status(u32),
31    /// Node result, continuation point or data shape is invalid.
32    #[error("invalid HistoryRead response")]
33    InvalidResponse,
34    /// A returned source time fell outside the window or went backwards.
35    #[error("historical source timestamp outside the requested window or out of order")]
36    InvalidTimestamp,
37    /// More pages or values would be needed than the configured bound.
38    #[error("history exceeds sample or page limit")]
39    Limit,
40}
41
42fn tick(time: OffsetDateTime) -> Result<ua::DateTime, HistoryError> {
43    super::sample::exact_datetime(time).ok_or(HistoryError::Window)
44}
45
46fn result(response: &Response) -> Result<&ua::HistoryReadResult, HistoryError> {
47    match response.results.as_deref() {
48        Some([result]) => Ok(result),
49        _ => Err(HistoryError::InvalidResponse),
50    }
51}
52
53fn cursor(r: &ua::HistoryReadResult) -> Result<&[u8], HistoryError> {
54    let bytes = r.continuation_point.as_ref();
55    if bytes.len() > 65536 {
56        Err(HistoryError::InvalidResponse)
57    } else {
58        Ok(bytes)
59    }
60}
61
62impl Client {
63    async fn history_request(
64        &self,
65        session: &mut ReadSession,
66        node: &ua::NodeId,
67        details: &Details,
68        point: &[u8],
69        release: bool,
70    ) -> Result<Response, HistoryError> {
71        let req = ua::HistoryReadRequest {
72            history_read_details: ua::ExtensionObject::new(details.clone()),
73            timestamps_to_return: ua::TimestampsToReturn::Both,
74            release_continuation_points: release,
75            nodes_to_read: Some(vec![ua::HistoryReadValueId {
76                node_id: node.clone(),
77                continuation_point: point.into(),
78                ..Default::default()
79            }]),
80            ..Default::default()
81        };
82        Ok(self.guarded(session, self.inner.request(req)).await?)
83    }
84
85    /// Read raw historical Boolean or numeric values with both timestamps, without interpolation.
86    /// The server must support raw HistoryRead for the chosen variable. Requests up to 256 values
87    /// per page, 64 pages and 4096 total samples. A truncated interval returns an error.
88    pub async fn read_history<T: FixedScalar>(
89        &self,
90        node: &NodeId,
91        start: OffsetDateTime,
92        end: OffsetDateTime,
93        limit: usize,
94    ) -> Result<HistoricalRead<T>, HistoryError> {
95        if start >= end || !(1..=4096).contains(&limit) {
96            return Err(HistoryError::Window);
97        }
98        let details = Details {
99            start_time: tick(start)?,
100            end_time: tick(end)?,
101            num_values_per_node: (limit + 1).min(256) as u32,
102            ..Default::default()
103        };
104        let (mut session, metadata) = self.read_session().await?;
105        let node = metadata.namespaces.wire_node(node, 0)?;
106        let mut out = HistoricalRead {
107            samples: Vec::new(),
108            page_statuses: Vec::new(),
109        };
110        let mut point = Vec::new();
111        let mut timestamps = SourceWindow {
112            earliest: start.unix_timestamp_nanos() * 100,
113            end: end.unix_timestamp_nanos() * 100,
114        };
115        loop {
116            let response = self
117                .history_request(&mut session, &node, &details, &point, false)
118                .await?;
119            let (r, next) = match result(&response).and_then(|r| Ok((r, cursor(r)?))) {
120                Ok(data) => data,
121                Err(err) => {
122                    session.interrupted = true;
123                    return Err(err);
124                }
125            };
126            point.clear();
127            point.extend_from_slice(next);
128            let appended = append(
129                &mut out,
130                r,
131                limit,
132                details.num_values_per_node as usize,
133                &mut timestamps,
134            );
135            if let Err(err) = appended.and({
136                if !point.is_empty()
137                    && (out.samples.len() == limit || out.page_statuses.len() == 64)
138                {
139                    Err(HistoryError::Limit)
140                } else {
141                    Ok(())
142                }
143            }) {
144                if !point.is_empty() {
145                    let released = self
146                        .history_request(&mut session, &node, &details, &point, true)
147                        .await?;
148                    // An unconfirmed release retires the session so its teardown frees the cursor.
149                    if !result(&released).is_ok_and(|r| {
150                        r.status_code.bits() == 0 && cursor(r).is_ok_and(|p| p.is_empty())
151                    }) {
152                        session.interrupted = true;
153                        return Err(HistoryError::InvalidResponse);
154                    }
155                }
156                return Err(err);
157            }
158            if point.is_empty() {
159                return Ok(out);
160            }
161        }
162    }
163}
164
165// Bounds in 10 ps units. Advancing the lower bound also orders samples across pages.
166struct SourceWindow {
167    earliest: i128,
168    end: i128,
169}
170impl SourceWindow {
171    fn accept(&mut self, clock: super::SampleTimestamp) -> Result<(), HistoryError> {
172        let point =
173            clock.base_unix_nanos * 100 + i128::from(clock.ten_picoseconds.unwrap_or(0).min(9999));
174        if !(self.earliest..=self.end).contains(&point) {
175            return Err(HistoryError::InvalidTimestamp);
176        }
177        self.earliest = point;
178        Ok(())
179    }
180}
181fn append<T: FixedScalar>(
182    out: &mut HistoricalRead<T>,
183    r: &ua::HistoryReadResult,
184    limit: usize,
185    page_size: usize,
186    timestamps: &mut SourceWindow,
187) -> Result<(), HistoryError> {
188    if r.status_code.bits() >> 30 != 0 {
189        return Err(HistoryError::Status(r.status_code.bits()));
190    }
191    let data = r
192        .history_data
193        .inner_as::<ua::HistoryData>()
194        .ok_or(HistoryError::InvalidResponse)?;
195    let values = data.data_values.as_deref().unwrap_or_default();
196    if values.len() > limit - out.samples.len() {
197        return Err(HistoryError::Limit);
198    }
199    if values.len() > page_size {
200        return Err(HistoryError::InvalidResponse);
201    }
202    for raw in values {
203        if raw.source_timestamp.is_none() && raw.server_timestamp.is_none() {
204            return Err(HistoryError::InvalidResponse);
205        }
206        let sample = super::sample::decode_borrowed(raw, T::decode)?;
207        if let Some(source) = sample.source_timestamp {
208            timestamps.accept(source)?;
209        }
210        out.samples.push(sample);
211    }
212    out.page_statuses.push(r.status_code.bits());
213    Ok(())
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn raw_windows_require_exact_non_sentinel_timestamps() {
222        let utc = OffsetDateTime::from_unix_timestamp_nanos;
223        for value in [
224            1,
225            99,
226            -11_644_473_600_000_000_000,
227            253_402_300_799_000_000_000,
228        ] {
229            assert!(tick(utc(value).unwrap()).is_err());
230        }
231        assert!(tick(utc(100).unwrap()).is_ok());
232        assert!(tick(utc(253_402_300_798_999_999_900).unwrap()).is_ok());
233    }
234}