Skip to main content

opcda_bridge_proto/
lib.rs

1/// Default TCP port used by the gateway and clients.
2pub const DEFAULT_BRIDGE_PORT: u16 = 7600;
3
4/// Generated compatibility contract metadata shared by the gateway and clients.
5pub mod compatibility {
6    /// A package release line and the protocol contracts it implements.
7    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
8    pub struct ReleaseLine {
9        pub name: &'static str,
10        pub min_version: &'static str,
11        pub max_version: &'static str,
12        pub status: &'static str,
13        pub core_protocol: u32,
14        pub namespace_protocol: u32,
15        pub indexed_search_protocol: u32,
16    }
17
18    include!(concat!(env!("OUT_DIR"), "/compatibility_generated.rs"));
19
20    /// The canonical compatibility catalog bundled with this crate.
21    pub const CATALOG_TOML: &str = include_str!("../compatibility.toml");
22
23    fn version_tuple(value: &str) -> Option<(u64, u64, u64)> {
24        let parts = value.split('.').collect::<Vec<_>>();
25        if parts.len() != 3 || parts.iter().any(|part| part.is_empty()) {
26            return None;
27        }
28        Some((
29            parts[0].parse().ok()?,
30            parts[1].parse().ok()?,
31            parts[2].parse().ok()?,
32        ))
33    }
34
35    /// Find the catalog release line containing an exact `X.Y.Z` version.
36    pub fn release_line_for(version: &str) -> Option<&'static ReleaseLine> {
37        let version = version_tuple(version)?;
38        RELEASE_LINES.iter().find(|line| {
39            let Some(minimum) = version_tuple(line.min_version) else {
40                return false;
41            };
42            let Some(maximum) = version_tuple(line.max_version) else {
43                return false;
44            };
45            minimum <= version && version <= maximum
46        })
47    }
48}
49
50#[allow(
51    clippy::double_must_use,
52    reason = "tonic's generated async-trait methods redundantly mark futures as must-use"
53)]
54pub mod bridge {
55    tonic::include_proto!("bridge");
56}
57
58#[cfg(test)]
59mod tests {
60    use super::DEFAULT_BRIDGE_PORT;
61    use crate::bridge::write_request::TypedValue;
62    use crate::bridge::{
63        BrowseNode, BrowseNodeKind, BrowsePage, BrowseRequest, BrowseSource,
64        CloseBrowseSessionRequest, ControlSearchIndexRequest, GetCapabilitiesRequest,
65        GetCapabilitiesResponse, GetSearchIndexStatusRequest, IndexedSearchMatch,
66        IndexedSearchProgress, ListServersRequest, ListServersResponse, NamespaceOrganization,
67        ReadRequest, ReadResponse, RefreshSearchIndexRequest, SearchCompleted, SearchEvent,
68        SearchIndexControlAction, SearchIndexRequest, SearchIndexResponse, SearchIndexState,
69        SearchIndexStatus, SearchMatch, SearchMatchMode, SearchProgress, TagValue, WriteRequest,
70        WriteResponse,
71    };
72
73    #[test]
74    fn test_default_bridge_port() {
75        assert_eq!(DEFAULT_BRIDGE_PORT, 7600);
76    }
77
78    #[test]
79    fn test_compatibility_catalog_release_lines() {
80        let legacy = crate::compatibility::release_line_for("0.3.1").unwrap();
81        assert_eq!(legacy.name, "legacy");
82        assert_eq!(legacy.namespace_protocol, 1);
83        assert_eq!(legacy.status, "legacy");
84
85        let paged = crate::compatibility::release_line_for("0.3.2").unwrap();
86        assert_eq!(paged.name, "paged");
87        assert_eq!(paged.namespace_protocol, 2);
88
89        let indexed = crate::compatibility::release_line_for("0.4.3").unwrap();
90        assert_eq!(indexed.name, "indexed");
91        assert_eq!(indexed.indexed_search_protocol, 1);
92        let on_demand = crate::compatibility::release_line_for("0.5.0").unwrap();
93        assert_eq!(on_demand.name, "indexed-on-demand");
94        assert_eq!(on_demand.indexed_search_protocol, 2);
95        assert!(crate::compatibility::release_line_for("1.0").is_none());
96        assert!(crate::compatibility::release_line_for("0.x.3").is_none());
97    }
98
99    #[test]
100    fn test_list_servers_request() {
101        let req = ListServersRequest {
102            host: "localhost".into(),
103        };
104        assert_eq!(req.host, "localhost");
105    }
106
107    #[test]
108    fn test_list_servers_request_empty() {
109        let req = ListServersRequest {
110            host: String::new(),
111        };
112        assert!(req.host.is_empty());
113    }
114
115    #[test]
116    fn test_list_servers_response_empty() {
117        let resp = ListServersResponse { servers: vec![] };
118        assert!(resp.servers.is_empty());
119    }
120
121    #[test]
122    fn test_list_servers_response_with_data() {
123        let resp = ListServersResponse {
124            servers: vec!["S1".into(), "S2".into()],
125        };
126        assert_eq!(resp.servers.len(), 2);
127        assert_eq!(resp.servers[0], "S1");
128    }
129
130    #[test]
131    fn test_browse_request() {
132        let req = BrowseRequest {
133            server: "MyServer".into(),
134            session_id: Some("session".into()),
135            parent_node_key: Some("parent".into()),
136            page_token: Some("page".into()),
137            page_size: 500,
138            refresh: true,
139        };
140        assert_eq!(req.server, "MyServer");
141        assert_eq!(req.session_id.as_deref(), Some("session"));
142        assert_eq!(req.parent_node_key.as_deref(), Some("parent"));
143        assert_eq!(req.page_token.as_deref(), Some("page"));
144        assert_eq!(req.page_size, 500);
145        assert!(req.refresh);
146    }
147
148    #[test]
149    fn test_browse_request_defaults() {
150        let req = BrowseRequest {
151            server: String::new(),
152            session_id: None,
153            parent_node_key: None,
154            page_token: None,
155            page_size: 0,
156            refresh: false,
157        };
158        assert!(req.session_id.is_none());
159        assert_eq!(req.page_size, 0);
160    }
161
162    #[test]
163    fn test_browse_page_and_node() {
164        let node = BrowseNode {
165            node_key: "opaque".into(),
166            display_name: "PV".into(),
167            kind: BrowseNodeKind::BranchAndItem as i32,
168            item_id: Some("FCS0201!204FI00510.PV".into()),
169        };
170        let page = BrowsePage {
171            session_id: "session".into(),
172            nodes: vec![node],
173            next_page_token: Some("next".into()),
174            complete: false,
175            organization: NamespaceOrganization::Hierarchical as i32,
176            source: BrowseSource::Da2 as i32,
177            warning: Some("partial".into()),
178        };
179        assert_eq!(page.nodes[0].display_name, "PV");
180        assert_eq!(page.next_page_token.as_deref(), Some("next"));
181        assert!(!page.complete);
182    }
183
184    #[test]
185    fn test_capabilities_and_close_request() {
186        let request = GetCapabilitiesRequest { server: "S".into() };
187        let response = GetCapabilitiesResponse {
188            application_version: "0.3.0".into(),
189            protocol_version: "2".into(),
190            max_page_size: 1000,
191            supports_browse_sessions: true,
192            supports_search: true,
193            organization: NamespaceOrganization::Flat as i32,
194            source: BrowseSource::Flat as i32,
195            supports_indexed_search: true,
196            indexed_search_protocol_version: "1".into(),
197            max_indexed_search_results: 50,
198            search_index_state: SearchIndexState::Ready as i32,
199            search_index_promoting: false,
200        };
201        let close = CloseBrowseSessionRequest {
202            session_id: "s".into(),
203        };
204        assert_eq!(request.server, "S");
205        assert_eq!(response.max_page_size, 1000);
206        assert_eq!(close.session_id, "s");
207        assert!(response.supports_indexed_search);
208        assert_eq!(response.max_indexed_search_results, 50);
209    }
210
211    #[test]
212    fn test_search_messages() {
213        let match_message = SearchMatch {
214            node: None,
215            breadcrumbs: vec![],
216        };
217        let progress = SearchProgress {
218            visited_nodes: 4,
219            matches: 2,
220            partial: true,
221        };
222        let completed = SearchCompleted {
223            complete: false,
224            cancelled: false,
225            truncated: true,
226            warning: Some("capped".into()),
227        };
228        let event = SearchEvent {
229            event: Some(crate::bridge::search_event::Event::Progress(progress)),
230        };
231        assert!(event.event.is_some());
232        assert!(match_message.breadcrumbs.is_empty());
233        assert!(completed.truncated);
234        assert_eq!(
235            SearchMatchMode::Contains as i32,
236            SearchMatchMode::try_from(SearchMatchMode::Contains as i32).unwrap() as i32
237        );
238    }
239
240    #[test]
241    fn test_indexed_search_messages() {
242        let status_request = GetSearchIndexStatusRequest { server: "S".into() };
243        let refresh_request = RefreshSearchIndexRequest {
244            server: "S".into(),
245            force: true,
246        };
247        let control_request = ControlSearchIndexRequest {
248            server: "S".into(),
249            action: SearchIndexControlAction::Pause as i32,
250        };
251        let search_request = SearchIndexRequest {
252            server: "S".into(),
253            query: "PV".into(),
254            match_mode: SearchMatchMode::Prefix as i32,
255            max_results: 50,
256        };
257        let status = SearchIndexStatus {
258            server: "S".into(),
259            state: SearchIndexState::Refreshing as i32,
260            configured: true,
261            active_generation: 2,
262            entry_count: 100,
263            unique_item_count: 99,
264            started_at: Some("start".into()),
265            completed_at: Some("complete".into()),
266            last_error: None,
267            database_bytes: 1024,
268            organization: NamespaceOrganization::Hierarchical as i32,
269            source: BrowseSource::Da3 as i32,
270            progress: Some(IndexedSearchProgress {
271                branches_visited: 1,
272                entries_seen: 2,
273                unique_items: 2,
274                active_time_ms: 3,
275                paused_time_ms: 4,
276                items_per_second: 5.0,
277                estimated_remaining_ms: Some(6),
278            }),
279            ..Default::default()
280        };
281        let response = SearchIndexResponse {
282            matches: vec![IndexedSearchMatch {
283                item_id: "Exact.ItemID".into(),
284                display_name: "PV".into(),
285                kind: BrowseNodeKind::Item as i32,
286                breadcrumbs: vec!["Area".into()],
287            }],
288            has_more: true,
289            status: Some(status),
290        };
291
292        assert_eq!(status_request.server, "S");
293        assert!(refresh_request.force);
294        assert_eq!(
295            control_request.action,
296            SearchIndexControlAction::Pause as i32
297        );
298        assert_eq!(search_request.max_results, 50);
299        assert!(response.has_more);
300        assert_eq!(response.matches[0].item_id, "Exact.ItemID");
301    }
302
303    #[test]
304    fn test_read_request() {
305        let req = ReadRequest {
306            server: "MyServer".into(),
307            tag_ids: vec!["t1".into(), "t2".into()],
308        };
309        assert_eq!(req.server, "MyServer");
310        assert_eq!(req.tag_ids.len(), 2);
311    }
312
313    #[test]
314    fn test_read_request_empty_tags() {
315        let req = ReadRequest {
316            server: "S".into(),
317            tag_ids: vec![],
318        };
319        assert!(req.tag_ids.is_empty());
320    }
321
322    #[test]
323    fn test_tag_value() {
324        let tv = TagValue {
325            tag_id: "t1".into(),
326            value: "42.5".into(),
327            quality: "Good".into(),
328            timestamp: "2026-01-01 00:00:00".into(),
329        };
330        assert_eq!(tv.tag_id, "t1");
331        assert_eq!(tv.value, "42.5");
332        assert_eq!(tv.quality, "Good");
333        assert_eq!(tv.timestamp, "2026-01-01 00:00:00");
334    }
335
336    #[test]
337    fn test_read_response() {
338        let resp = ReadResponse {
339            values: vec![TagValue {
340                tag_id: "t1".into(),
341                value: "42".into(),
342                quality: "Good".into(),
343                timestamp: "now".into(),
344            }],
345        };
346        assert_eq!(resp.values.len(), 1);
347    }
348
349    #[test]
350    fn test_read_response_empty() {
351        let resp = ReadResponse { values: vec![] };
352        assert!(resp.values.is_empty());
353    }
354
355    #[test]
356    fn test_write_request_string() {
357        let req = WriteRequest {
358            server: "S".into(),
359            tag_id: "t1".into(),
360            typed_value: Some(TypedValue::StringValue("hello".into())),
361        };
362        assert_eq!(req.server, "S");
363        assert_eq!(req.tag_id, "t1");
364        assert!(matches!(req.typed_value, Some(TypedValue::StringValue(ref s)) if s == "hello"));
365    }
366
367    #[test]
368    fn test_write_request_int() {
369        let req = WriteRequest {
370            server: "S".into(),
371            tag_id: "t1".into(),
372            typed_value: Some(TypedValue::IntValue(42)),
373        };
374        assert!(matches!(req.typed_value, Some(TypedValue::IntValue(42))));
375    }
376
377    #[test]
378    fn test_write_request_float() {
379        let req = WriteRequest {
380            server: "S".into(),
381            tag_id: "t1".into(),
382            typed_value: Some(TypedValue::FloatValue(9.5)),
383        };
384        assert!(
385            matches!(req.typed_value, Some(TypedValue::FloatValue(v)) if (v - 9.5).abs() < f64::EPSILON)
386        );
387    }
388
389    #[test]
390    fn test_write_request_bool() {
391        let req = WriteRequest {
392            server: "S".into(),
393            tag_id: "t1".into(),
394            typed_value: Some(TypedValue::BoolValue(true)),
395        };
396        assert!(matches!(req.typed_value, Some(TypedValue::BoolValue(true))));
397    }
398
399    #[test]
400    fn test_write_request_no_value() {
401        let req = WriteRequest {
402            server: "S".into(),
403            tag_id: "t1".into(),
404            typed_value: None,
405        };
406        assert!(req.typed_value.is_none());
407    }
408
409    #[test]
410    fn test_write_response_success() {
411        let resp = WriteResponse {
412            tag_id: "t1".into(),
413            success: true,
414            error: None,
415        };
416        assert_eq!(resp.tag_id, "t1");
417        assert!(resp.success);
418        assert_eq!(resp.error, None);
419    }
420
421    #[test]
422    fn test_write_response_failure() {
423        let resp = WriteResponse {
424            tag_id: "t1".into(),
425            success: false,
426            error: Some("access denied".into()),
427        };
428        assert!(!resp.success);
429        assert_eq!(resp.error, Some("access denied".into()));
430    }
431
432    #[test]
433    fn test_typed_value_string() {
434        let tv = TypedValue::StringValue("test".into());
435        assert!(matches!(tv, TypedValue::StringValue(ref s) if s == "test"));
436    }
437
438    #[test]
439    fn test_typed_value_int() {
440        let tv = TypedValue::IntValue(-1);
441        assert!(matches!(tv, TypedValue::IntValue(-1)));
442    }
443
444    #[test]
445    fn test_typed_value_float() {
446        let tv = TypedValue::FloatValue(0.0);
447        assert!(matches!(tv, TypedValue::FloatValue(v) if v == 0.0));
448    }
449
450    #[test]
451    fn test_typed_value_bool() {
452        let tv = TypedValue::BoolValue(false);
453        assert!(matches!(tv, TypedValue::BoolValue(false)));
454    }
455}