opcda-bridge 0.3.2

Reusable async Rust client library for the opcda-bridge gateway's gRPC API
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
//! Plain data types returned by [`crate::Client`]'s methods.

use crate::{Error, Result};
use opcda_bridge_proto::bridge as proto;
use std::fmt;

/// Default number of children requested for one browse page.
pub const DEFAULT_PAGE_SIZE: u32 = 200;
/// Default maximum number of matches requested by a search.
pub const DEFAULT_SEARCH_MAX_RESULTS: u32 = 200;

/// How the OPC server organizes its namespace.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NamespaceOrganization {
    Unspecified,
    Flat,
    Hierarchical,
}

impl fmt::Display for NamespaceOrganization {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Unspecified => "unspecified",
            Self::Flat => "flat",
            Self::Hierarchical => "hierarchical",
        })
    }
}

/// Native or configured strategy that produced browse results.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowseSource {
    Unspecified,
    Da3,
    Da2,
    Flat,
    Derived,
}

impl fmt::Display for BrowseSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Unspecified => "unspecified",
            Self::Da3 => "da3",
            Self::Da2 => "da2",
            Self::Flat => "flat",
            Self::Derived => "derived",
        })
    }
}

/// Whether a browse node is expandable, selectable as an OPC item, or both.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrowseNodeKind {
    Unspecified,
    Branch,
    Item,
    BranchAndItem,
}

impl BrowseNodeKind {
    /// Whether this node can be expanded with another browse request.
    pub fn is_branch(self) -> bool {
        matches!(self, Self::Branch | Self::BranchAndItem)
    }

    /// Whether this node identifies an OPC item that can be read or written.
    pub fn is_item(self) -> bool {
        matches!(self, Self::Item | Self::BranchAndItem)
    }
}

impl fmt::Display for BrowseNodeKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Unspecified => "unspecified",
            Self::Branch => "branch",
            Self::Item => "item",
            Self::BranchAndItem => "branch-and-item",
        })
    }
}

/// Match behavior for namespace search.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchMatchMode {
    Exact,
    Prefix,
    Contains,
}

impl fmt::Display for SearchMatchMode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Exact => "exact",
            Self::Prefix => "prefix",
            Self::Contains => "contains",
        })
    }
}

/// Gateway and namespace features reported for one OPC server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Capabilities {
    pub application_version: String,
    pub protocol_version: String,
    pub max_page_size: u32,
    pub supports_browse_sessions: bool,
    pub supports_search: bool,
    pub organization: NamespaceOrganization,
    pub source: BrowseSource,
}

/// One child returned by a browse page.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowseNode {
    /// Opaque navigation identity. Round-trip it unchanged when expanding.
    pub node_key: String,
    /// One local label suitable for display.
    pub display_name: String,
    pub kind: BrowseNodeKind,
    /// Exact OPC DA ItemID, present only for selectable nodes.
    pub item_id: Option<String>,
}

/// One bounded page of immediate children and its continuation metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowsePage {
    pub session_id: String,
    pub nodes: Vec<BrowseNode>,
    pub next_page_token: Option<String>,
    pub complete: bool,
    pub organization: NamespaceOrganization,
    pub source: BrowseSource,
    pub warning: Option<String>,
}

/// Parameters for one browse-page request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowsePageRequest {
    pub server: String,
    pub session_id: Option<String>,
    pub parent_node_key: Option<String>,
    pub page_token: Option<String>,
    pub page_size: u32,
    pub refresh: bool,
}

impl BrowsePageRequest {
    /// Open a new browse session and request its root page.
    pub fn root(server: impl Into<String>, page_size: u32) -> Self {
        Self {
            server: server.into(),
            session_id: None,
            parent_node_key: None,
            page_token: None,
            page_size,
            refresh: false,
        }
    }

    /// Request the first page beneath an already-discovered branch.
    pub fn children(
        server: impl Into<String>,
        session_id: impl Into<String>,
        parent_node_key: impl Into<String>,
        page_size: u32,
    ) -> Self {
        Self {
            server: server.into(),
            session_id: Some(session_id.into()),
            parent_node_key: Some(parent_node_key.into()),
            page_token: None,
            page_size,
            refresh: false,
        }
    }

    /// Request the next page for a root or child browse.
    pub fn next(
        server: impl Into<String>,
        session_id: impl Into<String>,
        parent_node_key: Option<String>,
        page_token: impl Into<String>,
        page_size: u32,
    ) -> Self {
        Self {
            server: server.into(),
            session_id: Some(session_id.into()),
            parent_node_key,
            page_token: Some(page_token.into()),
            page_size,
            refresh: false,
        }
    }

