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
use std::collections::HashSet;
use crate::error::{CaError, CaResult};
use crate::server::snapshot::Snapshot;
use crate::types::EpicsValue;
use super::PvDatabase;
impl PvDatabase {
/// Get a PV value synchronously from a blocking thread.
///
/// Uses `block_in_place` + `Handle::block_on` to bridge the async
/// `get_pv` call. Safe to call from std::threads spawned within
/// a tokio runtime context.
pub fn get_pv_blocking(&self, name: &str) -> CaResult<EpicsValue> {
let db = self.clone();
let name = name.to_string();
if crate::runtime::task::RuntimeHandle::try_current().is_ok() {
crate::__tokio::task::block_in_place(|| {
crate::runtime::task::RuntimeHandle::current().block_on(db.get_pv(&name))
})
} else {
Err(CaError::InvalidValue(
"no runtime for get_pv_blocking".into(),
))
}
}
/// Get the current value of a PV or record field.
/// Uses resolve_field for records (3-level priority).
pub async fn get_pv(&self, name: &str) -> CaResult<EpicsValue> {
let (base, field) = super::parse_pv_name(name);
let field = field.to_ascii_uppercase();
// Check simple PVs first (exact match)
if let Some(pv) = self.inner.simple_pvs.read().await.get(name) {
return Ok(pv.get().await);
}
// Records — alias-aware via `get_record` (epics-base PR #336).
if let Some(rec) = self.get_record(base).await {
let instance = rec.read().await;
return instance
.resolve_field(&field)
.ok_or_else(|| CaError::ChannelNotFound(name.to_string()));
}
Err(CaError::ChannelNotFound(name.to_string()))
}
/// Set a PV value or record field, notifying subscribers.
/// Tries record put_field first, then put_common_field as fallback.
///
/// Acquires the record's advisory write gate.
pub async fn put_pv(&self, name: &str, value: EpicsValue) -> CaResult<()> {
self.put_pv_inner(name, value, true).await
}
/// `put_pv` variant for a caller already holding the
/// record's advisory write gate (QSRV atomic group PUT). See
/// [`Self::put_record_field_from_ca_already_locked`].
pub async fn put_pv_already_locked(&self, name: &str, value: EpicsValue) -> CaResult<()> {
self.put_pv_inner(name, value, false).await
}
async fn put_pv_inner(
&self,
name: &str,
value: EpicsValue,
acquire_gate: bool,
) -> CaResult<()> {
let (base, field) = super::parse_pv_name(name);
let field = field.to_ascii_uppercase();
// Check simple PVs first
if let Some(pv) = self.inner.simple_pvs.read().await.get(name) {
pv.set(value).await;
return Ok(());
}
// Records — alias-aware (epics-base PR #336).
if let Some(rec) = self.get_record(base).await {
// `base` may be an alias; resolve to the canonical record
// name so scan-index updates target the right entry.
let canonical_base: String = self
.resolve_alias(base)
.await
.unwrap_or_else(|| base.to_string());
// advisory write gate (`dbScanLock` analogue) so a
// plain `put_pv` to a backing record cannot interleave
// with an atomic group transaction holding the same gate.
// Skipped when the caller already owns the gate.
let _record_gate = if acquire_gate {
Some(self.lock_record(&canonical_base).await)
} else {
None
};
let mut instance = rec.write().await;
// Coerce value to field's native type
let value = {
let target_type = instance
.record
.field_list()
.iter()
.find(|f| f.name.eq_ignore_ascii_case(&field))
.map(|f| f.dbf_type);
if let Some(target) = target_type {
if value.db_field_type() != target {
// C EPICS dbPut (12cfd41): nRequest=0 into a scalar
// field must NOT silently coerce. `convert_to` on an
// empty array calls `to_f64().unwrap_or(0.0)` and
// would produce a scalar zero — the same garbage-
// value bug the C fix raised LINK_ALARM for.
if value.is_empty_array() {
return Err(CaError::InvalidValue(format!(
"empty array cannot be coerced to scalar field {field}"
)));
}
value.convert_to(target)
} else {
value
}
} else {
value
}
};
// Capture the pre-put value so the metadata-cache
// invalidation (and the downstream `DBE_PROPERTY`
// emission) can be skipped when the put is a no-op —
// epics-base faac1df1.
let prev_value = instance.record.get_field(&field);
// put_pv is C EPICS dbPut: write value + special/on_put.
// Does NOT post monitor events (use put_pv_and_post for that).
// Does NOT clear UDF or trigger processing.
use crate::server::record::CommonFieldPutResult;
let common_result = match instance.record.put_field(&field, value.clone()) {
Ok(()) => {
instance.record.on_put(&field);
let _ = instance.record.special(&field, true);
CommonFieldPutResult::NoChange
}
Err(CaError::FieldNotFound(_)) => instance.put_common_field(&field, value)?,
Err(e) => return Err(e),
};
// Invalidate metadata cache only if the metadata-class
// field's value actually changed (faac1df1).
instance.notify_field_written_if_changed(&field, prev_value.as_ref());
// Update scan index if SCAN or PHAS changed
match common_result {
CommonFieldPutResult::ScanChanged {
old_scan,
new_scan,
phas,
} => {
drop(instance);
self.update_scan_index(&canonical_base, old_scan, new_scan, phas, phas)
.await;
}
CommonFieldPutResult::PhasChanged {
scan: s,
old_phas,
new_phas,
} => {
drop(instance);
self.update_scan_index(&canonical_base, s, s, old_phas, new_phas)
.await;
}
CommonFieldPutResult::NoChange => {}
}
// mirror the CA-write path's ASG-field notifier so
// restore scripts / autosave / admin tools that go via
// `put_pv` (not `put_record_field_from_ca`) also trigger
// per-client `reeval_access_rights`. C `dbAccess.c::
// dbPutSpecial` invokes the SPC_AS callback from dbPut
// regardless of caller entry path.
if field == "ASG" {
crate::server::access_security::notify_asg_field_changed();
}
return Ok(());
}
Err(CaError::ChannelNotFound(name.to_string()))
}
/// Write a value and post monitor events if changed.
/// Equivalent to C EPICS `dbPut` + `db_post_events(DBE_VALUE|DBE_LOG)`.
///
/// Use for readback/status mirror PVs that are written by sequencer-style
/// code and need to be visible to CA monitors without triggering record
/// processing. Clears UDF/UDF_ALARM on primary field write.
///
/// `origin`: writer ID for self-write filtering. Subscribers with the
/// same `ignore_origin` will skip this event. Pass 0 to disable.
pub async fn put_pv_and_post(&self, name: &str, value: EpicsValue) -> CaResult<()> {
self.put_pv_and_post_with_origin(name, value, 0).await
}
/// Push a monitor event holding the simple PV's *current* value
/// but with explicit alarm severity/status. Used by the gateway
/// to surface upstream-disconnect to downstream monitor
/// subscribers without dropping the shadow PV (which would force
/// downstream clients into ECA_DISCONN reconnect storms on every
/// transient hiccup). Returns `ChannelNotFound` for record-backed
/// PVs — those carry their own `common.sevr/stat` in record
/// processing.
pub async fn post_alarm(&self, name: &str, severity: u16, status: u16) -> CaResult<()> {
if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
pv.post_alarm(severity, status).await;
return Ok(());
}
Err(crate::error::CaError::ChannelNotFound(name.to_string()))
}
/// Propagate a full upstream snapshot (value + alarm status/severity +
/// IOC timestamp) to a simple shadow PV and fan out to downstream
/// monitor subscribers. Used by the CA gateway forwarding task to avoid
/// discarding the upstream alarm and timestamp decoded from the incoming
/// `DBR_TIME_*` frame. Returns `ChannelNotFound` for record-backed PVs
/// (those carry their own alarm engine and are not shadow PVs).
pub async fn put_pv_and_post_snapshot(&self, name: &str, snapshot: Snapshot) -> CaResult<()> {
if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
pv.set_snapshot(snapshot).await;
return Ok(());
}
Err(CaError::ChannelNotFound(name.to_string()))
}
/// Install upstream `DBR_CTRL_*` metadata (display / control limits,
/// enum labels) on a shadow simple PV WITHOUT posting an event.
///
/// The CA gateway calls this once on upstream connect, after its initial
/// `DBR_CTRL_*` get, so a later downstream `DBR_CTRL_*` / `DBR_GR_*` read
/// returns the real limits instead of zeroed ones. No `DBE_PROPERTY`
/// monitor event fires — nothing has *changed* yet, this only seeds the
/// attribute cache. Mirrors C `gatePvData::getCB` → `runDataCB` →
/// `vc->setPvData(dd)` (`gatePv.cc:1693-1695`), which seeds the property
/// cache from the initial control get in both cache modes before any
/// monitor is enabled.
///
/// Returns `ChannelNotFound` for record-backed PVs — those own their own
/// metadata via record processing and are not gateway shadow PVs.
pub async fn set_pv_metadata(&self, name: &str, snapshot: &Snapshot) -> CaResult<()> {
if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
pv.set_metadata(metadata_from_snapshot(snapshot));
return Ok(());
}
Err(CaError::ChannelNotFound(name.to_string()))
}
/// Refresh a shadow simple PV's upstream metadata AND post a
/// `DBE_PROPERTY` monitor event carrying `snapshot` to downstream
/// property subscribers.
///
/// `snapshot` is the decoded upstream `DBR_CTRL_*` property event: it
/// carries the control value and the upstream `status` / `severity`,
/// and (because control DBR structs carry no timestamp) an undefined
/// timestamp the caller must NOT replace with a fresh wall-clock. The
/// gateway's property monitor calls this on every upstream
/// `DBE_PROPERTY` event, mirroring C `gatePvData::propEventCB` →
/// `runDataCB` + `setPvData` + `runValueDataCB` +
/// `vcPostEvent(propertyEventMask())` (`gatePv.cc:1571-1607`): the
/// attribute cache is refreshed and a property event is posted with the
/// upstream alarm state preserved (`setStatSevr`) and the undefined
/// control-DBR timestamp left as-is (`gatePv.cc:1594-1595`).
///
/// Returns `ChannelNotFound` for record-backed PVs.
pub async fn post_pv_property(&self, name: &str, snapshot: Snapshot) -> CaResult<()> {
if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
pv.set_metadata(metadata_from_snapshot(&snapshot));
pv.post_property(snapshot).await;
return Ok(());
}
Err(CaError::ChannelNotFound(name.to_string()))
}
/// Like `put_pv_and_post` but with explicit origin tag.
pub async fn put_pv_and_post_with_origin(
&self,
name: &str,
value: EpicsValue,
origin: u64,
) -> CaResult<()> {
let (base, field) = super::parse_pv_name(name);
let field = field.to_ascii_uppercase();
// Simple-PV path: PVs registered via `add_pv` (e.g. CA gateway
// shadow PVs, IOCsh stats PVs) are stored in `simple_pvs`,
// not `records`. Without this branch the function would
// silently return `ChannelNotFound` for every gateway-mirrored
// PV — `ProcessVariable::set` already does the
// notify-subscribers fan-out internally so all we need here is
// to delegate. The `origin` tag is a no-op for simple PVs
// because they don't yet plumb origin through `set`.
if let Some(pv) = self.inner.simple_pvs.read().await.get(name).cloned() {
let _ = origin; // simple PVs don't currently honor origin tagging
pv.set(value).await;
return Ok(());
}
if let Some(rec) = self.get_record(base).await {
// `put_pv_and_post` is a public record-write API —
// it must take the same advisory write gate
// (`dbScanLock` analogue) as `put_pv` /
// `put_record_field_from_ca`, or a gateway/sequencer
// write through this helper can still land between the
// member writes of a QSRV atomic group or a pvalink
// atomic scan epoch holding `lock_records`. `base` is
// alias-resolved to the canonical record name so an alias
// and its target share one gate. Held until return.
let canonical_base: String = self
.resolve_alias(base)
.await
.unwrap_or_else(|| base.to_string());
let _record_gate = self.lock_record(&canonical_base).await;
let mut instance = rec.write().await;
// Type coercion
let value = {
let target_type = instance
.record
.field_list()
.iter()
.find(|f| f.name.eq_ignore_ascii_case(&field))
.map(|f| f.dbf_type);
if let Some(target) = target_type {
if value.db_field_type() != target {
// C EPICS dbPut (12cfd41): empty-array → scalar
// coercion would produce silent zero; reject.
if value.is_empty_array() {
return Err(CaError::InvalidValue(format!(
"empty array cannot be coerced to scalar field {field}"
)));
}
value.convert_to(target)
} else {
value
}
} else {
value
}
};
let old_value = instance.record.get_field(&field);
let old_stat = instance.common.stat;
let old_sevr = instance.common.sevr;
// Snapshot side-effect-prone fields BEFORE the put. The
// array-family records (waveform/aai/aao/subArray) update
// NORD as a side-effect of put_field("VAL"); other record
// types return None for "NORD" and the comparison reduces
// to None==None → unchanged.
let old_nord = if field == "VAL" {
instance.record.get_field("NORD")
} else {
None
};
// Write value + special/on_put
match instance.record.put_field(&field, value.clone()) {
Ok(()) => {
instance.record.on_put(&field);
let _ = instance.record.special(&field, true);
// Clear UDF/UDF_ALARM on primary field write
if field == instance.record.primary_field() {
instance.common.udf = false;
if instance.common.stat == crate::server::recgbl::alarm_status::UDF_ALARM {
instance.common.stat = 0;
instance.common.sevr = crate::server::record::AlarmSeverity::NoAlarm;
}
}
}
Err(CaError::FieldNotFound(_)) => {
instance.put_common_field(&field, value)?;
}
Err(e) => return Err(e),
}
// Invalidate metadata cache only if a metadata-class
// field actually changed value (faac1df1 — DBE_PROPERTY
// fires on real changes, not no-op writes).
instance.notify_field_written_if_changed(&field, old_value.as_ref());
// Post monitor events if value or alarm changed
let new_value = instance.record.get_field(&field);
let value_changed = old_value != new_value;
let alarm_changed =
old_stat != instance.common.stat || old_sevr != instance.common.sevr;
let new_nord = if field == "VAL" {
instance.record.get_field("NORD")
} else {
None
};
let nord_changed = field == "VAL" && old_nord != new_nord && new_nord.is_some();
if value_changed || alarm_changed || nord_changed {
// Update timestamp so the snapshot carries current time
instance.common.time = crate::runtime::general_time::get_current();
instance.cleanup_subscribers();
if value_changed || alarm_changed {
instance.notify_field_with_origin(
&field,
crate::server::recgbl::EventMask::VALUE
| crate::server::recgbl::EventMask::LOG
| crate::server::recgbl::EventMask::ALARM,
origin,
);
}
// Surface the implicit NORD update to NORD subscribers
// for waveform/aai/aao/subArray. Without this, a CA
// gateway forwarding upstream waveform monitors via
// put_pv_and_post would update VAL on the shadow PV
// but leave downstream NORD subscribers stuck at their
// last seen length — a frozen-element-count bug that
// surfaces in PyDM image views and similar consumers
// that compute height = element_count / width.
if nord_changed {
instance.notify_field_with_origin(
"NORD",
crate::server::recgbl::EventMask::VALUE
| crate::server::recgbl::EventMask::LOG,
origin,
);
}
}
// same SPC_AS parity as `put_pv` / `put_pv_no_process`
// / the CA-write path — a gateway mirroring `.ASG` via
// `put_pv_and_post` must still trigger per-client
// re-eval.
if field == "ASG" {
crate::server::access_security::notify_asg_field_changed();
}
return Ok(());
}
Err(CaError::ChannelNotFound(name.to_string()))
}
/// CA client's unified entry point for record field put.
/// Handles DISP/PROC/PACT/LCNT checks, field put, device write, and Passive process.
///
/// Acquires the record's advisory write gate
/// (`dbScanLock` analogue) for the duration of the write.
pub async fn put_record_field_from_ca(
&self,
record_name: &str,
field: &str,
value: EpicsValue,
) -> CaResult<Option<crate::runtime::sync::oneshot::Receiver<()>>> {
self.put_record_field_from_ca_inner(record_name, field, value, true, true)
.await
}
/// Variant for a caller that already owns the target
/// record's advisory write gate — the QSRV atomic group PUT,
/// which acquired every member-record gate up-front via
/// [`Self::lock_records`]. The per-record `tokio::sync::Mutex`
/// gate is NOT reentrant, so the atomic group path MUST use this
/// `_already_locked` entry to avoid dead-locking on its own
/// `ManyRecordWriteGuard`.
pub async fn put_record_field_from_ca_already_locked(
&self,
record_name: &str,
field: &str,
value: EpicsValue,
) -> CaResult<Option<crate::runtime::sync::oneshot::Receiver<()>>> {
self.put_record_field_from_ca_inner(record_name, field, value, false, true)
.await
}
/// Fire-and-forget variant — C `dbPutField` semantics: the put
/// processes the record but creates NO put-notify wait-set (C
/// builds a `putNotify` only in `dbPutNotify`, i.e. for
/// WRITE_NOTIFY). A caller that does not await the returned
/// receiver MUST use this entry: parking a wait-set whose receiver
/// is dropped occupies `RecordInstance::notify` until the record's
/// async work ends (a motor's whole motion), failing every
/// legitimate WRITE_NOTIFY on the record with ECA_PUTCBINPROG in
/// the meantime.
pub async fn put_record_field_from_ca_no_notify(
&self,
record_name: &str,
field: &str,
value: EpicsValue,
) -> CaResult<()> {
self.put_record_field_from_ca_inner(record_name, field, value, true, false)
.await
.map(|_| ())
}
/// Fire-and-forget + caller-held gate: see
/// [`Self::put_record_field_from_ca_no_notify`] and
/// [`Self::put_record_field_from_ca_already_locked`].
pub async fn put_record_field_from_ca_no_notify_already_locked(
&self,
record_name: &str,
field: &str,
value: EpicsValue,
) -> CaResult<()> {
self.put_record_field_from_ca_inner(record_name, field, value, false, false)
.await
.map(|_| ())
}
async fn put_record_field_from_ca_inner(
&self,
record_name: &str,
field: &str,
value: EpicsValue,
acquire_gate: bool,
want_notify: bool,
) -> CaResult<Option<crate::runtime::sync::oneshot::Receiver<()>>> {
let field = field.to_ascii_uppercase();
// Get record Arc — alias-aware (epics-base PR #336) so a CA
// client that connects via an alias name can put fields on
// the canonical record.
let rec = self
.get_record(record_name)
.await
.ok_or_else(|| CaError::ChannelNotFound(record_name.to_string()))?;
// Normalise to the canonical name for the rest of this
// function — every subsequent call (PACT/LCNT lookup,
// `process_record_with_links`, `update_scan_index`) uses the
// raw records map and would miss when `record_name` is an
// alias. Resolve once up front.
let canonical_owned;
let record_name: &str = if let Some(target) = self.resolve_alias(record_name).await {
canonical_owned = target;
&canonical_owned
} else {
record_name
};
// take the record's advisory write gate — the
// `dbScanLock(precord)` analogue. While a QSRV atomic group
// PUT/GET holds this record's gate via `lock_records`, this
// plain write blocks here, so a direct backing-record write
// can no longer land between member writes of an atomic group
// transaction. Held until the function returns. Skipped when
// the caller (atomic group PUT) already owns the gate — the
// gate `Mutex` is not reentrant.
let _record_gate = if acquire_gate {
Some(self.lock_record(record_name).await)
} else {
None
};
// Special field intercepts (read lock, then drop)
{
let instance = rec.read().await;
match field.as_str() {
"PACT" => return Err(CaError::ReadOnlyField("PACT".into())),
"LCNT" => return Err(CaError::ReadOnlyField("LCNT".into())),
"PUTF" => return Err(CaError::ReadOnlyField("PUTF".into())),
_ => {}
}
// PROC intercept: trigger processing regardless of DISP.
// Falls through to the put_notify_tx registration below
// so async records (motor, asyn-backed AO) signal real
// completion; otherwise WRITE_NOTIFY would return ECA_NORMAL
// before the device move actually finished.
if field == "PROC" {
// C `dbPutField` (dbAccess.c:1265) matches the proc field by
// pointer with NO value check: any write to PROC — including
// 0 — processes the record (when !pact). The standard
// `caput REC.PROC 0` / `dbpf REC.PROC 0` force-process idiom
// must therefore not be skipped for a zero value.
drop(instance);
// Continue to the put-notify setup + process below
// by jumping past the field-write step (the value
// itself isn't stored; PROC is a trigger). A
// fire-and-forget caller parks nothing — C `dbPutField`
// on PROC processes the record with no putNotify.
let parked = if want_notify {
let (completion_tx, completion_rx) = crate::runtime::sync::oneshot::channel();
let notify = crate::server::record::NotifyWaitSet::new(completion_tx);
{
let rec = self.inner.records.read().await;
if let Some(rec_arc) = rec.get(record_name) {
let mut guard = rec_arc.write().await;
if guard.notify.is_some() {
return Err(CaError::PutCallbackInProgress(
record_name.to_string(),
));
}
guard.notify = Some(notify.clone());
}
}
Some((notify, completion_rx))
} else {
None
};
let mut visited = HashSet::new();
// this PROC trigger already holds `record_name`'s
// advisory write gate — either `_record_gate` above, or
// the QSRV atomic group's `lock_records` epoch when
// entered via `put_record_field_from_ca_already_locked`.
// The gate `Mutex` is not reentrant, so the processing
// call MUST use the `_already_locked` variant.
let _ = self
.process_record_with_links_already_locked(record_name, &mut visited, 0)
.await;
// The wait-set fires the oneshot only after the whole
// FLNK/OUT chain (sync + async) settles. If it has
// already completed the chain was fully synchronous —
// report immediate success; otherwise hand the receiver
// to the CA layer to await the deferred completion.
return match parked {
Some((notify, completion_rx)) => {
if notify.completed() {
Ok(None)
} else {
Ok(Some(completion_rx))
}
}
None => Ok(None),
};
}
// DISP check: block CA puts to non-DISP fields when DISP=1
if instance.common.disp && field != "DISP" {
return Err(CaError::PutDisabled(field));
}
}
// Normal field put (write lock)
let common_result = {
let mut instance = rec.write().await;
instance.common.putf = true;
// Coerce value to the field's native DBR type (e.g. String → Double for ao.VAL).
// This matches C EPICS db_put_field() which converts from the CA client's type
// to the record field's native type.
let value = {
let target_type = instance
.record
.field_list()
.iter()
.find(|f| f.name.eq_ignore_ascii_case(&field))
.map(|f| f.dbf_type);
if let Some(target) = target_type {
if value.db_field_type() != target {
// C EPICS dbPut (12cfd41): empty-array → scalar
// coercion would produce silent zero; reject.
if value.is_empty_array() {
instance.common.putf = false;
return Err(CaError::InvalidValue(format!(
"empty array cannot be coerced to scalar field {field}"
)));
}
value.convert_to(target)
} else {
value
}
} else {
value
}
};
// SPC_NOMOD: reject writes to read-only fields (C EPICS S_db_noMod)
let is_read_only = instance
.record
.field_list()
.iter()
.find(|f| f.name.eq_ignore_ascii_case(&field))
.is_some_and(|f| f.read_only);
if is_read_only {
instance.common.putf = false;
return Err(CaError::ReadOnlyField(field));
}
// Pre-write special hook (C EPICS dbPutSpecial pass=0)
if let Err(e) = instance.record.special(&field, false) {
instance.common.putf = false;
return Err(e);
}
// Capture pre-put value for faac1df1 idempotent-write suppression.
let prev_value = instance.record.get_field(&field);
// Try record-specific field first; fall back to common on FieldNotFound.
// For record-owned fields, call on_put() and special() after successful put,
// matching what put_common_field() does for common fields.
use crate::server::record::CommonFieldPutResult;
// Snapshot alarm-ack state so the post block can replicate C
// putAckt/putAcks (dbAccess.c:1285-1315), which post only when
// `ackt`/`acks` actually change.
let ackt_before = instance.common.ackt;
let acks_before = instance.common.acks;
let common_result = match instance.record.put_field(&field, value.clone()) {
Ok(()) => {
instance.record.on_put(&field);
let _ = instance.record.special(&field, true);
// C `dbAccess.c::dbPut:1410-1411` clears
// `precord->udf = FALSE` synchronously when the
// put target is the record-type's primary value
// field (`dbIsValueField`). The clear happens
// BEFORE `dbProcess` runs, so any reader between
// the put and the process-cycle's own clear sees
// the new value with a consistent UDF=false.
//
// Rust's processing path also clears UDF via
// `clears_udf()` in process/complete_async_record,
// but that runs AFTER the put lock drops and the
// process re-acquires — leaving a small window
// where another reader can observe (new VAL,
// udf=true). For async records the window spans
// the entire device round trip. Clear here to
// close the window. The same clear already exists
// in `put_pv_and_post` (line 256-262); mirror it.
if field == instance.record.primary_field() {
instance.common.udf = false;
if instance.common.stat == crate::server::recgbl::alarm_status::UDF_ALARM {
instance.common.stat = 0;
instance.common.sevr = crate::server::record::AlarmSeverity::NoAlarm;
}
}
CommonFieldPutResult::NoChange
}
Err(CaError::FieldNotFound(_)) => instance.put_common_field(&field, value)?,
Err(e) => {
instance.common.putf = false;
return Err(e);
}
};
// Invalidate metadata cache only if the metadata-class
// field's value actually changed (faac1df1).
instance.notify_field_written_if_changed(&field, prev_value.as_ref());
// C `dbAccess.c::dbPutField:1276` sets `precord->putf = TRUE`
// immediately before calling `dbProcess`, and the flag stays
// TRUE through the entire process cycle. It is cleared only
// in `recGblFwdLink` (recGbl.c:302) after FLNK fires, OR in
// the disable-alarm bail (dbAccess.c:576). The Rust port
// previously cleared `putf` here — BEFORE the
// `process_record_with_links` call below — so any code
// path (TPRO trace, async-completion logic, monitor on
// .PUTF) observing the bit during the process cycle saw
// `putf=0` and could not distinguish put-driven vs
// scan-driven processing.
//
// DO NOT clear `putf` here. The clearing now happens after
// the process call returns (synchronous completion) or in
// `complete_async_record` (async completion).
instance.cleanup_subscribers();
// C `dbPut:1408-1414` posts DBE_VALUE|DBE_LOG for the put field
// unless `(isValueField && pfldDes->process_passive)` — the
// immediate post is suppressed for the value field ONLY when that
// field is `pp(TRUE)`, because then the reprocess cycle
// (`dbPutField:1265-1268`) re-posts it via the deadband snapshot.
// For a value field that is NOT `pp` (calc/calcout/aSub VAL), C
// posts here and does not reprocess; the port must do the same,
// because the `should_process` gate below skips the cycle for a
// non-`pp` value field — without this post a direct VAL put would
// fire no monitor at all.
if field.eq_ignore_ascii_case("ACKT") || field.eq_ignore_ascii_case("ACKS") {
// Alarm-acknowledge fields are C `dbPut`'s DBR_PUT_ACKT/ACKS
// special handlers (`dbAccess.c:1285-1315`), NOT a plain
// common-field put. They post with DBE_VALUE|DBE_ALARM (never
// DBE_LOG), and post a record-wide DBE_ALARM
// (`db_post_events(precord, NULL, DBE_ALARM)`) so an
// alarm-mask monitor on ANY field observes the ack — but only
// when the ack state actually changed, so the generic
// DBE_VALUE|DBE_LOG post below is fully suppressed here.
use crate::server::recgbl::EventMask;
let ack_mask = EventMask::VALUE | EventMask::ALARM;
if field.eq_ignore_ascii_case("ACKT") {
// putAckt: post only on a real ackt change; re-post ACKS
// when turning ACKT off lowered it (C:1294-1297).
if instance.common.ackt != ackt_before {
instance.notify_field(&field, ack_mask);
if instance.common.acks != acks_before {
instance.notify_field("ACKS", ack_mask);
}
instance.notify_record_alarm();
}
} else {
// putAcks: post only when the write actually cleared ACKS
// (C:1309-1313); a too-low ack severity posts nothing.
if instance.common.acks != acks_before {
instance.notify_field(&field, ack_mask);
instance.notify_record_alarm();
}
}
} else {
let suppress_value_field_post = field == instance.record.primary_field()
&& match instance.record.process_passive_fields() {
Some(pp) => pp.iter().any(|f| f.eq_ignore_ascii_case(&field)),
// Un-modeled record types keep the legacy "process on
// every put" behavior (`should_process = true` below),
// so the reprocess cycle posts the value field —
// suppress the immediate post here to avoid a
// duplicate event.
None => true,
};
if !suppress_value_field_post {
instance.notify_field(
&field,
crate::server::recgbl::EventMask::VALUE
| crate::server::recgbl::EventMask::LOG,
);
}
// Fields a `special()` changed as a side effect of this put
// (e.g. compress RES reset zeroing NUSE/VAL) get their monitors
// posted here, mirroring the explicit `db_post_events` a C
// `special()` makes — these fields are not pp(TRUE), so no
// process cycle would otherwise post them.
for sf in instance.record.monitor_side_effect_fields(&field) {
instance.notify_field(
sf,
crate::server::recgbl::EventMask::VALUE
| crate::server::recgbl::EventMask::LOG,
);
}
}
common_result
};
// ASG-field change re-evaluation hook. C
// `asDbLib.c:107-110,144` `asSpcAsCallback` invokes
// `asChangeGroup` → `asAddMemberPvt` → `asComputePvt` for
// every `ASGCLIENT` on `dbPut record.ASG NEW_ASG`. Pre-fix
// Rust mutated `common.asg` directly with no notification,
// so the wire ACCESS_RIGHTS the client saw still reflected
// the OLD ASG until something else triggered re-eval. Now we
// fire a process-wide notifier that the CA server folds into
// its per-client `reeval_access_rights` path.
if field == "ASG" {
crate::server::access_security::notify_asg_field_changed();
}
// record lock released
// Update scan index if SCAN or PHAS changed
match common_result {
crate::server::record::CommonFieldPutResult::ScanChanged {
old_scan,
new_scan,
phas,
} => {
self.update_scan_index(record_name, old_scan, new_scan, phas, phas)
.await;
}
crate::server::record::CommonFieldPutResult::PhasChanged {
scan: s,
old_phas,
new_phas,
} => {
self.update_scan_index(record_name, s, s, old_phas, new_phas)
.await;
}
crate::server::record::CommonFieldPutResult::NoChange => {}
}
// C `dbAccess.c::dbPutField:1263-1268` re-processes the
// record on a put only when the put field is `pp(TRUE)` AND the
// record is Passive (`SCAN == 0`). (The `PROC` field has its own
// always-process intercept above, matching C's
// `pfield == &precord->proc`; alarm-ack fields like ACKT/ACKS are
// not `pp(TRUE)` so they fall out here, matching C's
// `dbrType < DBR_PUT_ACKT`.) Processing on every put would
// double-process scanned records and spuriously process puts to
// non-`pp` fields (extra FLNK / monitors / device writes /
// timestamps). A record type whose DBD pp-flags are not modeled
// returns `None` and keeps the legacy "process on every put"
// behavior so un-modeled types (other crates, tests) are unchanged.
let should_process = {
let instance = rec.read().await;
match instance.record.process_passive_fields() {
Some(pp) => {
instance.common.scan == crate::server::record::ScanType::Passive
&& pp.iter().any(|f| f.eq_ignore_ascii_case(&field))
}
None => true,
}
};
if !should_process {
// No processing cycle. C never sets `putf` on this path, so
// clear the flag the field-put set at entry, and report
// immediate (synchronous) completion to a WRITE_NOTIFY caller.
let recs = self.inner.records.read().await;
if let Some(rec_arc) = recs.get(record_name) {
let mut guard = rec_arc.write().await;
if !guard.is_processing() {
guard.common.putf = false;
}
}
return Ok(None);
}
// Set up the put-notify wait-set BEFORE processing. The wait-set
// fires `completion_tx` only after the originating record AND
// every FLNK/OUT chain target it triggers (sync or async) has
// completed — C `dbNotify.c` `processNotify`/`dbNotifyCompletion`.
// Refuse a second concurrent WRITE_NOTIFY on the same record:
// C EPICS returns S_db_Blocked / ECA_PUTCBINPROG, and silently
// overwriting the wait-set would drop the prior Sender, waking
// the prior caller's rx with RecvError that the CA dispatcher
// treats as success.
//
// A fire-and-forget put parks NOTHING — C builds a `putNotify`
// only in `dbPutNotify`; `dbPutField` processes the record with
// no notify state at all. It therefore neither conflicts with
// nor disturbs a WRITE_NOTIFY already parked on the record.
let parked = if want_notify {
let (completion_tx, completion_rx) = crate::runtime::sync::oneshot::channel();
let notify = crate::server::record::NotifyWaitSet::new(completion_tx);
{
let rec = self.inner.records.read().await;
if let Some(rec_arc) = rec.get(record_name) {
let mut guard = rec_arc.write().await;
if guard.notify.is_some() {
return Err(CaError::PutCallbackInProgress(record_name.to_string()));
}
guard.notify = Some(notify.clone());
}
}
Some((notify, completion_rx))
} else {
None
};
// When a CA put writes directly to VAL on an INPUT record whose
// VAL is the engineering value, the built-in `RVAL → VAL`
// `convert()` must be suppressed for the put-driven process —
// re-deriving VAL from a stale RVAL would clobber the value the
// operator just wrote (the soft ai preset-NaN case, processing.rs
// ~line 677). The framework expresses this by calling
// `set_device_did_compute(true)`.
//
// This MUST be gated on `soft_channel_skips_convert()`. Output
// records (mbbo/mbbo_direct/bo/ao) implement
// `set_device_did_compute` as "skip the VAL → RVAL output
// convert" — the OPPOSITE direction. C `mbboRecord.c::process`
// (line 217), `mbboDirectRecord.c::process` (line 198) and
// `boRecord.c::process` (line 207) call `convert()`
// unconditionally on every non-pact process; a CA VAL-put on an
// output record MUST recompute RVAL/ORAW. Suppressing it there
// left RVAL/ORAW/ORBV stale. Output records return the default
// `false` from `soft_channel_skips_convert()`, so this gate
// matches the identical gates in processing.rs (line 694) and
// record_instance.rs (line 1381).
if field == "VAL" {
let recs = self.inner.records.read().await;
if let Some(rec_arc) = recs.get(record_name) {
let mut guard = rec_arc.write().await;
if guard.record.soft_channel_skips_convert() {
guard.record.set_device_did_compute(true);
}
}
}
// Process the record after field put.
{
let mut visited = HashSet::new();
// `record_name`'s advisory write gate is already
// held by this `put` (the `_record_gate` taken above, or
// the QSRV atomic group's `lock_records` epoch via
// `put_record_field_from_ca_already_locked`). The gate
// `Mutex` is not reentrant — use the `_already_locked`
// processing entry.
let _ = self
.process_record_with_links_already_locked(record_name, &mut visited, 0)
.await;
}
// Is the ORIGINATING record itself still async-pending? Its
// wait-set membership is taken + `leave`d at its own completion
// (sync-end, or later in `complete_async_record_inner`), so a
// lingering `notify` on its instance means its device round-trip
// is still in flight. This gates only the originating record's
// PUTF clear — independent of whether downstream chain targets
// are still pending.
//
// A fire-and-forget put parked nothing, and a `notify` it sees
// on the instance belongs to some other caller's WRITE_NOTIFY —
// not evidence about THIS put. Fall through to the guarded
// clear; its `!is_processing()` gate already preserves PUTF
// across an async-pending device round-trip.
let originating_pending = want_notify && {
let rec = self.inner.records.read().await;
if let Some(rec_arc) = rec.get(record_name) {
rec_arc.read().await.notify.is_some()
} else {
false
}
};
// C `recGbl.c::recGblFwdLink:302` clears `putf = FALSE` after
// the forward-link dispatch — the marker only lives for the
// duration of the put's processing cycle. For SYNCHRONOUS
// completions (PACT was cleared by the time
// `process_record_with_links` returns) clear it here. For
// async-pending records, the clearing happens later in
// `complete_async_record_inner` (which runs FLNK as part of
// the completion path) so the PUTF marker survives the
// device-write round trip.
if !originating_pending {
let rec = self.inner.records.read().await;
if let Some(rec_arc) = rec.get(record_name) {
let mut guard = rec_arc.write().await;
if !guard.is_processing() {
guard.common.putf = false;
}
}
}
// CA completion gates on the WHOLE chain, not just the
// originating record: the put-notify must not report
// done until every FLNK/OUT target it drove — including an async
// FLNK target that the originating record's sync cycle merely
// kicked off — has settled. `completed()` is true iff the
// wait-set drained to zero during this call (fully synchronous
// chain); otherwise the receiver fires later from the last
// chain member's `leave`.
match parked {
Some((notify, completion_rx)) => {
if notify.completed() {
Ok(None)
} else {
Ok(Some(completion_rx))
}
}
None => Ok(None),
}
}
/// Put a PV value without triggering process (for restore).
pub async fn put_pv_no_process(&self, name: &str, value: EpicsValue) -> CaResult<()> {
let (base, field) = super::parse_pv_name(name);
let field = field.to_ascii_uppercase();
if let Some(pv) = self.inner.simple_pvs.read().await.get(name) {
pv.set(value).await;
return Ok(());
}
// Records — alias-aware (epics-base PR #336).
if let Some(rec) = self.get_record(base).await {
// `put_pv_no_process` is a public record-write API
// (autosave restore). It must take the advisory write gate
// (`dbScanLock` analogue) so an autosave restore cannot
// land between the member writes of a QSRV atomic group or
// a pvalink atomic scan epoch holding `lock_records`.
// `base` is alias-resolved so an alias and its target
// share one gate. Held until return.
let canonical_base: String = self
.resolve_alias(base)
.await
.unwrap_or_else(|| base.to_string());
let _record_gate = self.lock_record(&canonical_base).await;
let mut instance = rec.write().await;
let prev_value = instance.record.get_field(&field);
match instance.record.put_field(&field, value.clone()) {
Ok(()) => {}
Err(CaError::FieldNotFound(_)) => {
instance.put_common_field(&field, value)?;
}
Err(e) => return Err(e),
}
// Invalidate metadata cache only if the metadata-class
// field actually changed (faac1df1).
instance.notify_field_written_if_changed(&field, prev_value.as_ref());
// same SPC_AS parity as `put_pv` / the CA-write
// path — autosave-style restores writing `.ASG` at IOC
// startup must still trigger per-client re-eval.
if field == "ASG" {
crate::server::access_security::notify_asg_field_changed();
}
return Ok(());
}
Err(CaError::ChannelNotFound(name.to_string()))
}
}
/// Project a decoded `DBR_CTRL_*` / `DBR_GR_*` snapshot's metadata fields
/// (display / control limits, enum labels) into the shadow-PV
/// [`PvMetadata`](crate::server::pv::PvMetadata) the CA gateway installs.
/// A non-metadata (TIME/STS) snapshot carries `None` in all three, which
/// clears the shadow metadata — but the gateway only ever feeds this a
/// control-class snapshot, matching C `setPvData` replacing the attribute
/// gdd wholesale from the control get/event.
fn metadata_from_snapshot(snapshot: &Snapshot) -> crate::server::pv::PvMetadata {
crate::server::pv::PvMetadata {
display: snapshot.display.clone(),
control: snapshot.control.clone(),
enums: snapshot.enums.clone(),
}
}
#[cfg(test)]
mod tests {
use super::super::PvDatabase;
use crate::types::EpicsValue;
/// Regression: prior to fixing B1, `put_pv_and_post` walked only
/// `inner.records` and returned `ChannelNotFound` for everything
/// `add_pv`-registered. The CA gateway's monitor forwarder uses
/// `add_pv` then expects `put_pv_and_post` to fan-out to
/// downstream subscribers — without the simple-PV branch, every
/// upstream event was silently dropped and the gateway delivered
/// no monitors.
#[tokio::test]
async fn put_pv_and_post_handles_simple_pv() {
let db = PvDatabase::new();
db.add_pv("gw:test", EpicsValue::Double(0.0)).await.unwrap();
// Should NOT return ChannelNotFound.
db.put_pv_and_post("gw:test", EpicsValue::Double(42.0))
.await
.expect("simple PV put_pv_and_post must succeed");
// Value actually landed.
let pv = db.find_pv("gw:test").await.expect("PV exists");
assert!(matches!(pv.get().await, EpicsValue::Double(v) if v == 42.0));
}
/// Regression: `get_pv`, `put_pv`, `put_pv_and_post`,
/// and `put_pv_no_process` all bypassed `get_record` and walked
/// `self.inner.records` directly, so alias names from epics-base
/// PR #336 silently returned `ChannelNotFound`. A later fix closed
/// `get_record` but the same defect was hiding in field_io.rs.
/// All four CA-server-and-bridge entry points must accept aliases.
#[tokio::test]
async fn field_io_entry_points_accept_aliases() {
use crate::server::records::ai::AiRecord;
let db = PvDatabase::new();
db.add_record("CANON", Box::new(AiRecord::new(0.0)))
.await
.unwrap();
db.add_alias("ALT", "CANON").await.unwrap();
// get_pv via alias
db.put_pv("CANON.VAL", EpicsValue::Double(1.5))
.await
.unwrap();
let v = db.get_pv("ALT.VAL").await.unwrap();
assert!(matches!(v, EpicsValue::Double(x) if x == 1.5));
// put_pv via alias
db.put_pv("ALT.VAL", EpicsValue::Double(7.0)).await.unwrap();
let v = db.get_pv("CANON.VAL").await.unwrap();
assert!(matches!(v, EpicsValue::Double(x) if x == 7.0));
// put_pv_and_post via alias
db.put_pv_and_post("ALT.VAL", EpicsValue::Double(11.0))
.await
.unwrap();
let v = db.get_pv("CANON.VAL").await.unwrap();
assert!(matches!(v, EpicsValue::Double(x) if x == 11.0));
// put_pv_no_process via alias
db.put_pv_no_process("ALT.VAL", EpicsValue::Double(13.0))
.await
.unwrap();
let v = db.get_pv("ALT.VAL").await.unwrap();
assert!(matches!(v, EpicsValue::Double(x) if x == 13.0));
}
/// `set_pv_metadata` installs the upstream `DBR_CTRL_*` metadata on a
/// shadow simple PV WITHOUT posting any event (the CA gateway's
/// connect-time seed). A later GET-class read must then see the
/// installed limits/units, and a `DBE_PROPERTY` subscriber must NOT
/// have received anything (nothing *changed* yet). An unknown / record
/// name is rejected with `ChannelNotFound`.
#[tokio::test]
async fn set_pv_metadata_installs_without_posting() {
use crate::error::CaError;
use crate::server::snapshot::{DisplayInfo, Snapshot};
use crate::types::DbFieldType;
use std::time::SystemTime;
let db = PvDatabase::new();
db.add_pv("gw:meta", EpicsValue::Double(0.0)).await.unwrap();
// A DBE_PROPERTY subscriber attached BEFORE the seed — it must stay
// empty, because seeding metadata is not a property *change*.
const DBE_PROPERTY: u16 = 8;
let pv = db.find_pv("gw:meta").await.expect("PV exists");
let mut prop_rx = pv
.add_subscriber(1, DbFieldType::Double, DBE_PROPERTY)
.await
.expect("subscriber added");
// Build a CTRL-class snapshot carrying display metadata.
let mut ctrl = Snapshot::new(EpicsValue::Double(0.0), 0, 0, SystemTime::UNIX_EPOCH);
ctrl.display = Some(DisplayInfo {
units: "mm".into(),
precision: 3,
upper_disp_limit: 10.0,
lower_disp_limit: -10.0,
..Default::default()
});
db.set_pv_metadata("gw:meta", &ctrl)
.await
.expect("simple PV set_pv_metadata must succeed");
// The metadata landed on the shadow PV.
let installed = pv.metadata();
assert_eq!(
installed.display.expect("display metadata installed").units,
"mm"
);
// No event was posted (seed != change).
assert!(
prop_rx.try_recv().is_err(),
"set_pv_metadata must not post a DBE_PROPERTY event"
);
// Unknown / non-simple PV is rejected.
assert!(matches!(
db.set_pv_metadata("no:such:pv", &ctrl).await,
Err(CaError::ChannelNotFound(_))
));
}
/// `post_pv_property` refreshes the shadow metadata AND posts a
/// `DBE_PROPERTY` event carrying the supplied snapshot's metadata,
/// upstream status/severity, and (undefined control-DBR) timestamp — to
/// `DBE_PROPERTY` subscribers only. This is the DB-routing layer the
/// gateway's property monitor drives on every upstream `DBE_PROPERTY`
/// event. An unknown / record name is rejected with `ChannelNotFound`.
#[tokio::test]
async fn post_pv_property_refreshes_and_posts_property_event() {
use crate::error::CaError;
use crate::server::snapshot::{DisplayInfo, Snapshot};
use crate::types::{DbFieldType, WallTime};
const DBE_PROPERTY: u16 = 8;
const DBE_VALUE: u16 = 1;
const MAJOR: u16 = 2;
const HIGH: u16 = 3;
let db = PvDatabase::new();
db.add_pv("gw:prop", EpicsValue::Double(0.0)).await.unwrap();
let pv = db.find_pv("gw:prop").await.expect("PV exists");
let mut prop_rx = pv
.add_subscriber(1, DbFieldType::Double, DBE_PROPERTY)
.await
.expect("property subscriber added");
let mut val_rx = pv
.add_subscriber(2, DbFieldType::Double, DBE_VALUE)
.await
.expect("value subscriber added");
// Upstream CTRL event: metadata + MAJOR/HIGH alarm + a fixed past
// timestamp that is unmistakably not a fresh wall clock.
let upstream_ts = WallTime::from_unix(2_000_000, 0);
let mut ctrl = Snapshot::new(EpicsValue::Double(5.0), HIGH, MAJOR, upstream_ts);
ctrl.display = Some(DisplayInfo {
units: "V".into(),
precision: 1,
..Default::default()
});
db.post_pv_property("gw:prop", ctrl)
.await
.expect("simple PV post_pv_property must succeed");
// The metadata was refreshed on the shadow PV.
assert_eq!(
pv.metadata().display.expect("metadata refreshed").units,
"V"
);
// The DBE_PROPERTY subscriber received the metadata-bearing event,
// with the upstream alarm and timestamp preserved.
let ev = prop_rx
.try_recv()
.expect("DBE_PROPERTY subscriber receives the property event");
assert_eq!(
ev.snapshot.display.expect("event carries metadata").units,
"V"
);
assert_eq!(
ev.snapshot.alarm.severity, MAJOR,
"upstream severity preserved"
);
assert_eq!(ev.snapshot.alarm.status, HIGH, "upstream status preserved");
assert_eq!(
ev.snapshot.timestamp, upstream_ts,
"control-DBR timestamp preserved, not a fresh wall clock"
);
// The DBE_VALUE-only subscriber must NOT receive a property event.
assert!(
val_rx.try_recv().is_err(),
"DBE_VALUE-only subscriber must not receive a property post"
);
// Unknown / non-simple PV is rejected.
let again = Snapshot::new(EpicsValue::Double(0.0), 0, 0, WallTime::UNIX_EPOCH);
assert!(matches!(
db.post_pv_property("no:such:pv", again).await,
Err(CaError::ChannelNotFound(_))
));
}
/// Regression: `put_record_field_from_ca` (the CA
/// server's main put fast path) must accept aliases. Pre-fix it
/// only consulted `inner.records` directly. Also exercises the
/// canonical-name normalisation that protects subsequent
/// `process_record_with_links` / `update_scan_index` calls.
#[tokio::test]
async fn put_record_field_from_ca_accepts_alias() {
use crate::server::records::ai::AiRecord;
let db = PvDatabase::new();
db.add_record("CANON", Box::new(AiRecord::new(0.0)))
.await
.unwrap();
db.add_alias("ALT", "CANON").await.unwrap();
// Put VAL via the alias name.
let _ = db
.put_record_field_from_ca("ALT", "VAL", EpicsValue::Double(2.5))
.await
.expect("put via alias must succeed");
// Read back via canonical to confirm the value landed on the
// right record.
let v = db.get_pv("CANON.VAL").await.unwrap();
assert!(matches!(v, EpicsValue::Double(x) if x == 2.5));
}
/// Regression: a DBR_PUT_ACKT alarm-acknowledge put posts a record-wide
/// DBE_ALARM (C `dbAccess.c:1299` putAckt
/// `db_post_events(precord, NULL, DBE_ALARM)`), so an alarm-mask monitor
/// on ANY field is notified — and a DBE_VALUE-only monitor is not.
/// Pre-fix the ack field posted only itself with DBE_VALUE|DBE_LOG, so no
/// alarm-mask subscriber observed the acknowledgement, and the post fired
/// on every put regardless of whether `ackt` changed.
#[tokio::test]
async fn alarm_ack_put_posts_record_wide_dbe_alarm() {
use crate::server::recgbl::EventMask;
use crate::server::records::ai::AiRecord;
use crate::types::DbFieldType;
let db = PvDatabase::new();
db.add_record("A:REC", Box::new(AiRecord::new(1.0)))
.await
.unwrap();
let rec = db.get_record("A:REC").await.expect("record exists");
let (mut alarm_rx, mut value_rx) = {
let mut inst = rec.write().await;
let a = inst
.add_subscriber("VAL", 1, DbFieldType::Double, EventMask::ALARM.bits())
.expect("alarm subscriber");
let v = inst
.add_subscriber("VAL", 2, DbFieldType::Double, EventMask::VALUE.bits())
.expect("value subscriber");
(a, v)
};
// DBR_PUT_ACKT arrives as Short. ACKT defaults YES (true), so writing
// 0 (disable transient acknowledgement) is a real change.
db.put_record_field_from_ca_no_notify("A:REC", "ACKT", EpicsValue::Short(0))
.await
.expect("ackt put");
// The alarm-mask monitor on VAL receives the record-wide DBE_ALARM.
assert!(
alarm_rx.try_recv().is_ok(),
"DBE_ALARM subscriber must receive the record-wide alarm post"
);
// The DBE_VALUE-only monitor on VAL must NOT: VAL's value is unchanged.
assert!(
value_rx.try_recv().is_err(),
"DBE_VALUE-only subscriber must not receive the alarm post"
);
// Re-putting the same ACKT value is a no-op: C putAckt returns early
// on an unchanged ackt, so no further alarm post fires.
db.put_record_field_from_ca_no_notify("A:REC", "ACKT", EpicsValue::Short(0))
.await
.expect("ackt re-put");
assert!(
alarm_rx.try_recv().is_err(),
"unchanged ACKT must post nothing"
);
}
/// `post_property_fields` writes each field through the internal put and
/// posts a `DBE_PROPERTY` monitor — the C
/// `db_post_events(precord, &precord->val, DBE_PROPERTY)` that asyn's
/// runtime enum re-propagation drives (devAsynInt32.c callbackEnum). A
/// `DBE_VALUE`-only subscriber on the same field must NOT receive it:
/// re-keying enum strings is a property change, not a value change.
#[tokio::test]
async fn post_property_fields_writes_and_posts_dbe_property_only() {
use crate::server::recgbl::EventMask;
use crate::server::records::mbbi::MbbiRecord;
use crate::types::DbFieldType;
let db = PvDatabase::new();
db.add_record("M:ENUM", Box::new(MbbiRecord::new(0)))
.await
.unwrap();
let rec = db.get_record("M:ENUM").await.expect("record exists");
let (mut prop_rx, mut val_rx) = {
let mut inst = rec.write().await;
let p = inst
.add_subscriber("ZRST", 1, DbFieldType::String, EventMask::PROPERTY.bits())
.expect("property subscriber");
let v = inst
.add_subscriber("ZRST", 2, DbFieldType::String, EventMask::VALUE.bits())
.expect("value subscriber");
(p, v)
};
let posted = db
.post_property_fields(
"M:ENUM",
vec![("ZRST".to_string(), EpicsValue::String("LABEL".into()))],
)
.await
.expect("post_property_fields succeeds");
assert_eq!(posted, vec!["ZRST".to_string()]);
// The field landed on the record.
assert_eq!(
db.get_pv("M:ENUM.ZRST").await.unwrap(),
EpicsValue::String("LABEL".into())
);
// The DBE_PROPERTY subscriber received the event; the DBE_VALUE-only
// subscriber did not (mask 0x08 vs 0x01, no intersection).
assert!(
prop_rx.try_recv().is_ok(),
"DBE_PROPERTY subscriber must receive the property post"
);
assert!(
val_rx.try_recv().is_err(),
"DBE_VALUE-only subscriber must not receive a property post"
);
}
/// Regression: a direct CA put to a record whose value field VAL is NOT
/// `pp(TRUE)` (calc / calcout / aSub) must still fire a DBE_VALUE monitor.
/// C `dbAccess.c::dbPut:1408-1414` posts the value field immediately
/// unless it is `pp(TRUE)`. The port previously suppressed the immediate
/// post for every `VAL` and — with the `should_process` gate — skipped
/// the reprocess cycle for a non-`pp` VAL, so the operator's write fired
/// no monitor at all. calc's VAL is not in its `pp` field set, so the
/// immediate post is the only event that can fire.
#[tokio::test]
async fn ca_put_to_non_pp_val_posts_monitor() {
use crate::server::database::db_access::DbSubscription;
use crate::server::records::calc::CalcRecord;
let db = PvDatabase::new();
db.add_record("CALC1", Box::new(CalcRecord::new("0")))
.await
.unwrap();
let mut sub = DbSubscription::subscribe(&db, "CALC1.VAL")
.await
.expect("subscribe to CALC1.VAL");
db.put_record_field_from_ca("CALC1", "VAL", EpicsValue::Double(5.0))
.await
.expect("CA put to CALC1.VAL must succeed");
let got = tokio::time::timeout(std::time::Duration::from_secs(1), sub.recv_f64())
.await
.expect("a DBE_VALUE monitor must fire for a direct VAL put to a non-pp record");
assert_eq!(got, Some(5.0));
}
/// Record-backed consumer half of the source-coalesced stale-tail rule.
///
/// `DbSubscription::next_event` shares the `coalesce_consume` ordering
/// rule with `PvSubscription`: a record-field monitor whose bounded
/// queue overflows mid-burst must converge on the newest value and
/// never step back to an older queued one. Each non-pp `VAL` put posts
/// exactly one DBE_VALUE monitor with the put value and does NOT
/// reprocess (see `ca_put_to_non_pp_val_posts_monitor`), so 80 distinct
/// puts produce a strictly increasing 1..=80 stream; with no consumer
/// draining, 1..=64 fill the queue and the newest (80) lands in the
/// coalesce slot.
///
/// Before the fix `next_event` returned the coalesced `80` and then
/// replayed the stale tail `1..=64` (`80, 1, 2, ...`) — value time
/// going backwards.
#[tokio::test]
async fn r0604_db_overflow_never_delivers_newest_then_old() {
use crate::server::database::db_access::DbSubscription;
use crate::server::records::calc::CalcRecord;
let db = PvDatabase::new();
db.add_record("CALC1", Box::new(CalcRecord::new("0")))
.await
.unwrap();
let mut sub = DbSubscription::subscribe(&db, "CALC1.VAL")
.await
.expect("subscribe to CALC1.VAL");
for i in 1..=80u32 {
db.put_record_field_from_ca("CALC1", "VAL", EpicsValue::Double(i as f64))
.await
.expect("CA put to CALC1.VAL must succeed");
}
// Drain every immediately-available delivery; the recv past the
// last event has nothing queued and times out, ending collection.
let mut seq = Vec::new();
while let Ok(Some(v)) =
tokio::time::timeout(std::time::Duration::from_millis(200), sub.recv_f64()).await
{
seq.push(v);
}
assert!(!seq.is_empty(), "consumer must observe at least one value");
for w in seq.windows(2) {
assert!(
w[0] <= w[1],
"record monitor delivery stepped backward {} -> {} (sequence {seq:?})",
w[0],
w[1],
);
}
assert_eq!(
*seq.last().unwrap(),
80.0,
"record consumer must converge on the newest produced value (sequence {seq:?})"
);
}
}