opcda-bridge 0.4.7

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
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
//! 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;
/// Default maximum number of matches requested from the persistent index.
pub const DEFAULT_INDEX_SEARCH_MAX_RESULTS: u32 = 50;

/// 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",
        })
    }
}

/// Readiness of a gateway-owned persistent namespace index.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchIndexState {
    Unspecified,
    NotIndexed,
    Partial,
    Ready,
    Stale,
    Refreshing,
    Promoting,
    Failed,
}

impl fmt::Display for SearchIndexState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Unspecified => "unspecified",
            Self::NotIndexed => "not-indexed",
            Self::Partial => "partial",
            Self::Ready => "ready",
            Self::Stale => "stale",
            Self::Refreshing => "refreshing",
            Self::Promoting => "promoting",
            Self::Failed => "failed",
        })
    }
}

/// Effective inventory limits currently applied by the gateway controller.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IndexInventoryLimits {
    pub item_rate_per_second: u32,
    pub batch_size: u32,
    pub duty_cycle_percent: u32,
}

/// Adaptive controller state for a namespace-index build.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndexControllerState {
    Unspecified,
    Ramping,
    Steady,
    Throttled,
    Paused,
}

impl fmt::Display for IndexControllerState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Unspecified => "unspecified",
            Self::Ramping => "ramping",
            Self::Steady => "steady",
            Self::Throttled => "throttled",
            Self::Paused => "paused",
        })
    }
}

/// Typed reason for a controller pause.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IndexPauseReason {
    Unspecified,
    Foreground,
    OpcHealth,
    HostCpu,
    Memory,
    Disk,
    Database,
    Operator,
    Circuit,
}

impl fmt::Display for IndexPauseReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Unspecified => "unspecified",
            Self::Foreground => "foreground",
            Self::OpcHealth => "opc-health",
            Self::HostCpu => "host-cpu",
            Self::Memory => "memory",
            Self::Disk => "disk",
            Self::Database => "database",
            Self::Operator => "operator",
            Self::Circuit => "circuit",
        })
    }
}

/// Rolling foreground operation measurements.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IndexForegroundDiagnostics {
    pub active_count: u64,
    pub operations: u64,
    pub errors: u64,
    pub bad_quality: u64,
    pub latency_p50_ms: Option<u64>,
    pub latency_p95_ms: Option<u64>,
    pub latency_max_ms: Option<u64>,
    pub last_error: bool,
    pub last_bad_quality: bool,
}

/// Host and gateway-process resource measurements.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct IndexHostDiagnostics {
    pub cpu_percent: Option<f64>,
    pub available_memory_percent: Option<f64>,
    pub disk_active_percent: Option<f64>,
    pub disk_queue: Option<f64>,
    pub process_working_set_bytes: Option<u64>,
    pub process_private_bytes: Option<u64>,
    pub process_read_bytes_per_second: Option<u64>,
    pub process_write_bytes_per_second: Option<u64>,
    pub disk_free_bytes: Option<u64>,
}

/// SQLite file and commit measurements.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IndexStorageDiagnostics {
    pub main_bytes: u64,
    pub wal_bytes: u64,
    pub shm_bytes: u64,
    pub free_bytes: Option<u64>,
    pub last_commit_latency_ms: Option<u64>,
}

/// Scheduler, retry, and circuit-breaker measurements.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IndexSchedulerDiagnostics {
    pub next_refresh_at: Option<String>,
    pub last_attempt_at: Option<String>,
    pub last_success_at: Option<String>,
    pub last_success_duration_ms: Option<u64>,
    pub retry_after: Option<String>,
    pub consecutive_failures: u32,
    pub circuit_open: bool,
}

/// Health-probe state reported for the indexed server.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum IndexHealthState {
    Unspecified,
    Healthy,
    Unhealthy,
    #[default]
    Unavailable,
}