    /// Ask the gateway to bypass cached namespace metadata.
    pub fn with_refresh(mut self, refresh: bool) -> Self {
        self.refresh = refresh;
        self
    }
}

/// Parameters for a bounded namespace search.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchRequest {
    pub server: String,
    pub query: String,
    pub match_mode: SearchMatchMode,
    pub session_id: Option<String>,
    pub scope_node_key: Option<String>,
    pub max_results: u32,
    pub include_branches: bool,
    pub refresh: bool,
}

impl SearchRequest {
    pub fn new(
        server: impl Into<String>,
        query: impl Into<String>,
        match_mode: SearchMatchMode,
    ) -> Self {
        Self {
            server: server.into(),
            query: query.into(),
            match_mode,
            session_id: None,
            scope_node_key: None,
            max_results: DEFAULT_SEARCH_MAX_RESULTS,
            include_branches: false,
            refresh: false,
        }
    }
}

/// One navigation step associated with a search match.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BrowseBreadcrumb {
    pub node_key: String,
    pub display_name: String,
}

/// A progressively emitted namespace-search result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchMatch {
    pub node: BrowseNode,
    pub breadcrumbs: Vec<BrowseBreadcrumb>,
}

/// Progress emitted while a namespace search is still running.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchProgress {
    pub visited_nodes: u32,
    pub matches: u32,
    pub partial: bool,
}

/// Terminal search metadata.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchCompleted {
    pub complete: bool,
    pub cancelled: bool,
    pub truncated: bool,
    pub warning: Option<String>,
}

/// One event from the gateway's search stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SearchEvent {
    Match(SearchMatch),
    Progress(SearchProgress),
    Completed(SearchCompleted),
}

/// A single tag's value returned by [`crate::Client::read`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TagValue {
    pub tag_id: String,
    pub value: String,
    pub quality: String,
    pub timestamp: String,
}

/// The result of a single [`crate::Client::write`] call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WriteResult {
    pub tag_id: String,
    pub success: bool,
    pub error: Option<String>,
}

/// A tag value to write, parsed from a raw string via [`parse_value`].
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
    String(String),
    Int(i32),
    Float(f64),
    Bool(bool),
}

/// Parse a raw string into bool, integer, float, or string form.
pub fn parse_value(raw: &str) -> Value {
    if let Ok(b) = raw.parse::<bool>() {
        return Value::Bool(b);
    }
    if let Ok(i) = raw.parse::<i32>() {
        return Value::Int(i);
    }
    if let Ok(f) = raw.parse::<f64>() {
        return Value::Float(f);
    }
    Value::String(raw.to_string())
}

fn invalid_enum(field: &str, value: i32) -> Error {
    Error::Protocol(format!("gateway returned unknown {field} value {value}"))
}

fn organization(value: i32) -> Result<NamespaceOrganization> {
    match proto::NamespaceOrganization::try_from(value)
        .map_err(|_| invalid_enum("namespace organization", value))?
    {
        proto::NamespaceOrganization::Unspecified => Ok(NamespaceOrganization::Unspecified),
        proto::NamespaceOrganization::Flat => Ok(NamespaceOrganization::Flat),
        proto::NamespaceOrganization::Hierarchical => Ok(NamespaceOrganization::Hierarchical),
    }
}

fn source(value: i32) -> Result<BrowseSource> {
    match proto::BrowseSource::try_from(value).map_err(|_| invalid_enum("browse source", value))? {
        proto::BrowseSource::Unspecified => Ok(BrowseSource::Unspecified),
        proto::BrowseSource::Da3 => Ok(BrowseSource::Da3),
        proto::BrowseSource::Da2 => Ok(BrowseSource::Da2),
        proto::BrowseSource::Flat => Ok(BrowseSource::Flat),
        proto::BrowseSource::Derived => Ok(BrowseSource::Derived),
    }
}

fn node_kind(value: i32) -> Result<BrowseNodeKind> {
    match proto::BrowseNodeKind::try_from(value)
        .map_err(|_| invalid_enum("browse node kind", value))?
    {
        proto::BrowseNodeKind::Unspecified => Ok(BrowseNodeKind::Unspecified),
        proto::BrowseNodeKind::Branch => Ok(BrowseNodeKind::Branch),
        proto::BrowseNodeKind::Item => Ok(BrowseNodeKind::Item),
        proto::BrowseNodeKind::BranchAndItem => Ok(BrowseNodeKind::BranchAndItem),
    }
}