impl fmt::Display for IndexHealthState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Unspecified => "unspecified",
            Self::Healthy => "healthy",
            Self::Unhealthy => "unhealthy",
            Self::Unavailable => "unavailable",
        })
    }
}

/// Health-probe availability and result.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct IndexHealthDiagnostics {
    pub state: IndexHealthState,
    pub sentinel_configured: bool,
}

impl Default for IndexHealthDiagnostics {
    fn default() -> Self {
        Self {
            state: IndexHealthState::Unavailable,
            sentinel_configured: false,
        }
    }
}

/// Operator action applied to an active namespace-index build.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SearchIndexControlAction {
    Pause,
    Resume,
    Cancel,
}

/// 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,
    pub supports_indexed_search: bool,
    pub indexed_search_protocol_version: String,
    pub max_indexed_search_results: u32,
    pub search_index_state: SearchIndexState,
    pub search_index_promoting: bool,
}

/// 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,
        }
    }
}

/// Parameters for one persistent-index query.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchIndexRequest {
    pub server: String,
    pub query: String,
    pub match_mode: SearchMatchMode,
    pub max_results: u32,
}

impl SearchIndexRequest {
    pub fn new(
        server: impl Into<String>,
        query: impl Into<String>,
        match_mode: SearchMatchMode,
    ) -> Self {
        Self {
            server: server.into(),
            query: query.into(),
            match_mode,
            max_results: DEFAULT_INDEX_SEARCH_MAX_RESULTS,
        }
    }
}

/// Progress reported for a running persistent namespace inventory.
#[derive(Debug, Clone, PartialEq)]
pub struct IndexedSearchProgress {
    pub branches_visited: u64,
    pub entries_seen: u64,
    pub unique_items: u64,
    pub active_time_ms: u64,
    pub paused_time_ms: u64,
    pub items_per_second: f64,
    pub estimated_remaining_ms: Option<u64>,
}

/// Persistent namespace-index state and build metadata.
#[derive(Debug, Clone, PartialEq)]
pub struct SearchIndexStatus {
    pub server: String,
    pub state: SearchIndexState,
    pub configured: bool,
    pub active_generation: u64,
    pub entry_count: u64,
    pub unique_item_count: u64,
    pub started_at: Option<String>,
    pub completed_at: Option<String>,
    pub last_error: Option<String>,
    pub database_bytes: u64,
    pub organization: NamespaceOrganization,
    pub source: BrowseSource,
    pub progress: Option<IndexedSearchProgress>,
    pub effective_limits: Option<IndexInventoryLimits>,
    pub controller_state: IndexControllerState,
    pub pause_reason: Option<IndexPauseReason>,
    pub recovery_deadline: Option<String>,
    pub pause_reason_detail: Option<String>,
    pub foreground: IndexForegroundDiagnostics,
    pub host: IndexHostDiagnostics,
    pub storage: IndexStorageDiagnostics,
    pub scheduler: IndexSchedulerDiagnostics,
    pub health: IndexHealthDiagnostics,
    pub promoting: bool,
}

/// One selectable result from the persistent namespace index.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexedSearchMatch {
    pub item_id: String,
    pub display_name: String,
    pub kind: BrowseNodeKind,
    pub breadcrumbs: Vec<String>,
}

/// Ranked persistent-index matches plus snapshot readiness metadata.
#[derive(Debug, Clone, PartialEq)]
pub struct SearchIndexResponse {
    pub matches: Vec<IndexedSearchMatch>,
    pub has_more: bool,
    pub status: SearchIndexStatus,
}

/// 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 semantic value returned by [`crate::Client::read`].
///
/// For an OPC DA `VT_BSTR`, `value` contains the exact BSTR contents. The
/// bridge does not add or remove quote characters.
#[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),
    }
}

fn search_index_state(value: i32) -> Result<SearchIndexState> {
    match proto::SearchIndexState::try_from(value)
        .map_err(|_| invalid_enum("search index state", value))?
    {
        proto::SearchIndexState::Unspecified => Ok(SearchIndexState::Unspecified),
        proto::SearchIndexState::NotIndexed => Ok(SearchIndexState::NotIndexed),
        proto::SearchIndexState::Partial => Ok(SearchIndexState::Partial),
        proto::SearchIndexState::Ready => Ok(SearchIndexState::Ready),
        proto::SearchIndexState::Stale => Ok(SearchIndexState::Stale),
        proto::SearchIndexState::Refreshing => Ok(SearchIndexState::Refreshing),
        proto::SearchIndexState::Promoting => Ok(SearchIndexState::Promoting),
        proto::SearchIndexState::Failed => Ok(SearchIndexState::Failed),
    }
}

fn index_controller_state(value: i32) -> Result<IndexControllerState> {
    match proto::IndexControllerState::try_from(value)
        .map_err(|_| invalid_enum("index controller state", value))?
    {
        proto::IndexControllerState::Unspecified => Ok(IndexControllerState::Unspecified),
        proto::IndexControllerState::Ramping => Ok(IndexControllerState::Ramping),
        proto::IndexControllerState::Steady => Ok(IndexControllerState::Steady),
        proto::IndexControllerState::Throttled => Ok(IndexControllerState::Throttled),
        proto::IndexControllerState::Paused => Ok(IndexControllerState::Paused),
    }
}

fn index_pause_reason(value: i32) -> Result<IndexPauseReason> {
    match proto::IndexPauseReason::try_from(value)
        .map_err(|_| invalid_enum("index pause reason", value))?
    {
        proto::IndexPauseReason::Unspecified => Ok(IndexPauseReason::Unspecified),
        proto::IndexPauseReason::Foreground => Ok(IndexPauseReason::Foreground),
        proto::IndexPauseReason::OpcHealth => Ok(IndexPauseReason::OpcHealth),
        proto::IndexPauseReason::HostCpu => Ok(IndexPauseReason::HostCpu),
        proto::IndexPauseReason::Memory => Ok(IndexPauseReason::Memory),
        proto::IndexPauseReason::Disk => Ok(IndexPauseReason::Disk),
        proto::IndexPauseReason::Database => Ok(IndexPauseReason::Database),
        proto::IndexPauseReason::Operator => Ok(IndexPauseReason::Operator),
        proto::IndexPauseReason::Circuit => Ok(IndexPauseReason::Circuit),
    }
}

fn index_health_state(value: i32) -> Result<IndexHealthState> {
    match proto::IndexHealthState::try_from(value)
        .map_err(|_| invalid_enum("index health state", value))?
    {
        proto::IndexHealthState::Unspecified => Ok(IndexHealthState::Unspecified),
        proto::IndexHealthState::Healthy => Ok(IndexHealthState::Healthy),
        proto::IndexHealthState::Unhealthy => Ok(IndexHealthState::Unhealthy),
        proto::IndexHealthState::Unavailable => Ok(IndexHealthState::Unavailable),
    }
}

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)?,
            supports_indexed_search: value.supports_indexed_search,
            indexed_search_protocol_version: value.indexed_search_protocol_version,
            max_indexed_search_results: value.max_indexed_search_results,
            search_index_state: search_index_state(value.search_index_state)?,
            search_index_promoting: value.search_index_promoting,
        })
    }
}

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 From<SearchIndexRequest> for proto::SearchIndexRequest {
    fn from(value: SearchIndexRequest) -> 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,
            max_results: value.max_results,
        }
    }
}

impl From<SearchIndexControlAction> for proto::SearchIndexControlAction {
    fn from(value: SearchIndexControlAction) -> Self {
        match value {
            SearchIndexControlAction::Pause => Self::Pause,
            SearchIndexControlAction::Resume => Self::Resume,
            SearchIndexControlAction::Cancel => Self::Cancel,
        }
    }
}