impl TryFrom<proto::GetCapabilitiesResponse> for Capabilities {
    type Error = Error;

    fn try_from(value: proto::GetCapabilitiesResponse) -> Result<Self> {
        Ok(Self {
            application_version: value.application_version,
            protocol_version: value.protocol_version,
            max_page_size: value.max_page_size,
            supports_browse_sessions: value.supports_browse_sessions,
            supports_search: value.supports_search,
            organization: organization(value.organization)?,
            source: source(value.source)?,
        })
    }
}

impl TryFrom<proto::BrowseNode> for BrowseNode {
    type Error = Error;

    fn try_from(value: proto::BrowseNode) -> Result<Self> {
        let kind = node_kind(value.kind)?;
        if kind.is_item() && value.item_id.is_none() {
            return Err(Error::Protocol(
                "gateway returned a selectable browse node without an ItemID".into(),
            ));
        }
        if !kind.is_item() && value.item_id.is_some() {
            return Err(Error::Protocol(
                "gateway returned an ItemID for a non-selectable browse node".into(),
            ));
        }
        Ok(Self {
            node_key: value.node_key,
            display_name: value.display_name,
            kind,
            item_id: value.item_id,
        })
    }
}

impl TryFrom<proto::BrowsePage> for BrowsePage {
    type Error = Error;

    fn try_from(value: proto::BrowsePage) -> Result<Self> {
        if value.complete && value.next_page_token.is_some() {
            return Err(Error::Protocol(
                "gateway returned a complete browse page with a continuation token".into(),
            ));
        }
        if !value.complete && value.next_page_token.is_none() {
            return Err(Error::Protocol(
                "gateway returned an incomplete browse page without a continuation token".into(),
            ));
        }
        Ok(Self {
            session_id: value.session_id,
            nodes: value
                .nodes
                .into_iter()
                .map(BrowseNode::try_from)
                .collect::<Result<_>>()?,
            next_page_token: value.next_page_token,
            complete: value.complete,
            organization: organization(value.organization)?,
            source: source(value.source)?,
            warning: value.warning,
        })
    }
}

impl From<BrowsePageRequest> for proto::BrowseRequest {
    fn from(value: BrowsePageRequest) -> Self {
        Self {
            server: value.server,
            session_id: value.session_id,
            parent_node_key: value.parent_node_key,
            page_token: value.page_token,
            page_size: value.page_size,
            refresh: value.refresh,
        }
    }
}

impl From<SearchRequest> for proto::SearchRequest {
    fn from(value: SearchRequest) -> Self {
        let match_mode = match value.match_mode {
            SearchMatchMode::Exact => proto::SearchMatchMode::Exact,
            SearchMatchMode::Prefix => proto::SearchMatchMode::Prefix,
            SearchMatchMode::Contains => proto::SearchMatchMode::Contains,
        };
        Self {
            server: value.server,
            query: value.query,
            match_mode: match_mode as i32,
            session_id: value.session_id,
            scope_node_key: value.scope_node_key,
            max_results: value.max_results,
            include_branches: value.include_branches,
            refresh: value.refresh,
        }
    }
}

impl TryFrom<proto::SearchEvent> for SearchEvent {
    type Error = Error;