impl From<proto::IndexedSearchProgress> for IndexedSearchProgress {
    fn from(value: proto::IndexedSearchProgress) -> Self {
        Self {
            branches_visited: value.branches_visited,
            entries_seen: value.entries_seen,
            unique_items: value.unique_items,
            active_time_ms: value.active_time_ms,
            paused_time_ms: value.paused_time_ms,
            items_per_second: value.items_per_second,
            estimated_remaining_ms: value.estimated_remaining_ms,
        }
    }
}

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

    fn try_from(value: proto::SearchIndexStatus) -> Result<Self> {
        Ok(Self {
            server: value.server,
            state: search_index_state(value.state)?,
            configured: value.configured,
            active_generation: value.active_generation,
            entry_count: value.entry_count,
            unique_item_count: value.unique_item_count,
            started_at: value.started_at,
            completed_at: value.completed_at,
            last_error: value.last_error,
            database_bytes: value.database_bytes,
            organization: organization(value.organization)?,
            source: source(value.source)?,
            progress: value.progress.map(Into::into),
            effective_limits: value.effective_limits.map(|limits| IndexInventoryLimits {
                item_rate_per_second: limits.item_rate_per_second,
                batch_size: limits.batch_size,
                duty_cycle_percent: limits.duty_cycle_percent,
            }),
            controller_state: index_controller_state(value.controller_state)?,
            pause_reason: value.pause_reason.map(index_pause_reason).transpose()?,
            recovery_deadline: value.recovery_deadline,
            pause_reason_detail: value.pause_reason_detail,
            foreground: value.foreground.map_or_else(
                IndexForegroundDiagnostics::default,
                |diagnostics| IndexForegroundDiagnostics {
                    active_count: diagnostics.active_count,
                    operations: diagnostics.operations,
                    errors: diagnostics.errors,
                    bad_quality: diagnostics.bad_quality,
                    latency_p50_ms: diagnostics.latency_p50_ms,
                    latency_p95_ms: diagnostics.latency_p95_ms,
                    latency_max_ms: diagnostics.latency_max_ms,
                    last_error: diagnostics.last_error,
                    last_bad_quality: diagnostics.last_bad_quality,
                },
            ),
            host: value
                .host
                .map_or_else(IndexHostDiagnostics::default, |diagnostics| {
                    IndexHostDiagnostics {
                        cpu_percent: diagnostics.cpu_percent,
                        available_memory_percent: diagnostics.available_memory_percent,
                        disk_active_percent: diagnostics.disk_active_percent,
                        disk_queue: diagnostics.disk_queue,
                        process_working_set_bytes: diagnostics.process_working_set_bytes,
                        process_private_bytes: diagnostics.process_private_bytes,
                        process_read_bytes_per_second: diagnostics.process_read_bytes_per_second,
                        process_write_bytes_per_second: diagnostics.process_write_bytes_per_second,
                        disk_free_bytes: diagnostics.disk_free_bytes,
                    }
                }),
            storage: value
                .storage
                .map_or_else(IndexStorageDiagnostics::default, |diagnostics| {
                    IndexStorageDiagnostics {
                        main_bytes: diagnostics.main_bytes,
                        wal_bytes: diagnostics.wal_bytes,
                        shm_bytes: diagnostics.shm_bytes,
                        free_bytes: diagnostics.free_bytes,
                        last_commit_latency_ms: diagnostics.last_commit_latency_ms,
                    }
                }),
            scheduler: value.scheduler.map_or_else(
                IndexSchedulerDiagnostics::default,
                |diagnostics| IndexSchedulerDiagnostics {
                    next_refresh_at: diagnostics.next_refresh_at,
                    last_attempt_at: diagnostics.last_attempt_at,
                    last_success_at: diagnostics.last_success_at,
                    last_success_duration_ms: diagnostics.last_success_duration_ms,
                    retry_after: diagnostics.retry_after,
                    consecutive_failures: diagnostics.consecutive_failures,
                    circuit_open: diagnostics.circuit_open,
                },
            ),
            health: value
                .health
                .map(|diagnostics| -> Result<IndexHealthDiagnostics> {
                    Ok(IndexHealthDiagnostics {
                        state: index_health_state(diagnostics.state)?,
                        sentinel_configured: diagnostics.sentinel_configured,
                    })
                })
                .transpose()?
                .unwrap_or_default(),
            promoting: value.promoting,
        })
    }
}

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

    fn try_from(value: proto::IndexedSearchMatch) -> Result<Self> {
        let kind = node_kind(value.kind)?;
        if !kind.is_item() {
            return Err(Error::Protocol(
                "gateway returned a non-selectable indexed search match".into(),
            ));
        }
        if value.item_id.is_empty() {
            return Err(Error::Protocol(
                "gateway returned an indexed search match without an ItemID".into(),
            ));
        }
        Ok(Self {
            item_id: value.item_id,
            display_name: value.display_name,
            kind,
            breadcrumbs: value.breadcrumbs,
        })
    }
}

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

    fn try_from(value: proto::SearchIndexResponse) -> Result<Self> {
        Ok(Self {
            matches: value
                .matches
                .into_iter()
                .map(IndexedSearchMatch::try_from)
                .collect::<Result<_>>()?,
            has_more: value.has_more,
            status: value
                .status
                .ok_or_else(|| {
                    Error::Protocol("gateway returned indexed search results without status".into())
                })?
                .try_into()?,
        })
    }
}

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_eq!(SearchIndexState::Unspecified.to_string(), "unspecified");
        assert_eq!(SearchIndexState::NotIndexed.to_string(), "not-indexed");
        assert_eq!(SearchIndexState::Partial.to_string(), "partial");
        assert_eq!(SearchIndexState::Ready.to_string(), "ready");
        assert_eq!(SearchIndexState::Stale.to_string(), "stale");
        assert_eq!(SearchIndexState::Refreshing.to_string(), "refreshing");
        assert_eq!(SearchIndexState::Promoting.to_string(), "promoting");
        assert_eq!(SearchIndexState::Failed.to_string(), "failed");
        assert_eq!(IndexControllerState::Unspecified.to_string(), "unspecified");
        assert_eq!(IndexControllerState::Ramping.to_string(), "ramping");
        assert_eq!(IndexControllerState::Steady.to_string(), "steady");
        assert_eq!(IndexControllerState::Throttled.to_string(), "throttled");
        assert_eq!(IndexControllerState::Paused.to_string(), "paused");
        assert_eq!(IndexPauseReason::Unspecified.to_string(), "unspecified");
        assert_eq!(IndexPauseReason::Foreground.to_string(), "foreground");
        assert_eq!(IndexPauseReason::OpcHealth.to_string(), "opc-health");
        assert_eq!(IndexPauseReason::HostCpu.to_string(), "host-cpu");
        assert_eq!(IndexPauseReason::Memory.to_string(), "memory");
        assert_eq!(IndexPauseReason::Disk.to_string(), "disk");
        assert_eq!(IndexPauseReason::Database.to_string(), "database");
        assert_eq!(IndexPauseReason::Operator.to_string(), "operator");
        assert_eq!(IndexPauseReason::Circuit.to_string(), "circuit");
        assert_eq!(IndexHealthState::Unspecified.to_string(), "unspecified");
        assert_eq!(IndexHealthState::Healthy.to_string(), "healthy");
        assert_eq!(IndexHealthState::Unhealthy.to_string(), "unhealthy");
        assert_eq!(IndexHealthState::Unavailable.to_string(), "unavailable");
        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 indexed_search_request_and_controls_map_all_variants() {
        for (mode, expected) in [
            (SearchMatchMode::Exact, proto::SearchMatchMode::Exact),
            (SearchMatchMode::Prefix, proto::SearchMatchMode::Prefix),
            (SearchMatchMode::Contains, proto::SearchMatchMode::Contains),
        ] {
            let request = SearchIndexRequest::new("S", "query", mode);
            assert_eq!(request.max_results, DEFAULT_INDEX_SEARCH_MAX_RESULTS);
            let mapped: proto::SearchIndexRequest = request.into();
            assert_eq!(mapped.match_mode, expected as i32);
        }
        for (action, expected) in [
            (
                SearchIndexControlAction::Pause,
                proto::SearchIndexControlAction::Pause,
            ),
            (
                SearchIndexControlAction::Resume,
                proto::SearchIndexControlAction::Resume,
            ),
            (
                SearchIndexControlAction::Cancel,
                proto::SearchIndexControlAction::Cancel,
            ),
        ] {
            assert_eq!(proto::SearchIndexControlAction::from(action), expected);
        }
    }

    #[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(_))));
        for (proto_state, state) in [
            (
                proto::SearchIndexState::Unspecified,
                SearchIndexState::Unspecified,
            ),
            (
                proto::SearchIndexState::NotIndexed,
                SearchIndexState::NotIndexed,
            ),
            (proto::SearchIndexState::Partial, SearchIndexState::Partial),
            (proto::SearchIndexState::Ready, SearchIndexState::Ready),
            (proto::SearchIndexState::Stale, SearchIndexState::Stale),
            (
                proto::SearchIndexState::Refreshing,
                SearchIndexState::Refreshing,
            ),
            (
                proto::SearchIndexState::Promoting,
                SearchIndexState::Promoting,
            ),
            (proto::SearchIndexState::Failed, SearchIndexState::Failed),
        ] {
            assert_eq!(search_index_state(proto_state as i32).unwrap(), state);
        }
        assert!(matches!(search_index_state(99), Err(Error::Protocol(_))));
        for (proto_state, state) in [
            (
                proto::IndexControllerState::Unspecified,
                IndexControllerState::Unspecified,
            ),
            (
                proto::IndexControllerState::Ramping,
                IndexControllerState::Ramping,
            ),
            (
                proto::IndexControllerState::Steady,
                IndexControllerState::Steady,
            ),
            (
                proto::IndexControllerState::Throttled,
                IndexControllerState::Throttled,
            ),
            (
                proto::IndexControllerState::Paused,
                IndexControllerState::Paused,
            ),
        ] {
            assert_eq!(index_controller_state(proto_state as i32).unwrap(), state);
        }
        assert!(matches!(
            index_controller_state(99),
            Err(Error::Protocol(_))
        ));
        for (proto_reason, reason) in [
            (
                proto::IndexPauseReason::Unspecified,
                IndexPauseReason::Unspecified,
            ),
            (
                proto::IndexPauseReason::Foreground,
                IndexPauseReason::Foreground,
            ),
            (
                proto::IndexPauseReason::OpcHealth,
                IndexPauseReason::OpcHealth,
            ),
            (proto::IndexPauseReason::HostCpu, IndexPauseReason::HostCpu),
            (proto::IndexPauseReason::Memory, IndexPauseReason::Memory),
            (proto::IndexPauseReason::Disk, IndexPauseReason::Disk),
            (
                proto::IndexPauseReason::Database,
                IndexPauseReason::Database,
            ),
            (
                proto::IndexPauseReason::Operator,
                IndexPauseReason::Operator,
            ),
            (proto::IndexPauseReason::Circuit, IndexPauseReason::Circuit),
        ] {
            assert_eq!(index_pause_reason(proto_reason as i32).unwrap(), reason);
        }
        assert!(matches!(index_pause_reason(99), Err(Error::Protocol(_))));
        for (proto_state, state) in [
            (
                proto::IndexHealthState::Unspecified,
                IndexHealthState::Unspecified,
            ),
            (proto::IndexHealthState::Healthy, IndexHealthState::Healthy),
            (
                proto::IndexHealthState::Unhealthy,
                IndexHealthState::Unhealthy,
            ),
            (
                proto::IndexHealthState::Unavailable,
                IndexHealthState::Unavailable,
            ),
        ] {
            assert_eq!(index_health_state(proto_state as i32).unwrap(), state);
        }
        assert!(matches!(index_health_state(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(_))
        ));
    }

    #[test]
    fn indexed_search_response_preserves_identity_and_status() {
        let response = proto::SearchIndexResponse {
            matches: vec![proto::IndexedSearchMatch {
                item_id: "FCS0201!204FI00510.PV".into(),
                display_name: "PV".into(),
                kind: proto::BrowseNodeKind::BranchAndItem as i32,
                breadcrumbs: vec!["FCS0201".into(), "204FI00510".into()],
            }],
            has_more: true,
            status: Some(proto::SearchIndexStatus {
                server: "Yokogawa.CSHIS_OPC.1".into(),
                state: proto::SearchIndexState::Refreshing as i32,
                configured: true,
                active_generation: 7,
                entry_count: 100_001,
                unique_item_count: 100_000,
                started_at: Some("start".into()),
                completed_at: Some("complete".into()),
                last_error: Some("prior error".into()),
                database_bytes: 4096,
                organization: proto::NamespaceOrganization::Hierarchical as i32,
                source: proto::BrowseSource::Da2 as i32,
                progress: Some(proto::IndexedSearchProgress {
                    branches_visited: 10,
                    entries_seen: 20,
                    unique_items: 19,
                    active_time_ms: 30,
                    paused_time_ms: 40,
                    items_per_second: 12.5,
                    estimated_remaining_ms: Some(50),
                }),
                effective_limits: Some(proto::IndexInventoryLimits {
                    item_rate_per_second: 100,
                    batch_size: 25,
                    duty_cycle_percent: 5,
                }),
                controller_state: proto::IndexControllerState::Throttled as i32,
                pause_reason: Some(proto::IndexPauseReason::Database as i32),
                recovery_deadline: Some("recover".into()),
                pause_reason_detail: Some("commit latency".into()),
                foreground: Some(proto::IndexForegroundDiagnostics {
                    active_count: 1,
                    operations: 2,
                    errors: 3,
                    bad_quality: 4,
                    latency_p50_ms: Some(5),
                    latency_p95_ms: Some(6),
                    latency_max_ms: Some(7),
                    last_error: true,
                    last_bad_quality: true,
                }),
                host: Some(proto::IndexHostDiagnostics {
                    cpu_percent: Some(8.0),
                    available_memory_percent: Some(9.0),
                    disk_active_percent: Some(10.0),
                    disk_queue: Some(11.0),
                    process_working_set_bytes: Some(12),
                    process_private_bytes: Some(13),
                    process_read_bytes_per_second: Some(14),
                    process_write_bytes_per_second: Some(15),
                    disk_free_bytes: Some(16),
                }),
                storage: Some(proto::IndexStorageDiagnostics {
                    main_bytes: 17,
                    wal_bytes: 18,
                    shm_bytes: 19,
                    free_bytes: Some(20),
                    last_commit_latency_ms: Some(21),
                }),
                scheduler: Some(proto::IndexSchedulerDiagnostics {
                    next_refresh_at: Some("next".into()),
                    last_attempt_at: Some("attempt".into()),
                    last_success_at: Some("success".into()),
                    last_success_duration_ms: Some(22),
                    retry_after: Some("retry".into()),
                    consecutive_failures: 23,
                    circuit_open: true,
                }),
                health: Some(proto::IndexHealthDiagnostics {
                    state: proto::IndexHealthState::Healthy as i32,
                    sentinel_configured: true,
                }),
                promoting: true,
            }),
        };
        let typed = SearchIndexResponse::try_from(response).unwrap();
        assert_eq!(typed.matches[0].item_id, "FCS0201!204FI00510.PV");
        assert_eq!(typed.matches[0].kind, BrowseNodeKind::BranchAndItem);
        assert_eq!(typed.status.state, SearchIndexState::Refreshing);
        assert_eq!(
            typed
                .status
                .progress
                .as_ref()
                .unwrap()
                .estimated_remaining_ms,
            Some(50)
        );
        assert_eq!(
            typed.status.effective_limits,
            Some(IndexInventoryLimits {
                item_rate_per_second: 100,
                batch_size: 25,
                duty_cycle_percent: 5,
            })
        );
        assert_eq!(
            typed.status.controller_state,
            IndexControllerState::Throttled
        );
        assert_eq!(typed.status.pause_reason, Some(IndexPauseReason::Database));
        assert_eq!(typed.status.recovery_deadline.as_deref(), Some("recover"));
        assert_eq!(
            typed.status.pause_reason_detail.as_deref(),
            Some("commit latency")
        );
        assert_eq!(
            typed.status.foreground,
            IndexForegroundDiagnostics {
                active_count: 1,
                operations: 2,
                errors: 3,
                bad_quality: 4,
                latency_p50_ms: Some(5),
                latency_p95_ms: Some(6),
                latency_max_ms: Some(7),
                last_error: true,
                last_bad_quality: true,
            }
        );
        assert_eq!(
            typed.status.host,
            IndexHostDiagnostics {
                cpu_percent: Some(8.0),
                available_memory_percent: Some(9.0),
                disk_active_percent: Some(10.0),
                disk_queue: Some(11.0),
                process_working_set_bytes: Some(12),
                process_private_bytes: Some(13),
                process_read_bytes_per_second: Some(14),
                process_write_bytes_per_second: Some(15),
                disk_free_bytes: Some(16),
            }
        );
        assert_eq!(
            typed.status.storage,
            IndexStorageDiagnostics {
                main_bytes: 17,
                wal_bytes: 18,
                shm_bytes: 19,
                free_bytes: Some(20),
                last_commit_latency_ms: Some(21),
            }
        );
        assert_eq!(
            typed.status.scheduler,
            IndexSchedulerDiagnostics {
                next_refresh_at: Some("next".into()),
                last_attempt_at: Some("attempt".into()),
                last_success_at: Some("success".into()),
                last_success_duration_ms: Some(22),
                retry_after: Some("retry".into()),
                consecutive_failures: 23,
                circuit_open: true,
            }
        );
        assert_eq!(
            typed.status.health,
            IndexHealthDiagnostics {
                state: IndexHealthState::Healthy,
                sentinel_configured: true,
            }
        );
        assert!(typed.status.promoting);
        assert!(typed.has_more);

        let defaults = SearchIndexStatus::try_from(proto::SearchIndexStatus::default()).unwrap();
        assert_eq!(defaults.foreground, IndexForegroundDiagnostics::default());
        assert_eq!(defaults.host, IndexHostDiagnostics::default());
        assert_eq!(defaults.storage, IndexStorageDiagnostics::default());
        assert_eq!(defaults.scheduler, IndexSchedulerDiagnostics::default());
        assert_eq!(defaults.health, IndexHealthDiagnostics::default());

        let item = IndexedSearchMatch::try_from(proto::IndexedSearchMatch {
            kind: proto::BrowseNodeKind::Item as i32,
            item_id: "id".into(),
            ..Default::default()
        })
        .unwrap();
        assert_eq!(item.kind, BrowseNodeKind::Item);
        assert!(matches!(
            IndexedSearchMatch::try_from(proto::IndexedSearchMatch {
                kind: proto::BrowseNodeKind::Item as i32,
                ..Default::default()
            }),
            Err(Error::Protocol(_))
        ));

        assert!(matches!(
            IndexedSearchMatch::try_from(proto::IndexedSearchMatch {
                kind: proto::BrowseNodeKind::Branch as i32,
                ..Default::default()
            }),
            Err(Error::Protocol(_))
        ));
        assert!(matches!(
            SearchIndexResponse::try_from(proto::SearchIndexResponse::default()),
            Err(Error::Protocol(_))
        ));
    }
}