    fn try_from(value: proto::SearchEvent) -> Result<Self> {
        match value.event {
            Some(proto::search_event::Event::Match(found)) => {
                let node = found.node.ok_or_else(|| {
                    Error::Protocol("gateway returned a search match without a node".into())
                })?;
                Ok(Self::Match(SearchMatch {
                    node: node.try_into()?,
                    breadcrumbs: found
                        .breadcrumbs
                        .into_iter()
                        .map(|part| BrowseBreadcrumb {
                            node_key: part.node_key,
                            display_name: part.display_name,
                        })
                        .collect(),
                }))
            }
            Some(proto::search_event::Event::Progress(progress)) => {
                Ok(Self::Progress(SearchProgress {
                    visited_nodes: progress.visited_nodes,
                    matches: progress.matches,
                    partial: progress.partial,
                }))
            }
            Some(proto::search_event::Event::Completed(completed)) => {
                Ok(Self::Completed(SearchCompleted {
                    complete: completed.complete,
                    cancelled: completed.cancelled,
                    truncated: completed.truncated,
                    warning: completed.warning,
                }))
            }
            None => Err(Error::Protocol(
                "gateway returned an empty search event".into(),
            )),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn value_parsing_covers_all_variants() {
        assert!(matches!(parse_value("true"), Value::Bool(true)));
        assert!(matches!(parse_value("false"), Value::Bool(false)));
        assert!(matches!(parse_value("42"), Value::Int(42)));
        assert!(matches!(parse_value("-1"), Value::Int(-1)));
        assert!(matches!(parse_value("9.5"), Value::Float(v) if v == 9.5));
        assert!(matches!(parse_value("hello"), Value::String(v) if v == "hello"));
    }

    #[test]
    fn enum_display_and_node_predicates_are_stable() {
        assert_eq!(
            NamespaceOrganization::Unspecified.to_string(),
            "unspecified"
        );
        assert_eq!(NamespaceOrganization::Flat.to_string(), "flat");
        assert_eq!(
            NamespaceOrganization::Hierarchical.to_string(),
            "hierarchical"
        );
        assert_eq!(BrowseSource::Unspecified.to_string(), "unspecified");
        assert_eq!(BrowseSource::Da3.to_string(), "da3");
        assert_eq!(BrowseSource::Da2.to_string(), "da2");
        assert_eq!(BrowseSource::Flat.to_string(), "flat");
        assert_eq!(BrowseSource::Derived.to_string(), "derived");
        assert_eq!(BrowseNodeKind::Unspecified.to_string(), "unspecified");
        assert_eq!(BrowseNodeKind::Branch.to_string(), "branch");
        assert_eq!(BrowseNodeKind::Item.to_string(), "item");
        assert_eq!(BrowseNodeKind::BranchAndItem.to_string(), "branch-and-item");
        assert_eq!(SearchMatchMode::Exact.to_string(), "exact");
        assert_eq!(SearchMatchMode::Prefix.to_string(), "prefix");
        assert_eq!(SearchMatchMode::Contains.to_string(), "contains");
        assert!(BrowseNodeKind::Branch.is_branch());
        assert!(!BrowseNodeKind::Branch.is_item());
        assert!(BrowseNodeKind::Item.is_item());
        assert!(!BrowseNodeKind::Item.is_branch());
        assert!(BrowseNodeKind::BranchAndItem.is_branch());
        assert!(BrowseNodeKind::BranchAndItem.is_item());
        assert!(!BrowseNodeKind::Unspecified.is_branch());
        assert!(!BrowseNodeKind::Unspecified.is_item());
    }

    #[test]
    fn browse_request_builders_map_all_fields() {
        let root = BrowsePageRequest::root("S", 20).with_refresh(true);
        assert_eq!(root.server, "S");
        assert_eq!(root.page_size, 20);
        assert!(root.refresh);

        let children = BrowsePageRequest::children("S", "session", "node", 30);
        assert_eq!(children.session_id.as_deref(), Some("session"));
        assert_eq!(children.parent_node_key.as_deref(), Some("node"));

        let next = BrowsePageRequest::next("S", "session", Some("node".into()), "token", 40);
        let proto: proto::BrowseRequest = next.into();
        assert_eq!(proto.page_token.as_deref(), Some("token"));
        assert_eq!(proto.page_size, 40);
    }

    #[test]
    fn search_request_defaults_and_mapping_are_typed() {
        for (mode, expected) in [
            (SearchMatchMode::Exact, proto::SearchMatchMode::Exact),
            (SearchMatchMode::Prefix, proto::SearchMatchMode::Prefix),
            (SearchMatchMode::Contains, proto::SearchMatchMode::Contains),
        ] {
            let request = SearchRequest::new("S", "query", mode);
            assert_eq!(request.max_results, DEFAULT_SEARCH_MAX_RESULTS);
            let mapped: proto::SearchRequest = request.into();
            assert_eq!(mapped.match_mode, expected as i32);
        }
    }

    #[test]
    fn invalid_and_inconsistent_proto_values_are_rejected() {
        assert_eq!(
            organization(proto::NamespaceOrganization::Unspecified as i32).unwrap(),
            NamespaceOrganization::Unspecified
        );
        assert_eq!(
            organization(proto::NamespaceOrganization::Flat as i32).unwrap(),
            NamespaceOrganization::Flat
        );
        assert_eq!(
            organization(proto::NamespaceOrganization::Hierarchical as i32).unwrap(),
            NamespaceOrganization::Hierarchical
        );
        assert_eq!(
            source(proto::BrowseSource::Unspecified as i32).unwrap(),
            BrowseSource::Unspecified
        );
        assert_eq!(
            source(proto::BrowseSource::Da3 as i32).unwrap(),
            BrowseSource::Da3
        );
        assert_eq!(
            source(proto::BrowseSource::Da2 as i32).unwrap(),
            BrowseSource::Da2
        );
        assert_eq!(
            source(proto::BrowseSource::Flat as i32).unwrap(),
            BrowseSource::Flat
        );
        assert_eq!(
            source(proto::BrowseSource::Derived as i32).unwrap(),
            BrowseSource::Derived
        );
        assert_eq!(
            node_kind(proto::BrowseNodeKind::Unspecified as i32).unwrap(),
            BrowseNodeKind::Unspecified
        );
        assert_eq!(
            node_kind(proto::BrowseNodeKind::Branch as i32).unwrap(),
            BrowseNodeKind::Branch
        );
        assert_eq!(
            node_kind(proto::BrowseNodeKind::Item as i32).unwrap(),
            BrowseNodeKind::Item
        );
        assert_eq!(
            node_kind(proto::BrowseNodeKind::BranchAndItem as i32).unwrap(),
            BrowseNodeKind::BranchAndItem
        );
        assert!(matches!(organization(99), Err(Error::Protocol(_))));
        assert!(matches!(source(99), Err(Error::Protocol(_))));
        assert!(matches!(node_kind(99), Err(Error::Protocol(_))));

        let missing_item_id = proto::BrowseNode {
            kind: proto::BrowseNodeKind::Item as i32,
            ..Default::default()
        };
        assert!(matches!(
            BrowseNode::try_from(missing_item_id),
            Err(Error::Protocol(_))
        ));
        let unexpected_item_id = proto::BrowseNode {
            kind: proto::BrowseNodeKind::Branch as i32,
            item_id: Some("not-valid".into()),
            ..Default::default()
        };
        assert!(matches!(
            BrowseNode::try_from(unexpected_item_id),
            Err(Error::Protocol(_))
        ));

        let complete_with_token = proto::BrowsePage {
            complete: true,
            next_page_token: Some("token".into()),
            ..Default::default()
        };
        assert!(matches!(
            BrowsePage::try_from(complete_with_token),
            Err(Error::Protocol(_))
        ));

        let incomplete_without_token = proto::BrowsePage::default();
        assert!(matches!(
            BrowsePage::try_from(incomplete_without_token),
            Err(Error::Protocol(_))
        ));
    }

    #[test]
    fn search_event_conversion_covers_every_event() {
        let found = proto::SearchEvent {
            event: Some(proto::search_event::Event::Match(proto::SearchMatch {
                node: Some(proto::BrowseNode {
                    node_key: "n".into(),
                    display_name: "PV".into(),
                    kind: proto::BrowseNodeKind::Item as i32,
                    item_id: Some("FCS!TAG.PV".into()),
                }),
                breadcrumbs: vec![proto::BrowseBreadcrumb {
                    node_key: "root".into(),
                    display_name: "FCS".into(),
                }],
            })),
        };
        assert!(matches!(
            SearchEvent::try_from(found).unwrap(),
            SearchEvent::Match(_)
        ));

        let progress = proto::SearchEvent {
            event: Some(proto::search_event::Event::Progress(
                proto::SearchProgress {
                    visited_nodes: 10,
                    matches: 2,
                    partial: true,
                },
            )),
        };
        assert!(matches!(
            SearchEvent::try_from(progress).unwrap(),
            SearchEvent::Progress(_)
        ));

        let completed = proto::SearchEvent {
            event: Some(proto::search_event::Event::Completed(
                proto::SearchCompleted {
                    complete: true,
                    cancelled: false,
                    truncated: false,
                    warning: None,
                },
            )),
        };
        assert!(matches!(
            SearchEvent::try_from(completed).unwrap(),
            SearchEvent::Completed(_)
        ));

        assert!(matches!(
            SearchEvent::try_from(proto::SearchEvent::default()),
            Err(Error::Protocol(_))
        ));
        let missing_node = proto::SearchEvent {
            event: Some(proto::search_event::Event::Match(
                proto::SearchMatch::default(),
            )),
        };
        assert!(matches!(
            SearchEvent::try_from(missing_node),
            Err(Error::Protocol(_))
        ));
    }
}