epics_base_rs/server/record/record_instance.rs
1use std::collections::HashMap;
2use std::sync::Arc;
3use std::sync::Mutex as StdMutex;
4use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
5
6use crate::error::{CaError, CaResult};
7use crate::server::event_queue::{EventReader, EventUser};
8use crate::server::pv::{MonitorEvent, Subscriber};
9use crate::server::recgbl::EventMask;
10use crate::server::snapshot::{
11 ControlInfo, DisplayInfo, EnumInfo, EnumStringForm, PropertySupport,
12};
13use crate::types::{DbFieldType, EpicsValue, PvString, c_parse};
14
15use super::alarm::{AlarmSeverity, AnalogAlarmConfig};
16use super::common_fields::CommonFields;
17use super::link::{
18 ParsedLink, out_link_discards_cp, parse_forward_link_v2, parse_link_v2, parse_output_link_v2,
19};
20use super::menu_choices::MenuBound;
21use super::record_trait::{
22 AuxPostMask, CommonFieldPutResult, FieldDeclaration, FieldDesc, ProcessSnapshot, Record,
23 RecordProcessResult, SubroutineFn,
24};
25use super::scan::{ScanType, SimModeScan};
26
27/// Every client-visible `special(SPC_NOMOD)` field of `dbCommon.dbd:13-190`.
28///
29/// These are common fields — no record's `field_list` declares them — so the
30/// declaration names them here. The remaining `SPC_NOMOD` entries in
31/// `dbCommon.dbd` (MLOK, MLIS, BKLNK, ASP, PPN, PPNR, SPVT, RSET, DSET, DPVT,
32/// RDES, LSET, BKPT) are `DBF_NOACCESS`: they have no field API in this port at
33/// all, and C refuses them one level earlier, at `dbNameToAddr`.
34///
35/// TIME is `DBF_NOACCESS` in C too (`dbpf REC.TIME` → "failed"), but this port
36/// resolves `.TIME`, so the declaration must cover it.
37///
38/// Read only through [`RecordInstance::is_no_mod`].
39const DBCOMMON_NOMOD: &[&str] = &[
40 "NAME", "STAT", "SEVR", "AMSG", "NSTA", "NSEV", "NAMSG", "ACKS", "ACKT", "LCNT", "PACT",
41 "PUTF", "RPRO", "TIME", "UTAG",
42];
43
44/// Put-notify completion wait-set — the C `dbNotify.c` `processNotify`
45/// waitList analogue (`dbNotifyAdd` / `dbNotifyCompletion`).
46///
47/// A `ca_put_callback` / WRITE_NOTIFY completion must fire only after the
48/// originating (put-target) record AND every record reached through its
49/// FLNK / OUT / process-action dispatch chain (synchronous *or* async)
50/// has finished processing. A single wait-set owns the completion
51/// oneshot; only it fires, and only when the last chain member leaves.
52///
53/// Counting convention: [`Self::new`] arms `pending = 1` for the
54/// originating record (which always joins). Every additional PP target
55/// that will process under the active notify [`Self::enter`]s on join
56/// (C `dbNotifyAdd`), and every record [`Self::leave`]s when its
57/// processing completes (C `dbNotifyCompletion`). The oneshot fires on
58/// the `leave` that drops `pending` to zero.
59pub struct NotifyWaitSet {
60 pending: AtomicUsize,
61 tx: StdMutex<Option<crate::runtime::sync::oneshot::Sender<()>>>,
62}
63
64impl NotifyWaitSet {
65 /// Arm a wait-set whose `tx` fires when the chain settles. `pending`
66 /// starts at 1 for the originating record — its completion `leave`s
67 /// that implicit slot, so a put with no chain targets fires
68 /// immediately on the originating record's own completion.
69 pub fn new(tx: crate::runtime::sync::oneshot::Sender<()>) -> Arc<Self> {
70 Arc::new(Self {
71 pending: AtomicUsize::new(1),
72 tx: StdMutex::new(Some(tx)),
73 })
74 }
75
76 /// A PP target joined the chain (C `dbNotifyAdd`). Balanced by exactly
77 /// one [`Self::leave`].
78 pub fn enter(&self) {
79 self.pending.fetch_add(1, Ordering::AcqRel);
80 }
81
82 /// A record finished its contribution (C `dbNotifyCompletion`). Fires
83 /// the completion oneshot on the `leave` that empties the set.
84 pub fn leave(&self) {
85 let prev = self.pending.fetch_sub(1, Ordering::AcqRel);
86 debug_assert!(prev >= 1, "NotifyWaitSet::leave underflow");
87 if prev == 1 {
88 if let Some(tx) = self.tx.lock().unwrap().take() {
89 let _ = tx.send(());
90 }
91 }
92 }
93
94 /// True once every chain member has left (the completion has fired).
95 /// Used by the put entry to decide synchronous (return `None`) vs
96 /// async-pending (return the receiver) completion.
97 pub fn completed(&self) -> bool {
98 self.pending.load(Ordering::Acquire) == 0
99 }
100}
101
102/// A put-notify (`dbPutNotify` — CA WRITE_NOTIFY, `caput -c`) that landed on a
103/// PACT record and was therefore deferred WHOLE.
104///
105/// C `processNotifyCommon` (dbNotify.c:225-231) tests `precord->pact` above
106/// `ppn->putCallback`, so nothing is written and nothing is marked: the record
107/// joins the notify's wait list in state `notifyRestartInProgress`, and when the
108/// async cycle completes the put is replayed against a record that is no longer
109/// active — value written, record processed, callback fired only after THAT
110/// process finishes. So a client's "callback returned" still means "the value I
111/// sent has been processed".
112///
113/// softIoc 7.0.10.1-DEV, `ASY` (calcout, `ODLY=4`, `A=5`), `caput -c ASY.A 7`
114/// issued 1 s into the async cycle:
115///
116/// ```text
117/// t=1s A=5 PACT=1 <- cycle in flight
118/// t=2s A=5 PACT=1 RPRO=0 <- put-notify pending: nothing written
119/// t=4s A=7 PACT=1 <- cycle done; the put is replayed
120/// callback returns at t=6.9s: A=7 VAL=7 <- after the RESTARTED process
121/// ```
122pub struct DeferredNotifyPut {
123 /// The field the client wrote (already upper-cased).
124 pub field: String,
125 /// The value it wrote — held here, unwritten, until the restart.
126 pub value: crate::types::EpicsValue,
127 /// The client's completion channel. The replayed put builds its wait-set
128 /// around this sender, so the callback fires on the restarted process, not
129 /// on the in-flight cycle.
130 pub completion: crate::runtime::sync::oneshot::Sender<()>,
131}
132
133/// The PACT→idle transition, as a value.
134///
135/// # Invariant
136///
137/// `RecordInstance::deferred_notify_put.is_some()` ⟹ PACT is held. A
138/// put-notify is parked ONLY on the `is_processing()` arm of the put entry
139/// ([`RecordInstance::park_notify_put`]), and PACT can be released ONLY by
140/// [`RecordInstance::leave_pact`], which takes the park with it. So the
141/// deferral cannot outlive the PACT window it was parked in — the strand is
142/// unrepresentable rather than guarded against.
143///
144/// The token is `#[must_use]`: a release site cannot silently drop the parked
145/// put. Its single consumer is `PvDatabase::apply_pact_exit`, called from the
146/// released cycle's `recGblFwdLink` tail — C `recGbl.c:295` (`if (pdbc->ppn)
147/// dbNotifyCompletion(pdbc)`), which is where C queues the restart callback
148/// (`dbNotify.c:466-469`, state `notifyRestartInProgress`). Holding the token
149/// to the tail rather than replaying at the `pact = FALSE` store is what keeps
150/// the replay behind the rest of the cycle, exactly as C's queued callback is.
151#[must_use = "a put-notify parked on this record is stranded unless the PactExit \
152 reaches PvDatabase::apply_pact_exit"]
153pub struct PactExit(Option<DeferredNotifyPut>);
154
155impl Drop for PactExit {
156 /// Last-resort canary. Every release site hands its token to
157 /// `PvDatabase::apply_pact_exit`; a token reaching here still holding a
158 /// parked put means a PACT release path was added without a tail. The
159 /// client is not left hanging (dropping `completion` errors its receiver),
160 /// but the put's value IS lost, so say so.
161 fn drop(&mut self) {
162 if self.0.is_some() {
163 tracing::error!(
164 "PactExit dropped with a put-notify still parked: a PACT release \
165 path is not routed through PvDatabase::apply_pact_exit"
166 );
167 }
168 }
169}
170
171impl PactExit {
172 /// The put-notify this release freed, if one was parked.
173 pub(crate) fn into_deferred(mut self) -> Option<DeferredNotifyPut> {
174 self.0.take()
175 }
176
177 /// Fold two releases of the same cycle into one token.
178 ///
179 /// A simulated SDLY continuation releases PACT inside `check_simulation_mode`
180 /// and again at the `is_continuation` arm; the second release finds PACT
181 /// already clear and carries nothing, because the first took the park.
182 pub(crate) fn merge(mut self, mut other: PactExit) -> PactExit {
183 debug_assert!(
184 self.0.is_none() || other.0.is_none(),
185 "a parked put-notify can be released only once per cycle"
186 );
187 PactExit(self.0.take().or_else(|| other.0.take()))
188 }
189
190 /// A cycle that released no PACT (and therefore freed no put-notify).
191 pub(crate) fn none() -> PactExit {
192 PactExit(None)
193 }
194}
195
196/// Cached metadata for a record.
197///
198/// Stores the result of `populate_display_info` / `populate_control_info` /
199/// `populate_enum_info` so subsequent `snapshot_for_field` /
200/// `make_monitor_snapshot` calls can skip rebuilding the metadata. The
201/// cache is invalidated whenever a metadata-class field is written
202/// (EGU, PREC, HOPR, LOPR, alarm limits, DRVH/DRVL, state strings).
203///
204/// In a CA-only IOC this is a CPU win; in a hybrid CA + PVA IOC where
205/// every snapshot needs full metadata for NTScalar serialization, the
206/// cache eliminates redundant per-event populate work.
207#[derive(Clone, Default)]
208pub(crate) struct MetadataSnapshot {
209 pub display: Option<DisplayInfo>,
210 pub control: Option<ControlInfo>,
211 pub enums: Option<EnumInfo>,
212}
213
214/// Returns true if this field is property-class — the C `prop(YES)`
215/// dbd attribute: writing a changed value posts `DBE_PROPERTY` to the
216/// record's subscribers AND invalidates the metadata cache. Field name
217/// is expected uppercase.
218///
219/// **Every field read by `populate_display_info`,
220/// `populate_control_info`, or `populate_enum_info` MUST be in this
221/// set** — otherwise the cache serves stale metadata until some other
222/// tracked field is written. The reverse does not hold: a field may be
223/// property-class without being a cache source (e.g. the motor fields
224/// below feed the live-computed `field_metadata_override`, never the
225/// cache — its invalidation on their write is harmless).
226///
227/// Currently uncovered (because it is not yet populated by any
228/// `populate_*` function): `DESC` (would map to `display.description`
229/// — populate hook missing). The `Q:form` info tag is now wired
230/// (`populate_display_info` -> `display.form`), but as an immutable
231/// load-time info tag — not a runtime field — it needs no cache
232/// invalidation and so is intentionally absent from this field set.
233fn is_metadata_field(name: &str) -> bool {
234 matches!(
235 name,
236 // Display info (analog + integer + motor) — `prop(YES)` in
237 // ai/ao/longin/longout DBDs.
238 "EGU" | "PREC" | "HOPR" | "LOPR" | "HLM" | "LLM"
239 // Alarm limits (used by both display and the analog_alarm config) —
240 // ai/ao/longin/longout `prop(YES)`.
241 | "HIHI" | "HIGH" | "LOW" | "LOLO"
242 // Alarm severities for the four limit thresholds —
243 // ai/ao/longin/longout `prop(YES)` per upstream DBDs
244 // (`aiRecord.dbd.pod` lines 357-388).
245 | "HHSV" | "HSV" | "LSV" | "LLSV"
246 // Output ctrl limits — ao/longout `prop(YES)`.
247 | "DRVH" | "DRVL"
248 // motor `prop(YES)` (`motorRecord.dbd` 154/161/289/361/368):
249 // VBAS/VMAX bound VELO's range, MRES the RVAL/RRBV raw range,
250 // DHLM/DLLM the DVAL/DRBV range — all served per field by
251 // `Record::field_metadata_override` (C get_graphic_double /
252 // get_control_double). HLM/LLM/EGU/PREC and the alarm limits
253 // are motor `prop(YES)` too, already listed above.
254 | "VBAS" | "VMAX" | "MRES" | "DHLM" | "DLLM"
255 // bi/bo/busy enum strings — `prop(YES)`.
256 | "ZNAM" | "ONAM"
257 // bi/bo state severities — `biRecord.dbd.pod` / `boRecord.dbd.pod`
258 // `prop(YES)` for ZSV/OSV/COSV (zero / one / change-of-state).
259 | "ZSV" | "OSV" | "COSV"
260 // mbbi/mbbo state strings (16 levels) — `prop(YES)`.
261 | "ZRST" | "ONST" | "TWST" | "THST" | "FRST" | "FVST" | "SXST" | "SVST"
262 | "EIST" | "NIST" | "TEST" | "ELST" | "TVST" | "TTST" | "FTST" | "FFST"
263 )
264}
265
266/// One alarm limit for a DBR_AL_DOUBLE response: the value when its
267/// severity threshold is enabled, `NaN` otherwise. Mirrors C
268/// `get_alarm_double`'s `prec->hhsv ? prec->hihi : epicsNAN` — a NONZERO
269/// test on the raw ordinal, so an out-of-range severity still enables the
270/// limit.
271fn gated(severity: i16, limit: f64) -> f64 {
272 if severity != 0 { limit } else { f64::NAN }
273}
274
275/// Extract the RAW stored ordinal a put lands in a `menu(menuAlarmSevr)`
276/// severity field (`HHSV`/`HSV`/`LSV`/`LLSV`/`UDFS`/`DISS`), WITHOUT clamping
277/// to the 0..=3 valid range.
278///
279/// C's numeric menu put stores whatever `(epicsEnum16)` the value truncates to
280/// (`dbConvert.c::putDoubleEnum` = `*pfield = (epicsEnum16)*psrc`), so
281/// `caput REC.HSV 4` keeps `4` and `caput REC.HSV -1` keeps `65535` — both
282/// wire-visible (served signed as `-1`) and both used verbatim to derive the
283/// alarm. The carrier is `i16` so the 16-bit pattern round-trips; the alarm
284/// meaning is read back with [`AlarmSeverity::from_u16`] and the C nonzero
285/// enable with `!= 0`.
286///
287/// A numeric value has already been wrapped to `epicsEnum16` upstream
288/// (`EpicsValue::convert_to(Enum)`, the one owner of C's double→enum cast); this
289/// only reinterprets its bit pattern. A `String` is a db-load / internal-link
290/// label (a client string put is rejected-or-resolved by `putStringMenu`
291/// upstream), resolved to its ordinal here.
292fn menu_ordinal_raw(value: &EpicsValue) -> i16 {
293 match value {
294 EpicsValue::String(s) => match s.as_str_lossy().as_ref() {
295 "NO_ALARM" => 0,
296 "MINOR" => 1,
297 "MAJOR" => 2,
298 "INVALID" => 3,
299 other => other
300 .parse::<i64>()
301 .ok()
302 .map(|n| n as u16 as i16)
303 .unwrap_or(0),
304 },
305 other => other.to_f64().unwrap_or(0.0) as i64 as u16 as i16,
306 }
307}
308
309/// Coerce a db-loaded `String` for a numeric/menu **common** field to that
310/// field's canonical DBF type before [`RecordInstance::put_common_field`]
311/// dispatches on it.
312///
313/// The db loader applies a record's own fields with the typed
314/// `EpicsValue::parse(desc.dbf_type, value_str)` (`db_loader::apply_fields`),
315/// but a field absent from `field_list` is pushed to the common-field path as
316/// a raw `EpicsValue::String` — it has no `FieldDesc` to parse against. The
317/// numeric common-field arms in `put_common_field` match only their typed
318/// variant, so without this step a `.db` `field(PHAS, "1")`,
319/// `field(PRIO, "HIGH")`, `field(DISS, "MAJOR")`, `field(DISA, "1")`, … is
320/// silently dropped at IOC load. Routing the String through the same
321/// `EpicsValue::parse` the record-field path uses handles the numeric *and*
322/// menu-label forms uniformly, so the arm receives the value it expects.
323///
324/// Only fields whose canonical type is numeric/menu are listed; the
325/// Port of libcom `epicsParseInt32(str, &to, 10, NULL)`
326/// (`libcom/src/misc/epicsStdlib.c:26-53,245-261`), which is how pvxs parses
327/// the `nsec:lsb:` digit count. Returns `None` for every status the C
328/// returns non-zero for:
329///
330/// - `S_stdlib_noConversion` — `strtol` consumed nothing (empty / no digits)
331/// - `S_stdlib_extraneous` — trailing non-space bytes with `units == NULL`
332/// - `S_stdlib_overflow` — outside `epicsInt32`
333///
334/// Leading and trailing ASCII whitespace and a leading `+`/`-` sign are
335/// accepted, matching `epicsParseLong`'s `isspace` skips and `strtol`.
336fn epics_parse_int32_base10(s: &str) -> Option<i32> {
337 // `while ((c = *str) && isspace(c)) ++str;` then `strtol(str, &endp, 10)`.
338 let body = s.trim_start_matches(|c: char| c.is_ascii_whitespace());
339 let (sign, digits) = match body.strip_prefix(['+', '-']) {
340 Some(rest) if body.starts_with('-') => (-1i64, rest),
341 Some(rest) => (1i64, rest),
342 None => (1i64, body),
343 };
344 let end = digits
345 .find(|c: char| !c.is_ascii_digit())
346 .unwrap_or(digits.len());
347 if end == 0 {
348 return None; // endp == str → S_stdlib_noConversion
349 }
350 // `if (c && !units) return S_stdlib_extraneous;` after skipping trailing
351 // whitespace.
352 if !digits[end..]
353 .trim_start_matches(|c: char| c.is_ascii_whitespace())
354 .is_empty()
355 {
356 return None;
357 }
358 // ERANGE from `strtol`, then the explicit `epicsInt32` range check.
359 let magnitude: i64 = digits[..end].parse().ok()?;
360 i32::try_from(sign * magnitude).ok()
361}
362
363/// The STORED type of a `dbCommon` field — the variant its
364/// [`RecordInstance::put_common_field_bounded`] arm binds, which is not always
365/// the type the `.dbd` DECLARES it as (a `menu()` field is declared `DBF_MENU`
366/// and served `DBR_ENUM`, but held here as its bare index).
367///
368/// String-typed common fields (DESC, ASG, OUT, TSEL, …) have no entry: their
369/// arms take the string verbatim.
370fn stored_common_field_type(name: &str) -> Option<DbFieldType> {
371 Some(match name {
372 "SCAN" | "SSCN" | "PINI" => DbFieldType::Enum,
373 "TSE" | "PHAS" | "PRIO" | "DISV" | "DISA" | "DISS" | "LCNT" | "UDFS" | "ACKT" | "ACKS"
374 | "SEVR" | "STAT" | "NSEV" | "NSTA" => DbFieldType::Short,
375 // The analog-alarm limits and the hysteresis margin — `DBF_DOUBLE` in
376 // every dbd that declares them (`aiRecord.dbd.pod:357-388`,
377 // `calcRecord.dbd.pod:716-744`, `sCalcoutRecord.dbd:479-531`). A field
378 // missing from this table reaches its arm as whatever variant the caller
379 // built, and an arm that binds a typed variant then drops it: that is
380 // how `field(HYST,"2")` silently became 0 on every record whose
381 // hysteresis lives in `common.hyst`
382 // (calc/calcout/scalcout/ai/ao/longin/int64in).
383 "HIHI" | "HIGH" | "LOW" | "LOLO" | "HYST" => DbFieldType::Double,
384 // The `DBF_UCHAR` flags. `bool` here, a NUMBER in C.
385 "DISP" | "UDF" | "TPRO" | "RPRO" | "BKPT" | "PROC" => DbFieldType::Char,
386 _ => return None,
387 })
388}
389
390/// **The single owner of "what type does a `dbCommon` field hold"**, run on
391/// EVERY put before the typed arms below see the value — so an arm may bind one
392/// variant and know the put cannot have arrived in another.
393///
394/// This is not a string-parsing convenience. A common field is reached by three
395/// writers with three different ideas of the value's shape: the db loader hands
396/// every field over as a raw `String`; a `dbPut` arrives coerced to the field's
397/// DECLARED type (`DBF_MENU` → `Enum` for PRIO, `DBF_UCHAR` → `Char` for DISP);
398/// an internal link delivers whatever its source stored. Before this ran on the
399/// non-`String` shapes too, each arm's single-variant `if let` was a silent
400/// drop for the other two writers — `caput REC.PRIO HIGH` resolved its label to
401/// `Enum(2)` and then vanished at the arm, leaving PRIO at 0.
402///
403/// An unparseable String is returned as-is so the arm drops it, and a menu
404/// field's bad label FAILS the put (`S_db_badChoice`) rather than landing as
405/// index 0.
406fn coerce_common_field(name: &str, value: EpicsValue, bound: MenuBound) -> CaResult<EpicsValue> {
407 let Some(dbf) = stored_common_field_type(name) else {
408 return Ok(value);
409 };
410 let EpicsValue::String(s) = &value else {
411 // Already typed: project onto the stored type through the one
412 // value-coercion owner. `convert_to` short-circuits a value that is
413 // already `dbf`, so the common case costs nothing.
414 return Ok(value.convert_to(dbf));
415 };
416 let text = s.as_str_lossy();
417 // A `DBF_MENU` common field resolves its label against THAT field's own
418 // menu through the one converter every menu-field string put uses
419 // (C `dbConvert.c::putStringMenu`: exact label, else an index below
420 // `nChoice`, else `S_db_badChoice`) — the same rule the record-specific
421 // menu fields follow in `coerce_write_value`. The failure PROPAGATES: the
422 // field-blind `EpicsValue::parse` fallback below must never see a menu
423 // field, or `caput REC.PRIO Bogus` lands as index 0 instead of failing.
424 //
425 // SCAN/SSCN/PINI are menu fields like any other and go through the same
426 // converter. They used to each carry a hand-written `from_str` that drifted
427 // from C: `ScanType::from_str` case-folded and invented `"0.5 second"`
428 // aliases for menuScan's `".5 second"` (and mapped any out-of-range index
429 // to Passive), `SimModeScan::from_str` took any u16, `PiniMode::from_str`
430 // trimmed. C has ONE converter and it does none of that.
431 if let Some(choices) = super::menu_choices::shared_menu_choices(name) {
432 return super::menu_choices::resolve_menu_field_string_bounded(
433 name, choices, dbf, &text, bound,
434 );
435 }
436 // Numeric (non-menu) common field: C's `dbPut` runs the string through the
437 // SAME `epicsParse*` (`dbConvert.c` `putString*`) the record data fields use,
438 // and a non-zero status REFUSES the whole put (`dbAccess.c:1362`, mapped to
439 // `ECA_PUTFAIL`). Route it through the single owner of that conversion —
440 // [`c_parse::put_string`] — instead of the field-blind `EpicsValue::parse`,
441 // which wrapped (`256 as u8 == 0`) and swallowed the error (`Err(_) =>
442 // Ok(value)`), so `caput REC.PROC 256` and `caput REC.PROC notanumber` were
443 // accepted where C rejects them.
444 //
445 // Key the parse on the field's C-DECLARED width, not its stored variant: the
446 // `DBF_UCHAR` flags (DISP/UDF/TPRO/RPRO/BKPT/PROC, `dbCommon.dbd`) are held in
447 // the signed `Char` variant here but C parses them with `epicsParseUInt8`, so
448 // `caput REC.PROC 255` and `caput REC.PROC -1` (→255) are accepted and only
449 // `256`+/non-numeric refused. `put_string` returns the value in the declared
450 // variant; project it back onto the stored variant through the one
451 // value-coercion owner (byte-identity for `UChar`→`Char`).
452 let declared = match dbf {
453 DbFieldType::Char => DbFieldType::UChar,
454 other => other,
455 };
456 let Some(target) = c_parse::NumericField::of(declared) else {
457 // Unreachable: every numeric `stored_common_field_type` (Char/Short/
458 // Double, all with a numeric row) reaches here; the `Enum` menu types
459 // returned above. Keep the pre-parse value rather than panic.
460 return Ok(value);
461 };
462 c_parse::put_string(name, target, text.trim()).map(|parsed| parsed.convert_to(dbf))
463}
464
465/// The alarm-acknowledge request types C's `dbPut` dispatches on
466/// (`dbAccess.c:1331-1335`): `DBR_PUT_ACKT` and `DBR_PUT_ACKS`.
467///
468/// Acknowledgement is a *request type*, not a field write — the two handlers
469/// run above the `SPC_NOMOD` gate that refuses every ordinary put to ACKT/ACKS.
470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
471pub enum AlarmAck {
472 /// `DBR_PUT_ACKT` → `putAckt`: set transient-alarm acknowledgement.
473 Transient,
474 /// `DBR_PUT_ACKS` → `putAcks`: acknowledge an alarm of this severity.
475 Severity,
476}
477
478/// A type-erased record instance stored in the database.
479pub struct RecordInstance {
480 pub name: String,
481 pub record: Box<dyn Record>,
482 pub common: CommonFields,
483 pub subscribers: HashMap<String, Vec<Subscriber>>,
484 // Link parse cache
485 pub parsed_inp: ParsedLink,
486 pub parsed_out: ParsedLink,
487 pub parsed_flnk: ParsedLink,
488 pub parsed_sdis: ParsedLink,
489 pub parsed_tsel: ParsedLink,
490 // Device support
491 pub device: Option<Box<dyn super::super::device_support::DeviceSupport>>,
492 // Subroutine (for sub records)
493 pub subroutine: Option<Arc<SubroutineFn>>,
494 /// PACT (C `precord->pact`) — the re-entrancy guard, and the record's
495 /// "busy" state for every put that lands on it.
496 ///
497 /// PRIVATE by construction: entered through [`RecordInstance::enter_pact`]
498 /// and released ONLY through [`RecordInstance::leave_pact`], which hands
499 /// back the [`PactExit`] carrying any put-notify parked on this PACT window.
500 /// A `pact.store(false)` open-coded at a release site is what stranded the
501 /// deferral on the ODLY/SDLY paths; it is no longer expressible.
502 pact: AtomicBool,
503 // Put-notify wait-set this record currently belongs to (C
504 // `precord->ppn`). Set when the record joins an active put-notify
505 // (originating put target, or a FLNK/OUT PP target via `dbNotifyAdd`);
506 // taken + `leave`d when the record's processing completes. `None`
507 // outside any put-notify. See [`NotifyWaitSet`].
508 pub notify: Option<Arc<NotifyWaitSet>>,
509 /// A put-notify that arrived while this record was PACT, deferred WHOLE —
510 /// C `processNotifyCommon` (dbNotify.c:225-231) tests `precord->pact`
511 /// ABOVE `putCallback`, so a `dbPutNotify` onto a busy record writes
512 /// nothing: no value, no RPRO. The record is parked on the notify's wait
513 /// list and the entire put — value, process, callback — is restarted once
514 /// the async cycle completes. See [`DeferredNotifyPut`] and
515 /// `PvDatabase::restart_deferred_notify_put`, the single owner that applies
516 /// it. `None` outside that window.
517 ///
518 /// PRIVATE, and paired with [`Self::pact`] by the [`PactExit`] invariant:
519 /// parked only by [`Self::park_notify_put`] (reachable only from the
520 /// PACT arm of the put entry), taken only by [`Self::leave_pact`].
521 deferred_notify_put: Option<DeferredNotifyPut>,
522 /// The value of each subscribed field as ALREADY PUBLISHED to that
523 /// field's `DBE_VALUE`/`DBE_LOG` subscribers. The generic
524 /// change-detection loop in every snapshot builder posts a field only
525 /// when its current value differs from this — so this map is what
526 /// C's per-record `*_lst` / MARK state is to `monitor()`.
527 ///
528 /// # Invariant (CONTRACT)
529 ///
530 /// A field's value MUST NOT be published twice by the framework.
531 /// Concretely: every value-class post (a `db_post_events` carrying
532 /// `DBE_VALUE` and/or `DBE_LOG`) MUST advance this map for the field it
533 /// posts; an alarm-only / property-only post MUST NOT (those classes do
534 /// not deliver the value to a `DBE_VALUE`/`DBE_LOG` subscriber, so the
535 /// change is still owed to them).
536 ///
537 /// In C, `dbPut` (dbAccess.c:1407-1414) is the record's ONLY post for a
538 /// put: `db_post_events(precord, pfieldsave, DBE_VALUE|DBE_LOG)`. No
539 /// record's `monitor()` re-posts that field — it posts a closed set and
540 /// compares against its own `*_lst` fields. A framework that posts on the
541 /// put and then change-detects the same field on the next process cycle
542 /// sends an event C never sends.
543 ///
544 /// # Owner
545 ///
546 /// [`RecordInstance::record_value_post`] is the SINGLE writer. The field
547 /// is private so no path outside this module can advance (or fail to
548 /// advance) it: the snapshot builders read it through
549 /// [`RecordInstance::posted_value`] and every poster —
550 /// [`RecordInstance::notify_field_with_origin`] included — advances it
551 /// through the owner.
552 last_posted: HashMap<String, EpicsValue>,
553 /// The live store for a field the record's `.dbd` DECLARES but the record
554 /// struct has no `put_field` arm / no storage for — the WRITE analog of the
555 /// read-side [`Self::declared_default`] fallback.
556 ///
557 /// C makes every `.dbd` field not just readable but WRITABLE: `dbPutField`
558 /// resolves the field from its `dbFldDes` and `dbPut` writes the incoming
559 /// value into record memory, whether or not any record code ever reads it
560 /// back — a `caput dfanout.HOPR 10` sticks even though `dfanoutRecord.c`
561 /// never touches HOPR. A Rust record models only the fields it has
562 /// behaviour for, so a field it declares but never stores had nowhere for a
563 /// put to land: [`Self::put_common_field`]'s catch-all reported
564 /// `S_dbLib_fieldNotFound` and the client's put was refused, while a READ of
565 /// the same field succeeded through `declared_default`. This map is that
566 /// missing storage — one uniform mechanism for the whole family, not a
567 /// per-field struct member on each record type.
568 ///
569 /// Keyed by upper-case field name, holding the value already coerced to the
570 /// field's C-declared DBF type (the same projection `declared_default` and
571 /// the read path serve). [`Self::resolve_field`] reads it BEFORE
572 /// `declared_default`, so a read reflects a prior write and an untouched
573 /// field still reads its `.dbd` initial. Empty for a record whose declared
574 /// fields are all modeled.
575 declared_overrides: HashMap<String, EpicsValue>,
576 /// Set by `check_deadband_ext` for waveform/aai/aao when their
577 /// content hash changed this cycle (C `monitor()` On Change mode,
578 /// waveformRecord.c:310-319). The snapshot builders read it to post
579 /// `HASH` with a literal `DBE_VALUE` event, independent of the VAL
580 /// post mask. False for every record without the MPST/APST/HASH
581 /// mechanism.
582 pub(crate) array_hash_changed: bool,
583 /// One-shot "skip the registered subroutine this cycle" signal for aSub
584 /// `LFLG=READ`. The async processing path resolves the `SUBL` link before
585 /// taking this lock; when the resolved name is bad (C `fetch_values` ->
586 /// `S_db_BadSub`) or the link read failed, C `process` runs `do_sub` only
587 /// on `!status`, so the subroutine is skipped. Set by the resolution
588 /// apply, consumed (and cleared) by [`Self::run_registered_subroutine`];
589 /// `false` for every record without a pending bad re-resolution.
590 pub(crate) suppress_subroutine_run: bool,
591 /// Generation counter for ReprocessAfter timer cancellation.
592 /// Bumped each process cycle. Spawned timers check this to avoid
593 /// stale re-processes from accumulated timers.
594 pub reprocess_generation: Arc<std::sync::atomic::AtomicU64>,
595 /// Generation counter for the monitor watchdog
596 /// ([`Record::watchdog_interval`] / [`Record::watchdog_fire`]), bumped by
597 /// each `PvDatabase::arm_watchdog` so a re-arm supersedes the tick already
598 /// in flight — C `callbackRequestDelayed` replacing an outstanding delayed
599 /// callback. Deliberately NOT `reprocess_generation`: C's histogram wdog is
600 /// its own `epicsCallback`, independent of the record's SDLY/async
601 /// re-entry, so an SDLY defer must not cancel the watchdog nor vice versa.
602 pub watchdog_generation: Arc<std::sync::atomic::AtomicU64>,
603 /// Per-record info tags from `info("key", "value")` directives in
604 /// the .db file (epics-base info(...) grammar). Consumers include
605 /// asyn (`asyn:READBACK`), record-as-PV bridge tags
606 /// (`Q:group`, `Q:form`), and IOC-specific extensions. Empty for
607 /// records loaded without info(...) clauses.
608 pub info: HashMap<String, String>,
609 /// Cached metadata (display/control/enums) — `None` means stale or
610 /// not yet built. Populated lazily by `snapshot_for_field` /
611 /// `make_monitor_snapshot` and invalidated by `invalidate_metadata_cache`
612 /// whenever a metadata-class field (EGU/PREC/HOPR/LOPR/limit/state)
613 /// is written.
614 ///
615 /// Wrapped in `std::sync::Mutex` for interior mutability — the
616 /// containing `RecordInstance` is shared via `Arc<RwLock<...>>` from
617 /// `PvDatabase`, and snapshot construction holds a read lock; the
618 /// inner Mutex lets us still mutate the cache from a `&self` method.
619 ///
620 /// # Cache invariant (CONTRACT)
621 ///
622 /// The cache is **only correct under the following contract**: every
623 /// code path that mutates a metadata-class field (the set defined in
624 /// the file-private `is_metadata_field` predicate) MUST call
625 /// [`RecordInstance::notify_field_written`] (or
626 /// [`RecordInstance::invalidate_metadata_cache`] directly) afterward.
627 ///
628 /// All current write paths in `field_io.rs` already do this. If you
629 /// add a new code path that:
630 ///
631 /// - calls `instance.record.put_field(...)` directly, OR
632 /// - mutates record fields from inside `Record::process()`,
633 /// `Record::on_put`, or `Record::special` and that mutation could
634 /// touch a metadata-class field, OR
635 /// - lets a `Box<dyn Record>` implementation expose its own
636 /// mutation methods that change metadata fields,
637 ///
638 /// then call `instance.notify_field_written(field_name)` to keep the
639 /// cache consistent. Forgetting will produce a stale snapshot —
640 /// monitors will continue to see the old EGU/PREC/limits until the
641 /// next legitimate metadata-field write triggers invalidation.
642 ///
643 /// # Symmetric note for `populate_*` extensions
644 ///
645 /// If a future change adds a new field to `populate_display_info`,
646 /// `populate_control_info`, or `populate_enum_info` (e.g. populating
647 /// `display.description` from DESC), the new source field name MUST
648 /// also be added to `is_metadata_field` so writes to it invalidate
649 /// the cache. (The `Q:form` -> `display.form` mapping is exempt: it
650 /// reads an immutable load-time info tag, not a runtime field.)
651 pub(crate) metadata_cache: StdMutex<Option<MetadataSnapshot>>,
652}
653
654/// The cycle status [`RecordInstance::run_registered_subroutine`] reports when
655/// `do_sub` was skipped — C's `fetch_values` failure / `S_db_BadSub` path, which
656/// leaves `process`'s `status` non-zero (aSubRecord.c:216-224).
657const SUBROUTINE_STATUS_SKIPPED: i64 = -1;
658/// No subroutine is bound: C `do_sub` returns `S_db_BadSub` (aSubRecord.c:255).
659const SUBROUTINE_STATUS_NO_SUB: i64 = -2;
660/// The bound subroutine returned `Err` — no C counterpart (a C subroutine
661/// returns a `long`), and a failed cycle either way.
662const SUBROUTINE_STATUS_ERROR: i64 = -3;
663
664/// C `monitor()`'s post of the deadband field, as assembled by the single owner
665/// [`RecordInstance::deadband_post`].
666pub(crate) struct DeadbandPost {
667 /// C's `monitor_mask` for this cycle. Also the mask the
668 /// [`Record::fields_posted_with_value_mask`] secondaries ride: C posts them
669 /// from INSIDE the `if (monitor_mask)` guard, with the same mask.
670 pub mask: EventMask,
671 /// The deadband field's own post — `(field, value)`. `None` when no class
672 /// fired (C's `if (monitor_mask)` skips the post) or the field does not
673 /// resolve.
674 pub field: Option<(String, EpicsValue)>,
675}
676
677/// A value's `DBR_STRING` form, for a source whose field metadata is NOT
678/// reachable (an external CA/PVA link, a constant, an lnkCalc result) — the
679/// fallback half of [`RecordInstance::field_as_dbr_string`], which is also the
680/// whole rule once the local choice table has had its say.
681///
682/// A pvalink NTEnum still resolves its label here: the carrier brings its own
683/// `choices` (pvxs `pvalink_lset.cpp:344-356` — a `DBR_STRING` target copies
684/// `choices[index]`). A bare `Enum` index from a link whose labels the port
685/// cannot reach falls back to its decimal form, like the CA `*_STRING` encoder.
686/// **The** declaration lookup: a field's `dbFldDes`, in C's terms.
687///
688/// The record type's declaration is [`FieldDeclaration::field_list`] — the
689/// generated `.dbd` table where one exists and the hand-written table where it
690/// does not, never both. `dbCommon` is asked last, so a record-specific field
691/// shadows the common one.
692///
693/// A free function, not just a [`RecordInstance`] method, because the sites that
694/// need the declaration do not all hold an instance — a constant-link seed, a
695/// link write, the db loader all have `&dyn Record`.
696///
697/// `None` for a field with no declaration at all: a virtual field (`RTYP`,
698/// `TIME`, ...), which C answers from dbStaticLib rather than from a `dbFldDes`.
699pub(crate) fn field_desc_of<R: Record + ?Sized>(
700 record: &R,
701 field: &str,
702) -> Option<&'static FieldDesc> {
703 let named = |t: &'static [FieldDesc]| t.iter().find(|f| f.name.eq_ignore_ascii_case(field));
704 named(record.field_list()).or_else(|| named(super::dbd_generated::DB_COMMON_FIELDS))
705}
706
707/// **The single owner of "which choice list does this field resolve against"**,
708/// asked by BOTH sides of a menu field:
709///
710/// * the READ side ([`RecordInstance::enum_string_form_for`]) — C `getMenuString`,
711/// which renders the stored index as its choice;
712/// * the WRITE side ([`crate::server::record::coerce_put_value`]) — C
713/// `putStringMenu`, which resolves an incoming label to that same index.
714///
715/// They MUST see the same list or the field is not round-trippable. The write
716/// side used to ask only [`Record::menu_field_choices`] (the record's hand
717/// table), so an `aSub`'s `caput FTA LONG` found no menu, fell through to the
718/// numeric parse and landed as index 0 — while the read side, on the `.dbd`
719/// menu, rendered index 0 as `STRING`.
720///
721/// Order is C's: the field's own `menu()` from the declaration, then the
722/// record's hand table where the `.dbd` does not reach (the downstream crates'
723/// record types), then the `dbCommon` menus.
724///
725/// The last step — [`shared_menu_choices`](super::menu_choices::shared_menu_choices)
726/// — is a heuristic keyed on the field NAME (`OSV`, `SIMS`, `HHSV`, …), so it is
727/// consulted ONLY when the field's declaration does not already pin a non-menu
728/// type: a menu is served as `DBR_ENUM`, so a field DECLARED `DBF_STRING` is
729/// never a menu. Without this gate scalcout's string `OSV` ("Output string
730/// value") matched the name-based `menuAlarmSevr` entry a same-named bi/bo
731/// severity field owns, and `caput SCALCOUT.OSV <string>` was rejected with
732/// `S_db_badChoice` where C accepts the string.
733pub(crate) fn menu_choices_of<R: Record + ?Sized>(
734 record: &R,
735 field: &str,
736) -> Option<&'static [&'static str]> {
737 // `DTYP` is `DBF_DEVICE`: its choices are the record type's DEVICE menu
738 // (C `dbDeviceMenu`, built from the `device()` declarations), which is
739 // per-record-type and so cannot live in the shared `dbCommon` FieldDesc.
740 if field.eq_ignore_ascii_case("DTYP") {
741 return super::dbd_generated::device_menu(record.record_type());
742 }
743 let desc = field_desc_of(record, field);
744 desc.and_then(|f| f.menu)
745 .or_else(|| record.menu_field_choices(field))
746 .or_else(|| {
747 // Name-based fallback — but the declared type wins: a `DBF_STRING`
748 // field is not a menu even when a same-named field elsewhere is.
749 if desc.is_some_and(|f| f.dbf_type == DbFieldType::String) {
750 None
751 } else {
752 super::menu_choices::shared_menu_choices(field)
753 }
754 })
755}
756
757/// The `DBF_*` type `field` is SERVED as, for a caller that holds only a
758/// `&dyn Record` — the free-function form of
759/// [`RecordInstance::declared_field_type`], and the ONLY way any site outside
760/// the instance may turn a [`FieldDesc`] into a type.
761///
762/// A [`FieldDesc::runtime_typed`] field (`waveform.VAL` typed by `FTVL`, an
763/// `aSub`'s `A`..`U` typed by `FTA`..`FTU`) has NO type in its declaration: C's
764/// `cvt_dbaddr` overwrites `paddr->field_type` from record state, so the `.dbd`
765/// entry is a placeholder and the value the record stores is the answer. Every
766/// caller falls back to that value, which is why this returns `None` rather than
767/// the placeholder — handing out `DBF_DOUBLE` for a `FTVL=CHAR` waveform is how
768/// a string written down an output link became `0.0`.
769pub(crate) fn declared_field_type_of<R: Record + ?Sized>(
770 record: &R,
771 field: &str,
772) -> Option<DbFieldType> {
773 let desc = field_desc_of(record, field)?;
774 (!desc.runtime_typed).then_some(desc.dbf_type)
775}
776
777pub(crate) fn value_as_dbr_string(value: &EpicsValue) -> Option<PvString> {
778 match value {
779 EpicsValue::String(s) => Some(s.clone()),
780 EpicsValue::Enum(v) => Some(PvString::from(v.to_string())),
781 EpicsValue::EnumWithChoices { index, choices } => Some(
782 choices
783 .get(*index as usize)
784 .cloned()
785 .unwrap_or_else(|| PvString::from(index.to_string())),
786 ),
787 other => match other.clone().convert_to(DbFieldType::String) {
788 EpicsValue::String(s) => Some(s),
789 _ => None,
790 },
791 }
792}
793
794impl RecordInstance {
795 pub fn new(name: String, record: impl Record) -> Self {
796 Self::new_boxed(name, Box::new(record))
797 }
798
799 pub fn new_boxed(name: String, record: Box<dyn Record>) -> Self {
800 let rtype = record.record_type();
801 let analog_alarm = match rtype {
802 // C parity: every record type whose dbd carries
803 // HIHI/HIGH/LOW/LOLO/HHSV/HSV/LSV/LLSV gets an analog-alarm
804 // config slot. Previously calc / calcout were missing —
805 // their put_field for those fields silently no-op'd
806 // because `self.common.analog_alarm` was None at the
807 // mutation site. Confirmed via
808 // calcRecord.dbd.pod:716-744 (HIHI..LLSV) and
809 // calcoutRecord.dbd.pod:1103+ (same). `sub` carries the same
810 // HIHI/HIGH/LOLO/LOW + HHSV/HSV/LSV/LLSV set
811 // (subRecord.dbd.pod:569-642) and runs the analog `checkAlarms`.
812 // `scalcout` declares the identical set (`sCalcoutRecord.dbd:479-531`
813 // HIHI/LOLO/HIGH/LOW/HHSV/LLSV/HSV/LSV/HYST + `:858` LALM) and its
814 // `checkAlarms` (`sCalcoutRecord.c:699-751`) is the same ladder, run
815 // BEFORE the OOPT switch (`:371`) precisely so a limit excursion can
816 // drive IVOA. Without the slot the record had no alarm surface at
817 // all: `caput scalc.HIHI 5` was a `FieldNotFound` and a scalcout
818 // could never go MINOR/MAJOR on its own result.
819 //
820 // **This match is the single owner of "which records have the analog
821 // ladder"** — `evaluate_alarms` runs it off the slot's presence, so a
822 // record added here gets the ladder and one absent cannot.
823 "ai" | "ao" | "longin" | "longout" | "int64in" | "int64out" | "calc" | "calcout"
824 | "sub" | "scalcout" => Some(AnalogAlarmConfig::default()),
825 _ => None,
826 };
827 let mut common = CommonFields::default();
828 common.analog_alarm = analog_alarm;
829
830 Self {
831 name,
832 record,
833 common,
834 subscribers: HashMap::new(),
835 parsed_inp: ParsedLink::None,
836 parsed_out: ParsedLink::None,
837 parsed_flnk: ParsedLink::None,
838 parsed_sdis: ParsedLink::None,
839 parsed_tsel: ParsedLink::None,
840 device: None,
841 subroutine: None,
842 pact: AtomicBool::new(false),
843 notify: None,
844 deferred_notify_put: None,
845 last_posted: HashMap::new(),
846 declared_overrides: HashMap::new(),
847 array_hash_changed: false,
848 suppress_subroutine_run: false,
849 reprocess_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
850 watchdog_generation: Arc::new(std::sync::atomic::AtomicU64::new(0)),
851 info: HashMap::new(),
852 metadata_cache: StdMutex::new(None),
853 }
854 }
855
856 /// **The owner of a record's init passes** — C `iocInit.c::doInitRecord0`
857 /// (`:508-536`) and `doInitRecord1`. Nothing else may call
858 /// `Record::init_record`.
859 ///
860 /// C runs a prologue on EVERY record before pass 0, and it is the reason
861 /// this is one function instead of two `init_record` calls at each caller:
862 ///
863 /// ```c
864 /// /* Reset the process active field */
865 /// precord->pact = FALSE;
866 ///
867 /// /* Initial UDF severity */
868 /// if (precord->udf && precord->stat == UDF_ALARM)
869 /// precord->sevr = precord->udfs;
870 /// ```
871 ///
872 /// A record is born `udf = 1`, `stat = UDF_ALARM` (dbCommon.dbd
873 /// `initial("UDF")`), `udfs = INVALID` — so after `iocInit` a record that
874 /// has NEVER processed advertises `STAT=UDF SEVR=INVALID`, not
875 /// `NO_ALARM`. That is what makes an `MS` consumer inherit
876 /// `LINK`/`INVALID` from a not-yet-processed source, the IOC-startup
877 /// ordering case MS exists for (softIoc-verified). A record whose
878 /// `init_record` or device support defines the value clears UDF and the
879 /// severity goes away on its first process.
880 ///
881 /// `name` is used only for the init-failure diagnostics C sends to errlog.
882 ///
883 /// Crate-private on purpose: the passes must run against the record's FINAL
884 /// loaded field set (the initial UDF severity is a function of UDF/STAT/
885 /// UDFS, and a `.db` `field(VAL,…)` clears UDF at load — C
886 /// `dbStaticLib.c:2653-2661`). The one caller is the creation sink,
887 /// [`crate::server::database::PvDatabase::add_loaded_record`], which takes
888 /// the load and the record together so no path can init a half-loaded
889 /// record.
890 pub(crate) fn run_init_passes(&mut self, name: &str) {
891 // C's `precord->pact = FALSE` — a record cannot be mid-process at init,
892 // so this release provably frees nothing: no client put has run, so the
893 // `PactExit` invariant (`deferred_notify_put.is_some()` ⟹ PACT) makes a
894 // parked put-notify here unreachable.
895 let deferred = self.leave_pact().into_deferred();
896 debug_assert!(
897 deferred.is_none(),
898 "a record cannot hold a parked put-notify at init"
899 );
900 drop(deferred);
901 if self.common.udf != 0
902 && self.common.stat == crate::server::recgbl::alarm_status::UDF_ALARM
903 {
904 self.common.sevr = AlarmSeverity::from_u16(self.common.udfs as u16);
905 }
906 if let Err(e) = self.record.init_record(0) {
907 eprintln!("init_record(0) failed for {name}: {e}");
908 }
909 if let Err(e) = self.record.init_record(1) {
910 eprintln!("init_record(1) failed for {name}: {e}");
911 }
912 // The UDF tail of pass 1. `init_record` cannot reach UDF (a common
913 // field), so the record types whose C `init_record` ends in
914 // `prec->udf = FALSE` — histogram's `clear_histogram`, aao's constant
915 // DOL, mbboDirect's B0..B1F fold (epics-base dabcf89) — deliver it
916 // through this hook instead. It lives HERE, inside the init owner,
917 // because it is part of the same C pass: a creation path that ran the
918 // passes but skipped the tail (iocsh `dbLoadRecords` did) left those
919 // records UDF=1 where C has UDF=0.
920 // The `post_init_finalize_undef` hook is a cross-crate record-trait API
921 // over a `bool` (histogram/aao/mbboDirect implement it); bridge the raw
922 // `u8` carrier through it here at the single init owner.
923 let mut udf = self.common.udf != 0;
924 if let Err(e) = self.record.post_init_finalize_undef(&mut udf) {
925 eprintln!("post_init_finalize_undef failed for {name}: {e}");
926 }
927 self.common.udf = udf as u8;
928 // C `init_record` that ends in `prec->udf = 0; recGblResetAlarms(prec)`
929 // — the asyn record, defined and no-alarm the moment it loads. The born
930 // `UDF`/`INVALID` (and the UDF-severity derivation above) are overwritten
931 // here: at init `nsta`/`nsev` are 0, so `rec_gbl_reset_alarms` transfers
932 // `STAT`/`SEVR` to `NO_ALARM`. Runs after `post_init_finalize_undef` so
933 // it is the final word on this record's initial alarm state.
934 if self.record.init_resets_alarms() {
935 self.common.udf = 0;
936 let _ = crate::server::recgbl::rec_gbl_reset_alarms(&mut self.common);
937 }
938 // C `init_record` can END with `prec->pact = TRUE` to disable a record
939 // it cannot process (`subRecord.c:119-123`, an empty SNAM). PACT has one
940 // owner, so the record declares the fact and the owner parks it — after
941 // the passes, so the `leave_pact()` above cannot undo it. There is
942 // nothing to release later: `dbProcess` takes the PACT-active branch on
943 // every scan from here on, which is exactly the point.
944 if self.record.init_record_parks_pact() {
945 self.enter_pact();
946 }
947 }
948
949 /// SINGLE OWNER of the DTYP -> soft-output-dset mapping. The dset table
950 /// decides what a soft OUT-link write carries; no caller may re-derive it.
951 ///
952 /// C ships two soft output dsets per output record type and DTYP picks one:
953 /// `devXxxSoft.c::write_xxx` puts VAL/OVAL on the OUT link, while
954 /// `devXxxSoftRaw.c::write_xxx` puts the RAW word — `dbPutLink(&prec->out,
955 /// DBR_LONG, &prec->rval, 1)` (`devAoSoftRaw.c:44`, `devBoSoftRaw.c:65`) or
956 /// `data = prec->rval & prec->mask` (`devMbboSoftRaw.c:71-75`,
957 /// `devMbboDirectSoftRaw.c:71-75`).
958 ///
959 /// `Record::raw_soft_output_value` IS the SoftRaw column of that table:
960 /// `Some` exactly for the record types C ships a SoftRaw dset for. A record
961 /// type C has no SoftRaw dset for keeps the plain soft-channel value —
962 /// `DTYP="Raw Soft Channel"` on a `longout` is a `.db` error C rejects at
963 /// init ("no device support"), and the port's lenient reading of it (the
964 /// same one [`crate::server::device_support::is_soft_dtyp`] already applies
965 /// on the input side) must not turn the write into a silent no-op.
966 ///
967 /// `None` means DTYP names device support that owns the write — real
968 /// hardware, or "Async Soft Channel", whose dset is a registered async
969 /// device.
970 pub fn soft_output_value(&self) -> Option<Option<EpicsValue>> {
971 if self.common.dtyp == "Raw Soft Channel" {
972 return Some(
973 self.record
974 .raw_soft_output_value()
975 .or_else(|| self.record.output_link_value()),
976 );
977 }
978 if self.common.dtyp.is_empty() || self.common.dtyp == "Soft Channel" {
979 return Some(self.record.output_link_value());
980 }
981 None
982 }
983
984 /// Set a single `info("key", "value")` tag on this record. Last
985 /// write wins. Used by the .db loader (`info(...)` directive) and
986 /// `dbpf`-style tools.
987 pub fn set_info(&mut self, key: impl Into<String>, value: impl Into<String>) {
988 self.info.insert(key.into(), value.into());
989 }
990
991 /// Look up a single info tag. Returns `None` when the record has
992 /// no tag with that key.
993 pub fn get_info(&self, key: &str) -> Option<&str> {
994 self.info.get(key).map(|s| s.as_str())
995 }
996
997 /// The value of `field` already published to its `DBE_VALUE`/`DBE_LOG`
998 /// subscribers, or `None` when the framework has never published one.
999 /// The read side of the `last_posted` contract — see the field's docs.
1000 pub(crate) fn posted_value(&self, field: &str) -> Option<&EpicsValue> {
1001 self.last_posted.get(field)
1002 }
1003
1004 /// SINGLE OWNER of `last_posted`: record that `value` has been published
1005 /// to `field`'s `DBE_VALUE`/`DBE_LOG` subscribers, so no later cycle
1006 /// change-detects and re-publishes it.
1007 ///
1008 /// Every value-class post — the snapshot builders' change-detected posts,
1009 /// the intermediate async-notify posts, and the put-time
1010 /// [`Self::notify_field_with_origin`] post that C makes from `dbPut`
1011 /// (dbAccess.c:1414) — routes through here. Alarm-only / property-only
1012 /// posts MUST NOT call it: they deliver nothing to a value-class
1013 /// subscriber, so the value is still owed.
1014 pub(crate) fn record_value_post(&mut self, field: &str, value: EpicsValue) {
1015 if let Some(slot) = self.last_posted.get_mut(field) {
1016 *slot = value;
1017 } else {
1018 self.last_posted.insert(field.to_string(), value);
1019 }
1020 }
1021
1022 /// Invalidate the metadata cache. Called after writing any
1023 /// metadata-class field (EGU, PREC, HOPR/LOPR, alarm limits,
1024 /// DRVH/DRVL, enum strings). The next snapshot will rebuild the
1025 /// cache from the new values.
1026 pub fn invalidate_metadata_cache(&self) {
1027 if let Ok(mut guard) = self.metadata_cache.lock() {
1028 *guard = None;
1029 }
1030 }
1031
1032 /// Hook called by the database after a field is written. If the
1033 /// field is in the metadata-class set, the cache is invalidated so
1034 /// the next snapshot picks up the new value.
1035 ///
1036 /// Field name is automatically uppercased.
1037 pub fn notify_field_written(&self, field: &str) {
1038 let upper = field.to_ascii_uppercase();
1039 if is_metadata_field(&upper) {
1040 self.invalidate_metadata_cache();
1041 }
1042 }
1043
1044 /// Like [`notify_field_written`] but skips the invalidation when
1045 /// the put did not actually change the field's value. Mirrors
1046 /// epics-base `faac1df1` — `DBE_PROPERTY` events fire only on
1047 /// real changes, not on idempotent writes (the C path compares
1048 /// `paddr->pfield` against the converted payload before setting
1049 /// the `propertyUpdate` flag).
1050 ///
1051 /// `prev` is the value captured BEFORE the put. Callers that
1052 /// don't need the change-detection (e.g. internal writers that
1053 /// know the field is non-metadata) can keep using
1054 /// [`notify_field_written`].
1055 // must post EventMask::PROPERTY to all field subscribers when metadata changes
1056 pub fn notify_field_written_if_changed(&mut self, field: &str, prev: Option<&EpicsValue>) {
1057 let upper = field.to_ascii_uppercase();
1058 if !is_metadata_field(&upper) {
1059 return;
1060 }
1061 let now = self.record.get_field(&upper);
1062 if prev != now.as_ref() {
1063 self.invalidate_metadata_cache();
1064 // mirror C dbAccess.c:1396-1397 db_post_events(precord, NULL, DBE_PROPERTY).
1065 // Collect keys first to avoid a re-entrant immutable borrow on subscribers.
1066 let fields: Vec<String> = self.subscribers.keys().cloned().collect();
1067 for f in fields {
1068 self.notify_field_with_origin(&f, crate::server::recgbl::EventMask::PROPERTY, 0);
1069 }
1070 }
1071 }
1072
1073 /// Returns the cached MetadataSnapshot, building and storing it on
1074 /// the first call (or after invalidation). Used by both
1075 /// `snapshot_for_field` and `make_monitor_snapshot` so the populate
1076 /// cost is paid at most once per metadata-stable interval.
1077 fn cached_metadata(&self) -> MetadataSnapshot {
1078 // Fast path: cache hit
1079 if let Ok(guard) = self.metadata_cache.lock()
1080 && let Some(cached) = guard.as_ref()
1081 {
1082 return cached.clone();
1083 }
1084
1085 // Cache miss: build a fresh metadata snapshot
1086 let mut tmp = super::super::snapshot::Snapshot::new(
1087 EpicsValue::Double(0.0),
1088 0,
1089 0,
1090 std::time::SystemTime::UNIX_EPOCH,
1091 );
1092 self.populate_display_info(&mut tmp);
1093 self.populate_control_info(&mut tmp);
1094 self.populate_enum_info(&mut tmp);
1095
1096 let meta = MetadataSnapshot {
1097 display: tmp.display,
1098 control: tmp.control,
1099 enums: tmp.enums,
1100 };
1101
1102 // Store back; ignore poisoning (cache is best-effort).
1103 if let Ok(mut guard) = self.metadata_cache.lock() {
1104 *guard = Some(meta.clone());
1105 }
1106 meta
1107 }
1108
1109 /// C `dbChannelSpecial(chan) == SPC_NOMOD` — **the single owner of the
1110 /// no-modify declaration**, for every consumer that needs to know whether a
1111 /// field can be written.
1112 ///
1113 /// C declares it once, in the `.dbd`, and reads it in two unrelated places:
1114 ///
1115 /// * `dbPut` (`dbAccess.c:123-126`, via `dbPutSpecial(paddr, 0)`) refuses
1116 /// the write — the port's `check_no_mod` gate;
1117 /// * `rsrvCheckPut` (`rsrv/camessage.c:2540-2551`) — `if
1118 /// (dbChannelSpecial(pciu->dbch) == SPC_NOMOD) return 0;` — which feeds
1119 /// the CA `ACCESS_RIGHTS` write bit (`camessage.c:1123-1124`) as well as
1120 /// both put paths, so a client sees `Access: read, no write` and never
1121 /// sends the doomed write.
1122 ///
1123 /// Only the first consumer existed in the port, so every dbCommon NOMOD
1124 /// field advertised WRITE on the wire (`caput N1.SEVR 2` was refused
1125 /// server-side, after the client had already sent it, with an async
1126 /// exception instead of C's clean client-side "Write access denied").
1127 ///
1128 /// Three sources, one answer:
1129 ///
1130 /// 1. the dbCommon `SPC_NOMOD` set below — common fields, so no record's
1131 /// `field_list` declares them;
1132 /// 2. the record type's **declaration**, resolved by [`Self::field_desc`] —
1133 /// the vendored `.dbd` whenever one exists, and only for a record type
1134 /// that has no `.dbd` at all (`motor`, `optics`, `scaler`, `std`) the
1135 /// record's own hand-written table, which for those Tier 3 types
1136 /// genuinely *is* their declaration;
1137 /// 3. [`Record::field_no_mod`] — an SPC_NOMOD a record's `cvt_dbaddr`
1138 /// raises from its own state (compress VAL under BALG=LIFO,
1139 /// `compressRecord.c:398-407`), which a static `FieldDesc` cannot
1140 /// express.
1141 ///
1142 /// `field` may be any case.
1143 pub fn is_no_mod(&self, field: &str) -> bool {
1144 if DBCOMMON_NOMOD.iter().any(|f| f.eq_ignore_ascii_case(field)) {
1145 return true;
1146 }
1147 if self.field_desc(field).is_some_and(|f| f.read_only) {
1148 return true;
1149 }
1150 self.record.field_no_mod(field)
1151 }
1152
1153 /// Check if the record is currently processing (PACT equivalent).
1154 pub fn is_processing(&self) -> bool {
1155 self.pact.load(std::sync::atomic::Ordering::Acquire)
1156 }
1157
1158 /// C `prec->pact = TRUE` — the record goes busy for an async device
1159 /// round-trip, an SDLY simulation defer, or an ODLY reprocess window.
1160 pub fn enter_pact(&self) {
1161 self.pact.store(true, std::sync::atomic::Ordering::Release);
1162 }
1163
1164 /// C `prec->pact = FALSE` — the ONLY release of PACT.
1165 ///
1166 /// Every PACT→idle transition takes the put-notify parked on that window
1167 /// with it (C `dbNotifyCompletion`, reached from `recGblFwdLink` on every
1168 /// path that ends a cycle). The returned [`PactExit`] is `#[must_use]`, so
1169 /// a release site cannot strand the deferral the way the open-coded
1170 /// `processing.store(false)` at the ODLY continuation and the three SIM/SDLY
1171 /// releases did.
1172 pub fn leave_pact(&mut self) -> PactExit {
1173 self.pact.store(false, std::sync::atomic::Ordering::Release);
1174 PactExit(self.deferred_notify_put.take())
1175 }
1176
1177 /// True when a put-notify already owns this record — an in-flight wait-set
1178 /// (C `precord->ppn`) or a park from a previous PACT arm. C
1179 /// `processNotifyCommon` (dbNotify.c:213-217) queues a second notify on the
1180 /// record's restart list; the port refuses it (`S_db_Blocked` /
1181 /// `ECA_PUTCBINPROG`) — see [`Self::park_notify_put`].
1182 pub fn put_notify_busy(&self) -> bool {
1183 self.notify.is_some() || self.deferred_notify_put.is_some()
1184 }
1185
1186 /// Park a put-notify that landed on a PACT record (C `processNotifyCommon`,
1187 /// dbNotify.c:225-231). `Err(put)` hands the put back when another
1188 /// put-notify already owns the record.
1189 ///
1190 /// The [`PactExit`] invariant — `deferred_notify_put.is_some()` ⟹ PACT —
1191 /// is established here: this is the only park, and it is only reachable
1192 /// from the caller's `is_processing()` arm.
1193 pub fn park_notify_put(&mut self, put: DeferredNotifyPut) -> Result<(), DeferredNotifyPut> {
1194 debug_assert!(
1195 self.is_processing(),
1196 "a put-notify may be parked only on a PACT record"
1197 );
1198 if self.put_notify_busy() {
1199 return Err(put);
1200 }
1201 self.deferred_notify_put = Some(put);
1202 Ok(())
1203 }
1204
1205 /// Unified field resolution: record fields → common fields → virtual fields.
1206 pub fn resolve_field(&self, name: &str) -> Option<EpicsValue> {
1207 let name = name.to_ascii_uppercase();
1208 self.record
1209 .get_field(&name)
1210 .or_else(|| self.get_common_field(&name))
1211 .or_else(|| self.get_virtual_field(&name))
1212 .or_else(|| self.declared_overrides.get(&name).cloned())
1213 .or_else(|| self.declared_default(&name))
1214 }
1215
1216 /// The value a field that is DECLARED by the `.dbd` but has no live store
1217 /// on this record serves: its `initial(...)`, or a type-zero.
1218 ///
1219 /// C makes *every* `.dbd` field addressable — `dbNameToAddr` resolves the
1220 /// field from its `dbFldDes` and `dbGet` reads it out of record memory,
1221 /// which the dbd loader seeded with `initial()` (or left zero). A Rust
1222 /// record implements only the fields it has behaviour for, so a field it
1223 /// declares but never touches — `aSub.OVAL`, `sub.LA`, `sel.HOPR` — had no
1224 /// channel at all: [`Self::resolve_field`]'s three accessors all returned
1225 /// `None` and CA create-channel answered `S_dbLib_recNotFound`.
1226 ///
1227 /// The declared table is the contract for *which* fields exist; this is the
1228 /// last resort for the *value* of one with no runtime accessor, and it is
1229 /// exactly what an unprocessed C record on an empty `.db` returns —
1230 /// [`apply_dbd_initials`](crate::server::db_loader) seeds the same
1231 /// `initial()` into the fields the record *does* store, from the same
1232 /// generated table, so the two paths agree by construction.
1233 fn declared_default(&self, name: &str) -> Option<EpicsValue> {
1234 let desc = self.field_desc(name)?;
1235 // A `runtime_typed` field (`VAL`/`BG`, re-typed from `FTVL`/`SDEF`) is
1236 // record-owned by definition and its placeholder `dbf_type` is not what
1237 // it serves; never synthesise one here — the record itself answers it.
1238 if desc.runtime_typed {
1239 return None;
1240 }
1241 let initial = desc.initial.unwrap_or("");
1242 if let Some(choices) = desc
1243 .menu
1244 .or_else(|| self.record.menu_field_choices(name))
1245 .or_else(|| super::shared_menu_choices(name))
1246 {
1247 // A menu field with no `initial(...)` is index 0, exactly as an
1248 // empty numeric field is 0 below.
1249 if initial.is_empty() {
1250 return Some(EpicsValue::Enum(0));
1251 }
1252 return super::resolve_menu_field_string_db_load(name, choices, desc.dbf_type, initial)
1253 .ok();
1254 }
1255 // `parse` maps an empty string to the declared type's zero, so this one
1256 // call serves both `initial(...)` and no-initial fields.
1257 EpicsValue::parse_bytes(desc.dbf_type, initial.as_bytes()).ok()
1258 }
1259
1260 /// Resolve a field for EPICS `$` long-string (character-array) access.
1261 ///
1262 /// The `$` channel-name modifier (C `dbChannel.c:486-505`) re-views a
1263 /// field as a `DBR_CHAR` array: a `DBF_STRING` field becomes a char
1264 /// array of `field_size` elements, a link field a char array of
1265 /// `PVLINK_STRINGSZ`, and every other field type is rejected with
1266 /// `S_dbLib_fieldNotFound`. pvxs serves that char view as a
1267 /// `form = "String"` long-string `NTScalar` — it reads the `DBR_CHAR`
1268 /// bytes and NUL-terminates them back into a string
1269 /// (`ioc/iocsource.cpp:133-136`, `ioc/channel.cpp:62-74`).
1270 ///
1271 /// Both `DBF_STRING` fields and link fields resolve to an
1272 /// [`EpicsValue::String`] in this database (a link resolves to its
1273 /// textual form, see [`Self::get_common_field`]), so a field is
1274 /// `$`-eligible exactly when it resolves to a string value. Returns
1275 /// that string value for an eligible field, or `None` for a field the
1276 /// `$` modifier cannot view as a char array (the
1277 /// `S_dbLib_fieldNotFound` case) — the single owner of the
1278 /// dbChannel `$`-eligibility rule for the channel-resolution layer.
1279 pub fn resolve_string_view_field(&self, name: &str) -> Option<EpicsValue> {
1280 match self.resolve_field(name)? {
1281 v @ EpicsValue::String(_) => Some(v),
1282 _ => None,
1283 }
1284 }
1285
1286 /// Choice table for a field served as `DBR_ENUM` from a `DBF_MENU`:
1287 /// the record's own record-specific menu
1288 /// ([`Record::menu_field_choices`](super::record_trait::Record::menu_field_choices)),
1289 /// else a shared menu keyed by field name
1290 /// ([`shared_menu_choices`](super::menu_choices::shared_menu_choices)).
1291 /// The choices a `menu()` field serves as its `DBR_ENUM` labels.
1292 ///
1293 /// The `.dbd` declaration is the first and best answer: a generated
1294 /// [`FieldDesc`] carries the field's own `menu(...)` choices, which is what
1295 /// C's `dbGetFieldIndex` -> `pamapdbfType` -> menu lookup resolves. The two
1296 /// hand-maintained fallbacks below are for record types still on a
1297 /// hand-written table; they go away with the last of them.
1298 ///
1299 /// `shared_menu_choices` in particular keys on the field NAME alone, across
1300 /// every record type — which is only correct while no two record types give
1301 /// the same field name different menus. Asking the field's own descriptor
1302 /// first removes that assumption.
1303 fn menu_choices_for(&self, field: &str) -> Option<&'static [&'static str]> {
1304 menu_choices_of(self.record.as_ref(), field)
1305 }
1306
1307 /// The choices this record's `DTYP` selects among — C's `dbDeviceMenu` for
1308 /// the record type, in `.dbd` declaration order.
1309 ///
1310 /// C's DTYP field IS the index into this list, and an unset DTYP is index 0
1311 /// — which is why a bare `record(ai,"X"){}` serves `Soft Channel` and a
1312 /// `record(calc,"X"){}`, whose record type declares no device support at
1313 /// all, serves the empty string.
1314 ///
1315 /// The port stores the device NAME rather than the index, because the name
1316 /// is what the device-support registry dispatches on, and a name registered
1317 /// at runtime by a downstream crate (`asynInt32`) has no `device()` line in
1318 /// any vendored `.dbd`. Such a name is appended as its own slot, so the
1319 /// index and the string still name the SAME device support: there is no
1320 /// value of DTYP that renders as a device this record is not bound to.
1321 /// `None` when the record type declares NO device support at all — C's
1322 /// `dbDeviceMenu *pdevs = paddr->pfldDes->ftPvt; if (!pdevs) goto nostrs;`
1323 /// (`dbAccess.c:176-179`), which clears `DBR_ENUM_STRS` so the client is
1324 /// sent no choice list at all.
1325 ///
1326 /// C keeps that case DISTINCT from a device menu that exists but is empty,
1327 /// and says so at `dbAccess.c:205`: *"indicate option data not available.
1328 /// distinct from no_str==0"*. An empty-but-present menu is still marked,
1329 /// with `no_str = 0`; a missing menu is not marked. Returning `Vec` here
1330 /// and defaulting the missing menu to `[]` collapsed the two, so a
1331 /// `record(calc,"X"){}` — whose record type has no `device()` line — served
1332 /// `value.choices = {0}[]` where QSRV2 omits the leaf entirely.
1333 pub(crate) fn device_choices(&self) -> Option<Vec<PvString>> {
1334 let declared = super::dbd_generated::device_menu(self.record.record_type())?;
1335 let mut slots: Vec<PvString> = declared.iter().map(|c| PvString::from(*c)).collect();
1336 let dtyp = self.common.dtyp.as_str();
1337 if !dtyp.is_empty() && !declared.contains(&dtyp) {
1338 slots.push(PvString::from(dtyp));
1339 }
1340 Some(slots)
1341 }
1342
1343 /// C `dbPutFieldLink`'s link-type gate (`dbAccess.c:1125-1137`): a link
1344 /// written at RUNTIME is held to the same `dbCanSetLink` rule as one written
1345 /// by the `.db`, against the device support the record's CURRENT `DTYP`
1346 /// binds. Same rule, same owner — [`super::check_link_assignment`]; only the
1347 /// DTYP it is asked about differs (the record's, not the `.db` text's).
1348 ///
1349 /// [`MenuBound::DbLoad`] is exempt, and that is not a hole: on the db-load
1350 /// path C does not check a link as each field is parsed either. It checks
1351 /// once, at `iocInit`, over the record as loaded (`dbStaticLib.c:2178-2231`)
1352 /// — which is why `field(INP,…)` may precede `field(DTYP,…)` in a `.db` and
1353 /// still bind. `db_loader::check_link_types` is that pass, and it reads the
1354 /// record's DTYP out of the whole field set, so it does not depend on the
1355 /// order the `.db` happened to spell them in. Gating here as well would
1356 /// re-introduce exactly that order dependence.
1357 fn check_link_assignment(
1358 &self,
1359 upper_field: &str,
1360 text: &str,
1361 bound: MenuBound,
1362 ) -> CaResult<()> {
1363 if matches!(bound, MenuBound::DbLoad) {
1364 return Ok(());
1365 }
1366 super::check_link_assignment(
1367 self.record.record_type(),
1368 Some(self.common.dtyp.as_str()),
1369 upper_field,
1370 text,
1371 )
1372 }
1373
1374 /// The value of the `DTYP` field: the index of the bound device support in
1375 /// [`Self::device_choices`]. An unset DTYP is index 0, exactly as in C.
1376 pub(crate) fn dtyp_index(&self) -> u16 {
1377 let dtyp = self.common.dtyp.as_str();
1378 if dtyp.is_empty() {
1379 return 0;
1380 }
1381 // A record type with no device menu has no slot for any DTYP, so the
1382 // index stays 0 — the same answer the old `unwrap_or(&[])` gave.
1383 self.device_choices()
1384 .unwrap_or_default()
1385 .iter()
1386 .position(|c| c.as_str_lossy() == dtyp)
1387 .unwrap_or(0) as u16
1388 }
1389
1390 /// **The** owner of "what string does this enum-valued field render as" —
1391 /// C's `[DBF_*][DBR_STRING]` conversion row, chosen by the field's DBF
1392 /// class. Every path that renders an enum as a string goes through here:
1393 /// the CA/PVA encoders (via [`snapshot::EnumInfo::string_form`] on the
1394 /// snapshot this builds) and the db-link read
1395 /// ([`Self::field_as_dbr_string`]). There is exactly one such table per
1396 /// field, and no path may reconstruct a second one.
1397 ///
1398 /// C's dispatch, and this function's, in the same order:
1399 ///
1400 /// * `DBF_MENU` / `DBF_DEVICE` -> `getMenuString` / `getDeviceString`, the
1401 /// field's own choice list. Asked FIRST, because a menu field on a record
1402 /// whose `VAL` is an enum (`bo.OMSL`) must render its menu's choices, not
1403 /// the record's `ZNAM`/`ONAM`.
1404 /// * `DBF_ENUM` `VAL` -> `getEnumString` -> the record's `get_enum_str`
1405 /// rset ([`Record::enum_string_form`](super::record_trait::Record::enum_string_form)).
1406 ///
1407 /// `None` when the field has neither — C answers `S_db_noRSET`, an error;
1408 /// the port renders empty.
1409 ///
1410 /// Each class brings its own out-of-range rule with it (see
1411 /// [`EnumOverflow`](crate::server::snapshot::EnumOverflow)); the index is
1412 /// rendered as a number for a `DBF_MENU` and ONLY for a `DBF_MENU`.
1413 pub(crate) fn enum_string_form_for(&self, field: &str) -> Option<EnumStringForm> {
1414 if field.eq_ignore_ascii_case("DTYP") {
1415 // `None` propagates C's `goto nostrs` (`dbAccess.c:178`): a record
1416 // type with no `device()` declaration supplies no choice list, so
1417 // the leaf is omitted rather than marked empty.
1418 return self.device_choices().map(EnumStringForm::device);
1419 }
1420 if let Some(choices) = self.menu_choices_for(field) {
1421 return Some(EnumStringForm::menu(
1422 choices.iter().map(|c| PvString::from(*c)),
1423 ));
1424 }
1425 if field.eq_ignore_ascii_case("VAL") {
1426 return self.record.enum_string_form();
1427 }
1428 None
1429 }
1430
1431 /// Is `field` one of the DBF classes C's soft device support writes as
1432 /// `DBR_STRING`?
1433 ///
1434 /// `devsCalcoutSoft.c:128-130` (and its async twin, :83-85) switches the
1435 /// scalcout OUT put on the TARGET field's DBF type and sends `OSV` — the
1436 /// string result — for seven of them:
1437 ///
1438 /// ```c
1439 /// case DBF_STRING: case DBF_ENUM: case DBF_MENU: case DBF_DEVICE:
1440 /// case DBF_INLINK: case DBF_OUTLINK: case DBF_FWDLINK:
1441 /// status = dbPutLink(&pscalcout->out, DBR_STRING, &pscalcout->osv, 1);
1442 /// ```
1443 ///
1444 /// [`DbFieldType`] is the port's DBR *wire* type and cannot express
1445 /// `DBF_MENU` / `DBF_DEVICE` — C's DBF class is not the DBR type. The
1446 /// classification therefore lives here, with the record's field metadata,
1447 /// where each class is already known:
1448 ///
1449 /// * `DBF_STRING` and the three link classes — the port stores links and
1450 /// `DTYP` (C's only `DBF_DEVICE` field) as strings;
1451 /// * `DBF_ENUM` — an enum-typed field;
1452 /// * `DBF_MENU` — a menu-index field, i.e. one this record resolves choice
1453 /// labels for ([`Self::menu_choices_for`]): `PRIO`, `STAT`, `SEVR`,
1454 /// `DISS`, `ACKT`, `SCAN`, `IVOA`, `OMSL`, … The index is stored as a
1455 /// short, so a same-named field that is NOT a menu index (scalcout's
1456 /// string `OSV` shares a name with the alarm-severity menu) is
1457 /// classified by its own type, not by the name collision.
1458 ///
1459 /// Everything else (`DBF_DOUBLE`, `DBF_LONG`, `DBF_CHAR`, …) falls to the
1460 /// device support's `default:` arm.
1461 ///
1462 /// The question is about the target field's DECLARED class, so it is asked
1463 /// of the declaration ([`Self::declared_field_type`]) and not of the
1464 /// variant the record stores: C's `switch` is on `dbAddr.field_type`, which
1465 /// `dbNameToAddr` took from the `dbFldDes`. `DBF_MENU` and `DBF_DEVICE` both
1466 /// map to `DbFieldType::Enum` in the generated tables (`mapDBFToDBR`), and
1467 /// the three link classes to `DbFieldType::String`, so the seven C arms are
1468 /// exactly these two.
1469 pub(crate) fn field_puts_as_string(&self, field: &str) -> bool {
1470 let Some(declared) = self.declared_field_type(field) else {
1471 return false;
1472 };
1473 matches!(declared, DbFieldType::String | DbFieldType::Enum)
1474 }
1475
1476 /// The field's value as C `dbGetLink(plink, DBR_STRING, ...)` delivers it —
1477 /// the SOURCE side of an input link read with
1478 /// [`LinkReadAs::String`](super::record_trait::LinkReadAs::String).
1479 ///
1480 /// C converts at the source, through `dbConvert.c`'s
1481 /// `[field_type][DBR_STRING]` table: a `DBF_ENUM` field goes through
1482 /// `getEnumString` → the record's `get_enum_str` (mbbi's `ZRST`.., bi's
1483 /// `ZNAM`/`ONAM`) and a `DBF_MENU` field through `getMenuString` → the
1484 /// menu's choice string, i.e. the state LABEL in both cases, never the
1485 /// index. Only the record holds those tables, so the render lives here with
1486 /// the field metadata — the link-read owner has an index and nothing to
1487 /// resolve it with.
1488 ///
1489 /// The render goes through [`Self::enum_string_form_for`], the same owner
1490 /// the CA/PVA encoders use, so a link read and a `caget -t` of one field can
1491 /// never disagree about its string.
1492 pub(crate) fn field_as_dbr_string(&self, field: &str) -> Option<PvString> {
1493 let value = self.resolve_field(field)?;
1494 // A `DBF_ENUM` index, and a `DBF_MENU` index (stored as a short),
1495 // render through the field's string source. A short field that is
1496 // neither has no source and stays the plain number C converts it to.
1497 let idx = match value {
1498 EpicsValue::Enum(v) => Some(v),
1499 EpicsValue::Short(v) => u16::try_from(v).ok(),
1500 _ => None,
1501 };
1502 if let Some(idx) = idx
1503 && let Some(form) = self.enum_string_form_for(field)
1504 {
1505 return Some(form.render(idx));
1506 }
1507 value_as_dbr_string(&value)
1508 }
1509
1510 /// The field's declaration — its `dbFldDes`, in C's terms.
1511 ///
1512 /// The `.dbd` is the declaration, so the table generated FROM the `.dbd`
1513 /// ([`dbd_generated::record_fields`](super::dbd_generated::record_fields))
1514 /// is asked first, for every record type that has one. A record's own
1515 /// [`Record::field_list`](super::record_trait::Record::field_list) is a
1516 /// hand-written stand-in for that table, and it is consulted only for a
1517 /// record type the `.dbd` does not cover (`subArray`, and the record types
1518 /// the downstream crates add). It cannot be the primary answer: several of
1519 /// those tables are *derived from the record's Rust storage types* — the
1520 /// `#[derive(EpicsRecord)]` records type `longin.ADEL` `DBF_DOUBLE`
1521 /// because the struct member is an `f64`, where the `.dbd` says
1522 /// `DBF_LONG` — and reading the type off the storage is the whole defect
1523 /// this owner exists to close.
1524 ///
1525 /// `dbCommon` last, matching the order [`Self::resolve_field`] reads the
1526 /// value in, so a record-specific field always shadows the common one in
1527 /// both halves.
1528 ///
1529 /// `None` for a field with no declaration at all: a virtual field
1530 /// (`RTYP`, `TIME`, ...), which C answers from dbStaticLib rather than
1531 /// from a `dbFldDes`.
1532 pub(crate) fn field_desc(&self, field: &str) -> Option<&'static FieldDesc> {
1533 field_desc_of(self.record.as_ref(), field)
1534 }
1535
1536 /// The `DBF_*` type `field` is SERVED as — the single source of truth for
1537 /// the type on the wire, on every delivery path.
1538 ///
1539 /// This is the field's DECLARED type ([`FieldDesc::dbf_type`], from the
1540 /// `.dbd`), not the type of whatever variant the record happens to store.
1541 /// C resolves a channel's `field_type` from the `dbFldDes` at
1542 /// name-resolution time (`dbChannelCreate` -> `dbNameToAddr`,
1543 /// `dbAccess.c:184-205`) and every later `dbGet`/`db_post_events` converts
1544 /// the stored bytes to it — the storage is private to the record, the
1545 /// declaration is the contract.
1546 ///
1547 /// Two answers are NOT the declaration:
1548 ///
1549 /// * a [`FieldDesc::runtime_typed`] field — C's `cvt_dbaddr` overwrites
1550 /// `paddr->field_type` from record state (`FTVL`, `FTA`, `SDEF`), and
1551 /// this port's `cvt_dbaddr` is the variant the record stores;
1552 /// * a field with no `FieldDesc` at all (a virtual field).
1553 ///
1554 /// In both cases the value's own type is the answer, so this returns
1555 /// `None` and [`Self::project_to_declared_type`] leaves the value alone.
1556 pub fn declared_field_type(&self, field: &str) -> Option<DbFieldType> {
1557 declared_field_type_of(self.record.as_ref(), field)
1558 }
1559
1560 /// Project a field's stored value onto its declared type
1561 /// ([`Self::declared_field_type`]) — the single owner of "what type this
1562 /// field goes on the wire as", run by the CA create-channel path
1563 /// ([`Self::client_field_value`]), the GET path
1564 /// ([`Self::snapshot_for_field`]) and the MONITOR path
1565 /// ([`Self::make_monitor_snapshot`]), so all three announce and serve the
1566 /// same type.
1567 ///
1568 /// The projection is [`EpicsValue::convert_to`], the one value-coercion
1569 /// owner — the same routine `dbGet` converts through. Never re-derive a
1570 /// conversion here: C picks its routine from BOTH the source and the
1571 /// destination type, and only `convert_to` knows that table.
1572 ///
1573 /// Idempotent: a value already of its declared type is short-circuited by
1574 /// `convert_to`, and re-projecting a projected value is a no-op. That is
1575 /// what lets the CA path derive the native type from the value it is about
1576 /// to serve.
1577 pub fn project_to_declared_type(&self, field: &str, value: EpicsValue) -> EpicsValue {
1578 match self.declared_field_type(field) {
1579 Some(declared) => value.convert_to(declared),
1580 None => value,
1581 }
1582 }
1583
1584 /// The client-facing value of `field`: the resolved value projected onto
1585 /// the field's declared type ([`Self::project_to_declared_type`]), so a
1586 /// native type derived from the value — which is what the CA
1587 /// create-channel path does — is the DECLARED type, and matches the
1588 /// GET/MONITOR data byte for byte.
1589 pub fn client_field_value(&self, field: &str) -> Option<EpicsValue> {
1590 let value = self.resolve_field(field)?;
1591 Some(self.project_to_declared_type(field, value))
1592 }
1593
1594 /// Attach a `DBF_MENU` field's `menu()` choice labels to a built snapshot,
1595 /// so the CA/PVA enum encoders present `"NO CONVERSION"` rather than `0`.
1596 ///
1597 /// The VALUE half of the `DBF_MENU` -> `DBR_ENUM` mapping is not here: the
1598 /// `.dbd` declares a menu field `DBF_MENU`, the generator types that
1599 /// `DbFieldType::Enum` (`mapDBFToDBR`), and
1600 /// [`Self::project_to_declared_type`] — which every delivery path runs —
1601 /// makes the served value an [`EpicsValue::Enum`] on that declaration
1602 /// alone. So the label table is all that is left to attach, and it is
1603 /// attached exactly when the served value came out an enum. A same-named
1604 /// field that is NOT a menu index (`scalcout.OSV`, declared `DBF_STRING`,
1605 /// shares a name with the alarm-severity menu) is served as its own
1606 /// declared string and gets no choice table.
1607 fn attach_menu_enum(&self, field: &str, snap: &mut super::super::snapshot::Snapshot) {
1608 if !matches!(snap.value, EpicsValue::Enum(_)) {
1609 return;
1610 }
1611 // `VAL` is the one field whose two rset slots differ: C's
1612 // `get_enum_strs` (the `DBR_GR_ENUM` labels) is TRIMMED to `no_str`
1613 // while `get_enum_str` (the DBR_STRING form) indexes the untrimmed
1614 // state array. `populate_enum_info` owns that pair; every OTHER
1615 // enum-valued field is a menu or a device, whose one choice list
1616 // answers both (C `getMenuString`/`getDeviceString` index the same
1617 // `papChoiceValue` the GR_ENUM reply carries).
1618 if field.eq_ignore_ascii_case("VAL") {
1619 return;
1620 }
1621 let Some(form) = self.enum_string_form_for(field) else {
1622 return;
1623 };
1624 snap.enums = Some(super::super::snapshot::EnumInfo::with_string_form(
1625 form.slots.clone(),
1626 form,
1627 ));
1628 }
1629
1630 /// Build a Snapshot with full metadata for the given field.
1631 pub fn snapshot_for_field(&self, field: &str) -> Option<super::super::snapshot::Snapshot> {
1632 // The GET path serves the field at its DECLARED type, the same type
1633 // the CA create-channel path announced from `client_field_value` and
1634 // the same one the monitor path posts.
1635 let value = self.client_field_value(field)?;
1636 let mut snap = super::super::snapshot::Snapshot::new(
1637 value,
1638 self.common.stat,
1639 self.common.sevr as u16,
1640 self.common.time,
1641 );
1642 // Default the served `timeStamp.userTag` to the record's `utag`,
1643 // mirroring pvxs `iocsource.cpp:245` (`auto utag = meta.utag;`).
1644 // The 64-bit `epicsUTag` narrows to the int32 NT wire field by
1645 // truncating to the low 32 bits — pvxs assigns the same uint64
1646 // straight into the `Int32` `timeStamp.userTag`. The `Q:time:tag`
1647 // nsec-LSB split below overrides this when configured, matching
1648 // pvxs `if(info.nsecMask) utag = meta.time.nsec & info.nsecMask;`
1649 // (:247).
1650 snap.user_tag = self.common.utag as i32;
1651
1652 // Pull display/control/enums from the metadata cache (build on
1653 // first call, hit thereafter until invalidated by a metadata-class
1654 // field write).
1655 let meta = self.cached_metadata();
1656 snap.display = meta.display;
1657 snap.control = meta.control;
1658 snap.enums = meta.enums;
1659
1660 // The cache above is the record's VAL metadata. C routes PER FIELD, so
1661 // a non-VAL-class field does NOT get VAL's limits — see
1662 // [`Self::route_field_metadata`], which owns that decision.
1663 self.route_field_metadata(field, &mut snap);
1664
1665 // Per-field RSET metadata (C get_units/get_precision/
1666 // get_graphic_double/get_control_double/get_alarm_double key on
1667 // dbGetFieldIndex) patches the record-level cache for this field.
1668 self.apply_field_metadata_override(field, &mut snap);
1669
1670 // DBF_MENU field (a shared menu such as `SCAN`/`OMSL`/`HHSV`/... or
1671 // a record-specific menu such as `sel.SELM`): carry the menu index
1672 // as DBR_ENUM and attach its `menu()` choice labels. See
1673 // `attach_menu_enum`. This overrides any record VAL enum table
1674 // copied from the metadata cache above, because a menu field
1675 // carries its own menu's choices, not the record's VAL state
1676 // strings.
1677 self.attach_menu_enum(field, &mut snap);
1678
1679 // The metadata VALUES and the mask that says which of them this
1680 // channel actually supplies are assigned by the same owner, from the
1681 // settled value, so they cannot disagree.
1682 self.assign_property_support(field, &mut snap);
1683
1684 // apply `info(Q:time:tag, "nsec:lsb:N")` — pvxs
1685 // `iocsource.cpp:239-248` publishes `nanoseconds & ~nsecMask` and
1686 // moves `nanoseconds & nsecMask` into `timeStamp.userTag`. The
1687 // split is applied to both `snap.timestamp` and `snap.user_tag` so
1688 // downstream encoders (NTScalar `timeStamp`, QSRV groups) all see
1689 // the same shape. A zero mask (tag absent or unparseable) is a
1690 // no-op inside the helper, exactly as pvxs's `if(info.nsecMask)`
1691 // gate is.
1692 crate::server::snapshot::apply_nsec_mask(&mut snap, self.qtime_nsec_mask());
1693
1694 Some(snap)
1695 }
1696
1697 /// Resolve `info(Q:time:tag)` to pvxs's `MappingInfo::nsecMask`.
1698 /// Returns 0 (the "no split" mask) when the tag is absent or does not
1699 /// parse — pvxs leaves `nsecMask` at its 0 initialiser in that case.
1700 ///
1701 /// pvxs `ioc/typeutils.cpp:79-88`:
1702 ///
1703 /// ```c
1704 /// if(auto val = ent.info("Q:time:tag")) {
1705 /// epicsInt32 dig = 0;
1706 /// if(strncmp(val, "nsec:lsb:", 9)==0 && !epicsParseInt32(&val[9], &dig, 10, nullptr)) {
1707 /// nsecMask = (uint64_t(1u)<<dig)-1u;
1708 /// }
1709 /// }
1710 /// ```
1711 ///
1712 /// The prefix test is a byte-exact `strncmp` — no case folding and no
1713 /// whitespace tolerance, so `NSEC:LSB:4` and `nsec: lsb: 4` do NOT
1714 /// match and leave the timestamp alone. There is no bounds clamp
1715 /// either: any `dig` `epicsParseInt32` accepts is shifted verbatim, so
1716 /// `nsec:lsb:31` yields the `0x7FFF_FFFF` mask pvxs actually serves.
1717 fn qtime_nsec_mask(&self) -> u64 {
1718 let Some(rest) = self
1719 .get_info("Q:time:tag")
1720 .and_then(|v| v.strip_prefix("nsec:lsb:"))
1721 else {
1722 return 0;
1723 };
1724 let Some(dig) = epics_parse_int32_base10(rest) else {
1725 return 0;
1726 };
1727 // C shifts `uint64_t(1u)` by an `epicsInt32`. A `dig` outside
1728 // `0..=63` is UB in C++; every ISA EPICS builds on (x86-64 `shlq`,
1729 // aarch64 `lsl`) takes the shift count modulo 64, which is what
1730 // `wrapping_shl` does — so `nsec:lsb:64` disables the split
1731 // (mask 0) and a negative `dig` shifts by `dig & 63`, the same
1732 // masks pvxs produces on those hosts.
1733 1u64.wrapping_shl(dig as u32) - 1
1734 }
1735
1736 /// Populate DisplayInfo from record fields if applicable.
1737 /// Resolve the `Q:form` info-tag value to a `display.form` menu index.
1738 ///
1739 /// pvxs publishes the fixed seven-entry form menu
1740 /// (Default/String/Binary/Decimal/Hex/Exponential/Engineering) for every
1741 /// numeric value and, for the VAL field only, sets `display.form.index`
1742 /// to the slot whose name equals the field's `Q:form` info tag
1743 /// (`iocsource.cpp:42-62`, case-sensitive). Unset or unrecognised ->
1744 /// `None` (form stays 0 = Default), exactly as pvxs leaves the index
1745 /// untouched on no match.
1746 fn q_form_index(&self) -> Option<i16> {
1747 const FORM_NAMES: [&str; 7] = [
1748 "Default",
1749 "String",
1750 "Binary",
1751 "Decimal",
1752 "Hex",
1753 "Exponential",
1754 "Engineering",
1755 ];
1756 let tag = self.info.get("Q:form")?;
1757 FORM_NAMES
1758 .iter()
1759 .position(|name| name == tag)
1760 .map(|i| i as i16)
1761 }
1762
1763 /// Stamp a built snapshot with the property mask THIS channel supplies —
1764 /// [`Self::property_support`] narrowed to the addressed field by C's
1765 /// second gate ([`PropertySupport::narrowed_to_field`]). Called by both
1766 /// snapshot builders once the value has settled (after
1767 /// [`Self::attach_menu_enum`] promoted a `DBF_MENU` field to its
1768 /// `DBR_ENUM` form), so the mask is read off the same value the client
1769 /// receives and no consumer has to re-derive either gate.
1770 fn assign_property_support(&self, field: &str, snap: &mut super::super::snapshot::Snapshot) {
1771 snap.properties = self.record.property_support().narrowed_to_field(
1772 snap.value.db_field_type(),
1773 self.menu_choices_for(field).is_some(),
1774 );
1775 }
1776
1777 /// The property mask a channel on `field` supplies, without building a
1778 /// snapshot — what a PVA server needs to decide which NT leaves it may
1779 /// MARK for a channel it has not read yet (QSRV resolves a group's member
1780 /// masks once, at monitor start, rather than per event).
1781 ///
1782 /// Same two gates, same owner as [`Self::assign_property_support`]: an
1783 /// unknown field supplies nothing.
1784 pub fn property_support_for_field(&self, field: &str) -> PropertySupport {
1785 let Some(value) = self.client_field_value(field) else {
1786 return PropertySupport::NONE;
1787 };
1788 self.record.property_support().narrowed_to_field(
1789 value.db_field_type(),
1790 self.menu_choices_for(field).is_some(),
1791 )
1792 }
1793
1794 fn populate_display_info(&self, snap: &mut super::super::snapshot::Snapshot) {
1795 let rtype = self.record.record_type();
1796 match rtype {
1797 "ai" | "ao" | "calc" | "calcout" => {
1798 let egu = self
1799 .record
1800 .get_field("EGU")
1801 .and_then(|v| {
1802 if let EpicsValue::String(s) = v {
1803 Some(s)
1804 } else {
1805 None
1806 }
1807 })
1808 .unwrap_or_default();
1809 let prec = self
1810 .record
1811 .get_field("PREC")
1812 .and_then(|v| v.to_f64())
1813 .unwrap_or(0.0) as i16;
1814 let hopr = self
1815 .record
1816 .get_field("HOPR")
1817 .and_then(|v| v.to_f64())
1818 .unwrap_or(0.0);
1819 let lopr = self
1820 .record
1821 .get_field("LOPR")
1822 .and_then(|v| v.to_f64())
1823 .unwrap_or(0.0);
1824 snap.display = Some(super::super::snapshot::DisplayInfo {
1825 units: egu,
1826 precision: prec,
1827 upper_disp_limit: hopr,
1828 lower_disp_limit: lopr,
1829 ..Default::default()
1830 });
1831 }
1832 "longin" | "longout" | "int64in" | "int64out" => {
1833 let egu = self
1834 .record
1835 .get_field("EGU")
1836 .and_then(|v| {
1837 if let EpicsValue::String(s) = v {
1838 Some(s)
1839 } else {
1840 None
1841 }
1842 })
1843 .unwrap_or_default();
1844 let hopr = self
1845 .record
1846 .get_field("HOPR")
1847 .and_then(|v| v.to_f64())
1848 .unwrap_or(0.0);
1849 let lopr = self
1850 .record
1851 .get_field("LOPR")
1852 .and_then(|v| v.to_f64())
1853 .unwrap_or(0.0);
1854 snap.display = Some(super::super::snapshot::DisplayInfo {
1855 units: egu,
1856 precision: 0,
1857 upper_disp_limit: hopr,
1858 lower_disp_limit: lopr,
1859 ..Default::default()
1860 });
1861 }
1862 // waveform/aai/aao — HOPR/LOPR/PREC/EGU for VAL display limits.
1863 // (waveformRecord.c:251-252,239; aaiRecord.c:280-281,268; aaoRecord.c:283-284)
1864 "waveform" | "aai" | "aao" => {
1865 let egu = self
1866 .record
1867 .get_field("EGU")
1868 .and_then(|v| {
1869 if let EpicsValue::String(s) = v {
1870 Some(s)
1871 } else {
1872 None
1873 }
1874 })
1875 .unwrap_or_default();
1876 let prec = self
1877 .record
1878 .get_field("PREC")
1879 .and_then(|v| v.to_f64())
1880 .unwrap_or(0.0) as i16;
1881 let hopr = self
1882 .record
1883 .get_field("HOPR")
1884 .and_then(|v| v.to_f64())
1885 .unwrap_or(0.0);
1886 let lopr = self
1887 .record
1888 .get_field("LOPR")
1889 .and_then(|v| v.to_f64())
1890 .unwrap_or(0.0);
1891 snap.display = Some(super::super::snapshot::DisplayInfo {
1892 units: egu,
1893 precision: prec,
1894 upper_disp_limit: hopr,
1895 lower_disp_limit: lopr,
1896 ..Default::default()
1897 });
1898 }
1899 // compress — HOPR/LOPR/PREC/EGU for VAL display limits.
1900 // (compressRecord.c:478-479,464,455)
1901 "compress" => {
1902 let egu = self
1903 .record
1904 .get_field("EGU")
1905 .and_then(|v| {
1906 if let EpicsValue::String(s) = v {
1907 Some(s)
1908 } else {
1909 None
1910 }
1911 })
1912 .unwrap_or_default();
1913 let prec = self
1914 .record
1915 .get_field("PREC")
1916 .and_then(|v| v.to_f64())
1917 .unwrap_or(0.0) as i16;
1918 let hopr = self
1919 .record
1920 .get_field("HOPR")
1921 .and_then(|v| v.to_f64())
1922 .unwrap_or(0.0);
1923 let lopr = self
1924 .record
1925 .get_field("LOPR")
1926 .and_then(|v| v.to_f64())
1927 .unwrap_or(0.0);
1928 snap.display = Some(super::super::snapshot::DisplayInfo {
1929 units: egu,
1930 precision: prec,
1931 upper_disp_limit: hopr,
1932 lower_disp_limit: lopr,
1933 ..Default::default()
1934 });
1935 }
1936 "motor" => {
1937 let egu = self
1938 .record
1939 .get_field("EGU")
1940 .and_then(|v| {
1941 if let EpicsValue::String(s) = v {
1942 Some(s)
1943 } else {
1944 None
1945 }
1946 })
1947 .unwrap_or_default();
1948 let prec = self
1949 .record
1950 .get_field("PREC")
1951 .and_then(|v| v.to_f64())
1952 .unwrap_or(0.0) as i16;
1953 let hlm = self
1954 .record
1955 .get_field("HLM")
1956 .and_then(|v| v.to_f64())
1957 .unwrap_or(0.0);
1958 let llm = self
1959 .record
1960 .get_field("LLM")
1961 .and_then(|v| v.to_f64())
1962 .unwrap_or(0.0);
1963 snap.display = Some(super::super::snapshot::DisplayInfo {
1964 units: egu,
1965 precision: prec,
1966 upper_disp_limit: hlm,
1967 lower_disp_limit: llm,
1968 ..Default::default()
1969 });
1970 }
1971 _ => {}
1972 }
1973 // Apply the `Q:form` display-format hint. The match above builds
1974 // `snap.display` only for numeric record types — the same set for
1975 // which pvxs emits `display.form.choices`. This cache is
1976 // record-level (it is the VAL field's metadata); the VAL-only rule
1977 // pvxs applies to `display.form.index` (`iocsource.cpp:53`) is
1978 // enforced per served field in `apply_field_metadata_override`.
1979 if let Some(display) = snap.display.as_mut() {
1980 if let Some(form) = self.q_form_index() {
1981 display.form = form;
1982 }
1983 }
1984 }
1985
1986 /// Populate ControlInfo from record fields if applicable.
1987 fn populate_control_info(&self, snap: &mut super::super::snapshot::Snapshot) {
1988 let rtype = self.record.record_type();
1989 match rtype {
1990 // ao unconditionally uses DRVH/DRVL (aoRecord.c:356-357).
1991 "ao" => {
1992 let upper = self
1993 .record
1994 .get_field("DRVH")
1995 .and_then(|v| v.to_f64())
1996 .unwrap_or(0.0);
1997 let lower = self
1998 .record
1999 .get_field("DRVL")
2000 .and_then(|v| v.to_f64())
2001 .unwrap_or(0.0);
2002 snap.control = Some(super::super::snapshot::ControlInfo {
2003 upper_ctrl_limit: upper,
2004 lower_ctrl_limit: lower,
2005 });
2006 }
2007 // longout/int64out use DRVH/DRVL only when drvh > drvl, else HOPR/LOPR
2008 // (longoutRecord.c:282-287, int64outRecord.c:265-270).
2009 "longout" | "int64out" => {
2010 let drvh = self
2011 .record
2012 .get_field("DRVH")
2013 .and_then(|v| v.to_f64())
2014 .unwrap_or(0.0);
2015 let drvl = self
2016 .record
2017 .get_field("DRVL")
2018 .and_then(|v| v.to_f64())
2019 .unwrap_or(0.0);
2020 let (upper, lower) = if drvh > drvl {
2021 (drvh, drvl)
2022 } else {
2023 let hopr = self
2024 .record
2025 .get_field("HOPR")
2026 .and_then(|v| v.to_f64())
2027 .unwrap_or(0.0);
2028 let lopr = self
2029 .record
2030 .get_field("LOPR")
2031 .and_then(|v| v.to_f64())
2032 .unwrap_or(0.0);
2033 (hopr, lopr)
2034 };
2035 snap.control = Some(super::super::snapshot::ControlInfo {
2036 upper_ctrl_limit: upper,
2037 lower_ctrl_limit: lower,
2038 });
2039 }
2040 "motor" => {
2041 // Motor records use HLM/LLM as control limits
2042 let hlm = self
2043 .record
2044 .get_field("HLM")
2045 .and_then(|v| v.to_f64())
2046 .unwrap_or(0.0);
2047 let llm = self
2048 .record
2049 .get_field("LLM")
2050 .and_then(|v| v.to_f64())
2051 .unwrap_or(0.0);
2052 snap.control = Some(super::super::snapshot::ControlInfo {
2053 upper_ctrl_limit: hlm,
2054 lower_ctrl_limit: llm,
2055 });
2056 }
2057 // int64in uses HOPR/LOPR as control limits (int64inRecord.c:226-227)
2058 "ai" | "int64in" | "longin" | "calc" | "calcout" => {
2059 // Input records use HOPR/LOPR as control limits
2060 let hopr = self
2061 .record
2062 .get_field("HOPR")
2063 .and_then(|v| v.to_f64())
2064 .unwrap_or(0.0);
2065 let lopr = self
2066 .record
2067 .get_field("LOPR")
2068 .and_then(|v| v.to_f64())
2069 .unwrap_or(0.0);
2070 snap.control = Some(super::super::snapshot::ControlInfo {
2071 upper_ctrl_limit: hopr,
2072 lower_ctrl_limit: lopr,
2073 });
2074 }
2075 // Array records map their VAL control limits to HOPR/LOPR, exactly
2076 // like the display limits above (waveformRecord.c get_control_double
2077 // VAL case; aaiRecord.c:293-303; aaoRecord.c; compressRecord.c:487-501).
2078 // Without this arm an array DBR_CTRL collapses the control range to
2079 // 0/0 while the scalar records expose it.
2080 "waveform" | "aai" | "aao" | "compress" => {
2081 let hopr = self
2082 .record
2083 .get_field("HOPR")
2084 .and_then(|v| v.to_f64())
2085 .unwrap_or(0.0);
2086 let lopr = self
2087 .record
2088 .get_field("LOPR")
2089 .and_then(|v| v.to_f64())
2090 .unwrap_or(0.0);
2091 snap.control = Some(super::super::snapshot::ControlInfo {
2092 upper_ctrl_limit: hopr,
2093 lower_ctrl_limit: lopr,
2094 });
2095 }
2096 _ => {}
2097 }
2098 }
2099
2100 /// Populate EnumInfo — C rset `get_enum_strs`.
2101 ///
2102 /// The table comes from [`Record::enum_state_strings`], the SAME slot the
2103 /// string-put converter (`dbConvert.c::putStringEnum`) resolves against, so
2104 /// the choice list a client reads and the names it may write are one table
2105 /// by construction. It arrives already trimmed to C's `no_str` (bi/bo/busy
2106 /// drop an empty ONAM behind a set ZNAM — `boRecord.c:342-352`; mbbi/mbbo
2107 /// cut at the last non-empty state — `mbbiRecord.c:262-269`).
2108 ///
2109 /// The `DBR_STRING` half of the same channel is the record's OTHER rset slot
2110 /// (`get_enum_str`), which is not this trimmed list — see
2111 /// [`EnumStringForm`]. A record that has no such slot (every record but
2112 /// bi/bo/busy/mbbi/mbbo, including the downstream crates' own enum records)
2113 /// renders from its label list, which is what C's absent slot amounts to.
2114 fn populate_enum_info(&self, snap: &mut super::super::snapshot::Snapshot) {
2115 if let Some(strings) = self.record.enum_state_strings() {
2116 snap.enums = Some(match self.record.enum_string_form() {
2117 Some(form) => super::super::snapshot::EnumInfo::with_string_form(strings, form),
2118 None => super::super::snapshot::EnumInfo::new(strings),
2119 });
2120 }
2121 }
2122
2123 /// Get a common field value.
2124 pub fn get_common_field(&self, name: &str) -> Option<EpicsValue> {
2125 match name {
2126 "SEVR" => Some(EpicsValue::Short(self.common.sevr as i16)),
2127 "STAT" => Some(EpicsValue::Short(self.common.stat as i16)),
2128 "NSEV" => Some(EpicsValue::Short(self.common.nsev as i16)),
2129 "NSTA" => Some(EpicsValue::Short(self.common.nsta as i16)),
2130 // epics-base PR #568 / #566 — alarm message string.
2131 "AMSG" => Some(EpicsValue::String(self.common.amsg.clone().into())),
2132 "NAMSG" => Some(EpicsValue::String(self.common.namsg.clone().into())),
2133 "ACKS" => Some(EpicsValue::Short(self.common.acks as i16)),
2134 // `ACKT` and `PINI` are `DBF_MENU` (`menuYesNo` /`menuPini`,
2135 // `dbCommon.dbd.pod:335,169`), not `DBF_UCHAR`: they carry a menu
2136 // index, which `promote_menu_value` lifts to `DBR_ENUM` with the
2137 // menu's choice strings. Storing them as `Short` is what makes
2138 // them eligible for that promotion — see `promote_menu_value`.
2139 "ACKT" => Some(EpicsValue::Short(if self.common.ackt { 1 } else { 0 })),
2140 // DBF_UCHAR: served as UChar (declared type) so the raw put byte
2141 // round-trips to the wire — see the DISP/TPRO comment above.
2142 "UDF" => Some(EpicsValue::UChar(self.common.udf)),
2143 "UDFS" => Some(EpicsValue::Short(self.common.udfs)),
2144 "SCAN" => Some(EpicsValue::Enum(self.common.scan.to_u16())),
2145 "SSCN" => Some(EpicsValue::Enum(self.common.sscn.to_u16())),
2146 // `OLDSIMM` is `DBF_MENU`/`menu(menuSimm)`, stored as the menu index
2147 // and promoted to `DBR_ENUM` with the NO/YES/RAW labels by
2148 // `promote_menu_value` (shared registry — the saved copy is ALWAYS
2149 // menuSimm, unlike the live SIMM). Written only by the simulation
2150 // owner (`rec_gbl_save_simm`); `special(SPC_NOMOD)` for clients.
2151 "OLDSIMM" => Some(EpicsValue::Short(self.common.oldsimm)),
2152 "PINI" => Some(EpicsValue::Short(self.common.pini)),
2153 // DISP/TPRO/RPRO/UDF are `DBF_UCHAR` in `dbCommon.dbd`. Serve them
2154 // as `UChar` — their DECLARED type — so `project_to_declared_type`
2155 // is identity and the raw put byte reaches the wire untouched (C
2156 // stores the byte and `caget` renders `DBR_CHAR` signed: 255 → -1).
2157 // Serving `Char` here instead routed the value through the lossy
2158 // `Char → UChar` projection (signed −1 clamped to 0), so a
2159 // `caput DISP 255` read back as 0 rather than C's -1. `BKPT` is
2160 // `DBF_NOACCESS`: no `FieldDesc`, no projection, served `Char`.
2161 "TPRO" => Some(EpicsValue::UChar(self.common.tpro)),
2162 "BKPT" => Some(EpicsValue::Char(self.common.bkpt)),
2163 "FLNK" => Some(EpicsValue::String(self.common.flnk.clone().into())),
2164 // A record type whose C `.dbd` has no INP has no `.INP` channel
2165 // either — C's dbChannel resolution is the dbd, so `dbgf HI.INP` on
2166 // a histogram answers "PV 'HI.INP' not found". The port keeps INP on
2167 // `CommonFields` for every record, so `declares_inp_link()` is what
2168 // stands in for the dbd, and it must gate the read side as well as
2169 // the write side (`put_common_field`) — otherwise the field is
2170 // unloadable and unwritable yet still resolves as a channel.
2171 "INP" if self.record.declares_inp_link() => {
2172 Some(EpicsValue::String(self.common.inp.clone().into()))
2173 }
2174 "OUT" => Some(EpicsValue::String(self.common.out.clone().into())),
2175 // C's DTYP is `DBF_DEVICE`: an epicsEnum16 index into the record
2176 // type's device menu, NOT the name. The name is what this port
2177 // stores and dispatches on; the index is what the wire carries.
2178 "DTYP" => Some(EpicsValue::Enum(self.dtyp_index())),
2179 "TSE" => Some(EpicsValue::Short(self.common.tse)),
2180 "TSEL" => Some(EpicsValue::String(self.common.tsel.clone().into())),
2181 // C `UTAG` is DBF_UINT64 — exposed natively as the unsigned
2182 // 64-bit value variant so values above i64::MAX round-trip.
2183 "UTAG" => Some(EpicsValue::UInt64(self.common.utag)),
2184 "ASG" => Some(EpicsValue::String(self.common.asg.clone().into())),
2185 "ASL" => Some(EpicsValue::Char(self.common.asl)),
2186 "DESC" => Some(EpicsValue::String(self.common.desc.clone())),
2187 "PHAS" => Some(EpicsValue::Short(self.common.phas)),
2188 "EVNT" => Some(EpicsValue::String(self.common.evnt.clone().into())),
2189 "PRIO" => Some(EpicsValue::Short(self.common.prio)),
2190 "DISV" => Some(EpicsValue::Short(self.common.disv)),
2191 "DISA" => Some(EpicsValue::Short(self.common.disa)),
2192 "SDIS" => Some(EpicsValue::String(self.common.sdis.clone().into())),
2193 "DISS" => Some(EpicsValue::Short(self.common.diss)),
2194 "HYST" => Some(EpicsValue::Double(self.common.hyst)),
2195 "LCNT" => Some(EpicsValue::Short(self.common.lcnt)),
2196 "DISP" => Some(EpicsValue::UChar(self.common.disp)),
2197 "PUTF" => Some(EpicsValue::Char(if self.common.putf { 1 } else { 0 })),
2198 "RPRO" => Some(EpicsValue::UChar(self.common.rpro)),
2199 "PACT" => Some(EpicsValue::Char(if self.is_processing() { 1 } else { 0 })),
2200 // C `dbCommon.dbd`: `field(PROC,DBF_UCHAR)` — the raw put byte is
2201 // retained in `prec->proc` and served back SIGNED as `DBR_CHAR`
2202 // (`caput PROC 255` → `caget` = -1), exactly like DISP/RPRO. The
2203 // `pp(TRUE)` force-process is orthogonal: writing PROC still
2204 // reprocesses the record (put-path intercept), but the byte sticks.
2205 "PROC" => Some(EpicsValue::UChar(self.common.proc_field)),
2206 // Analog alarm fields
2207 "HIHI" => self
2208 .common
2209 .analog_alarm
2210 .as_ref()
2211 .map(|a| EpicsValue::Double(a.hihi)),
2212 "HIGH" => self
2213 .common
2214 .analog_alarm
2215 .as_ref()
2216 .map(|a| EpicsValue::Double(a.high)),
2217 "LOW" => self
2218 .common
2219 .analog_alarm
2220 .as_ref()
2221 .map(|a| EpicsValue::Double(a.low)),
2222 "LOLO" => self
2223 .common
2224 .analog_alarm
2225 .as_ref()
2226 .map(|a| EpicsValue::Double(a.lolo)),
2227 "HHSV" => self
2228 .common
2229 .analog_alarm
2230 .as_ref()
2231 .map(|a| EpicsValue::Short(a.hhsv)),
2232 "HSV" => self
2233 .common
2234 .analog_alarm
2235 .as_ref()
2236 .map(|a| EpicsValue::Short(a.hsv)),
2237 "LSV" => self
2238 .common
2239 .analog_alarm
2240 .as_ref()
2241 .map(|a| EpicsValue::Short(a.lsv)),
2242 "LLSV" => self
2243 .common
2244 .analog_alarm
2245 .as_ref()
2246 .map(|a| EpicsValue::Short(a.llsv)),
2247 // swait OUTN is aliased to common.out
2248 "OUTN" => {
2249 if self.record.record_type() == "swait" {
2250 Some(EpicsValue::String(self.common.out.clone().into()))
2251 } else {
2252 None
2253 }
2254 }
2255 _ => None,
2256 }
2257 }
2258
2259 /// `true` when the record type declares `name` in its own `field_list`,
2260 /// i.e. the record stores the field itself and owns whatever behaviour
2261 /// hangs off it.
2262 ///
2263 /// This separates the two meanings a link field carries. `common.inp` /
2264 /// `common.out` is the link *text* — always the value the `.db` file
2265 /// wrote, for every record type, because C device support reads
2266 /// `prec->inp` / `prec->out` at `init_record` no matter which layer owns
2267 /// the field ([`crate::server::db_loader::apply_fields`] keeps it
2268 /// populated). `parsed_inp` / `parsed_out` is the *framework's* dispatch
2269 /// of that link, and is armed only for a record type that does NOT
2270 /// declare the field: a record that declares it drives the link itself
2271 /// (`multi_output_links` for `acalcout`/`scalcout`, device support for
2272 /// `motorRecord`/`scalerRecord`, or its own `process`). Arming the
2273 /// framework path for those too would write the link twice per cycle.
2274 fn record_declares_field(&self, name: &str) -> bool {
2275 self.record.implements_field(name)
2276 }
2277
2278 /// Set a common field value from a runtime `dbPut` (CA/PVA/`dbpf`/link).
2279 /// Returns what scan index changes are needed.
2280 ///
2281 /// A `DBF_MENU` common field's string is converted by C's runtime
2282 /// converter, `dbConvert.c::putStringMenu` — see [`MenuBound::DbPut`].
2283 pub fn put_common_field(
2284 &mut self,
2285 name: &str,
2286 value: EpicsValue,
2287 ) -> CaResult<CommonFieldPutResult> {
2288 self.put_common_field_bounded(name, value, MenuBound::DbPut)
2289 }
2290
2291 /// **The single owner of a record's SCAN transition** — C `dbPutField` on
2292 /// SCAN, which is `scanDelete(precord)` … `scanAdd(precord)`
2293 /// (`dbAccess.c::dbPutSpecial` SPC_SCAN, dbScan.c:236-248).
2294 ///
2295 /// Two callers reach it, and they are the two C sites that move a record
2296 /// between scan lists: a `SCAN` put ([`Self::put_common_field`]) and the
2297 /// simulation-mode scan swap (`recGblCheckSimm`, recGbl.c:427-437, which
2298 /// calls exactly the same `scanDelete`/`scanAdd` pair). Returns the delta
2299 /// for the scan-index owner (`PvDatabase::update_scan_index`) to apply once
2300 /// the record lock is down; [`CommonFieldPutResult::NoChange`] when the scan
2301 /// did not move.
2302 pub fn set_scan(&mut self, new_scan: ScanType) -> CommonFieldPutResult {
2303 let old_scan = self.common.scan;
2304 self.common.scan = new_scan;
2305 if old_scan == new_scan {
2306 return CommonFieldPutResult::NoChange;
2307 }
2308 // C `scanDelete`/`scanAdd` call the record's device support
2309 // `get_ioint_info(1)` / `get_ioint_info(0)`. Only a change of I/O Intr
2310 // *membership* reaches those; a Passive→"1 second" move calls neither.
2311 let was_io_intr = old_scan == ScanType::IoIntr;
2312 let is_io_intr = new_scan == ScanType::IoIntr;
2313 if was_io_intr != is_io_intr {
2314 self.record.set_io_intr_scan(is_io_intr);
2315 }
2316 CommonFieldPutResult::ScanChanged {
2317 old_scan,
2318 new_scan,
2319 phas: self.common.phas,
2320 }
2321 }
2322
2323 /// C `recGblSaveSimm` (`recGbl.c:421-425`) — latch the CURRENT simulation
2324 /// mode into OLDSIMM:
2325 ///
2326 /// ```c
2327 /// void recGblSaveSimm(const epicsEnum16 sscn,
2328 /// epicsEnum16 *poldsimm, const epicsEnum16 simm) {
2329 /// if (sscn == USHRT_MAX) return;
2330 /// *poldsimm = simm;
2331 /// }
2332 /// ```
2333 ///
2334 /// **The only writer of `CommonFields::oldsimm`.** Must run BEFORE the SIMM
2335 /// value moves — C calls it from `special(SPC_MOD)` pass 0 (before the put)
2336 /// and from `recGblGetSimm`/`recGblInitSimm` before the SIML read. The
2337 /// `sscn == 65535` guard is C's: with SSCN unset there is no scan to swap
2338 /// to, so the latch is not even taken (and [`Self::rec_gbl_check_simm`]
2339 /// bails on the same test, so the stale OLDSIMM is never read).
2340 ///
2341 /// A record type with no SSCN/OLDSIMM in its C dbd (`busy`, `swait`) passes
2342 /// neither pointer to any recGbl helper: no-op here.
2343 pub fn rec_gbl_save_simm(&mut self) {
2344 if !self.record.uses_recgbl_simm_helpers() {
2345 return;
2346 }
2347 // C `recGblSaveSimm`: `if (*psscn == USHRT_MAX) return;` — the literal
2348 // sentinel, not "any index outside the menu".
2349 if self.common.sscn.is_unset() {
2350 return;
2351 }
2352 if let Some(EpicsValue::Short(simm)) = self.record.get_field("SIMM") {
2353 self.common.oldsimm = simm;
2354 }
2355 }
2356
2357 /// C `recGblCheckSimm` (`recGbl.c:427-437`) — on a SIMM transition, swap the
2358 /// record's SCAN with SSCN:
2359 ///
2360 /// ```c
2361 /// void recGblCheckSimm(struct dbCommon *pcommon, epicsEnum16 *psscn,
2362 /// const epicsEnum16 oldsimm, const epicsEnum16 simm) {
2363 /// if (*psscn == USHRT_MAX) return;
2364 /// if (simm != oldsimm) {
2365 /// epicsUInt16 scan = pcommon->scan;
2366 /// scanDelete(pcommon);
2367 /// pcommon->scan = *psscn;
2368 /// scanAdd(pcommon);
2369 /// *psscn = scan;
2370 /// }
2371 /// }
2372 /// ```
2373 ///
2374 /// This is what makes SSCN mean anything at all: a record configured
2375 /// `field(SCAN,"1 second") field(SSCN,"Passive")` stops periodic scanning
2376 /// the moment SIMM leaves NO, and resumes it when SIMM goes back — with the
2377 /// two fields having traded places each time. Both are a genuine swap, not
2378 /// an assignment: SSCN ends up holding the scan the record just left.
2379 ///
2380 /// **The only writer of the SIMM-driven SCAN/SSCN swap.** The scan-list
2381 /// move itself goes through the single SCAN owner [`Self::set_scan`], whose
2382 /// [`CommonFieldPutResult`] the caller hands to
2383 /// `PvDatabase::update_scan_index` once the record lock is down. Runs AFTER
2384 /// the SIMM value moved — C `special(SPC_MOD)` pass 1, and the tail of
2385 /// `recGblGetSimm`/`recGblInitSimm`.
2386 pub fn rec_gbl_check_simm(&mut self) -> CommonFieldPutResult {
2387 if !self.record.uses_recgbl_simm_helpers() {
2388 return CommonFieldPutResult::NoChange;
2389 }
2390 let Some(sim_scan) = self.common.sscn.scan() else {
2391 // `*psscn == USHRT_MAX` — SSCN unset, no swap. An SSCN that is
2392 // merely ILLEGAL still swaps: C assigns it into SCAN and `scanAdd`
2393 // then declines to scan the record.
2394 return CommonFieldPutResult::NoChange;
2395 };
2396 let Some(EpicsValue::Short(simm)) = self.record.get_field("SIMM") else {
2397 return CommonFieldPutResult::NoChange;
2398 };
2399 if simm == self.common.oldsimm {
2400 return CommonFieldPutResult::NoChange;
2401 }
2402 let previous_scan = self.common.scan;
2403 let result = self.set_scan(sim_scan);
2404 self.common.sscn = SimModeScan::from_scan(previous_scan);
2405 result
2406 }
2407
2408 /// C `dbAccess.c::putAckt` (`:1285-1300`) — the **only** writer of ACKT.
2409 ///
2410 /// Reached from `dbPut` for a `DBR_PUT_ACKT` request *type*
2411 /// (`dbAccess.c:1331-1332`), ABOVE the `SPC_NOMOD` gate that refuses every
2412 /// ordinary put to the field. Posts exactly what C posts: the ACKT change,
2413 /// the ACKS it may lower, and the record-wide `DBE_ALARM` — and only when
2414 /// `ackt` actually changed (C returns 0 early otherwise).
2415 pub fn put_ackt(&mut self, value: u16) {
2416 let new_ackt = value != 0;
2417 if new_ackt == self.common.ackt {
2418 return;
2419 }
2420 use crate::server::recgbl::EventMask;
2421 let ack_mask = EventMask::VALUE | EventMask::ALARM;
2422 self.common.ackt = new_ackt;
2423 self.cleanup_subscribers();
2424 self.notify_field("ACKT", ack_mask);
2425 // C `:1294-1297`: turning transient acknowledgement off lowers a
2426 // sticky ACKS down to the current SEVR — an alarm that has already
2427 // cleared must not keep a higher unacknowledged severity.
2428 if !new_ackt && self.common.acks > self.common.sevr {
2429 self.common.acks = self.common.sevr;
2430 self.notify_field("ACKS", ack_mask);
2431 }
2432 self.notify_record_alarm();
2433 }
2434
2435 /// C `dbAccess.c::putAcks` (`:1302-1315`) — the **only** runtime writer of
2436 /// ACKS. Reached from `dbPut` for a `DBR_PUT_ACKS` request type, ABOVE the
2437 /// `SPC_NOMOD` gate.
2438 ///
2439 /// The acknowledged severity is compared against the STORED unacknowledged
2440 /// severity `acks`, not the current `sevr`: an operator acknowledging at
2441 /// the severity that was latched into ACKS clears it even after `sevr` has
2442 /// since dropped. A too-low acknowledgement changes nothing and posts
2443 /// nothing; an acknowledgement of an already-clear ACKS still posts, which
2444 /// is C's literal `if (*psev >= precord->acks)` (0 >= 0 holds).
2445 pub fn put_acks(&mut self, value: u16) {
2446 let sev = AlarmSeverity::from_u16(value);
2447 if sev < self.common.acks {
2448 return;
2449 }
2450 use crate::server::recgbl::EventMask;
2451 self.common.acks = AlarmSeverity::NoAlarm;
2452 self.cleanup_subscribers();
2453 self.notify_field("ACKS", EventMask::VALUE | EventMask::ALARM);
2454 self.notify_record_alarm();
2455 }
2456
2457 /// Set a common field value from the `.db` loader, which in C is a
2458 /// different converter with a different out-of-menu bound
2459 /// (`dbStaticRun.c::dbPutStringNum`; see [`MenuBound::DbLoad`]). It is what
2460 /// lets `field(SSCN,"65535")` — the menuScan "use SCAN" sentinel, out of
2461 /// the menu's 0-9 range — load, while `caput REC.SSCN 65535` is refused at
2462 /// runtime exactly as C refuses it.
2463 pub fn put_common_field_db_load(
2464 &mut self,
2465 name: &str,
2466 value: EpicsValue,
2467 ) -> CaResult<CommonFieldPutResult> {
2468 self.put_common_field_bounded(name, value, MenuBound::DbLoad)
2469 }
2470
2471 fn put_common_field_bounded(
2472 &mut self,
2473 name: &str,
2474 value: EpicsValue,
2475 bound: MenuBound,
2476 ) -> CaResult<CommonFieldPutResult> {
2477 let name = name.to_ascii_uppercase();
2478 self.record.validate_put(&name, &value)?;
2479 self.record.special(&name, false)?;
2480 // The db loader hands every common field to this path as a raw
2481 // `EpicsValue::String` (no per-field `FieldDesc` to parse against).
2482 // Coerce it to the field's canonical numeric/menu type up front so the
2483 // typed arms below apply a `field(PHAS, "1")` / `field(PRIO, "HIGH")`
2484 // directive instead of silently dropping it at IOC load. String-typed
2485 // and already-typed values pass through unchanged.
2486 let value = coerce_common_field(&name, value, bound)?;
2487 match name.as_str() {
2488 // `special(SPC_NOMOD)` — C `dbPutSpecial` refuses the put with
2489 // `S_db_noMod` (dbAccess.c:123-127). OLDSIMM is written only by the
2490 // simulation-mode owner (`rec_gbl_save_simm`).
2491 "OLDSIMM" => return Err(CaError::ReadOnlyField(name)),
2492 "SEVR" => {
2493 if let EpicsValue::Short(v) = value {
2494 self.common.sevr = AlarmSeverity::from_u16(v as u16);
2495 }
2496 }
2497 "STAT" => {
2498 if let EpicsValue::Short(v) = value {
2499 self.common.stat = v as u16;
2500 }
2501 }
2502 "NSEV" => {
2503 if let EpicsValue::Short(v) = value {
2504 self.common.nsev = AlarmSeverity::from_u16(v as u16);
2505 }
2506 }
2507 "NSTA" => {
2508 if let EpicsValue::Short(v) = value {
2509 self.common.nsta = v as u16;
2510 }
2511 }
2512 "AMSG" => {
2513 if let EpicsValue::String(s) = value {
2514 self.common.amsg = s.as_str_lossy().into_owned();
2515 }
2516 }
2517 "NAMSG" => {
2518 if let EpicsValue::String(s) = value {
2519 self.common.namsg = s.as_str_lossy().into_owned();
2520 }
2521 }
2522 // ACKS/ACKT carry NO acknowledgement semantics here. They are
2523 // `special(SPC_NOMOD)` in `dbCommon.dbd:150-159`, so no runtime put
2524 // reaches this arm — the gate refuses it. C's acknowledgement is
2525 // driven by the DBR *request type* (`DBR_PUT_ACKS`/`ACKT`), which
2526 // `dbPut` intercepts ABOVE the SPC_NOMOD gate and hands to
2527 // [`Self::put_acks`] / [`Self::put_ackt`]. What is left here is the
2528 // `dbLoadRecords` / `dbStaticLib` load path (`field(ACKT,"YES")`),
2529 // which stores the value verbatim — C `dbPutString` never crosses
2530 // `dbPut`.
2531 "ACKS" => {
2532 if let EpicsValue::Short(v) = value {
2533 self.common.acks = AlarmSeverity::from_u16(v as u16);
2534 }
2535 }
2536 "ACKT" => match value {
2537 EpicsValue::Char(v) => self.common.ackt = v != 0,
2538 EpicsValue::Short(v) => self.common.ackt = v != 0,
2539 _ => return Ok(CommonFieldPutResult::NoChange),
2540 },
2541 "UDF" => {
2542 // Store the raw put byte (C keeps the epicsUInt8 verbatim); a
2543 // record that re-derives UDF on process overwrites it, one that
2544 // sources nothing this cycle keeps it (put-defect cluster #3).
2545 // The calc family reads UDF straight from `common` too
2546 // (`clears_udf() == false`), so the stored byte stands.
2547 if let EpicsValue::Char(v) = value {
2548 self.common.udf = v;
2549 }
2550 }
2551 "UDFS" => {
2552 self.common.udfs = menu_ordinal_raw(&value);
2553 }
2554 // The `String` form never reaches these three menu arms:
2555 // `coerce_common_field` has already run it through the one
2556 // menu converter, which either produced an `Enum` index or failed
2557 // the put with `S_db_badChoice`.
2558 "SCAN" => {
2559 let new_scan = match &value {
2560 EpicsValue::Short(v) => ScanType::from_u16(*v as u16),
2561 EpicsValue::Enum(v) => ScanType::from_u16(*v),
2562 _ => return Ok(CommonFieldPutResult::NoChange),
2563 };
2564 let result = self.set_scan(new_scan);
2565 if !matches!(result, CommonFieldPutResult::NoChange) {
2566 self.record.on_put(&name);
2567 self.record.special(&name, true)?;
2568 return Ok(result);
2569 }
2570 }
2571 "SSCN" => {
2572 let new_sscn = match &value {
2573 EpicsValue::Short(v) => SimModeScan::from_u16(*v as u16),
2574 EpicsValue::Enum(v) => SimModeScan::from_u16(*v),
2575 _ => return Ok(CommonFieldPutResult::NoChange),
2576 };
2577 self.common.sscn = new_sscn;
2578 }
2579 // `PINI` is `menu(menuPini)` — the six choices NO/YES/RUN/RUNNING/
2580 // PAUSE/PAUSED (`menuPini.dbd.pod:59-65`). Resolved exactly like
2581 // `SCAN`: a menu label or a bare index, never a truthiness test.
2582 // The pre-fix `bool` arm collapsed `RUN` (index 2) to `false`, so
2583 // `caput REC.PINI RUN` *disabled* PINI instead of selecting the
2584 // iocRun pass.
2585 "PINI" => {
2586 // Store the RAW ordinal (see [`CommonFields::pini`]): C's numeric
2587 // menu put keeps `(epicsEnum16)`, so an out-of-range `caput
2588 // REC.PINI 6` / `-1` round-trips and simply matches no lifecycle
2589 // pass in `doRecordPini`. A `String` label is already resolved to
2590 // `Enum` by `coerce_common_field` (menuPini via `putStringMenu`).
2591 self.common.pini = match &value {
2592 EpicsValue::Short(v) => *v,
2593 EpicsValue::Char(v) => *v as i16,
2594 EpicsValue::Enum(v) => *v as i16,
2595 _ => return Ok(CommonFieldPutResult::NoChange),
2596 };
2597 }
2598 "TPRO" => {
2599 if let EpicsValue::Char(v) = value {
2600 self.common.tpro = v;
2601 }
2602 }
2603 "BKPT" => {
2604 if let EpicsValue::Char(v) = value {
2605 self.common.bkpt = v;
2606 }
2607 }
2608 "FLNK" => {
2609 if let EpicsValue::String(s) = value {
2610 self.common.flnk = s.as_str_lossy().into_owned();
2611 self.parsed_flnk = parse_forward_link_v2(&self.common.flnk);
2612 }
2613 }
2614 "INP" => {
2615 // A record type whose C `.dbd` has no INP must refuse it, the
2616 // way C's dbd does ("field not found" at load, record inert) —
2617 // `histogram`'s input link is SVL, not INP
2618 // (histogramRecord.dbd.pod:212). Without this the port accepts a
2619 // `field(INP,...)` no C IOC can load.
2620 if !self.record.declares_inp_link() {
2621 return Err(CaError::FieldNotFound("INP".to_string()));
2622 }
2623 if let EpicsValue::String(s) = value {
2624 self.check_link_assignment("INP", &s.as_str_lossy(), bound)?;
2625 self.common.inp = s.as_str_lossy().into_owned();
2626 if !self.record_declares_field("INP") {
2627 self.parsed_inp = parse_link_v2(&self.common.inp);
2628 }
2629 }
2630 }
2631 "OUT" => {
2632 if let EpicsValue::String(s) = value {
2633 let s = s.as_str_lossy();
2634 self.check_link_assignment("OUT", &s, bound)?;
2635 // C `dbParseLink` (dbStaticLib.c:2382-2386) discards a
2636 // CP/CPP modifier on a DBF_OUTLINK and warns once, naming
2637 // the holder record, its field and the target. The discard
2638 // itself is owned by `parse_output_link_v2` below; only the
2639 // diagnostic lives here, where the record name exists and
2640 // the link text is being (re)loaded rather than re-parsed
2641 // per process cycle.
2642 if out_link_discards_cp(&s) {
2643 tracing::warn!(
2644 target: "epics_base_rs::record",
2645 record = %self.name,
2646 field = "OUT",
2647 link = %s,
2648 "Discarding CP/CPP modifier in CA output link"
2649 );
2650 }
2651 self.common.out = s.into_owned();
2652 // C `dbDbPutValue` (dbDbLink.c:386-389): an OUT
2653 // link processes its target only on an explicit
2654 // ` PP` token (or a `.PROC` destination). A bare
2655 // OUT link is NPP — `parse_output_link_v2`
2656 // downgrades the modifier-less `ProcessPassive`
2657 // default that `parse_link_v2` would otherwise
2658 // apply.
2659 if !self.record_declares_field("OUT") {
2660 self.parsed_out = parse_output_link_v2(&self.common.out);
2661 }
2662 // C `longoutRecord.c::special` (PR #6c573b4 part 2)
2663 // and similar OOCH-style hooks need `after=true`
2664 // to fire after the link has actually moved. The
2665 // earlier `validate_put` + `special(name, false)`
2666 // pair only covered the before-side.
2667 self.record.special(&name, true)?;
2668 }
2669 }
2670 // Two shapes reach DTYP and both name a device support:
2671 //
2672 // * the `.db` loader hands over the NAME verbatim, and it may be a
2673 // name registered at runtime by a downstream crate ("asynInt32")
2674 // that no vendored `.dbd` declares — C would reject that at load,
2675 // the port's registry accepts it (Tier 3);
2676 // * a `dbPut` arrives as the menu INDEX, because `DBF_DEVICE` is
2677 // served as `DBR_ENUM` and `coerce_put_value` already resolved an
2678 // incoming label through the device menu (C `putStringMenu`,
2679 // which fails `S_db_badChoice` on a name the menu does not have).
2680 //
2681 // The index is only meaningful against the DECLARED menu, which is
2682 // what the converter bounded it by.
2683 "DTYP" => match value {
2684 EpicsValue::String(s) => self.common.dtyp = s.as_str_lossy().into_owned(),
2685 EpicsValue::Enum(i) => {
2686 let declared =
2687 super::dbd_generated::device_menu(self.record.record_type()).unwrap_or(&[]);
2688 match declared.get(i as usize) {
2689 Some(name) => self.common.dtyp = (*name).to_string(),
2690 None => return Ok(CommonFieldPutResult::NoChange),
2691 }
2692 }
2693 _ => return Ok(CommonFieldPutResult::NoChange),
2694 },
2695 "TSE" => {
2696 if let EpicsValue::Short(v) = value {
2697 self.common.tse = v;
2698 }
2699 }
2700 "TSEL" => {
2701 if let EpicsValue::String(s) = value {
2702 self.common.tsel = s.as_str_lossy().into_owned();
2703 self.parsed_tsel = parse_link_v2(&self.common.tsel);
2704 }
2705 }
2706 "UTAG" => {
2707 // C UTAG is DBF_UINT64 — accept any integer-shaped value and
2708 // store the unsigned 64-bit tag. The db loader feeds every
2709 // common field as EpicsValue::String, so parse field(UTAG, "N")
2710 // rather than dropping it silently at IOC load; a CA write to
2711 // this u64 field crosses as DBR_DOUBLE (CA has no uint64 wire
2712 // type), so accept Double too.
2713 match value {
2714 EpicsValue::UInt64(v) => self.common.utag = v,
2715 EpicsValue::Int64(v) => self.common.utag = v as u64,
2716 EpicsValue::Long(v) => self.common.utag = v as u64,
2717 EpicsValue::Short(v) => self.common.utag = v as u64,
2718 EpicsValue::Enum(v) => self.common.utag = v as u64,
2719 EpicsValue::Char(v) => self.common.utag = v as u64,
2720 EpicsValue::Double(v) => self.common.utag = v as u64,
2721 EpicsValue::String(s) => {
2722 if let Ok(EpicsValue::UInt64(v)) =
2723 EpicsValue::parse(DbFieldType::UInt64, s.as_str_lossy().trim())
2724 {
2725 self.common.utag = v;
2726 }
2727 }
2728 _ => {}
2729 }
2730 }
2731 "ASG" => {
2732 if let EpicsValue::String(s) = value {
2733 self.common.asg = s.as_str_lossy().into_owned();
2734 }
2735 }
2736 "ASL" => {
2737 // C dbCommon.ASL is `epicsUInt32` in the .dbd but
2738 // only ever 0 or 1; accept Char / Short / Long for
2739 // the common put paths and clamp to {0, 1}.
2740 // db_loader feeds every common field as
2741 // `EpicsValue::String`; also accept that so a
2742 // `.db` `field(ASL, "1")` directive isn't silently
2743 // ignored at IOC load.
2744 let n: i64 = match value {
2745 EpicsValue::Char(v) => v as i64,
2746 EpicsValue::Short(v) => v as i64,
2747 EpicsValue::Long(v) => v as i64,
2748 EpicsValue::Int64(v) => v,
2749 EpicsValue::String(s) => s.as_str_lossy().trim().parse().unwrap_or(0),
2750 _ => return Ok(CommonFieldPutResult::NoChange),
2751 };
2752 self.common.asl = if n != 0 { 1 } else { 0 };
2753 }
2754 "DESC" => {
2755 if let EpicsValue::String(s) = value {
2756 // DBF_STRING data field — store the bytes verbatim so a
2757 // non-UTF-8 DESC round-trips unchanged.
2758 self.common.desc = s;
2759 }
2760 }
2761 "PHAS" => {
2762 if let EpicsValue::Short(v) = value {
2763 let old_phas = self.common.phas;
2764 self.common.phas = v;
2765 // Only a record that IS in a scan list can be re-sorted
2766 // within one; the same gate the index owner applies.
2767 if old_phas != v && self.common.scan.scan_list().is_some() {
2768 let scan = self.common.scan;
2769 self.record.on_put(&name);
2770 self.record.special(&name, true)?;
2771 return Ok(CommonFieldPutResult::PhasChanged {
2772 scan,
2773 old_phas,
2774 new_phas: v,
2775 });
2776 }
2777 }
2778 }
2779 "EVNT" => {
2780 // C `EVNT` is DBF_STRING (event name). Accept a
2781 // string directly; accept a numeric value too for
2782 // backward compatibility (numeric events / a calc
2783 // record driving EVNT) by formatting it as a string.
2784 match value {
2785 EpicsValue::String(s) => self.common.evnt = s.as_str_lossy().into_owned(),
2786 EpicsValue::Short(v) => self.common.evnt = v.to_string(),
2787 EpicsValue::Long(v) => self.common.evnt = v.to_string(),
2788 EpicsValue::Enum(v) => self.common.evnt = v.to_string(),
2789 EpicsValue::Double(v) => {
2790 // Match C `eventNameToHandle`: a double with
2791 // an integer part is treated as that integer.
2792 self.common.evnt = (v as i64).to_string();
2793 }
2794 _ => {}
2795 }
2796 }
2797 "PRIO" => {
2798 if let EpicsValue::Short(v) = value {
2799 self.common.prio = v;
2800 }
2801 }
2802 "DISV" => {
2803 if let EpicsValue::Short(v) = value {
2804 self.common.disv = v;
2805 }
2806 }
2807 "DISA" => {
2808 if let EpicsValue::Short(v) = value {
2809 self.common.disa = v;
2810 }
2811 }
2812 "SDIS" => {
2813 if let EpicsValue::String(s) = value {
2814 self.common.sdis = s.as_str_lossy().into_owned();
2815 self.parsed_sdis = parse_link_v2(&self.common.sdis);
2816 }
2817 }
2818 "DISS" => {
2819 self.common.diss = menu_ordinal_raw(&value);
2820 }
2821 "HYST" => {
2822 if let Some(v) = value.to_f64() {
2823 self.common.hyst = v;
2824 }
2825 }
2826 "LCNT" => {
2827 if let EpicsValue::Short(v) = value {
2828 self.common.lcnt = v;
2829 }
2830 }
2831 "DISP" => {
2832 if let EpicsValue::Char(v) = value {
2833 self.common.disp = v;
2834 }
2835 }
2836 "PUTF" => return Err(CaError::ReadOnlyField("PUTF".into())),
2837 "RPRO" => {
2838 if let EpicsValue::Char(v) = value {
2839 self.common.rpro = v;
2840 }
2841 }
2842 "PACT" => return Err(CaError::ReadOnlyField("PACT".into())),
2843 // C `dbPut` stores the raw byte in `prec->proc` (retained across
2844 // processing — C never resets it); `coerce_common_field` has
2845 // already projected the put onto `DBF_UCHAR` (→ `Char`). The
2846 // `pp(TRUE)` reprocess is driven separately by the put-path
2847 // force-process intercept, so this arm ONLY records the byte.
2848 "PROC" => {
2849 if let EpicsValue::Char(v) = value {
2850 self.common.proc_field = v;
2851 }
2852 }
2853 // Analog alarm limits. The DB-load String was already coerced to
2854 // `Double` by `coerce_common_field` — the one owner of
2855 // "what type does this common field hold" — so every writer
2856 // (`.db` load, `caput`, a link) lands here with a numeric value.
2857 "HIHI" => {
2858 if let (Some(v), Some(a)) = (value.to_f64(), self.common.analog_alarm.as_mut()) {
2859 a.hihi = v;
2860 }
2861 }
2862 "HIGH" => {
2863 if let (Some(v), Some(a)) = (value.to_f64(), self.common.analog_alarm.as_mut()) {
2864 a.high = v;
2865 }
2866 }
2867 "LOW" => {
2868 if let (Some(v), Some(a)) = (value.to_f64(), self.common.analog_alarm.as_mut()) {
2869 a.low = v;
2870 }
2871 }
2872 "LOLO" => {
2873 if let (Some(v), Some(a)) = (value.to_f64(), self.common.analog_alarm.as_mut()) {
2874 a.lolo = v;
2875 }
2876 }
2877 "HHSV" => {
2878 if let Some(a) = &mut self.common.analog_alarm {
2879 a.hhsv = menu_ordinal_raw(&value);
2880 }
2881 }
2882 "HSV" => {
2883 if let Some(a) = &mut self.common.analog_alarm {
2884 a.hsv = menu_ordinal_raw(&value);
2885 }
2886 }
2887 "LSV" => {
2888 if let Some(a) = &mut self.common.analog_alarm {
2889 a.lsv = menu_ordinal_raw(&value);
2890 }
2891 }
2892 "LLSV" => {
2893 if let Some(a) = &mut self.common.analog_alarm {
2894 a.llsv = menu_ordinal_raw(&value);
2895 }
2896 }
2897 // swait-specific: OUTN is the output link name for swait records.
2898 // Mirrors to common.out so the processing framework dispatches it.
2899 "OUTN" => {
2900 if self.record.record_type() != "swait" {
2901 // No OUTN field on any other record type — the same
2902 // `S_dbLib_fieldNotFound` the catch-all below reports.
2903 return Err(self.unknown_field_error(name));
2904 }
2905 if let EpicsValue::String(s) = value {
2906 self.common.out = s.as_str_lossy().into_owned();
2907 // Bare OUT link is NPP — see the "OUT" arm.
2908 self.parsed_out = parse_output_link_v2(&self.common.out);
2909 }
2910 }
2911 // C `dbNameToAddr` (dbAccess.c:660-676) resolves the field part
2912 // with `dbFindFieldPart`, then falls back to `dbGetAttributePart`.
2913 // A name that is neither a record field, nor a dbCommon field, nor
2914 // an attribute resolves to nothing (`S_dbLib_fieldNotFound`), so
2915 // `dbPutField` is never reached and the caller reports the error —
2916 // `dbpf` prints "PV '%s' not found" and returns -1 (dbTest.c:787-795).
2917 // Returning success here made a put to a misspelled field a silent
2918 // no-op.
2919 //
2920 // But a field the record's `.dbd` DECLARES and no arm above stored
2921 // is NOT unknown: C `dbPut` writes it into record memory even when
2922 // no record code reads it back (`caput dfanout.HOPR 10`). Land it in
2923 // the per-instance declared-override store — the write analog of
2924 // `declared_default` — so the put is accepted and a later read
2925 // reflects it. `put_declared_override` still returns
2926 // `unknown_field_error` for a name with no `dbFldDes`, so a
2927 // misspelled field is refused exactly as before.
2928 _ => return self.put_declared_override(&name, value),
2929 }
2930 self.record.on_put(&name);
2931 // C `dbPut` (dbAccess.c:1399-1405) returns the after-put
2932 // `dbPutSpecial(paddr, 1)` status to the caller — the stored value
2933 // stays, but the monitor post and the process are skipped and the
2934 // client sees the failure. Never drop it.
2935 self.record.special(&name, true)?;
2936 Ok(CommonFieldPutResult::NoChange)
2937 }
2938
2939 /// The error C reports for a write to a field name that
2940 /// [`Self::put_common_field`] does not own.
2941 ///
2942 /// Two C outcomes, split by whether the name resolves at all:
2943 ///
2944 /// - A record *attribute* (`NAME`, `RTYP`) resolves — `dbGetAttributePart`
2945 /// succeeds — but the write is refused: `NAME` is `special(SPC_NOMOD)`
2946 /// (dbCommon.dbd:13-17) so `dbPutSpecial` pass 0 returns `S_db_noMod`
2947 /// (dbAccess.c:123-124), and an attribute address carries
2948 /// `special == SPC_ATTRIBUTE`, which `dbPutField` rejects with the same
2949 /// `S_db_noMod` (dbAccess.c:1252-1253).
2950 /// - Anything else does not resolve: `S_dbLib_fieldNotFound`.
2951 fn unknown_field_error(&self, name: String) -> CaError {
2952 if self.get_virtual_field(&name).is_some() {
2953 CaError::ReadOnlyField(name)
2954 } else {
2955 CaError::FieldNotFound(name)
2956 }
2957 }
2958
2959 /// Store a put to a field the record's `.dbd` DECLARES but the record
2960 /// models no storage for — the WRITE owner of [`Self::declared_overrides`]
2961 /// and the write analog of [`Self::declared_default`].
2962 ///
2963 /// Reached only from [`Self::put_common_field_bounded`]'s catch-all, i.e.
2964 /// after both `Record::put_field` (returned `FieldNotFound`) and every
2965 /// `dbCommon` arm above have declined the field. Three gates, mirroring
2966 /// C `dbNameToAddr`/`dbPut`:
2967 ///
2968 /// * NO `dbFldDes` (`field_desc` is `None`) — the name is not a field of
2969 /// this record type at all. C resolves nothing and `dbPutField` reports
2970 /// `S_dbLib_fieldNotFound`; return [`Self::unknown_field_error`] (which
2971 /// also renders `NAME`/`RTYP` as the read-only attributes they are).
2972 /// * `special(SPC_NOMOD)` — a declared field that is immutable
2973 /// ([`Self::is_no_mod`]: the `.dbd` `read_only`/attribute bit or the
2974 /// record's runtime `field_no_mod`). C refuses the put with `S_db_noMod`;
2975 /// the runtime dispatch already gates this via `field_io::check_no_mod`,
2976 /// but the db-load path does not, so enforce it here too — never store an
2977 /// SPC_NOMOD field in the override map.
2978 /// * [`FieldDesc::runtime_typed`] — a field whose served type C's
2979 /// `cvt_dbaddr` re-derives from record state (`waveform.VAL` from `FTVL`,
2980 /// `aSub.A` from `FTA`). Such a field is record-owned by definition, so
2981 /// its `put_field` should have taken the put; if it somehow reached here
2982 /// the override store must not shadow it (`declared_default` skips it for
2983 /// the same reason). Treat as not-found rather than store a value under
2984 /// the wrong type.
2985 /// * PARTIALLY modeled — `Record::get_field` serves the field but no
2986 /// `put_field` arm accepts it (`calcout.PVAL` → `self.pval`). The record
2987 /// owns the read path, so the write belongs in its own `put_field`, not a
2988 /// shadow cell; refuse here rather than store a value `resolve_field`
2989 /// would never reach. See the inline note on the `get_field` guard.
2990 ///
2991 /// Otherwise coerce the incoming value to the field's C-declared DBF type
2992 /// through the one write-side value-coercion owner
2993 /// ([`coerce_put_value`](crate::server::record::coerce_put_value)) — so a
2994 /// `.db`/`caput` string parses with C's range rules (`caput REC.PREC 99999`
2995 /// into a `DBF_SHORT` is refused, not wrapped) and a menu label resolves
2996 /// against the field's own choices — and store it. Returns
2997 /// [`CommonFieldPutResult::NoChange`]: there is no scan/phas/alarm side
2998 /// effect for a metadata field with no record behaviour, and the caller's
2999 /// value-field monitor post reads the stored value back through
3000 /// [`Self::resolve_field`].
3001 fn put_declared_override(
3002 &mut self,
3003 name: &str,
3004 value: EpicsValue,
3005 ) -> CaResult<CommonFieldPutResult> {
3006 let Some(desc) = self.field_desc(name) else {
3007 return Err(self.unknown_field_error(name.to_string()));
3008 };
3009 if desc.runtime_typed {
3010 return Err(self.unknown_field_error(name.to_string()));
3011 }
3012 if self.is_no_mod(name) {
3013 // C `dbPutSpecial` pass 0 refuses SPC_NOMOD with `S_db_noMod`.
3014 return Err(CaError::ReadOnlyField(name.to_string()));
3015 }
3016 // The override is the WRITABLE TWIN of `declared_default`, and
3017 // `declared_default` is `resolve_field`'s fallback ONLY when the record
3018 // itself serves nothing (`Record::get_field` is `None`). If the record
3019 // DOES serve this field (`get_field` is `Some`), it is not unmodeled —
3020 // it is PARTIALLY modeled: a getter into record memory (e.g.
3021 // `calcout.PVAL` → `self.pval`, which `process()` also writes) but no
3022 // matching `put_field` arm. Storing here would place the value in a
3023 // second cell that `resolve_field` never reaches (`get_field` shadows
3024 // the override) and that no `process()` keeps in step — a silent write
3025 // loss. Such a field's put belongs in the record's OWN `put_field`
3026 // (a per-record setter, a distinct change); refuse it here rather than
3027 // half-accept it, so `resolve_field` stays single-valued. A field the
3028 // record does not serve at all falls through to be stored.
3029 if self.record.get_field(name).is_some() {
3030 return Err(self.unknown_field_error(name.to_string()));
3031 }
3032 let target = desc.dbf_type;
3033 let coerced =
3034 crate::server::record::coerce_put_value(self.record.as_ref(), name, target, value)?;
3035 self.declared_overrides
3036 .insert(name.to_ascii_uppercase(), coerced);
3037 Ok(CommonFieldPutResult::NoChange)
3038 }
3039
3040 /// Get virtual fields (NAME, RTYP).
3041 pub fn get_virtual_field(&self, name: &str) -> Option<EpicsValue> {
3042 match name {
3043 "NAME" => Some(EpicsValue::String(self.name.clone().into())),
3044 "RTYP" => Some(EpicsValue::String(
3045 self.record.record_type().to_string().into(),
3046 )),
3047 _ => None,
3048 }
3049 }
3050
3051 /// Evaluate alarms based on record type and current value.
3052 /// Uses rec_gbl_set_sevr to accumulate into nsta/nsev.
3053 ///
3054 /// CALC_ALARM is NOT raised here. C raises it inside the record's own
3055 /// `process()` (`calcRecord.c:121-123`, `calcoutRecord.c:238-241`,
3056 /// `sCalcoutRecord.c:357-363`, `aCalcoutRecord.c:304-305`,
3057 /// `swaitRecord.c:409-410`), and in the port [`Record::check_alarms`] — which
3058 /// runs immediately before this — is that owner. It used to be raised here
3059 /// instead, keyed on a hardcoded `rtype` list plus a `CALC_ALARM` pseudo-field
3060 /// no DBD declares; swait is what that construction cost: it carried the flag
3061 /// but was not on the list, so a failed `calcPerform` alarmed nowhere.
3062 pub fn evaluate_alarms(&mut self) {
3063 use crate::server::recgbl;
3064
3065 // Check UDF first — but only for record types whose C support carries
3066 // the `if (prec->udf) recGblSetSevr(..., UDF_ALARM, ...)` guard. C has
3067 // no central UDF alarm; see `Record::raises_udf_alarm`.
3068 if self.record.raises_udf_alarm() {
3069 recgbl::rec_gbl_check_udf(&mut self.common, self.record.udf_alarm_on_exact_one());
3070 }
3071
3072 // The analog-alarm SLOT is the enumeration — a record has the ladder iff
3073 // `new_boxed` gave it a config, which is the one place the C `.dbd`
3074 // survey lives. A second `match rtype` here was the same list written
3075 // twice, and the two could disagree: scalcout was in neither, so its ten
3076 // C alarm fields could not even be put.
3077 //
3078 // bi / bo / busy / mbbi / mbbo STATE+COS (and mbbo SOFT) alarm evaluation
3079 // lives in each record's `Record::check_alarms` hook (C `checkAlarms`);
3080 // those records carry no analog config, so they never reach here and
3081 // cannot double-raise.
3082 if let Some(ref alarm_cfg) = self.common.analog_alarm.clone() {
3083 let val = match self.record.val() {
3084 Some(EpicsValue::Double(v)) => v,
3085 Some(EpicsValue::Long(v)) => v as f64,
3086 Some(EpicsValue::Int64(v)) => v as f64,
3087 _ => return,
3088 };
3089 self.evaluate_analog_alarm(val, alarm_cfg);
3090 }
3091 }
3092
3093 fn evaluate_analog_alarm(&mut self, val: f64, cfg: &AnalogAlarmConfig) {
3094 use crate::server::recgbl::{self, alarm_status};
3095
3096 // C `checkAlarms` returns immediately on a UDF cycle: it raises
3097 // `UDF_ALARM`/`UDFS` (already done by `rec_gbl_check_udf` in
3098 // `evaluate_alarms`), zeroes `AFVL` on the AFTC-capable records, and
3099 // returns BEFORE the range check — so `LALM` is left untouched and
3100 // `AFVL` is not filtered this cycle. The identical guard appears in
3101 // every record that shares this arm (`aiRecord.c:319-323`,
3102 // `aoRecord.c:383-386`, `longinRecord.c:274-278`,
3103 // `longoutRecord.c:317-320`, `int64inRecord.c:267-271`,
3104 // `int64outRecord.c:298-301`, `calcRecord.c:300-304`,
3105 // `calcoutRecord.c:563-566`). AFTC-capable records (ai/longin/
3106 // int64in/calc) carry `AFVL` and zero it (`prec->afvl = 0`); the
3107 // out records (ao/longout/int64out/calcout) have no `AFVL` and just
3108 // return. Running the range check here would drift `LALM` to `val`
3109 // (NaN on an undefined cycle) and filter `AFVL` — both observable.
3110 if self.common.udf != 0 {
3111 if matches!(
3112 self.record.record_type(),
3113 "calc" | "ai" | "longin" | "int64in"
3114 ) && self.record.get_field("AFVL").and_then(|v| v.to_f64()) != Some(0.0)
3115 {
3116 let _ = self.record.put_field("AFVL", EpicsValue::Double(0.0));
3117 }
3118 return;
3119 }
3120
3121 let hyst = self.common.hyst;
3122 let lalm = self
3123 .record
3124 .get_field("LALM")
3125 .and_then(|v| v.to_f64())
3126 .unwrap_or(val);
3127
3128 // C-style per-level hysteresis: alarm fires if val passes the level,
3129 // OR if we were already at that alarm level (lalm == alev) and val
3130 // hasn't retreated past the hysteresis margin.
3131 //
3132 // `alarm_range` is the C-style integer level: 1=Lolo, 2=Low,
3133 // 3=Normal, 4=High, 5=Hihi. Required for the calc-record AFTC
3134 // filter (`calcRecord.c::checkAlarms:339-381`) which filters
3135 // on the range level (not on severity) and re-maps back.
3136 // C's `checkAlarms` enables each level with a NONZERO test on the raw
3137 // severity ordinal (`if (prec->hhsv && …)`) and passes that raw ordinal
3138 // to `recGblSetSevr`; `recGblResetAlarms` then clamps the resulting
3139 // *severity* to `INVALID_ALARM` while the *status* keeps the level. So an
3140 // out-of-range selector (`HHSV = 4`) still fires HIHI and lands
3141 // SEVR=INVALID/STAT=HIHI — reproduced by testing `!= 0` and mapping the
3142 // ordinal through [`AlarmSeverity::from_u16`] (which clamps `>= 3` to
3143 // `Invalid`).
3144 let (mut new_sevr, mut new_stat, mut alev, mut alarm_range) = if cfg.hhsv != 0
3145 && (val >= cfg.hihi || (lalm == cfg.hihi && val >= cfg.hihi - hyst))
3146 {
3147 (
3148 AlarmSeverity::from_u16(cfg.hhsv as u16),
3149 alarm_status::HIHI_ALARM,
3150 cfg.hihi,
3151 5u16,
3152 )
3153 } else if cfg.llsv != 0 && (val <= cfg.lolo || (lalm == cfg.lolo && val <= cfg.lolo + hyst))
3154 {
3155 (
3156 AlarmSeverity::from_u16(cfg.llsv as u16),
3157 alarm_status::LOLO_ALARM,
3158 cfg.lolo,
3159 1u16,
3160 )
3161 } else if cfg.hsv != 0 && (val >= cfg.high || (lalm == cfg.high && val >= cfg.high - hyst))
3162 {
3163 (
3164 AlarmSeverity::from_u16(cfg.hsv as u16),
3165 alarm_status::HIGH_ALARM,
3166 cfg.high,
3167 4u16,
3168 )
3169 } else if cfg.lsv != 0 && (val <= cfg.low || (lalm == cfg.low && val <= cfg.low + hyst)) {
3170 (
3171 AlarmSeverity::from_u16(cfg.lsv as u16),
3172 alarm_status::LOW_ALARM,
3173 cfg.low,
3174 2u16,
3175 )
3176 } else {
3177 (AlarmSeverity::NoAlarm, alarm_status::NO_ALARM, val, 3u16)
3178 };
3179
3180 // C parity: the alarm-range AFTC low-pass filter
3181 // (`{ai,longin,int64in,calc}Record.c::checkAlarms`) smooths the
3182 // integer `alarmRange` and re-maps. Only records that carry the
3183 // AFTC/AFVL fields run it — `ao`/`longout`/`int64out`/`calcout`
3184 // have no AFTC field (confirmed via the respective `.dbd.pod`),
3185 // so they are excluded.
3186 let aftc_capable = matches!(
3187 self.record.record_type(),
3188 "calc" | "ai" | "longin" | "int64in"
3189 );
3190 if aftc_capable {
3191 let aftc = self
3192 .record
3193 .get_field("AFTC")
3194 .and_then(|v| v.to_f64())
3195 .unwrap_or(0.0);
3196 let afvl = self
3197 .record
3198 .get_field("AFVL")
3199 .and_then(|v| v.to_f64())
3200 .unwrap_or(0.0);
3201 if aftc > 0.0 {
3202 let now = crate::runtime::general_time::get_current();
3203 let (filtered_range, new_afvl) = crate::server::records::alarm_filter::aftc_filter(
3204 alarm_range,
3205 aftc,
3206 afvl,
3207 self.common.time,
3208 now,
3209 );
3210 let _ = self.record.put_field("AFVL", EpicsValue::Double(new_afvl));
3211 if filtered_range != alarm_range {
3212 // Re-map filtered range back to (sevr, stat, alev).
3213 let (mapped_sevr, mapped_stat, mapped_alev) = match filtered_range {
3214 5 => (
3215 AlarmSeverity::from_u16(cfg.hhsv as u16),
3216 alarm_status::HIHI_ALARM,
3217 cfg.hihi,
3218 ),
3219 4 => (
3220 AlarmSeverity::from_u16(cfg.hsv as u16),
3221 alarm_status::HIGH_ALARM,
3222 cfg.high,
3223 ),
3224 2 => (
3225 AlarmSeverity::from_u16(cfg.lsv as u16),
3226 alarm_status::LOW_ALARM,
3227 cfg.low,
3228 ),
3229 1 => (
3230 AlarmSeverity::from_u16(cfg.llsv as u16),
3231 alarm_status::LOLO_ALARM,
3232 cfg.lolo,
3233 ),
3234 _ => (AlarmSeverity::NoAlarm, alarm_status::NO_ALARM, val),
3235 };
3236 new_sevr = mapped_sevr;
3237 new_stat = mapped_stat;
3238 alev = mapped_alev;
3239 alarm_range = filtered_range;
3240 }
3241 } else {
3242 // aftc <= 0 disables the filter. C `checkAlarms`
3243 // (e.g. aiRecord.c:356,402) initialises the local
3244 // `afvl = 0` and unconditionally stores `prec->afvl =
3245 // afvl` at the end, so a disabled filter drives AFVL to
3246 // 0. Mirror that here so a stale accumulator from a prior
3247 // `aftc > 0` run cannot mis-seed the filter if AFTC is
3248 // re-enabled later.
3249 if afvl != 0.0 {
3250 let _ = self.record.put_field("AFVL", EpicsValue::Double(0.0));
3251 }
3252 }
3253 }
3254 let _ = alarm_range; // suppress unused-var on non-calc paths
3255
3256 if new_sevr != AlarmSeverity::NoAlarm {
3257 recgbl::rec_gbl_set_sevr(&mut self.common, new_stat, new_sevr);
3258 // C sets LALM to the alarm threshold level, not the current value
3259 let _ = self.record.put_field("LALM", EpicsValue::Double(alev));
3260 } else {
3261 // No alarm condition: reset LALM to current value (like C)
3262 let _ = self.record.put_field("LALM", EpicsValue::Double(val));
3263 }
3264 }
3265
3266 /// Invoke the registered subroutine (`sub`/`aSub` `SNAM`) if one is
3267 /// bound, before the record's `process()` body runs.
3268 ///
3269 /// C `subRecord.c::do_sub` / `aSubRecord.c::do_sub` call the named
3270 /// subroutine on EVERY `process()`. The function registry lives on the
3271 /// framework (`RecordInstance::subroutine`), not on the record, so the
3272 /// record's own `process()` is a no-op for these two types and the
3273 /// framework must drive the call. This is the SINGLE owner of that call
3274 /// for every dispatch path: the main engine
3275 /// (`process_record_with_links_inner`, the SCAN / event / CA-put-to-PP /
3276 /// FLNK path) and the by-name `process_local` (`db.process_record`,
3277 /// QSRV group / foreign-call path) both route through here, so a
3278 /// `sub`/`aSub` runs identically regardless of how it is processed.
3279 /// Previously only `process_local` invoked the subroutine, so on the
3280 /// main engine path `VAL`/`VALA..VALU`/`OUTA..OUTU` never updated.
3281 /// The cycle's status is delivered to the record on EVERY exit path — see
3282 /// [`Record::set_subroutine_status`], which aSub's OUT-link gate reads. The
3283 /// delivery is factored out of the body below so a future early return
3284 /// cannot skip it: the body returns the status, this wrapper publishes it.
3285 pub(crate) fn run_registered_subroutine(&mut self) -> CaResult<()> {
3286 let outcome = self.run_subroutine_body();
3287 // A subroutine that errored out has no C counterpart (a C subroutine
3288 // returns a `long`); it is a failed cycle, so it takes the non-zero
3289 // arm — no outputs.
3290 let status = *outcome.as_ref().unwrap_or(&SUBROUTINE_STATUS_ERROR);
3291 self.record.set_subroutine_status(status);
3292 outcome.map(|_| ())
3293 }
3294
3295 /// Returns C `process`'s `status` for this cycle: 0 only when `do_sub` ran
3296 /// and returned 0.
3297 fn run_subroutine_body(&mut self) -> CaResult<i64> {
3298 use crate::server::recgbl::{self, alarm_status};
3299
3300 // aSub `LFLG=READ`: a `SUBL` re-resolution that found a bad/unregistered
3301 // name (C `fetch_values` -> `S_db_BadSub`) or failed to read the link
3302 // signals "skip do_sub this cycle" — C `process` runs `do_sub` only on
3303 // `!status`. The framework's failed input-link fetch arms the same flag.
3304 // One-shot: taken (cleared) whether or not a subroutine is set, so it
3305 // never leaks into the next cycle. The single consumer of the flag,
3306 // shared by every process path.
3307 if std::mem::take(&mut self.suppress_subroutine_run) {
3308 return Ok(SUBROUTINE_STATUS_SKIPPED);
3309 }
3310
3311 // Clone the Arc so the borrow on `self.subroutine` is released
3312 // before we mutate `self.record` / `self.common` below.
3313 let Some(sub_fn) = self.subroutine.clone() else {
3314 // C `do_sub` with no bound routine returns `S_db_BadSub`
3315 // (aSubRecord.c:255-258), so the cycle's status is non-zero.
3316 return Ok(SUBROUTINE_STATUS_NO_SUB);
3317 };
3318 // C `do_sub` returns the subroutine's `long` status.
3319 let status = sub_fn(&mut *self.record)?;
3320
3321 // aSub publishes the status as VAL (C `aSubRecord.c:223`
3322 // `prec->val = status`). The subroutine's computed outputs live in
3323 // VALA..VALU, so VAL is the return code and overwrites whatever the
3324 // closure may have written to VAL. `sub` does NOT do this — its VAL
3325 // is the value the subroutine computed.
3326 if self.record.record_type() == "aSub" {
3327 // aSub VAL is DBF_LONG (epicsInt32); the do_sub status is a C `long`
3328 // truncated into it (`prec->val = status`).
3329 let _ = self
3330 .record
3331 .put_field("VAL", EpicsValue::Long(status as i32));
3332 }
3333
3334 // A negative status raises SOFT_ALARM at the record's BRSV severity
3335 // (C `do_sub`: `if (status < 0) recGblSetSevr(SOFT_ALARM,
3336 // prec->brsv)`). It accumulates into nsta/nsev for this cycle's
3337 // recGblResetAlarms commit and runs before checkAlarms, so a higher
3338 // analog severity (e.g. the shared analog-alarm owner) still wins via
3339 // the raise-only rule. BRSV defaults to NO_ALARM, under which
3340 // recGblSetSevr is a no-op.
3341 if status < 0 {
3342 let brsv = self
3343 .record
3344 .get_field("BRSV")
3345 .and_then(|v| v.to_f64())
3346 .map(|f| AlarmSeverity::from_u16(f as u16))
3347 .unwrap_or(AlarmSeverity::NoAlarm);
3348 recgbl::rec_gbl_set_sevr(&mut self.common, alarm_status::SOFT_ALARM, brsv);
3349 } else if self.record.record_type() == "aSub" {
3350 // C `aSubRecord.c::do_sub` (469-470): a subroutine that ran and
3351 // returned `>= 0` DEFINES the record — `else prec->udf = FALSE`.
3352 // aSub opts out of the framework's per-cycle blanket UDF re-derive
3353 // (`Record::clears_udf` == false), so THIS is aSub's UDF clear,
3354 // reached only on the path where the subroutine actually executed
3355 // (past the suppress / no-sub early returns above). `sub` keeps the
3356 // blanket re-derive (`clears_udf` true, C `do_sub` `udf =
3357 // isnan(val)`), so it is deliberately not cleared here.
3358 self.common.udf = 0;
3359 }
3360 Ok(status)
3361 }
3362
3363 /// The single owner of a process cycle's SUBSCRIBER posts — C `monitor()`'s
3364 /// "post every subscribed field this cycle touched" loop.
3365 ///
3366 /// Every processing path (`process_record_with_links_inner`, the deferred
3367 /// async-completion path, the simulation path, and [`Self::process_local`])
3368 /// calls this; none of them may reimplement the rules, because a rule that
3369 /// holds on one path and not another is a monitor that fires on a scan cycle
3370 /// but not on an async completion. The per-field mask resolvers
3371 /// ([`AuxPostMask`], [`crate::server::record::value_gate`]) were already
3372 /// single-owned for the same reason — this is the loop around them.
3373 ///
3374 /// It also UPDATES `last_posted` for everything it emits, and it TAKES the
3375 /// record's per-cycle post mask ([`Record::take_cycle_posted_fields`]), so
3376 /// it must run exactly once per cycle.
3377 ///
3378 /// The rules, in order:
3379 ///
3380 /// * The deadband field (default VAL), the
3381 /// [`recgbl::RECGBL_POSTED_ALARM_FIELDS`](crate::server::recgbl::RECGBL_POSTED_ALARM_FIELDS)
3382 /// (SEVR/STAT/AMSG/ACKS) and UDF are emitted by the caller with their own
3383 /// C masks and are skipped here.
3384 /// * [`Record::event_posted_fields`] post from their own event path
3385 /// (waveform HASH) — never from change detection.
3386 /// * [`Record::process_posted_fields`], when declared, is the closed set of
3387 /// fields a process cycle may post at all.
3388 /// * A secondary value field ([`Record::fields_posted_with_value_mask`])
3389 /// carries VAL's monitor mask, gated per its [`ValuePostGate`].
3390 /// * A CHANGED field carries [`AuxPostMask::mask_for`] — unless it is a
3391 /// [`Record::fields_posted_only_when_marked`] field, which C never
3392 /// change-detects (aCalcout AA..LL) and which therefore posts from its
3393 /// mark alone.
3394 /// * An UNCHANGED field posts only if the record marked it this cycle:
3395 /// statically ([`Record::force_posted_fields`]), per-cycle
3396 /// ([`Record::take_cycle_posted_fields`]), on the alarm transition
3397 /// ([`Record::alarm_cycle_monitored_fields`]), or in the DBE_LOG sweep
3398 /// ([`Record::log_swept_fields`]).
3399 pub(crate) fn collect_subscriber_posts(
3400 &mut self,
3401 deadband_field: &str,
3402 deadband_mask: EventMask,
3403 alarm_bits: EventMask,
3404 aux_post: AuxPostMask,
3405 include_val: bool,
3406 ) -> Vec<(String, EpicsValue, EventMask)> {
3407 use crate::server::record::{CyclePostMask, ValuePostGate, value_gate};
3408
3409 // C's default for a change-detected auxiliary post:
3410 // `monitor_mask | DBE_VALUE | DBE_LOG` (calcRecord.c:420, subRecord.c:400;
3411 // motor `DBE_VAL_LOG` for marked fields, motorRecord.cc:3522-3645).
3412 let aux_mask = alarm_bits | EventMask::VALUE | EventMask::LOG;
3413 let alarm_fanout: &[&str] = if alarm_bits.is_empty() {
3414 &[]
3415 } else {
3416 self.record.alarm_cycle_monitored_fields()
3417 };
3418 let force_fields = self.record.force_posted_fields();
3419 // TAKE — this also clears the state it answers from (C's
3420 // `pcalc->newm = 0`), which is why this loop may run only once per cycle.
3421 let cycle_posted = self.record.take_cycle_posted_fields();
3422 let log_swept = self.record.log_swept_fields();
3423 // C change-detects nothing about these fields; only the record's own
3424 // per-cycle mark may post them (aCalcout AA..LL — no PAA..PLL previous
3425 // copy exists to compare against).
3426 let marked_only = self.record.fields_posted_only_when_marked();
3427 let value_masked = self.record.fields_posted_with_value_mask();
3428 let event_posted = self.record.event_posted_fields();
3429 let process_posted = self.record.process_posted_fields();
3430
3431 let mut sub_updates: Vec<(String, EpicsValue, EventMask)> = Vec::new();
3432 for (field, subs) in &self.subscribers {
3433 if subs.is_empty()
3434 || field == deadband_field
3435 // SEVR/STAT/AMSG/ACKS are posted by `recGblResetAlarms` itself,
3436 // each with its own C mask (recGbl.c:201-217) — the caller emits
3437 // them from `alarm_field_posts`. A second, change-detected copy
3438 // here would double-post with a mask C never uses for them
3439 // (`alarm_bits | DBE_VALUE | DBE_LOG` instead of C's DBE_VALUE
3440 // on ACKS). UDF is excluded for the opposite reason: NO C
3441 // `monitor()` posts it at all, so a processing cycle that
3442 // redefines VAL must emit no `.UDF` event (a caput to `.UDF`
3443 // still posts, through the generic put path).
3444 || crate::server::recgbl::RECGBL_POSTED_ALARM_FIELDS.contains(&field.as_str())
3445 || field == "UDF"
3446 || event_posted.contains(&field.as_str())
3447 || !process_posted.is_none_or(|allowed| allowed.contains(&field.as_str()))
3448 {
3449 continue;
3450 }
3451 let Some(val) = self.resolve_field(field) else {
3452 continue;
3453 };
3454 let changed = match self.posted_value(field) {
3455 Some(prev) => prev != &val,
3456 None => true,
3457 };
3458 if let Some(gate) = value_gate(value_masked, field) {
3459 // C posts this secondary value field with VAL's own monitor_mask,
3460 // from inside the guard that decides whether VAL posts at all —
3461 // never a forced DBE_VALUE|DBE_LOG. `ValuePostGate` says whether C
3462 // also re-tests the field's own value inside that guard (ai RVAL,
3463 // aiRecord.c:462) or posts it whenever the guard fires (timestamp
3464 // RVAL, timestampRecord.c:160).
3465 let post = match gate {
3466 ValuePostGate::OnChange => changed && !deadband_mask.is_empty(),
3467 ValuePostGate::WithValue => include_val,
3468 };
3469 if post {
3470 sub_updates.push((field.clone(), val.clone(), deadband_mask));
3471 }
3472 } else if changed && !marked_only.contains(&field.as_str()) {
3473 sub_updates.push((
3474 field.clone(),
3475 val.clone(),
3476 aux_post.mask_for(field, alarm_bits, deadband_mask),
3477 ));
3478 } else if force_fields.contains(&field.as_str()) {
3479 // C `monitor()` posts a statically re-marked field with
3480 // `monitor_mask | DBE_VAL_LOG` even when unchanged.
3481 sub_updates.push((field.clone(), val.clone(), aux_mask));
3482 } else if cycle_posted.iter().any(|(name, _)| *name == field) {
3483 // One event per MARK, each with the mask of the C call site that
3484 // made it (`CyclePostMask`) — a field marked twice (aCalcout's
3485 // AMASK `afterCalc` post AND its NEWM `monitor()` post) is posted
3486 // twice, exactly as C posts it from both loops.
3487 for (_, cycle_mask) in cycle_posted.iter().filter(|(name, _)| *name == field) {
3488 let mask = match cycle_mask {
3489 CyclePostMask::Value => EventMask::VALUE,
3490 CyclePostMask::ValueLog => EventMask::VALUE | EventMask::LOG,
3491 CyclePostMask::MonitorValueLog => aux_mask,
3492 };
3493 sub_updates.push((field.clone(), val.clone(), mask));
3494 }
3495 } else if alarm_fanout.contains(&field.as_str()) {
3496 // C motor `monitor()` (motorRecord.cc:3513-3645) posts every listed
3497 // field once `monitor_mask != 0`, so a DBE_ALARM-only subscriber
3498 // observes the alarm moment on any of them.
3499 sub_updates.push((field.clone(), val.clone(), alarm_bits));
3500 }
3501 // C `scalerRecord.c::monitor():757-773` posts EVERY S1..Snch with a
3502 // literal DBE_LOG on every cycle it runs (it runs when `ss == IDLE`,
3503 // scalerRecord.c:510). That sweep is INDEPENDENT of the change post,
3504 // not an alternative to it: on the count-completion cycle `ss` is
3505 // IDLE and `updateCounts()` has ALREADY posted each changed Sn with
3506 // DBE_VALUE (:582), so C emits two events for that field in that one
3507 // cycle — DBE_VALUE, then DBE_LOG. Making this an `else if` on
3508 // `changed` dropped the DBE_LOG half exactly when it matters: a
3509 // DBE_LOG-only archiver would never receive the final counts.
3510 //
3511 // The sweep carries the ALARM-transition bits too. DEVIATION from C,
3512 // deliberate — CBUG-B19. C's `monitor()` opens with
3513 // `monitor_mask = recGblResetAlarms(pscal); monitor_mask |=
3514 // (DBE_VALUE|DBE_LOG);` and then posts with a LITERAL `DBE_LOG`
3515 // (scalerRecord.c:764-771) — `monitor_mask` is assigned, OR-ed, and
3516 // never read. Those two lines are dead, and their only plausible use
3517 // was as the third `db_post_events` argument.
3518 // `recGblResetAlarms` returns the alarm-transition mask that every
3519 // other record ORs into its value posts, so discarding it drops the
3520 // alarm bit: a client subscribed to `Sn` with DBE_ALARM receives
3521 // NOTHING on an alarm-severity transition of the record.
3522 //
3523 // The DBE_VALUE half of C's dead `|=` is deliberately NOT
3524 // resurrected: this sweep is unconditional, so adding VALUE would
3525 // fire a value event at every VALUE subscriber on every idle scan,
3526 // changed or not — that would be a new defect, not a fix. The value
3527 // path is separately served by the change post (C's `updateCounts()`
3528 // DBE_VALUE at `:582`).
3529 if log_swept.contains(&field.as_str()) {
3530 sub_updates.push((field.clone(), val, EventMask::LOG | alarm_bits));
3531 }
3532 }
3533 for (field, val, _) in &sub_updates {
3534 self.record_value_post(field, val.clone());
3535 }
3536 sub_updates
3537 }
3538
3539 /// Basic process: process record, evaluate alarms, timestamp, build snapshot.
3540 /// This does NOT handle links — see process_with_context in database.rs.
3541 ///
3542 /// Returns the value/log snapshot plus a list of alarm-field posts
3543 /// (`SEVR`/`STAT`/`AMSG`/`ACKS`) with their individual C event masks.
3544 /// `SEVR` is posted `DBE_VALUE` only; `STAT`/`AMSG` carry `DBE_ALARM`
3545 /// (sevr/amsg change) and/or `DBE_VALUE` (stat change). The caller
3546 /// must fire these via `notify_field` so a `DBE_VALUE`-only `.SEVR`
3547 /// subscriber is not missed on an alarm-only change and a
3548 /// `DBE_ALARM`-only subscriber is not wrongly notified — C parity
3549 /// with `recGblResetAlarms` (recGbl.c:201-220), matching the
3550 /// `processing.rs` link path.
3551 pub fn process_local(
3552 &mut self,
3553 ) -> CaResult<(
3554 ProcessSnapshot,
3555 Vec<(&'static str, crate::server::recgbl::EventMask)>,
3556 )> {
3557 use crate::server::recgbl::{self, EventMask};
3558 const LCNT_ALARM_THRESHOLD: i16 = 10;
3559
3560 if self.pact.swap(true, std::sync::atomic::Ordering::AcqRel) {
3561 // C `dbProcess` PACT-active guard (dbAccess.c:544-557):
3562 //
3563 // if ((precord->stat == SCAN_ALARM) ||
3564 // (precord->lcnt++ < MAX_LOCK) ||
3565 // (precord->sevr >= INVALID_ALARM)) goto all_done;
3566 // recGblSetSevrMsg(precord, SCAN_ALARM, INVALID_ALARM,
3567 // "Async in progress");
3568 //
3569 // The alarm fires EXACTLY ONCE — on the attempt whose
3570 // pre-increment lcnt equals MAX_LOCK — and is then blocked
3571 // by the stat == SCAN_ALARM / sevr >= INVALID bails, the
3572 // same shape as the link path
3573 // (`process_record_with_links_inner`). The pre-fix guard
3574 // here used post-increment `lcnt >= threshold` with no
3575 // already-raised bail, so every reentrant attempt past the
3576 // threshold re-posted the unchanged SEVR/STAT/VAL (and the
3577 // first fire came one attempt early); it also wrote
3578 // sevr/stat directly, skipping `recGblSetSevrMsg` +
3579 // `recGblResetAlarms` — losing the "Async in progress"
3580 // AMSG and the acks bookkeeping the reset performs.
3581 let already_scan_alarm = self.common.stat == recgbl::alarm_status::SCAN_ALARM;
3582 let already_invalid = self.common.sevr >= AlarmSeverity::Invalid;
3583 let lcnt_before = self.common.lcnt;
3584 self.common.lcnt = lcnt_before.saturating_add(1);
3585 if already_scan_alarm || lcnt_before < LCNT_ALARM_THRESHOLD || already_invalid {
3586 return Ok((
3587 ProcessSnapshot {
3588 changed_fields: Vec::new(),
3589 },
3590 Vec::new(),
3591 ));
3592 }
3593 recgbl::rec_gbl_set_sevr_msg(
3594 &mut self.common,
3595 recgbl::alarm_status::SCAN_ALARM,
3596 AlarmSeverity::Invalid,
3597 "Async in progress",
3598 );
3599 let _ = recgbl::rec_gbl_reset_alarms(&mut self.common);
3600 // Per-field C masks (recGbl.c:201-220): this guard only
3601 // runs on a fresh SCAN_ALARM/INVALID raise, so sevr AND
3602 // stat both moved — SEVR posts DBE_VALUE, STAT/AMSG post
3603 // the shared `stat_mask` = DBE_ALARM|DBE_VALUE, VAL posts
3604 // DBE_VALUE|DBE_LOG plus `val_mask` = DBE_ALARM.
3605 let stat_mask = EventMask::ALARM | EventMask::VALUE;
3606 let mut changed_fields = Vec::new();
3607 if let Some(val) = self.record.val() {
3608 changed_fields.push((
3609 "VAL".to_string(),
3610 val,
3611 EventMask::VALUE | EventMask::LOG | EventMask::ALARM,
3612 ));
3613 }
3614 changed_fields.push((
3615 "SEVR".to_string(),
3616 EpicsValue::Short(self.common.sevr as i16),
3617 EventMask::VALUE,
3618 ));
3619 changed_fields.push((
3620 "STAT".to_string(),
3621 EpicsValue::Short(self.common.stat as i16),
3622 stat_mask,
3623 ));
3624 // AMSG carries "Async in progress" alongside the STAT
3625 // transition (C recGbl.c posts STAT and AMSG together
3626 // when any alarm field moved).
3627 changed_fields.push((
3628 "AMSG".to_string(),
3629 EpicsValue::String(self.common.amsg.clone().into()),
3630 stat_mask,
3631 ));
3632 return Ok((ProcessSnapshot { changed_fields }, Vec::new()));
3633 }
3634 self.common.lcnt = 0;
3635 // RAII guard that resets `self.pact` to false on drop — both for the
3636 // normal exit path and for any `?` early return. The guard holds a raw
3637 // pointer rather than a reference because we still need `self` mutably
3638 // while the guard is alive (the record body below mutates other `self`
3639 // fields).
3640 //
3641 // This is the one PACT release that does not go through `leave_pact`,
3642 // and it provably frees nothing: `process_local` holds `&mut self` for
3643 // the whole PACT window, and a put-notify is parked only through
3644 // `park_notify_put`, which needs that same `&mut`. So no deferral can
3645 // be created inside the window, and the `swap(true)` above proved none
3646 // existed on entry (`deferred_notify_put.is_some()` ⟹ PACT).
3647 debug_assert!(
3648 self.deferred_notify_put.is_none(),
3649 "PactExit invariant: a parked put-notify implies PACT, which the \
3650 swap above proved was clear"
3651 );
3652 struct ProcessGuard(*const AtomicBool);
3653 // SAFETY: AtomicBool is Sync; raw pointers don't auto-derive
3654 // Send. We hand-roll Send because the ptr targets a field of
3655 // `self`, which the caller already proves can be borrowed
3656 // through this code path. The pointer is only ever read for an
3657 // atomic store, never written, dereferenced for raw access, or
3658 // escaped from this scope.
3659 unsafe impl Send for ProcessGuard {}
3660 impl Drop for ProcessGuard {
3661 fn drop(&mut self) {
3662 // SAFETY: `self.0` was constructed from
3663 // `&self.pact as *const AtomicBool` below, where
3664 // `self` is the live RecordInstance whose lifetime
3665 // strictly outlives `_guard`. RecordInstance is
3666 // !Unpin-equivalent in practice (we never move it
3667 // while held in the database's `Arc<RwLock<_>>`), so
3668 // the pointer remains valid until Drop runs.
3669 unsafe { &*self.0 }.store(false, std::sync::atomic::Ordering::Release);
3670 }
3671 }
3672 let _guard = ProcessGuard(&self.pact as *const AtomicBool);
3673
3674 // Call subroutine if registered (for sub/aSub records). Single owner
3675 // shared with the main engine path — see `run_registered_subroutine`.
3676 self.run_registered_subroutine()?;
3677 // Soft-Channel input records must skip the RVAL->VAL convert
3678 // (C `devAiSoft.c` `read_ai` returns 2 = "don't convert" for
3679 // every Soft-Channel input record, incl. one with a constant /
3680 // unset INP). Without this, `process_local` on a soft input
3681 // with a preset VAL — e.g. NaN — would run `convert()` and
3682 // clobber it, after which the UDF check below would see a
3683 // defined value and wrongly clear UDF. The
3684 // `processing.rs` link path already does this; `process_local`
3685 // is the separate foreign-call path (`db.process_record`) and
3686 // needs the same skip. "Raw Soft Channel" has a distinct DTYP
3687 // so it is excluded by `is_soft` and still runs convert.
3688 //
3689 // Gated on `soft_channel_skips_convert()` — identical to the
3690 // `processing.rs` link path — so this only suppresses the
3691 // `RVAL → VAL` convert step. `set_device_did_compute` is an
3692 // overloaded hook: `ai/bi/mbbi/mbbi_direct` read it as
3693 // "skip convert" (override true), but `epid` reads it as
3694 // "skip the whole built-in PID compute" (keeps default false).
3695 // Without this gate, a Soft-Channel `epid` driven through
3696 // `process_local` (`db.process_record`, e.g. QSRV group proc
3697 // members) would skip `do_pid()` entirely — the regression
3698 // d1032fe5 fixed on the `processing.rs` path only.
3699 {
3700 let is_soft = self.common.dtyp.is_empty() || self.common.dtyp == "Soft Channel";
3701 let is_output = self.record.can_device_write();
3702 if is_soft && !is_output && self.record.soft_channel_skips_convert() {
3703 self.record.set_device_did_compute(true);
3704 }
3705 }
3706 // Push framework-owned common state (UDF/PHAS/TSE/TSEL) so the
3707 // record's process() can see it — same as the processing.rs link
3708 // path. `process_local` is the foreign-call path
3709 // (`db.process_record`); without this a record driven through it
3710 // (e.g. QSRV group-process members) would not see UDF/TSE.
3711 {
3712 let ctx = self.common.process_context();
3713 self.record.set_process_context(&ctx);
3714 }
3715 let outcome = self.record.process()?;
3716 let process_result = outcome.result;
3717 // Note: process_local() does not execute ProcessActions — those are
3718 // handled by the full process_record_with_links() path in processing.rs.
3719
3720 // If the record reports it modified a metadata-class field during
3721 // process(), invalidate the metadata cache so the next snapshot
3722 // rebuilds from the new values. Default impl returns false, so
3723 // most records pay zero cost here.
3724 if self.record.took_metadata_change() {
3725 self.invalidate_metadata_cache();
3726 // mirror C db_post_events(precord, NULL, DBE_PROPERTY) after record processing.
3727 let fields: Vec<String> = self.subscribers.keys().cloned().collect();
3728 for f in fields {
3729 self.notify_field_with_origin(&f, crate::server::recgbl::EventMask::PROPERTY, 0);
3730 }
3731 }
3732
3733 if process_result == RecordProcessResult::AsyncPending {
3734 // Async: PACT stays set, no further processing this cycle
3735 // Don't clear processing flag (guard won't run — we leak it intentionally)
3736 std::mem::forget(_guard);
3737 return Ok((
3738 ProcessSnapshot {
3739 changed_fields: Vec::new(),
3740 },
3741 Vec::new(),
3742 ));
3743 }
3744 if let RecordProcessResult::AsyncPendingNotify(fields) = process_result {
3745 // Intermediate notification (e.g. DMOV=0 at move start).
3746 // Unlike AsyncPending, we DO release the processing flag so
3747 // subsequent I/O Intr cycles can continue processing normally.
3748 self.common.time = crate::runtime::general_time::get_current();
3749 // Filter out fields that haven't actually changed, and update
3750 // MLST/last_posted for those that have. Each intermediate
3751 // post carries DBE_VALUE|DBE_LOG — C motor's mid-move
3752 // `db_post_events` calls use `DBE_VAL_LOG`
3753 // (motorRecord.cc:2606 DMOV, and every other do_work post);
3754 // no alarm transition ran on this pending pass.
3755 let mut changed_fields = Vec::new();
3756 for (name, val) in fields {
3757 let changed = match self.posted_value(&name) {
3758 Some(prev) => prev != &val,
3759 None => true,
3760 };
3761 if changed {
3762 if name == "VAL" {
3763 if let Some(f) = val.to_f64() {
3764 self.put_coerced("MLST", f);
3765 self.common.mlst = Some(f);
3766 }
3767 }
3768 self.record_value_post(&name, val.clone());
3769 changed_fields.push((name, val, EventMask::VALUE | EventMask::LOG));
3770 }
3771 }
3772 // _guard drops here, clearing the processing flag
3773 return Ok((ProcessSnapshot { changed_fields }, Vec::new()));
3774 }
3775 if process_result == RecordProcessResult::CompleteNoEmit {
3776 // The record accumulated this cycle without emitting (compress
3777 // `status == 1`). C `compressRecord.c:365` runs the completion
3778 // epilogue (udf clear, timestamp, monitor, FLNK) only on an emit
3779 // cycle (`if (status != 1)`), so a non-emitting cycle must publish
3780 // nothing — skip the epilogue and return an empty snapshot, exactly
3781 // as the production engine path does in `processing.rs`. This keeps
3782 // the emit-gate uniform across both process-dispatch paths so the
3783 // invariant holds by construction, not by "process_local never
3784 // produces it". CompleteNoEmit is synchronous (PACT already
3785 // cleared); the `_guard` drops here, clearing the processing flag.
3786 return Ok((
3787 ProcessSnapshot {
3788 changed_fields: Vec::new(),
3789 },
3790 Vec::new(),
3791 ));
3792 }
3793
3794 // `CompleteDeferOutput` (swait ODLY delay-start) is NOT special-cased
3795 // here: it deliberately shares the Complete value-side snapshot builder
3796 // below. C `swaitRecord.c::process` posts the value side (`monitor()`,
3797 // line 475) on the delaying cycle, so building the snapshot now is the
3798 // correct, parity-matching behavior — unlike `CompleteNoEmit` above,
3799 // whose fall-through would wrongly emit. The variant's *other* halves —
3800 // holding PACT across the delay and deferring OUT/OEVT/FLNK to the
3801 // `ReprocessAfter` continuation — are the engine path's responsibility
3802 // (`processing.rs::process_record_with_links_inner`); `process_local` is
3803 // a body-only test helper that dispatches no FLNK/output and no
3804 // `ProcessAction`, and no test drives a swait ODLY record through it. So
3805 // the invariant still holds by construction across both dispatch paths:
3806 // both publish the value side here, both leave the output side to the
3807 // engine.
3808
3809 // UDF update before alarm evaluation — C parity (see
3810 // `processing.rs`). A NaN / undefined value keeps UDF true so
3811 // `recGblCheckUDF` raises UDF_ALARM this cycle instead of the
3812 // record reporting a stale/garbage value with no alarm.
3813 if self.record.clears_udf() {
3814 self.common.udf = self.record.value_is_undefined() as u8;
3815 }
3816 // Per-record alarm hook (C `checkAlarms()`).
3817 self.record.check_alarms(&mut self.common);
3818
3819 // Evaluate alarms (accumulates into nsta/nsev)
3820 self.evaluate_alarms();
3821
3822 // Transfer nsta/nsev → sevr/stat, detect alarm change
3823 let alarm_result = recgbl::rec_gbl_reset_alarms(&mut self.common);
3824
3825 self.common.time = crate::runtime::general_time::get_current();
3826 // UDF already updated above — do not clear unconditionally.
3827
3828 // Deadband check for VAL monitor filtering
3829 let (include_val, include_archive) = self.check_deadband_ext();
3830 // C `recGblResetAlarms` `val_mask = DBE_ALARM`
3831 // (recGbl.c:194/203/212): every monitored-value post this cycle
3832 // carries DBE_ALARM when the severity/status OR the alarm
3833 // message moved — same parity rule as the `processing.rs`
3834 // paths.
3835 let alarm_bits = if alarm_result.alarm_changed || alarm_result.amsg_changed {
3836 EventMask::ALARM
3837 } else {
3838 EventMask::NONE
3839 };
3840
3841 // Build snapshot
3842 let mut changed_fields = Vec::new();
3843 // Same deadband-field routing and per-field mask as the
3844 // `processing.rs` paths: the tracked field posts the classes
3845 // that actually fired (MDEL → DBE_VALUE, ADEL → DBE_LOG, alarm
3846 // movement → DBE_ALARM); a non-primary deadband field (motor
3847 // RBV — C motor `monitor()`, motorRecord.cc:3468-3507) leaves
3848 // VAL to the generic change-detection loop below.
3849 let deadband_field = self.record.monitor_deadband_field();
3850 // The mask every change-detected aux field posts with — owned by
3851 // `AuxPostMask`, the same resolver the `processing.rs` paths use, so
3852 // this builder cannot drift from them on what mask a field carries.
3853 let aux_post = AuxPostMask::of(self.record.as_ref());
3854 // The deadband field's post — mask owned by `deadband_post`, the single
3855 // assembler C's `db_post_events(&prec->val, monitor_mask)` maps to.
3856 let deadband = self.deadband_post(alarm_bits, include_val, include_archive);
3857 let deadband_mask = deadband.mask;
3858 if let Some((field, value)) = deadband.field {
3859 changed_fields.push((field, value, deadband_mask));
3860 }
3861 // C `recGblResetAlarms` (recGbl.c:201-220) posts each alarm
3862 // field with its OWN per-field mask, not one record-wide mask:
3863 // * SEVR — DBE_VALUE, ONLY on a sevr change.
3864 // * STAT — DBE_ALARM (sevr change) | DBE_VALUE (stat change).
3865 // * ACKS — DBE_VALUE, only when an alarm field moved.
3866 // Pushing SEVR/STAT into `changed_fields` collapses them onto
3867 // the single record-wide `event_mask` (which carries ALARM on
3868 // `alarm_changed`): a DBE_VALUE-only `.SEVR` subscriber would
3869 // miss a stat-only-driven sevr change, and a DBE_ALARM-only
3870 // `.SEVR` subscriber would be wrongly notified. Post them via
3871 // `notify_field` with their individual masks instead — exactly
3872 // as the `processing.rs` link path does.
3873 let sevr_changed = self.common.sevr != alarm_result.prev_sevr;
3874 let stat_changed = self.common.stat != alarm_result.prev_stat;
3875 let stat_mask = {
3876 let mut m = EventMask::NONE;
3877 // C `recGblResetAlarms` carries DBE_ALARM on the STAT/AMSG
3878 // posts whenever the severity OR the alarm message moved —
3879 // not on a severity change alone. Aligning with the
3880 // `processing.rs` link path (and `complete_async_record`).
3881 if sevr_changed || alarm_result.amsg_changed {
3882 m |= EventMask::ALARM;
3883 }
3884 if stat_changed {
3885 m |= EventMask::VALUE;
3886 }
3887 m
3888 };
3889 let mut alarm_posts: Vec<(&'static str, EventMask)> = Vec::new();
3890 if sevr_changed {
3891 alarm_posts.push(("SEVR", EventMask::VALUE));
3892 }
3893 if !stat_mask.is_empty() {
3894 alarm_posts.push(("STAT", stat_mask));
3895 // AMSG shares STAT's mask — C posts it alongside STAT when
3896 // any alarm field moved.
3897 alarm_posts.push(("AMSG", stat_mask));
3898 }
3899 // C parity (recGbl.c:214-217): ACKS is posted (DBE_VALUE) whenever the
3900 // alarm-acknowledge rule fires — `acks_posted` already folds in C's
3901 // `if (stat_mask)` guard, and the post carries no value-change test.
3902 if alarm_result.acks_posted {
3903 alarm_posts.push(("ACKS", EventMask::VALUE));
3904 }
3905
3906 // The cycle's subscriber posts — assembled by the single owner
3907 // `collect_subscriber_posts`, shared with every `processing.rs` path.
3908 changed_fields.extend(self.collect_subscriber_posts(
3909 deadband_field,
3910 deadband_mask,
3911 alarm_bits,
3912 aux_post,
3913 include_val,
3914 ));
3915 // C waveform/aai/aao `monitor()` posts HASH with a literal
3916 // `DBE_VALUE` only on a content-hash change (waveformRecord.c:
3917 // 317-319), independent of the VAL post mask. `array_hash_changed`
3918 // was set by `check_deadband_ext` this cycle.
3919 if self.array_hash_changed {
3920 if let Some(h) = self.resolve_field("HASH") {
3921 changed_fields.push(("HASH".to_string(), h, EventMask::VALUE));
3922 }
3923 }
3924
3925 // No `.UDF` post — C `monitor()` posts UDF nowhere, and
3926 // `recGblResetAlarms` (recGbl.c:204-216) posts only SEVR/STAT/AMSG/
3927 // ACKS. A `.UDF` event exists only where C's generic `dbPut` posts
3928 // the field it wrote (dbAccess.c:1420-1430) — i.e. a client caput to
3929 // `.UDF` itself.
3930
3931 Ok((ProcessSnapshot { changed_fields }, alarm_posts))
3932 }
3933
3934 /// Put a f64 value into a record field, coercing to the field's native type.
3935 pub(crate) fn put_coerced(&mut self, field: &str, val: f64) {
3936 use crate::types::EpicsValue;
3937 let target_type = self
3938 .record
3939 .get_field(field)
3940 .map(|v| v.db_field_type())
3941 .unwrap_or(crate::types::DbFieldType::Double);
3942 let coerced = EpicsValue::Double(val).convert_to(target_type);
3943 let _ = self.record.put_field(field, coerced);
3944 }
3945
3946 /// Check MDEL/ADEL deadbands for VAL monitor/archive filtering.
3947 /// Returns `(monitor_trigger, archive_trigger)`.
3948 ///
3949 /// Updates `MLST`/`ALST` (record-owned) and the `CommonFields`
3950 /// `mlst/alst` shadow when a trigger fires. Records without
3951 /// MDEL/ADEL (e.g. motor) default to deadband=0 (any actual
3952 /// change triggers).
3953 ///
3954 /// Delegates per-axis deadband comparison to the free function
3955 /// [`check_deadband`] below — see that function's docstring for
3956 /// the four-quadrant NaN/infinity rule mirroring C
3957 /// `recGblCheckDeadband` (recGbl.c:345-370).
3958 ///
3959 /// **C-parity design note**: the Rust port uses `NaN` as the
3960 /// "never posted" sentinel for `MLST`/`ALST`. C achieves the
3961 /// same first-publish guarantee by allocating MLST/ALST in
3962 /// BSS-zeroed storage with a value of 0.0 that the C code is
3963 /// allowed to match against — but the first observed value is
3964 /// not necessarily 0.0, and the C rule "MLST==0 means never
3965 /// posted" relies on the deadband comparison `abs(val - 0.0)`
3966 /// firing on any non-zero first value. NaN is strictly more
3967 /// correct for the Rust port because a legitimate first
3968 /// `val=0.0` still fires on `NaN.is_nan() → true`. This
3969 /// sentinel-as-design is intentional, documented inside
3970 /// [`check_deadband`] (the `oldval.is_nan() → return true` short
3971 /// circuit). It is NOT a deviation inherited from an earlier
3972 /// silent compromise — `record_tests.rs::deadband_*` pins both
3973 /// the NaN-sentinel behaviour and the C four-quadrant transitions.
3974 /// The single owner of the deadband field's monitor post — C `monitor()`'s
3975 /// `db_post_events(&prec->val, monitor_mask)`, the one post every record
3976 /// makes for the value it deadbands.
3977 ///
3978 /// [`Self::check_deadband_ext`] decides WHETHER the MDEL/ADEL classes fired;
3979 /// this decides what the resulting post looks like, and it is the only place
3980 /// that assembles that mask. The three `processing.rs` snapshot builders and
3981 /// the `notify_monitors` path all route through here, so a record's mask rule
3982 /// cannot hold on one processing path and not another.
3983 ///
3984 /// Two record hooks strip C's `DBE_LOG` from the post:
3985 ///
3986 /// * [`Record::value_only_change_fields`] — C posts a literal `DBE_VALUE`
3987 /// (scaler VAL, scalerRecord.c:478).
3988 /// * [`Record::fields_posted_with_monitor_mask`] — C posts
3989 /// `monitor_mask | DBE_VALUE` (event VAL, eventRecord.c:163). `monitor_mask`
3990 /// there is `recGblResetAlarms`'s return, i.e. the alarm bits alone, so the
3991 /// post carries `DBE_VALUE` (+ `DBE_ALARM` when the alarm moved) and never
3992 /// the archive `DBE_LOG` — an event's VAL reaches a `DBE_LOG` archiver on
3993 /// no cycle at all.
3994 ///
3995 /// [`DeadbandPost::field`] is `None` when no class fired, i.e. when C's
3996 /// `if (monitor_mask)` guard would skip the post.
3997 /// C `monitor()`'s VALUE / LOG gate for the primary-value post —
3998 /// `(include_val, include_archive)`, the single owner every processing path
3999 /// feeds into [`Self::deadband_post`] and [`Self::collect_subscriber_posts`].
4000 /// Keeping it in one place is what stops the rule from holding on the
4001 /// synchronous path but not the async-continuation / put-notify paths.
4002 pub(crate) fn value_include_classes(&mut self) -> (bool, bool) {
4003 // fanout/seq "trigger" records post VAL only with the alarm events
4004 // `recGblResetAlarms` returns, never DBE_VALUE/DBE_LOG — see
4005 // `Record::process_posts_value_monitor`. The alarm bits still reach VAL
4006 // via `deadband_post`'s `alarm_bits`, so an alarm transition still posts
4007 // it; only the value/archive classes are suppressed.
4008 if !self.record.process_posts_value_monitor() {
4009 return (false, false);
4010 }
4011 match self.record.monitor_value_changed() {
4012 // lsi/lso post VALUE|LOG only when the string actually changed (C
4013 // `lsiRecord.c`/`lsoRecord.c` monitor: `len != olen || memcmp(oval,
4014 // val, len)`); they have no MDEL/ADEL deadband to express that, so
4015 // the gate is explicit. The MPST/APST `menuPost` "Always" override
4016 // OR-adds DBE_VALUE / DBE_LOG even on an unchanged cycle (C monitor:
4017 // `if (mpst == menuPost_Always) events |= DBE_VALUE; if (apst ==
4018 // menuPost_Always) events |= DBE_LOG;`).
4019 Some(changed) => {
4020 let (val_always, archive_always) = self.record.monitor_always_post();
4021 (changed || val_always, changed || archive_always)
4022 }
4023 None => {
4024 if self.record.uses_monitor_deadband() {
4025 self.check_deadband_ext()
4026 } else {
4027 // Binary records (bi/bo/busy/mbbi/mbbo): always post monitors
4028 (true, true)
4029 }
4030 }
4031 }
4032 }
4033
4034 pub(crate) fn deadband_post(
4035 &self,
4036 alarm_bits: EventMask,
4037 include_val: bool,
4038 include_archive: bool,
4039 ) -> DeadbandPost {
4040 let field = self.record.monitor_deadband_field();
4041 let log_suppressed = self.record.value_only_change_fields().contains(&field)
4042 || self
4043 .record
4044 .fields_posted_with_monitor_mask()
4045 .contains(&field);
4046
4047 let mut mask = alarm_bits;
4048 if include_val {
4049 mask |= EventMask::VALUE;
4050 }
4051 if include_archive && !log_suppressed {
4052 mask |= EventMask::LOG;
4053 }
4054
4055 // The closed set applies to THIS post too. `process_posted_fields` is
4056 // "the CLOSED set of fields a process cycle of this record may post" —
4057 // and the deadband post is a post. A record whose C `monitor()` never
4058 // names the deadband field must not have one invented for it: transform
4059 // `monitor()` (transformRecord.c:786-808) walks A..P and posts no VAL
4060 // at all — VAL is an inert dummy (`:422`) — so an alarm cycle, whose
4061 // `alarm_bits` alone make `mask` non-empty, was firing a `.VAL` monitor
4062 // C never sends. Gating here rather than at each builder keeps the
4063 // single owner of the deadband post the single enforcer of the set.
4064 let in_closed_set = self
4065 .record
4066 .process_posted_fields()
4067 .is_none_or(|allowed| allowed.contains(&field));
4068
4069 let value = if mask.is_empty() || !in_closed_set {
4070 None
4071 } else if field == "VAL" {
4072 self.record.val()
4073 } else {
4074 self.resolve_field(field)
4075 };
4076 DeadbandPost {
4077 mask,
4078 field: value.map(|v| (field.to_string(), v)),
4079 }
4080 }
4081
4082 pub fn check_deadband_ext(&mut self) -> (bool, bool) {
4083 // C waveform/aai/aao `monitor()` (waveformRecord.c:291-326) replaces
4084 // the analog MDEL/ADEL deadband with the MPST/APST "Always vs On
4085 // Change" mechanism: the record hashes its array content and posts
4086 // `DBE_VALUE`/`DBE_LOG` either always or only when the hash changed,
4087 // and posts `HASH` (`DBE_VALUE`) on a hash change. The record owns
4088 // the hash compute + `HASH` update; `array_hash_changed` carries the
4089 // event to the snapshot builders, which post `HASH` (the field is
4090 // excluded from the generic change-detection loop via
4091 // `event_posted_fields`).
4092 if let Some(post) = self.record.array_monitor_post() {
4093 self.array_hash_changed = post.hash_changed;
4094 return (post.post_value, post.post_archive);
4095 }
4096 self.array_hash_changed = false;
4097
4098 // The deadband is evaluated against `monitor_deadband_value()`,
4099 // not `val()` directly: a record whose monitored quantity is
4100 // not its primary value (e.g. the motor record, VAL=setpoint /
4101 // RBV=readback — C `monitor()` deadbands RBV) overrides that
4102 // hook. Default is `val()`, so other records are unaffected.
4103 let val = match self
4104 .record
4105 .monitor_deadband_value()
4106 .and_then(|v| v.to_f64())
4107 {
4108 Some(v) => v,
4109 None => return (true, true),
4110 };
4111
4112 let mdel = self
4113 .record
4114 .get_field("MDEL")
4115 .and_then(|v| v.to_f64())
4116 .unwrap_or(0.0);
4117 let adel = self
4118 .record
4119 .get_field("ADEL")
4120 .and_then(|v| v.to_f64())
4121 .unwrap_or(0.0);
4122
4123 // Use record's MLST/ALST fields if available, otherwise fall back to CommonFields
4124 let mlst = self
4125 .record
4126 .get_field("MLST")
4127 .and_then(|v| v.to_f64())
4128 .or(self.common.mlst)
4129 .unwrap_or(f64::NAN);
4130 let alst = self
4131 .record
4132 .get_field("ALST")
4133 .and_then(|v| v.to_f64())
4134 .or(self.common.alst)
4135 .unwrap_or(f64::NAN);
4136
4137 let monitor_trigger = check_deadband(val, mlst, mdel);
4138 let archive_trigger = check_deadband(val, alst, adel);
4139
4140 if archive_trigger {
4141 self.put_coerced("ALST", val);
4142 self.common.alst = Some(val);
4143 }
4144 if monitor_trigger {
4145 self.put_coerced("MLST", val);
4146 self.common.mlst = Some(val);
4147 }
4148
4149 (monitor_trigger, archive_trigger)
4150 }
4151
4152 /// Build a Snapshot for a given value, populated with the record's display metadata.
4153 /// Uses the metadata cache so the populate cost is paid at most once
4154 /// per metadata-stable interval (cf. `cached_metadata`).
4155 pub fn make_monitor_snapshot(
4156 &self,
4157 field: &str,
4158 value: EpicsValue,
4159 ) -> super::super::snapshot::Snapshot {
4160 // A monitor update is posted from the record's own change-detection
4161 // loop, which hands over the STORED variant. Project it onto the
4162 // field's declared type here, at the same owner the GET path and the
4163 // CA create-channel path use, or a client that was told `DBR_ENUM` at
4164 // create time would be posted a `DBR_SHORT` update.
4165 let value = self.project_to_declared_type(field, value);
4166 let mut snap = super::super::snapshot::Snapshot::new(
4167 value,
4168 self.common.stat,
4169 self.common.sevr as u16,
4170 self.common.time,
4171 );
4172 // Carry the record's `utag` into the monitor update's
4173 // `timeStamp.userTag`, same as the GET path
4174 // (`snapshot_for_field`) and pvxs `iocsource.cpp:245`. Narrows
4175 // the 64-bit `epicsUTag` to the int32 wire field by low-32-bit
4176 // truncation.
4177 snap.user_tag = self.common.utag as i32;
4178 let meta = self.cached_metadata();
4179 snap.display = meta.display;
4180 snap.control = meta.control;
4181 snap.enums = meta.enums;
4182 // Same per-field routing owner as the GET path — a monitor update must
4183 // carry the same metadata a read of that field would.
4184 self.route_field_metadata(field, &mut snap);
4185 // Per-field RSET metadata, same as the GET path
4186 // (`snapshot_for_field`) — a monitor update for VELO must carry
4187 // VELO's limits, not the record-level VAL limits.
4188 self.apply_field_metadata_override(field, &mut snap);
4189 // A monitored DBF_MENU field carries the same DBR_ENUM value and
4190 // choice labels as the GET path, so a `camonitor`/`pvmonitor`
4191 // update shows the menu label, not a bare index.
4192 self.attach_menu_enum(field, &mut snap);
4193 // Same owner, same settled value, same mask as the GET path.
4194 self.assign_property_support(field, &mut snap);
4195 snap
4196 }
4197
4198 /// Apply a record's per-field metadata override (C RSET
4199 /// `get_units`/`get_precision`/`get_graphic_double`/
4200 /// `get_control_double`/`get_alarm_double`, all keyed by field)
4201 /// over the cached record-level metadata. Shared by the GET and
4202 /// monitor snapshot builders. Computed live on every call — never
4203 /// cached — so overrides derived from fields outside the
4204 /// `is_metadata_field` set cannot go stale.
4205 ///
4206 /// This is also where the record-level `Q:form` info tag is narrowed to
4207 /// the served field: QSRV assigns `display.form.index` only when the
4208 /// channel addresses the VAL field (`IOCSource::initialize` gates it on
4209 /// `dbIsValueField(dbChannelFldDes(chan))`, `iocsource.cpp:53`; the form
4210 /// *menu*, `form.choices`, is published for every field). The metadata
4211 /// cache is per-record, so a channel on `REC.RVAL` of a record carrying
4212 /// `info(Q:form, "Hex")` used to report Hex where pvxs reports Default.
4213 /// Both `Snapshot` producers (`snapshot_for_field` for GET,
4214 /// `make_monitor_snapshot` for updates) run this one owner, so
4215 /// `DisplayInfo::form` means exactly one thing on every path: the form
4216 /// index that applies to THIS field.
4217 fn apply_field_metadata_override(
4218 &self,
4219 field: &str,
4220 snap: &mut super::super::snapshot::Snapshot,
4221 ) {
4222 if let Some(display) = snap.display.as_mut()
4223 && !crate::server::database::is_value_field(field)
4224 {
4225 display.form = 0;
4226 }
4227 let Some(ov) = self.record.field_metadata_override(field) else {
4228 return;
4229 };
4230 if ov.units.is_some()
4231 || ov.precision.is_some()
4232 || ov.disp_limits.is_some()
4233 || ov.alarm_limits.is_some()
4234 {
4235 let d = snap.display.get_or_insert_with(Default::default);
4236 if let Some(units) = ov.units {
4237 d.units = units;
4238 }
4239 if let Some(precision) = ov.precision {
4240 d.precision = precision;
4241 }
4242 if let Some((upper, lower)) = ov.disp_limits {
4243 d.upper_disp_limit = upper;
4244 d.lower_disp_limit = lower;
4245 }
4246 if let Some((hihi, high, low, lolo)) = ov.alarm_limits {
4247 d.upper_alarm_limit = hihi;
4248 d.upper_warning_limit = high;
4249 d.lower_warning_limit = low;
4250 d.lower_alarm_limit = lolo;
4251 }
4252 }
4253 if let Some((upper, lower)) = ov.ctrl_limits {
4254 let c = snap.control.get_or_insert_with(Default::default);
4255 c.upper_ctrl_limit = upper;
4256 c.lower_ctrl_limit = lower;
4257 }
4258 }
4259
4260 /// C's rset metadata slots route **per field**, on `dbGetFieldIndex`. The
4261 /// port's metadata cache is the record's VAL metadata, and serving it to
4262 /// every field is what made a non-VAL field report VAL's limits.
4263 ///
4264 /// Every base record's `get_control_double` / `get_alarm_double` has the
4265 /// same two-arm shape: a listed set of field indices that take the
4266 /// record's own limits, and a `default:` arm that hands the field to
4267 /// `recGblGetControlDouble` / `recGblGetAlarmDouble` — the field TYPE's
4268 /// numeric range, and four NaN. This routes the `default:` arm; a listed
4269 /// field keeps the cache, which already holds exactly the record's own
4270 /// limits (and already distinguishes `ao`'s DRVH/DRVL from `ai`'s
4271 /// HOPR/LOPR).
4272 ///
4273 /// The three slots' listed sets are **different**, and each has its own
4274 /// owner here: [`Self::control_explicit_field`],
4275 /// [`Self::graphic_explicit_field`] and [`Self::alarm_explicit_field`].
4276 /// They are separate switches over separate field lists in C, so the
4277 /// membership question is asked once per slot, never once for both — and
4278 /// each list varies by record TYPE, so it is asked once per type too.
4279 ///
4280 /// Measured on a real `softIocPVX` against `record(calc,"X"){}`:
4281 /// `.PHAS` (DBF_SHORT, unlisted) serves control ±32767 — the SHRT range —
4282 /// while `.VAL` and `.HIHI` (both listed) serve 0/0 from HOPR/LOPR.
4283 ///
4284 /// Deliberately NOT routed here, and why:
4285 ///
4286 /// * **display (graphic) limits.** Unlike control, the `default:` arm of
4287 /// `get_graphic_double` tries a LINK first
4288 /// (`calcRecord.c` `get_linkNumber` → `dbGetGraphicLimits`) and only
4289 /// falls to `recGbl` for a field that backs no link. A constant (unset)
4290 /// link has no metadata getters, so the `dbAccess.c:216` 0/0 seed stands
4291 /// — measured: `CALC.A` serves display 0/0 but control ±1e300. Which
4292 /// fields back links is per-record C knowledge the port models nowhere
4293 /// (no `FieldDesc` relation, no trait hook), so defaulting display to the
4294 /// type range would CREATE defects on every link-backed field.
4295 /// * **units / precision.** Same link-first shape
4296 /// (`calcRecord.c` `get_units`, `get_precision`).
4297 ///
4298 /// Both remain a measured residue rather than a guess.
4299 ///
4300 /// The last arm is not the same for every record type — a slot can also
4301 /// fall through WITHOUT delegating, keeping the seed. That fact is one bit
4302 /// per record type, read from its C source: [`control_default_arm`].
4303 fn route_field_metadata(&self, field: &str, snap: &mut super::super::snapshot::Snapshot) {
4304 // The rset slots this record type actually supplies. A NULL slot makes
4305 // `dbAccess.c` clear the option bit, so the leaf is never served and
4306 // there is nothing to route — minting a value here would put a
4307 // fabricated number on the CA wire, which has no marking layer to
4308 // suppress it (`codec.rs` `get_limits` reads these structs ungated).
4309 let slots = self.record.property_support();
4310 let rtype = self.record.record_type();
4311
4312 // C `get_control_double`'s last arm. No base record routes control
4313 // through a link: `dbGetControlLimits` has zero callers in all of
4314 // base, so unlike display this arm needs no link branch.
4315 if slots.control_double && !Self::control_explicit_field(rtype, field) {
4316 let (upper, lower) =
4317 match super::record_trait::control_default_arm(self.record.record_type()) {
4318 // `recGblGetControlDouble` → `getMaxRangeValues(field_type)`.
4319 // A type with no case in C's switch (STRING/MENU/DEVICE/links)
4320 // is written by nothing, leaving the `dbAccess.c:256` seed —
4321 // which is 0/0, exactly what `unwrap_or` supplies.
4322 super::record_trait::RsetDefaultArm::RecGblRange => {
4323 self.rec_gbl_range_for(field).unwrap_or((0.0, 0.0))
4324 }
4325 // The slot exists but writes nothing here, so the same
4326 // `dbAccess.c:256` seed stands. Modelled as a value rather
4327 // than as `None`: C's option bit is ON (the slot is supplied
4328 // and returned 0), so the leaf IS served — carrying the seed.
4329 super::record_trait::RsetDefaultArm::Seed => (0.0, 0.0),
4330 };
4331 snap.control = Some(super::super::snapshot::ControlInfo {
4332 upper_ctrl_limit: upper,
4333 lower_ctrl_limit: lower,
4334 });
4335 }
4336
4337 // C `get_graphic_double`'s last arm. Unlike control this one has a LINK
4338 // branch ahead of the recGbl call, so the three answers are: keep the
4339 // cache (listed on HOPR/LOPR), the link's limits, or the default arm.
4340 if slots.graphic_double && !Self::graphic_explicit_field(rtype, field) {
4341 let (upper, lower) = if Self::graphic_link_backed_field(rtype, field) {
4342 // `dbGetGraphicLimits` on a CONSTANT link writes nothing — a
4343 // constant has no metadata getters — so the `dbAccess.c:216`
4344 // seed stands. The port has no link metadata to consult, and a
4345 // link that IS connected would be answered by the upstream
4346 // record, which this routing does not model either; both land
4347 // here as the seed.
4348 (0.0, 0.0)
4349 } else {
4350 match super::record_trait::graphic_default_arm(rtype) {
4351 super::record_trait::RsetDefaultArm::RecGblRange => {
4352 self.rec_gbl_range_for(field).unwrap_or((0.0, 0.0))
4353 }
4354 super::record_trait::RsetDefaultArm::Seed => (0.0, 0.0),
4355 }
4356 };
4357 let d = snap.display.get_or_insert_with(Default::default);
4358 d.upper_disp_limit = upper;
4359 d.lower_disp_limit = lower;
4360 }
4361
4362 // C `get_alarm_double`, BOTH arms. This branch owns the four limits
4363 // outright: `slots.alarm_double` is exactly the condition under which
4364 // `getProperties` assigns the four `valueAlarm.*Limit` leaves, so
4365 // whenever the leaves are served this assigns them.
4366 //
4367 // The explicit arm used to be left to the record-level metadata cache
4368 // (`populate_display_info`), whose `match rtype` covered only some of
4369 // the types that supply the slot. A type it missed reached the wire
4370 // with `snap.display == None` and the four leaves kept the NT's
4371 // structural 0 — measured: DFANOUT.VAL, SEL.VAL and SUB.VAL served 0
4372 // where C serves NaN. That made "which limits does VAL carry" depend on
4373 // a match arm existing somewhere else, which is the dual meaning this
4374 // single owner removes.
4375 if slots.alarm_double {
4376 let (hihi, high, low, lolo) = if Self::alarm_explicit_field(rtype, field) {
4377 self.explicit_alarm_limits(rtype)
4378 } else {
4379 // The link-backed sibling arm lands on the same answer:
4380 // `dbAccess.c:294` seeds four NaN, and a constant link supplies
4381 // no alarm limits to overwrite them.
4382 crate::server::recgbl::rec_gbl_get_alarm_double()
4383 };
4384 // The four alarm limits live on DisplayInfo because that mirrors
4385 // C's `dbr_gr_double` packing, which the CA encoder depends on.
4386 // Minting it here is safe: every other DisplayInfo field defaults
4387 // to the same value the `None` path already served.
4388 let d = snap.display.get_or_insert_with(Default::default);
4389 d.upper_alarm_limit = hihi;
4390 d.upper_warning_limit = high;
4391 d.lower_warning_limit = low;
4392 d.lower_alarm_limit = lolo;
4393 }
4394 }
4395
4396 /// The four limits C's `get_alarm_double` serves for the fields its rset
4397 /// lists — [`alarm_explicit_fields`](super::record_trait::alarm_explicit_fields).
4398 ///
4399 /// Read through [`Self::resolve_field`], the same unified accessor C's
4400 /// `prec->hihi` is. The port stores the eight alarm fields in one of two
4401 /// disjoint homes — `common.analog_alarm` for the types with the analog
4402 /// ladder (`ai`/`ao`/`calc`/…), the record's own struct for the types
4403 /// without it (`dfanout`/`sel`) — and `resolve_field` spans both. Reading
4404 /// the ladder slot directly instead would answer NaN for every `dfanout`
4405 /// and `sel` no matter how its HIHI/HHSV were set, because those two types
4406 /// have no slot at all.
4407 fn explicit_alarm_limits(&self, rtype: &str) -> (f64, f64, f64, f64) {
4408 let limit = |name: &str| {
4409 self.resolve_field(name)
4410 .and_then(|v| v.to_f64())
4411 .unwrap_or(0.0)
4412 };
4413 // The raw stored ordinal, NOT clamped to 0..=3: C tests `prec->hhsv`
4414 // for NONZERO, so an out-of-range severity still enables its limit.
4415 let severity = |name: &str| {
4416 self.resolve_field(name)
4417 .and_then(|v| v.to_f64())
4418 .unwrap_or(0.0) as i16
4419 };
4420 match super::record_trait::alarm_val_arm(rtype) {
4421 super::record_trait::AlarmValArm::Unconditional => {
4422 (limit("HIHI"), limit("HIGH"), limit("LOW"), limit("LOLO"))
4423 }
4424 super::record_trait::AlarmValArm::Gated => (
4425 gated(severity("HHSV"), limit("HIHI")),
4426 gated(severity("HSV"), limit("HIGH")),
4427 gated(severity("LSV"), limit("LOW")),
4428 gated(severity("LLSV"), limit("LOLO")),
4429 ),
4430 }
4431 }
4432
4433 /// The fields C's **`get_control_double`** answers with the record's own
4434 /// cached limits, rather than letting them fall to the `default:` arm.
4435 ///
4436 /// "VAL plus the seven alarm bands" is one type's list, not the shared
4437 /// one: it holds for `ai` (`aiRecord.c:267-288`), `ao`, `calc`, `calcout`,
4438 /// `longin`, `longout`, `int64in`, `int64out` and `sub`
4439 /// (`subRecord.c:272-292`) — the `_` arm — and for no other type. Every
4440 /// list below is transcribed from that type's own rset:
4441 ///
4442 /// * `aSub` (`aSubRecord.c:372-376`) is a bare `recGblGetControlDouble`:
4443 /// it lists NOTHING, VAL included.
4444 /// * `seq` (`seqRecord.c:342-353`) lists only DLYn and `bo`
4445 /// (`boRecord.c:310-318`) only HIGH — and both answer a LITERAL rather
4446 /// than the cache, so they come from
4447 /// [`Record::field_metadata_override`] (which runs after this routing
4448 /// and wins over the `default:` arm). Nothing of these two types keeps
4449 /// the cache, VAL included.
4450 /// * `dfanout` (`dfanoutRecord.c:197-213`) lists VAL and the three
4451 /// latches but NOT the four bands.
4452 /// * `sel` (`selRecord.c:203-235`) lists the eight plus `A`..`L` /
4453 /// `LA`..`LL`; `acalcout`/`scalcout` (`aCalcoutRecord.c:793-822`,
4454 /// `sCalcoutRecord.c:653-680`) list VAL and the four bands but NOT the
4455 /// latches, plus `A`..`L` / `PA`..`PL`.
4456 /// * `epid` (`epidRecord.c:157-180`) lists VAL, the four bands and CVAL on
4457 /// HOPR/LOPR; `motor` (`motorRecord.cc:3269-3305`) lists VAL and RBV on
4458 /// HLM/LLM.
4459 /// * the array types (`waveformRecord.c:268-289`, `aaiRecord.c:293-310`,
4460 /// `aaoRecord.c:296-313`, `compressRecord.c:487-502`,
4461 /// `histogramRecord.c:458-475`, `subArrayRecord.c:262-291`) list VAL
4462 /// alone on the cache — their other listed fields answer computed spans,
4463 /// so those too come from [`Record::field_metadata_override`].
4464 ///
4465 /// Fields whose listed case answers something OTHER than the record's
4466 /// cached limits are deliberately absent — `motor`'s DVAL/DRBV (DHLM/DLLM)
4467 /// and `epid`'s OVAL/P/I/D (DRVH/DRVL) have no override yet and so still
4468 /// take the `default:` arm.
4469 ///
4470 /// **Not** the other two slots' lists — see [`Self::alarm_explicit_field`]
4471 /// (smaller) and [`Self::graphic_explicit_field`] (larger, and cut short
4472 /// for different types). C's three rset arms are separate switches over
4473 /// separate field lists, so one shared predicate could only ever be right
4474 /// for one of them.
4475 fn control_explicit_field(rtype: &str, field: &str) -> bool {
4476 // The two types that list nothing the cache can answer, VAL included.
4477 if matches!(rtype, "aSub" | "seq" | "bo") {
4478 return false;
4479 }
4480 if crate::server::database::is_value_field(field) {
4481 return true;
4482 }
4483 let f = field.to_ascii_uppercase();
4484 let bands: &[&str] = match rtype {
4485 "dfanout" => &["LALM", "ALST", "MLST"],
4486 "acalcout" | "scalcout" | "epid" => &["HIHI", "HIGH", "LOW", "LOLO"],
4487 "waveform" | "aai" | "aao" | "compress" | "histogram" | "subArray" | "motor" => &[],
4488 _ => &["HIHI", "HIGH", "LOW", "LOLO", "LALM", "ALST", "MLST"],
4489 };
4490 if bands.contains(&f.as_str()) {
4491 return true;
4492 }
4493 match rtype {
4494 // sel's args are 12 (`SEL_MAX`), not the calc family's 21.
4495 "sel" => Self::calc_arg_field(&f, 12),
4496 "acalcout" | "scalcout" => {
4497 Self::calc_arg_field(&f, 12)
4498 || matches!(f.as_bytes(), [b'P', c] if c.is_ascii_uppercase() && *c <= b'L')
4499 }
4500 "epid" => f == "CVAL",
4501 "motor" => f == "RBV",
4502 _ => false,
4503 }
4504 }
4505
4506 /// The fields C's **`get_alarm_double`** lists explicitly — **VAL alone**,
4507 /// not the eight [`Self::control_explicit_field`] lists.
4508 ///
4509 /// Transcribed from every rset in base that supplies the slot; each is a
4510 /// bare `if (dbGetFieldIndex(paddr) == indexof(VAL))` with every other
4511 /// field falling to `recGblGetAlarmDouble` (`recGbl.c:155-162`, four NaN):
4512 /// `aiRecord.c:293`, `aoRecord.c:365`, `calcRecord.c:258`,
4513 /// `calcoutRecord.c`, `dfanoutRecord.c:216`, `int64inRecord.c:235`,
4514 /// `int64outRecord.c`, `longinRecord.c`, `longoutRecord.c`,
4515 /// `selRecord.c:222`, `subRecord.c:236`.
4516 ///
4517 /// So `.HIHI` serves VAL's *control* limits but NOT VAL's *alarm* limits —
4518 /// the band fields' four alarm limits are the recGbl NaN. Routing both
4519 /// slots off one VAL-class predicate is what put the record's own
4520 /// valueAlarm limits on all eight.
4521 ///
4522 /// Which fields each type lists — and the fact that some list none, and
4523 /// that `motor` lists two — is one per-type table,
4524 /// [`alarm_explicit_fields`](super::record_trait::alarm_explicit_fields);
4525 /// what that listed arm ANSWERS is its twin,
4526 /// [`alarm_val_arm`](super::record_trait::alarm_val_arm). Keeping the two
4527 /// questions in one place is what lets this predicate stay a pure
4528 /// membership test.
4529 fn alarm_explicit_field(rtype: &str, field: &str) -> bool {
4530 super::record_trait::alarm_explicit_fields(rtype)
4531 .iter()
4532 .any(|f| field.eq_ignore_ascii_case(f))
4533 }
4534
4535 /// `A`..`A+n-1` (a single letter) or `LA`..`LA+n-1` — C's calc-family
4536 /// argument fields, addressed by index range rather than by name.
4537 ///
4538 /// `calcRecord.c:161-167` / `calcoutRecord.c:417-423` test
4539 /// `idx >= indexof(A) && idx < indexof(A) + CALCPERFORM_NARGS`, and the dbd
4540 /// declares those `CALCPERFORM_NARGS` fields contiguously as the single
4541 /// letters `A`..`U` (`postfix.h:29` = 21, `calcRecord.dbd.pod:801-985`), so
4542 /// the index range and the letter range are the same set.
4543 fn calc_arg_field(field: &str, nargs: u8) -> bool {
4544 let last = b'A' + nargs - 1;
4545 match field.as_bytes() {
4546 [c] => c.is_ascii_uppercase() && *c <= last,
4547 [b'L', c] => c.is_ascii_uppercase() && *c <= last,
4548 _ => false,
4549 }
4550 }
4551
4552 /// The fields C's **`get_graphic_double`** answers with the record's own
4553 /// `HOPR`/`LOPR` — which is exactly what the VAL metadata cache already
4554 /// holds, so routing must leave them on it.
4555 ///
4556 /// The third membership question, and a third distinct set: the alarm arm
4557 /// lists VAL alone and the control arm lists the eight, but graphic lists
4558 /// the eight PLUS a per-type tail, and two types cut it short.
4559 ///
4560 /// * base analog (`aiRecord.c:244-266`, `aoRecord.c:316-339`,
4561 /// `calcRecord.c:187-212`, `calcoutRecord.c:452-484`,
4562 /// `subRecord.c:222-247`, `selRecord.c:181-201`,
4563 /// `dfanoutRecord.c:181-195`, `longinRecord.c:190-204`,
4564 /// `longoutRecord.c`, `int64inRecord.c:196-210`, `int64outRecord.c`):
4565 /// the eight.
4566 /// * `acalcout`/`scalcout` (`aCalcoutRecord.c:1046`, `sCalcoutRecord.c:906`)
4567 /// list only VAL/HIHI/HIGH/LOW/LOLO — NOT LALM/ALST/MLST — plus the
4568 /// `A`..`L` and `PA`..`PL` ranges.
4569 /// * `sel` (`selRecord.c:193-196`) also lists `A`..`L` / `LA`..`LL`, via a
4570 /// GCC case range. It has no link arm at all, so its args are HOPR/LOPR
4571 /// where calc's identically-named ones are link-backed.
4572 /// * the SVAL family (`aiRecord.c:253`, `longinRecord.c`,
4573 /// `int64inRecord.c:205`), `ao`'s `OVAL`/`PVAL`/`IVOV`
4574 /// (`aoRecord.c:322-338`), and `compress`'s `IHIL`/`ILIL`
4575 /// (`compressRecord.c:474-476`).
4576 ///
4577 /// Fields whose graphic case answers something OTHER than HOPR/LOPR are
4578 /// NOT here — they cannot keep the cache and are supplied by
4579 /// [`Record::field_metadata_override`] instead (`histogram` WDTH,
4580 /// `subArray`/`waveform`/`aai`/`aao` index fields, `seq` DLYn,
4581 /// `calcout` ODLY).
4582 fn graphic_explicit_field(rtype: &str, field: &str) -> bool {
4583 // The two types that do not list VAL. Neither switch is keyed on
4584 // VAL at all: `seqRecord.c:282-297` keys on `index - indexof(DLY0)`,
4585 // so every field BELOW DLY0 — VAL included — reaches
4586 // `recGblGetGraphicDouble`; `aSubRecord.c:350-368` keys on the link
4587 // number, and VAL is neither an inlink nor an outlink, so it falls out
4588 // having written nothing (the `graphic_default_arm` Seed).
4589 //
4590 // Measured: `SEQ.VAL` served display 0/0 — the empty VAL cache — where
4591 // C serves the DBF_LONG range.
4592 if matches!(rtype, "seq" | "aSub") {
4593 return false;
4594 }
4595 if crate::server::database::is_value_field(field) {
4596 return true;
4597 }
4598 let f = field.to_ascii_uppercase();
4599 let bands: &[&str] = match rtype {
4600 "acalcout" | "scalcout" => &["HIHI", "HIGH", "LOW", "LOLO"],
4601 _ => &["HIHI", "HIGH", "LOW", "LOLO", "LALM", "ALST", "MLST"],
4602 };
4603 if bands.contains(&f.as_str()) {
4604 return true;
4605 }
4606 match rtype {
4607 "ai" | "longin" | "int64in" => f == "SVAL",
4608 "ao" => matches!(f.as_str(), "OVAL" | "PVAL" | "IVOV"),
4609 "compress" => matches!(f.as_str(), "IHIL" | "ILIL"),
4610 // sel's args are 12 (`SEL_MAX`), not the calc family's 21.
4611 "sel" => Self::calc_arg_field(&f, 12),
4612 // A..L and PA..PL, both to HOPR/LOPR.
4613 "acalcout" | "scalcout" => {
4614 Self::calc_arg_field(&f, 12)
4615 || matches!(f.as_bytes(), [b'P', c] if c.is_ascii_uppercase() && *c <= b'L')
4616 }
4617 _ => false,
4618 }
4619 }
4620
4621 /// The fields whose C `get_graphic_double` routes through a LINK —
4622 /// `dbGetGraphicLimits` on the link that backs the field, not the field's
4623 /// own type range.
4624 ///
4625 /// This is the one thing display needs that control never did:
4626 /// `dbGetControlLimits` has zero callers in all of base, so the control
4627 /// arm had no link branch to model. Graphic does, and it is what makes the
4628 /// display default arm NOT a straight flip to the type range.
4629 ///
4630 /// A link left unset is a CONSTANT link, which supplies no metadata
4631 /// getters, so `dbGetGraphicLimits` writes nothing and the
4632 /// `dbAccess.c:216` `(0.0, 0.0)` seed stands — measured: `CALC.A` serves
4633 /// display 0/0 where its DBF_DOUBLE type range would be ±1e300, while
4634 /// `CALC.PHAS` (no link) serves the DBF_SHORT range ±32767.
4635 ///
4636 /// Four types, both by mechanical index test:
4637 /// * `calc`/`calcout`/`sub` — `get_linkNumber` (`calcRecord.c:161-167`,
4638 /// `calcoutRecord.c:417-423`, `subRecord.c:198-204`): `A`..`A+NARGS` and
4639 /// `LA`..`LA+NARGS`, both onto `&prec->inpa + n`. calc/calcout use
4640 /// `CALCPERFORM_NARGS` (21); `sub` uses `INP_ARG_MAX`
4641 /// (`subRecord.c:89`), also 21.
4642 /// * `seq` — `seqRecord.c:322-338`: field offset from `DLY0` with
4643 /// `offset & 3 == 2` is `DOn`, routed through `get_dol(prec, offset)`.
4644 ///
4645 /// `sel` names its args the same way and is deliberately NOT here: its
4646 /// rset lists them explicitly on HOPR/LOPR and calls `dbGetGraphicLimits`
4647 /// nowhere.
4648 fn graphic_link_backed_field(rtype: &str, field: &str) -> bool {
4649 let f = field.to_ascii_uppercase();
4650 match rtype {
4651 "calc" | "calcout" | "sub" => Self::calc_arg_field(&f, 21),
4652 // DLY0/DOL0/DO0/LNK0, DLY1/... — DOn is offset 2 of each group of
4653 // four, i.e. the `DO` prefix over the same 0-F suffix set.
4654 "seq" => {
4655 matches!(f.as_bytes(), [b'D', b'O', c] if c.is_ascii_digit() || (b'A'..=b'F').contains(c))
4656 }
4657 _ => false,
4658 }
4659 }
4660
4661 /// The field's type as the **dbd declares it**, which is the only type
4662 /// `recGblGetPrec` / `getMaxRangeValues` ever see.
4663 ///
4664 /// C reads `pdbFldDes->field_type` (`recGbl.c:127`, `:151`, `:169`) — the
4665 /// STATIC descriptor — so a `cvt_dbaddr` retype (the port's
4666 /// `runtime_typed`, DBF_NOACCESS in the dbd) never reaches the switch and
4667 /// the switch has no case for it. `None` reproduces that: no case, no
4668 /// write.
4669 fn static_field_type(&self, field: &str) -> Option<crate::types::DbFieldType> {
4670 let desc = self.field_desc(field)?;
4671 (!desc.runtime_typed).then_some(desc.dbf_type)
4672 }
4673
4674 /// `recGblGetGraphicDouble` / `recGblGetControlDouble` for `field` — the
4675 /// same `getMaxRangeValues` table both C entry points share
4676 /// (`recGbl.c:146-171`). `None` where C's switch has no case (STRING,
4677 /// MENU, DEVICE, NOACCESS, links), which writes nothing.
4678 fn rec_gbl_range_for(&self, field: &str) -> Option<(f64, f64)> {
4679 let desc = self.field_desc(field)?;
4680 crate::server::recgbl::rec_gbl_get_graphic_double(
4681 self.static_field_type(field),
4682 desc.menu.is_some(),
4683 )
4684 }
4685
4686 /// Notify subscribers from a snapshot (call outside lock).
4687 /// Each entry carries its own posting mask: only subscribers whose
4688 /// mask intersects that field's mask are notified, and the
4689 /// delivered [`MonitorEvent`] reports exactly that field's classes
4690 /// (C `db_post_events(prec, &field, mask)` per-field granularity).
4691 pub fn notify_from_snapshot(&self, snapshot: &ProcessSnapshot) {
4692 use crate::server::database::filters::FilteredMonitorEvent;
4693 use crate::server::recgbl::EventMask;
4694
4695 for (field, value, posting_mask) in &snapshot.changed_fields {
4696 let posting_mask = *posting_mask;
4697 if let Some(subs) = self.subscribers.get(field) {
4698 // Build a full snapshot once per field (with display metadata)
4699 let mon_snap = self.make_monitor_snapshot(field, value.clone());
4700 for sub in subs {
4701 // Paused subscriber (`db_event_disable`): suppress at
4702 // the source — no delivery, no coalesce.
4703 if !sub.active {
4704 continue;
4705 }
4706 let sub_mask = EventMask::from_bits(sub.mask);
4707 // Only send when posting mask intersects subscriber mask.
4708 // Empty posting mask means nothing changed — skip.
4709 if !posting_mask.is_empty() && sub_mask.intersects(posting_mask) {
4710 let event = MonitorEvent {
4711 snapshot: mon_snap.clone(),
4712 origin: 0,
4713 mask: posting_mask,
4714 };
4715 // Server-side filter chain (3.15.7). Empty chain
4716 // is identity, so no behaviour change for the
4717 // common no-filter case.
4718 let filtered = if sub.filters.is_empty() {
4719 Some(event)
4720 } else {
4721 sub.filters
4722 .apply(FilteredMonitorEvent::new(event))
4723 .map(|fe| fe.event)
4724 };
4725 let Some(event) = filtered else {
4726 continue;
4727 };
4728 // C `db_queue_event_log`: append, or replace this
4729 // monitor's last queued entry in place when the queue
4730 // is in flow control or nearly full. The queue owns
4731 // that decision and counts the displaced value.
4732 sub.post(event);
4733 }
4734 }
4735 }
4736 }
4737 }
4738
4739 /// Notify subscribers of a specific field, filtering by event mask.
4740 pub fn notify_field(&mut self, field: &str, mask: crate::server::recgbl::EventMask) {
4741 self.notify_field_with_origin(field, mask, 0);
4742 }
4743
4744 /// C `db_post_events(precord, NULL, DBE_ALARM)`: post a record-wide
4745 /// alarm event. Delivers to every subscriber on any field whose mask
4746 /// includes DBE_ALARM, each carrying its own monitored field's current
4747 /// value (the per-field `notify_field` already filters by mask
4748 /// intersection). Used by the alarm-acknowledge (ACKT/ACKS) put path so
4749 /// an alarm-mask monitor on any field observes the acknowledgement.
4750 pub fn notify_record_alarm(&mut self) {
4751 let fields: Vec<String> = self.subscribers.keys().cloned().collect();
4752 for field in fields {
4753 self.notify_field(&field, crate::server::recgbl::EventMask::ALARM);
4754 }
4755 }
4756
4757 /// Notify subscribers with an origin tag for self-write filtering.
4758 ///
4759 /// This is C `db_post_events(precord, pfield, mask)` for one field, and —
4760 /// per the `last_posted` contract — the poster that advances the
4761 /// already-published value when `mask` carries a value class. Taking
4762 /// `&mut self` is what makes that unbypassable: there is no way to publish
4763 /// a field's value through the framework without the change detector
4764 /// learning that it was published.
4765 pub fn notify_field_with_origin(
4766 &mut self,
4767 field: &str,
4768 mask: crate::server::recgbl::EventMask,
4769 origin: u64,
4770 ) {
4771 use crate::server::database::filters::FilteredMonitorEvent;
4772 // A value-class post publishes the field to its DBE_VALUE/DBE_LOG
4773 // subscribers, exactly as C's `dbPut` does for the put field
4774 // (dbAccess.c:1414) — record it so the next process cycle's
4775 // change-detection loop does not publish the same value a second
4776 // time. An alarm-only / property-only post publishes no value, so it
4777 // leaves the map alone.
4778 let publishes_value = mask.intersects(
4779 crate::server::recgbl::EventMask::VALUE | crate::server::recgbl::EventMask::LOG,
4780 );
4781 let mut posted: Option<EpicsValue> = None;
4782 if let Some(subs) = self.subscribers.get(field) {
4783 if let Some(value) = self.resolve_field(field) {
4784 if publishes_value {
4785 posted = Some(value.clone());
4786 }
4787 let mon_snap = self.make_monitor_snapshot(field, value);
4788 for sub in subs {
4789 // Paused subscriber (`db_event_disable`): suppress at
4790 // the source — no delivery, no coalesce.
4791 if !sub.active {
4792 continue;
4793 }
4794 let sub_mask = crate::server::recgbl::EventMask::from_bits(sub.mask);
4795 if mask.is_empty() || sub_mask.intersects(mask) {
4796 let event = MonitorEvent {
4797 snapshot: mon_snap.clone(),
4798 origin,
4799 mask,
4800 };
4801 // Server-side filter chain (3.15.7). Empty
4802 // chain (the default for every subscriber
4803 // until a `.{filter:opts}` PV-name suffix
4804 // parser wires one in) is the identity, so
4805 // existing subscribers see no behaviour
4806 // change. A filter returning `None` silences
4807 // this event for this subscriber only.
4808 let filtered = if sub.filters.is_empty() {
4809 Some(event)
4810 } else {
4811 sub.filters
4812 .apply(FilteredMonitorEvent::new(event))
4813 .map(|fe| fe.event)
4814 };
4815 let Some(event) = filtered else {
4816 continue;
4817 };
4818 // Same single post owner as the snapshot path.
4819 sub.post(event);
4820 }
4821 }
4822 }
4823 }
4824 // The value is now published to this field's value-class subscribers:
4825 // hand it to the `last_posted` owner so the change detector does not
4826 // publish it again. Delivery to any individual subscriber may have
4827 // been filtered out, exactly as C's `db_post_events` may find an empty
4828 // `mlis` — C still leaves `monitor()`'s `*_lst` state advanced by the
4829 // cycle that ran, so the post, not the delivery, is what counts.
4830 if let Some(value) = posted {
4831 self.record_value_post(field, value);
4832 }
4833 }
4834
4835 /// Add a subscriber for a specific field. Returns `None` when the
4836 /// per-field subscriber cap (`EPICS_CAS_MAX_SUBSCRIBERS_PER_PV`)
4837 /// is reached. the parallel cap on `ProcessVariable`
4838 /// defends against a misbehaving client opening many
4839 /// MONITOR ops against one shared PV; the same defence is needed
4840 /// for record fields, which the CA server's
4841 /// `ChannelTarget::RecordField` path lands on.
4842 pub fn add_subscriber(
4843 &mut self,
4844 field: &str,
4845 sid: u32,
4846 data_type: DbFieldType,
4847 mask: u16,
4848 ) -> Option<EventReader> {
4849 self.add_subscriber_on(&EventUser::new(), field, sid, data_type, mask)
4850 }
4851
4852 /// Add a field subscriber whose events queue on `user`'s event queue —
4853 /// C `db_add_event` with the circuit's `event_user` as context. Every
4854 /// subscription on one CA circuit shares that queue and therefore its
4855 /// `nDuplicates`, so a duplicate queued for one of them releases the
4856 /// EVENTS_OFF drain for all of them (`dbEvent.c:947`). In-process consumers
4857 /// use [`Self::add_subscriber`], which gives each its own `event_user`.
4858 pub fn add_subscriber_on(
4859 &mut self,
4860 user: &EventUser,
4861 field: &str,
4862 sid: u32,
4863 data_type: DbFieldType,
4864 mask: u16,
4865 ) -> Option<EventReader> {
4866 let cap = crate::server::pv::max_subscribers_per_pv();
4867 let field_str = field.to_string();
4868 let bucket = self.subscribers.entry(field_str.clone()).or_default();
4869 // Reap rows whose consumer is gone before
4870 // counting against the cap. A record field whose value
4871 // never changes (e.g. a quasi-static catalog field) never
4872 // triggers `notify_field_with_origin`'s retain-filter, so
4873 // a long-lived subscribe-disconnect storm could pin the
4874 // bucket at `cap` worth of dead rows and lock out
4875 // genuine new subscribers.
4876 bucket.retain(|s| !s.is_closed());
4877 if bucket.len() >= cap {
4878 tracing::warn!(
4879 record = %self.name,
4880 field = %field_str,
4881 live = bucket.len(),
4882 cap,
4883 "record field subscriber cap reached, refusing add_subscriber"
4884 );
4885 return None;
4886 }
4887 let (sink, reader) = crate::server::event_queue::attach(user, sid);
4888 bucket.push(Subscriber {
4889 sid,
4890 data_type,
4891 mask,
4892 sink,
4893 filters: crate::server::database::filters::FilterChain::new(),
4894 active: true,
4895 });
4896 // Initialize last_posted with current value so the first process cycle
4897 // doesn't treat it as "changed" (the initial value is already sent
4898 // to the client as part of EVENT_ADD response).
4899 if !self.last_posted.contains_key(&field_str) {
4900 if let Some(val) = self.resolve_field(&field_str) {
4901 self.last_posted.insert(field_str, val);
4902 }
4903 }
4904 Some(reader)
4905 }
4906
4907 /// Attach a filter to the most recently added subscriber for
4908 /// `field`. Returns `false` when no subscriber exists yet on that
4909 /// field (call `add_subscriber` first). The CA / PVA channel-name
4910 /// parsers will use this once `.{filter:opts}` syntax is wired.
4911 /// Tests can also use it directly to compose filter chains.
4912 pub fn attach_filter_to_last_subscriber(
4913 &mut self,
4914 field: &str,
4915 filter: std::sync::Arc<dyn crate::server::database::filters::SubscriptionFilter>,
4916 ) -> bool {
4917 if let Some(bucket) = self.subscribers.get_mut(field) {
4918 if let Some(sub) = bucket.last_mut() {
4919 sub.filters.push(filter);
4920 return true;
4921 }
4922 }
4923 false
4924 }
4925
4926 /// Remove a subscriber by subscription ID from all fields.
4927 pub fn remove_subscriber(&mut self, sid: u32) {
4928 for subs in self.subscribers.values_mut() {
4929 subs.retain(|s| s.sid != sid);
4930 }
4931 }
4932
4933 /// Pause / resume one subscriber's event flow at the source
4934 /// (`db_event_disable` / `db_event_enable`). `active == false`
4935 /// suppresses every subsequent post to this subscriber, so the record stops
4936 /// doing per-event work for it. Entries already queued stay queued and are
4937 /// still delivered, exactly as in C: `db_event_disable` only unlinks the
4938 /// subscription from the record's monitor list (`dbEvent.c:521-533`) and
4939 /// never reaches into the event queue. No-op if no subscriber has this
4940 /// `sid`. The caller holds the record write lock, so this is exclusive with
4941 /// the read-locked post paths that consult `Subscriber::active`.
4942 pub fn set_subscriber_active(&mut self, sid: u32, active: bool) {
4943 for subs in self.subscribers.values_mut() {
4944 for sub in subs.iter_mut() {
4945 if sub.sid == sid {
4946 sub.active = active;
4947 }
4948 }
4949 }
4950 }
4951
4952 /// Clean up subscriber rows whose consumer is gone.
4953 pub fn cleanup_subscribers(&mut self) {
4954 for subs in self.subscribers.values_mut() {
4955 subs.retain(|s| !s.is_closed());
4956 }
4957 }
4958}
4959
4960/// C `recGblCheckDeadband` parity (recGbl.c:345-370). The four branches
4961/// the C path enumerates:
4962///
4963/// 1. Both `newval` and `oldval` finite: `delta = |old - new|`, fire when
4964/// `delta > deadband`.
4965/// 2. Exactly one of {newval, oldval} is NaN, the other not — OR exactly
4966/// one is +/-inf, the other not: `delta = +inf`, always fires.
4967/// 3. Both infinite with opposite signs: `delta = +inf`, always fires.
4968/// 4. Otherwise (e.g. both NaN, both same-signed infinity): no fire.
4969///
4970/// `oldval = NaN` is treated as "never posted" and fires (matches the
4971/// `mlst.is_nan() → trigger` short-circuit the Rust port already had).
4972/// `deadband < 0` fires unconditionally (matches `delta > deadband`
4973/// with a negative deadband — same effect on every numeric value).
4974pub(crate) fn check_deadband(newval: f64, oldval: f64, deadband: f64) -> bool {
4975 // Fire unconditionally when no prior posting has happened. C achieves
4976 // the same effect through the field being default-initialised to a
4977 // sentinel; Rust uses NaN-as-sentinel.
4978 if oldval.is_nan() {
4979 return true;
4980 }
4981 // Negative deadband short-circuits — any value passes.
4982 if deadband < 0.0 {
4983 return true;
4984 }
4985 let new_finite = newval.is_finite();
4986 let old_finite = oldval.is_finite();
4987 if new_finite && old_finite {
4988 return (newval - oldval).abs() > deadband;
4989 }
4990 // From here on, at least one of the two is not finite. We've already
4991 // ruled out oldval=NaN above, so any newval=NaN here is the "newval
4992 // went NaN while oldval was finite/inf" case — must fire (C case 2).
4993 if newval.is_nan() {
4994 return true;
4995 }
4996 // Exactly one infinite, the other finite: C case 2 → fire.
4997 if new_finite != old_finite {
4998 return true;
4999 }
5000 // Both infinite. Opposite signs → fire (C case 3); same sign → no
5001 // fire (C path leaves delta=0 and the `delta > deadband` check fails
5002 // for any non-negative deadband).
5003 newval != oldval
5004}
5005
5006#[cfg(test)]
5007mod device_menu_marking_tests {
5008 use super::*;
5009 use crate::server::records::ai::AiRecord;
5010 use crate::server::records::calc::CalcRecord;
5011
5012 /// C `dbAccess.c:176-179`: a `DBF_DEVICE` field whose record type declares
5013 /// no device support has `pfldDes->ftPvt == NULL` and takes `goto nostrs`,
5014 /// which clears `DBR_ENUM_STRS` — the client is sent NO choice list.
5015 ///
5016 /// `calc` declares no `device()` line, so QSRV2 omits `value.choices` on
5017 /// `CALC.DTYP`. The port used to default the missing menu to `[]` and mark
5018 /// an empty list instead.
5019 #[test]
5020 fn dtyp_of_a_record_type_with_no_device_support_supplies_no_choices() {
5021 let inst = RecordInstance::new("X".into(), CalcRecord::default());
5022 assert!(
5023 super::super::dbd_generated::device_menu("calc").is_none(),
5024 "precondition: calc declares no device() line (C ftPvt == NULL)"
5025 );
5026 assert!(
5027 inst.device_choices().is_none(),
5028 "a record type with no device menu must report None, not an empty list"
5029 );
5030 assert!(
5031 inst.enum_string_form_for("DTYP").is_none(),
5032 "DTYP must supply no enum-string form, so no `value.choices` is marked"
5033 );
5034 }
5035
5036 /// The other side of C's `dbAccess.c:205` comment — *"indicate option data
5037 /// not available. distinct from no_str==0"*. `ai` DOES declare device
5038 /// support, so its menu exists and its choices are served.
5039 #[test]
5040 fn dtyp_of_a_record_type_with_device_support_supplies_its_choices() {
5041 let inst = RecordInstance::new("X".into(), AiRecord::default());
5042 let choices = inst
5043 .device_choices()
5044 .expect("ai declares device() lines, so its menu exists");
5045 assert!(
5046 choices.iter().any(|c| c.as_str_lossy() == "Soft Channel"),
5047 "ai's device menu must carry its declared choices, got {choices:?}"
5048 );
5049 assert!(inst.enum_string_form_for("DTYP").is_some());
5050 }
5051
5052 /// An unset `DTYP` is index 0 on both sides of the distinction — a record
5053 /// type with no device menu has no slot for any DTYP, so the index stays 0
5054 /// rather than panicking or shifting.
5055 #[test]
5056 fn dtyp_index_is_zero_when_the_record_type_has_no_device_menu() {
5057 let inst = RecordInstance::new("X".into(), CalcRecord::default());
5058 assert_eq!(inst.dtyp_index(), 0);
5059 }
5060}
5061
5062#[cfg(test)]
5063mod property_support_owner_tests {
5064 use crate::server::record::record_trait::default_property_support;
5065 use crate::server::snapshot::PropertySupport as P;
5066
5067 /// `sseqRecord.c:124-144` — the rset table NULLs every property slot
5068 /// except `get_precision`:
5069 ///
5070 /// ```c
5071 /// NULL, /* get_units */
5072 /// get_precision, /* get_precision */
5073 /// NULL, /* get_enum_str */
5074 /// NULL, /* get_enum_strs */
5075 /// NULL, /* put_enum_str */
5076 /// NULL, /* get_graphic_double */
5077 /// NULL, /* get_control_double */
5078 /// NULL /* get_alarm_double */
5079 /// ```
5080 ///
5081 /// `sseq` was previously grouped with the full-numeric synApps types, so
5082 /// the port marked six leaves per field that QSRV2 omits entirely.
5083 #[test]
5084 fn sseq_supplies_only_precision() {
5085 assert_eq!(
5086 default_property_support("sseq"),
5087 P {
5088 precision: true,
5089 ..P::NONE
5090 }
5091 );
5092 }
5093
5094 /// A record type the table does not name keeps the permissive
5095 /// `NUMERIC` default rather than silently losing metadata. This is the
5096 /// arm `asyn` used to land on — and why marking had to become a trait
5097 /// method: asyn-rs cannot add a row here.
5098 #[test]
5099 fn an_untranscribed_record_type_keeps_the_permissive_default() {
5100 assert_eq!(default_property_support("no-such-record-type"), P::NUMERIC);
5101 }
5102}
5103
5104#[cfg(test)]
5105mod metadata_cache_tests {
5106 use super::*;
5107 use crate::server::records::ai::AiRecord;
5108
5109 /// Helper: build an AiRecord wrapped in a RecordInstance with EGU/PREC/HOPR/LOPR set.
5110 fn ai_instance() -> RecordInstance {
5111 let mut rec = AiRecord::default();
5112 let _ = rec.put_field("EGU", EpicsValue::String("degC".into()));
5113 let _ = rec.put_field("PREC", EpicsValue::Short(2));
5114 let _ = rec.put_field("HOPR", EpicsValue::Double(100.0));
5115 let _ = rec.put_field("LOPR", EpicsValue::Double(0.0));
5116 let _ = rec.put_field("VAL", EpicsValue::Double(25.0));
5117 RecordInstance::new("TEMP".to_string(), rec)
5118 }
5119
5120 /// a record-field monitor whose event queue has run short of room
5121 /// replaces its last queued entry in place (C `db_queue_event_log`,
5122 /// `dbEvent.c:812-820`), and the displaced value — which the consumer never
5123 /// observed — must be counted in the shared `dropped_monitor_events()`
5124 /// counter (C `nreplace`), the same accounting a `ProcessVariable` post
5125 /// uses. Before the fix the record-field path overwrote its coalesce slot
5126 /// without counting, hiding slow-consumer loss on the path most CA/PVA
5127 /// database monitors use. The counter is process-global, so the assertion is
5128 /// a strict monotonic increase (robust under parallel tests); the
5129 /// revert-verify runs this test in isolation.
5130 #[test]
5131 fn bfr10_record_field_overflow_counts_dropped_event() {
5132 use crate::server::event_queue::{event_que_size, events_per_que};
5133 use crate::server::pv::dropped_monitor_events;
5134 use crate::server::recgbl::EventMask;
5135 let mut inst = ai_instance();
5136 // Keep the reader alive and do NOT drain, so the ring fills to the
5137 // replace threshold and later posts displace the tail entry.
5138 let _reader = inst
5139 .add_subscriber(
5140 "VAL",
5141 1,
5142 crate::types::DbFieldType::Double,
5143 EventMask::VALUE.bits(),
5144 )
5145 .expect("subscriber added");
5146 let before = dropped_monitor_events();
5147 let posts = event_que_size() - events_per_que() + 10;
5148 for _ in 0..posts {
5149 inst.notify_field_with_origin("VAL", EventMask::VALUE, 0);
5150 }
5151 let after = dropped_monitor_events();
5152 assert!(
5153 after > before,
5154 "a post that replaces an unobserved queued entry must record a \
5155 dropped monitor event (before={before}, after={after})"
5156 );
5157 }
5158
5159 #[test]
5160 fn metadata_field_set_check() {
5161 // Sanity check that the metadata field set is recognized.
5162 assert!(is_metadata_field("EGU"));
5163 assert!(is_metadata_field("PREC"));
5164 assert!(is_metadata_field("HOPR"));
5165 assert!(is_metadata_field("LOPR"));
5166 assert!(is_metadata_field("HIHI"));
5167 assert!(is_metadata_field("DRVH"));
5168 assert!(is_metadata_field("ZNAM"));
5169 assert!(is_metadata_field("ZRST"));
5170 assert!(is_metadata_field("FFST"));
5171
5172 // Non-metadata fields should NOT invalidate the cache
5173 assert!(!is_metadata_field("VAL"));
5174 assert!(!is_metadata_field("DESC"));
5175 assert!(!is_metadata_field("SCAN"));
5176 assert!(!is_metadata_field("PHAS"));
5177 }
5178
5179 #[test]
5180 fn cache_starts_empty_then_populates_on_first_snapshot() {
5181 let inst = ai_instance();
5182
5183 // Cache starts empty
5184 assert!(inst.metadata_cache.lock().unwrap().is_none());
5185
5186 // First snapshot triggers populate + cache store
5187 let snap = inst.snapshot_for_field("VAL").unwrap();
5188 let display = snap.display.expect("ai snapshot must have display");
5189 assert_eq!(display.units, "degC");
5190 assert_eq!(display.precision, 2);
5191 assert_eq!(display.upper_disp_limit, 100.0);
5192 assert_eq!(display.lower_disp_limit, 0.0);
5193
5194 // Cache is now populated
5195 assert!(inst.metadata_cache.lock().unwrap().is_some());
5196 }
5197
5198 #[test]
5199 fn q_form_info_tag_sets_display_form_index() {
5200 // pvxs maps the `Q:form` info tag to `display.form.index` for the
5201 // VAL field (iocsource.cpp:42-62). "Hex" is slot 4 of the
5202 // seven-entry menu (Default/String/Binary/Decimal/Hex/...).
5203 let mut inst = ai_instance();
5204 inst.set_info("Q:form", "Hex");
5205 let snap = inst.snapshot_for_field("VAL").unwrap();
5206 let display = snap.display.expect("ai snapshot must have display");
5207 assert_eq!(display.form, 4, "Q:form=Hex -> display.form index 4");
5208 }
5209
5210 /// R16-31: `Q:form` is a record-level info tag, but QSRV assigns
5211 /// `display.form.index` only when the channel addresses the VAL field
5212 /// (`if(dbIsValueField(dbChannelFldDes(chan)))`, `iocsource.cpp:53`). A
5213 /// snapshot of any other field of the same record reports the default
5214 /// form, on both the GET and the monitor producer.
5215 #[test]
5216 fn q_form_applies_to_the_val_field_only() {
5217 let mut inst = ai_instance();
5218 inst.set_info("Q:form", "Hex");
5219
5220 let val = inst.snapshot_for_field("VAL").unwrap();
5221 assert_eq!(val.display.expect("ai display").form, 4);
5222
5223 for non_val in ["RVAL", "SEVR", "HOPR"] {
5224 let Some(snap) = inst.snapshot_for_field(non_val) else {
5225 panic!("ai.{non_val} must resolve");
5226 };
5227 assert_eq!(
5228 snap.display.expect("ai display").form,
5229 0,
5230 "Q:form must not reach ai.{non_val} — pvxs applies it to VAL only"
5231 );
5232 }
5233
5234 // The monitor producer shares the same per-field owner.
5235 let update = inst.make_monitor_snapshot("RVAL", EpicsValue::Long(7));
5236 assert_eq!(
5237 update.display.expect("ai display").form,
5238 0,
5239 "a monitor update on a non-VAL field carries the default form too"
5240 );
5241 let update = inst.make_monitor_snapshot("VAL", EpicsValue::Double(1.0));
5242 assert_eq!(update.display.expect("ai display").form, 4);
5243 }
5244
5245 #[test]
5246 fn q_form_absent_or_unknown_leaves_form_default() {
5247 // No `Q:form` tag -> form stays 0 (Default).
5248 let inst = ai_instance();
5249 let snap = inst.snapshot_for_field("VAL").unwrap();
5250 assert_eq!(snap.display.expect("ai display").form, 0);
5251
5252 // Unrecognised tag -> pvxs leaves the index untouched (0).
5253 let mut inst2 = ai_instance();
5254 inst2.set_info("Q:form", "Nonsense");
5255 let snap2 = inst2.snapshot_for_field("VAL").unwrap();
5256 assert_eq!(snap2.display.expect("ai display").form, 0);
5257 }
5258
5259 /// `info(Q:time:tag)` resolves to pvxs's `nsecMask`
5260 /// (`ioc/typeutils.cpp:79-88`). The prefix test there is a byte-exact
5261 /// `strncmp("nsec:lsb:", 9)` and the digit count is fed straight to
5262 /// `(uint64_t(1u)<<dig)-1u` — no case folding, no whitespace tolerance
5263 /// around the prefix, and no bounds clamp. Each boundary gets a case.
5264 #[test]
5265 fn qtime_nsec_mask_matches_pvxs_updatensecmask() {
5266 let cases: &[(&str, u64)] = &[
5267 // parses: `epicsParseInt32` skips whitespace around the digits
5268 // and accepts a sign.
5269 ("nsec:lsb:20", (1 << 20) - 1),
5270 ("nsec:lsb:1", 1),
5271 ("nsec:lsb: 4 ", 0xF),
5272 ("nsec:lsb:+4", 0xF),
5273 // no clamp: 31 is the mask pvxs actually serves (the old Rust
5274 // `(1..=30)` guard dropped it), and 0 is pvxs's "off" mask.
5275 ("nsec:lsb:31", 0x7FFF_FFFF),
5276 ("nsec:lsb:0", 0),
5277 // `strncmp` is byte-exact: case-folded or whitespace-split
5278 // prefixes do not match, so pvxs leaves `nsecMask` at 0.
5279 ("NSEC:LSB:4", 0),
5280 ("Nsec:Lsb:4", 0),
5281 ("nsec: lsb: 4", 0),
5282 (" nsec:lsb:4", 0),
5283 // `epicsParseInt32` failures: no conversion, extraneous trailing
5284 // bytes, overflow past epicsInt32.
5285 ("nsec:lsb:", 0),
5286 ("nsec:lsb:abc", 0),
5287 ("nsec:lsb:4x", 0),
5288 ("nsec:lsb:4 5", 0),
5289 ("nsec:lsb:99999999999999999999", 0),
5290 ("nsec:lsb:2147483648", 0),
5291 ];
5292 for (tag, want) in cases {
5293 let mut inst = ai_instance();
5294 inst.set_info("Q:time:tag", *tag);
5295 assert_eq!(
5296 inst.qtime_nsec_mask(),
5297 *want,
5298 "info(Q:time:tag, {tag:?}) must resolve to nsecMask {want:#x}"
5299 );
5300 }
5301 // Tag absent entirely → pvxs never enters the `if(auto val = ...)`
5302 // body and `nsecMask` stays 0.
5303 assert_eq!(ai_instance().qtime_nsec_mask(), 0);
5304 }
5305
5306 /// End-to-end on the snapshot: `nsec:lsb:31` publishes
5307 /// `nanoseconds & ~mask` (0, since nanoseconds < 1e9 < 2^31) and
5308 /// `userTag = nanoseconds & mask` (pvxs `iocsource.cpp:239-248`). The
5309 /// old `(1..=30)` clamp served the raw nanoseconds and the record's
5310 /// utag instead.
5311 #[test]
5312 fn qtime_nsec_lsb_31_is_served_not_ignored() {
5313 use std::time::{Duration, SystemTime};
5314 let mut inst = ai_instance();
5315 // 123_456_700, not …789: Windows `SystemTime` is a FILETIME with 100 ns
5316 // resolution, so a sub-100 ns literal is truncated on readback and the
5317 // assertion below would see …700. Any value < 2^31 exercises the
5318 // nsec:lsb:31 mask identically, so pin one that survives the round trip.
5319 inst.common.time = SystemTime::UNIX_EPOCH + Duration::new(42, 123_456_700);
5320 inst.common.utag = 5;
5321 inst.set_info("Q:time:tag", "nsec:lsb:31");
5322
5323 let snap = inst.snapshot_for_field("VAL").unwrap();
5324 assert_eq!(snap.user_tag, 123_456_700);
5325 assert_eq!(snap.timestamp.subsec_nanos(), 0);
5326 assert_eq!(snap.timestamp.unix_secs(), 42);
5327 }
5328
5329 /// The mirror boundary: a tag pvxs's `strncmp` rejects must leave the
5330 /// timestamp and the record's own utag alone. The old case-insensitive
5331 /// split matched `NSEC:LSB:4` and masked the wire timestamp pvxs serves
5332 /// unmasked.
5333 #[test]
5334 fn qtime_uppercase_tag_leaves_timestamp_untouched() {
5335 use std::time::{Duration, SystemTime};
5336 let mut inst = ai_instance();
5337 // 100 ns-multiple so the subsec_nanos assertion holds on Windows too;
5338 // see qtime_nsec_lsb_31_is_served_not_ignored for the FILETIME reason.
5339 inst.common.time = SystemTime::UNIX_EPOCH + Duration::new(42, 123_456_700);
5340 inst.common.utag = 5;
5341 inst.set_info("Q:time:tag", "NSEC:LSB:4");
5342
5343 let snap = inst.snapshot_for_field("VAL").unwrap();
5344 assert_eq!(
5345 snap.user_tag, 5,
5346 "record utag must survive a non-matching tag"
5347 );
5348 assert_eq!(snap.timestamp.subsec_nanos(), 123_456_700);
5349 }
5350
5351 /// the served `timeStamp.userTag` defaults to the record's `utag`
5352 /// (pvxs `iocsource.cpp:245`), on both the GET (`snapshot_for_field`)
5353 /// and MONITOR (`make_monitor_snapshot`) paths. Pre-fix both hard-set
5354 /// it to 0, dropping the record's tag. A bit-31 utag also pins the
5355 /// `u64 -> i32` narrowing: the low 32 bits' pattern is preserved
5356 /// (no clamp), matching pvxs assigning `epicsUTag` into the `Int32`
5357 /// wire field.
5358 #[test]
5359 fn snapshot_serves_record_utag_as_timestamp_usertag() {
5360 let mut inst = ai_instance();
5361 // no `info(Q:time:tag, ...)` on this record, so the nsec-LSB
5362 // override never fires and the utag default is what is served.
5363 inst.common.utag = 0x9000_0000;
5364 let want = 0x9000_0000u32 as i32;
5365
5366 let get = inst.snapshot_for_field("VAL").unwrap();
5367 assert_eq!(
5368 get.user_tag, want,
5369 "GET path must serve the record's utag as timeStamp.userTag"
5370 );
5371
5372 let mon = inst.make_monitor_snapshot("VAL", EpicsValue::Double(1.0));
5373 assert_eq!(
5374 mon.user_tag, want,
5375 "MONITOR path must carry the record's utag too"
5376 );
5377 }
5378
5379 #[test]
5380 fn cache_hit_returns_same_metadata() {
5381 let inst = ai_instance();
5382
5383 // Prime the cache
5384 let snap1 = inst.snapshot_for_field("VAL").unwrap();
5385 let display1 = snap1.display.unwrap();
5386
5387 // Subsequent snapshots return the same cached metadata
5388 let snap2 = inst.snapshot_for_field("VAL").unwrap();
5389 let display2 = snap2.display.unwrap();
5390
5391 assert_eq!(display1.units, display2.units);
5392 assert_eq!(display1.precision, display2.precision);
5393 assert_eq!(display1.upper_disp_limit, display2.upper_disp_limit);
5394 assert_eq!(display1.lower_disp_limit, display2.lower_disp_limit);
5395 }
5396
5397 #[test]
5398 fn invalidate_clears_cache() {
5399 let inst = ai_instance();
5400 let _ = inst.snapshot_for_field("VAL");
5401 assert!(inst.metadata_cache.lock().unwrap().is_some());
5402
5403 inst.invalidate_metadata_cache();
5404 assert!(inst.metadata_cache.lock().unwrap().is_none());
5405 }
5406
5407 #[test]
5408 fn notify_field_written_invalidates_for_metadata_field() {
5409 let inst = ai_instance();
5410 let _ = inst.snapshot_for_field("VAL");
5411 assert!(inst.metadata_cache.lock().unwrap().is_some());
5412
5413 // Writing a metadata field should invalidate
5414 inst.notify_field_written("EGU");
5415 assert!(inst.metadata_cache.lock().unwrap().is_none());
5416 }
5417
5418 #[test]
5419 fn notify_field_written_skips_non_metadata_field() {
5420 let inst = ai_instance();
5421 let _ = inst.snapshot_for_field("VAL");
5422 assert!(inst.metadata_cache.lock().unwrap().is_some());
5423
5424 // Writing a value field should NOT invalidate the cache
5425 inst.notify_field_written("VAL");
5426 assert!(inst.metadata_cache.lock().unwrap().is_some());
5427
5428 // Same for DESC
5429 inst.notify_field_written("DESC");
5430 assert!(inst.metadata_cache.lock().unwrap().is_some());
5431 }
5432
5433 #[test]
5434 fn notify_field_written_is_case_insensitive() {
5435 let inst = ai_instance();
5436 let _ = inst.snapshot_for_field("VAL");
5437 assert!(inst.metadata_cache.lock().unwrap().is_some());
5438
5439 // Lowercase metadata field name should still trigger invalidation
5440 inst.notify_field_written("egu");
5441 assert!(inst.metadata_cache.lock().unwrap().is_none());
5442 }
5443
5444 /// epics-base faac1df1 — `notify_field_written_if_changed` must
5445 /// SKIP the cache invalidation when the metadata field's value
5446 /// didn't actually change. Otherwise a stream of idempotent puts
5447 /// from a CSS panel binds DBE_PROPERTY subscribers to bogus
5448 /// "property changed" events on every cycle.
5449 #[test]
5450 fn notify_field_written_if_changed_skips_when_unchanged() {
5451 let mut inst = ai_instance();
5452 let _ = inst.snapshot_for_field("VAL");
5453 assert!(inst.metadata_cache.lock().unwrap().is_some());
5454
5455 // Capture prev, do a no-op put, then notify — cache must remain.
5456 let prev = inst.record.get_field("EGU");
5457 let _ = inst.record.put_field("EGU", prev.clone().unwrap());
5458 inst.notify_field_written_if_changed("EGU", prev.as_ref());
5459 assert!(
5460 inst.metadata_cache.lock().unwrap().is_some(),
5461 "no-op put must not invalidate the metadata cache"
5462 );
5463 }
5464
5465 /// And when the value DID change, the cache must invalidate.
5466 #[test]
5467 fn notify_field_written_if_changed_invalidates_on_real_change() {
5468 let mut inst = ai_instance();
5469 let _ = inst.snapshot_for_field("VAL");
5470 assert!(inst.metadata_cache.lock().unwrap().is_some());
5471
5472 let prev = inst.record.get_field("EGU");
5473 let _ = inst
5474 .record
5475 .put_field("EGU", EpicsValue::String("kPa".into()));
5476 inst.notify_field_written_if_changed("EGU", prev.as_ref());
5477 assert!(
5478 inst.metadata_cache.lock().unwrap().is_none(),
5479 "real metadata change must invalidate cache"
5480 );
5481 }
5482
5483 /// Non-metadata fields don't carry property semantics — the
5484 /// `if_changed` variant must never invalidate for them, matching
5485 /// the existing `notify_field_written` short-circuit.
5486 #[test]
5487 fn notify_field_written_if_changed_skips_non_metadata_field() {
5488 let mut inst = ai_instance();
5489 let _ = inst.snapshot_for_field("VAL");
5490 assert!(inst.metadata_cache.lock().unwrap().is_some());
5491 // VAL is not in is_metadata_field set — must be skipped even
5492 // with a changed value.
5493 inst.notify_field_written_if_changed("VAL", None);
5494 assert!(inst.metadata_cache.lock().unwrap().is_some());
5495 }
5496
5497 #[test]
5498 fn cache_picks_up_new_value_after_invalidation() {
5499 let mut inst = ai_instance();
5500
5501 // First snapshot: degC
5502 let snap1 = inst.snapshot_for_field("VAL").unwrap();
5503 assert_eq!(snap1.display.unwrap().units, "degC");
5504
5505 // Mutate EGU and invalidate
5506 let _ = inst
5507 .record
5508 .put_field("EGU", EpicsValue::String("mV".into()));
5509 inst.notify_field_written("EGU");
5510
5511 // Second snapshot: mV (rebuilt)
5512 let snap2 = inst.snapshot_for_field("VAL").unwrap();
5513 assert_eq!(snap2.display.unwrap().units, "mV");
5514 }
5515
5516 /// R19-41: every snapshot carries the mask of which properties the
5517 /// channel SUPPLIES — C's `rset` slots (`dbAccess.c:336-430` clears the
5518 /// option bit of each NULL slot) narrowed to the addressed field. One
5519 /// case per gate boundary; the three record types are the ones measured
5520 /// against pvxs, which marks none of these leaves.
5521 #[test]
5522 fn property_support_masks_what_the_record_type_does_not_supply() {
5523 use crate::server::records::longout::LongoutRecord;
5524 use crate::server::records::stringout::StringoutRecord;
5525 use crate::server::records::waveform::WaveformRecord;
5526
5527 // ai VAL (DBF_DOUBLE): every numeric slot, no enum strings.
5528 let ai = ai_instance();
5529 let p = ai.snapshot_for_field("VAL").unwrap().properties;
5530 assert_eq!(p, PropertySupport::NUMERIC);
5531 assert_eq!(
5532 ai.snapshot_for_field("VAL").unwrap().precision(),
5533 Some(2),
5534 "an ai supplies get_precision and VAL is DBF_DOUBLE"
5535 );
5536
5537 // ai RVAL (DBF_LONG): the SAME rset, but C keeps DBR_PRECISION only
5538 // for DBF_FLOAT/DBF_DOUBLE (`dbAccess.c:386-395`).
5539 let rval = ai.snapshot_for_field("RVAL").unwrap();
5540 assert!(
5541 !rval.properties.precision && rval.precision().is_none(),
5542 "a non-float field supplies no precision even when the rset does"
5543 );
5544 assert!(
5545 rval.properties.units,
5546 "the other slots are unaffected by the field's type"
5547 );
5548
5549 // longout: `#define get_precision NULL`.
5550 let lo = RecordInstance::new("LO".to_string(), LongoutRecord::default());
5551 let lo = lo.snapshot_for_field("VAL").unwrap();
5552 assert!(!lo.properties.precision && lo.precision().is_none());
5553 assert!(lo.properties.units && lo.properties.graphic_double);
5554
5555 // stringout: no property slot at all.
5556 let so = RecordInstance::new("SO".to_string(), StringoutRecord::default());
5557 let so = so.snapshot_for_field("VAL").unwrap();
5558 assert_eq!(so.properties, PropertySupport::NONE);
5559 assert!(so.units().is_none(), "a stringout supplies no EGU");
5560
5561 // waveform: `#define get_alarm_double NULL`.
5562 let wf = RecordInstance::new("WF".to_string(), WaveformRecord::default());
5563 let wf = wf.snapshot_for_field("VAL").unwrap();
5564 assert!(
5565 !wf.properties.alarm_double && wf.alarm_limits().is_none(),
5566 "a waveform supplies no alarm limits — a GUI must not draw bands at zero"
5567 );
5568 assert!(wf.properties.units && wf.properties.graphic_double);
5569 }
5570
5571 #[test]
5572 fn make_monitor_snapshot_uses_cache() {
5573 let inst = ai_instance();
5574 assert!(inst.metadata_cache.lock().unwrap().is_none());
5575
5576 // make_monitor_snapshot should also populate the cache
5577 let snap = inst.make_monitor_snapshot("VAL", EpicsValue::Double(42.0));
5578 assert!(snap.display.is_some());
5579 assert!(inst.metadata_cache.lock().unwrap().is_some());
5580
5581 // Subsequent call hits cache
5582 let snap2 = inst.make_monitor_snapshot("VAL", EpicsValue::Double(43.0));
5583 let d1 = snap.display.unwrap();
5584 let d2 = snap2.display.unwrap();
5585 assert_eq!(d1.units, d2.units);
5586 assert_eq!(d1.precision, d2.precision);
5587 }
5588
5589 /// Stub record with a per-field metadata override on SPD only —
5590 /// models a C RSET whose get_units/get_graphic_double key on
5591 /// dbGetFieldIndex (e.g. motorRecord.cc:3156-3361).
5592 struct PerFieldMetaRecord;
5593
5594 impl Record for PerFieldMetaRecord {
5595 fn record_type(&self) -> &'static str {
5596 "ai" // record-level metadata populates from EGU/PREC/HOPR/LOPR
5597 }
5598 fn get_field(&self, name: &str) -> Option<EpicsValue> {
5599 match name {
5600 "VAL" | "SPD" => Some(EpicsValue::Double(1.0)),
5601 "EGU" => Some(EpicsValue::String("mm".into())),
5602 "PREC" => Some(EpicsValue::Short(3)),
5603 "HOPR" => Some(EpicsValue::Double(100.0)),
5604 "LOPR" => Some(EpicsValue::Double(-100.0)),
5605 _ => None,
5606 }
5607 }
5608 fn put_field(&mut self, name: &str, _value: EpicsValue) -> CaResult<()> {
5609 Err(CaError::FieldNotFound(name.to_string()))
5610 }
5611 fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
5612 &[]
5613 }
5614 fn field_metadata_override(
5615 &self,
5616 field: &str,
5617 ) -> Option<crate::server::record::FieldMetadataOverride> {
5618 if field != "SPD" {
5619 return None;
5620 }
5621 Some(crate::server::record::FieldMetadataOverride {
5622 units: Some("mm/sec".into()),
5623 precision: Some(1),
5624 disp_limits: Some((5.0, 0.5)),
5625 ctrl_limits: Some((4.0, 1.0)),
5626 alarm_limits: Some((9.0, 8.0, -8.0, -9.0)),
5627 })
5628 }
5629 }
5630
5631 #[test]
5632 fn field_metadata_override_applies_on_get_and_monitor_paths() {
5633 let inst = RecordInstance::new("PFM".to_string(), PerFieldMetaRecord);
5634
5635 // VAL: no override — record-level metadata serves it.
5636 let snap = inst.snapshot_for_field("VAL").unwrap();
5637 let d = snap.display.unwrap();
5638 assert_eq!(d.units, "mm");
5639 assert_eq!(d.precision, 3);
5640 assert_eq!(d.upper_disp_limit, 100.0);
5641
5642 // SPD via the GET path: every member patched over the cache.
5643 let snap = inst.snapshot_for_field("SPD").unwrap();
5644 let d = snap.display.unwrap();
5645 assert_eq!(d.units, "mm/sec");
5646 assert_eq!(d.precision, 1);
5647 assert_eq!((d.upper_disp_limit, d.lower_disp_limit), (5.0, 0.5));
5648 assert_eq!(
5649 (
5650 d.upper_alarm_limit,
5651 d.upper_warning_limit,
5652 d.lower_warning_limit,
5653 d.lower_alarm_limit
5654 ),
5655 (9.0, 8.0, -8.0, -9.0)
5656 );
5657 let c = snap.control.unwrap();
5658 assert_eq!((c.upper_ctrl_limit, c.lower_ctrl_limit), (4.0, 1.0));
5659
5660 // SPD via the monitor path: identical override.
5661 let snap = inst.make_monitor_snapshot("SPD", EpicsValue::Double(2.0));
5662 let d = snap.display.unwrap();
5663 assert_eq!(d.units, "mm/sec");
5664 assert_eq!((d.upper_disp_limit, d.lower_disp_limit), (5.0, 0.5));
5665 let c = snap.control.unwrap();
5666 assert_eq!((c.upper_ctrl_limit, c.lower_ctrl_limit), (4.0, 1.0));
5667 }
5668
5669 /// Stub modelling the motor monitor() shape (C motorRecord.cc:
5670 /// 3468-3507): VAL is a setpoint, the MDEL/ADEL deadband tracks
5671 /// the RBV readback, which advances on every process.
5672 struct ReadbackDeadbandRecord {
5673 val: f64,
5674 rbv: f64,
5675 deadband: f64,
5676 }
5677
5678 impl Record for ReadbackDeadbandRecord {
5679 fn record_type(&self) -> &'static str {
5680 "ai"
5681 }
5682 fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
5683 self.rbv += 30.0;
5684 Ok(crate::server::record::ProcessOutcome::complete())
5685 }
5686 fn get_field(&self, name: &str) -> Option<EpicsValue> {
5687 match name {
5688 "VAL" => Some(EpicsValue::Double(self.val)),
5689 "RBV" => Some(EpicsValue::Double(self.rbv)),
5690 "MDEL" | "ADEL" => Some(EpicsValue::Double(self.deadband)),
5691 _ => None,
5692 }
5693 }
5694 fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
5695 match (name, value) {
5696 ("VAL", EpicsValue::Double(v)) => {
5697 self.val = v;
5698 Ok(())
5699 }
5700 ("MDEL", EpicsValue::Double(v)) => {
5701 self.deadband = v;
5702 Ok(())
5703 }
5704 _ => Err(CaError::FieldNotFound(name.to_string())),
5705 }
5706 }
5707 fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
5708 &[]
5709 }
5710 fn monitor_deadband_value(&self) -> Option<EpicsValue> {
5711 Some(EpicsValue::Double(self.rbv))
5712 }
5713 fn monitor_deadband_field(&self) -> &'static str {
5714 "RBV"
5715 }
5716 }
5717
5718 /// C motor monitor() parity: MDEL/ADEL throttle the deadband
5719 /// field's (RBV) delivery; VAL posts only when the setpoint
5720 /// actually changed — not on every readback poll.
5721 #[test]
5722 fn deadband_field_routes_readback_and_val_posts_only_on_change() {
5723 use crate::server::recgbl::EventMask;
5724 let mut inst = RecordInstance::new(
5725 "RDB".to_string(),
5726 ReadbackDeadbandRecord {
5727 val: 5.0,
5728 rbv: 0.0,
5729 deadband: 10.0,
5730 },
5731 );
5732 let _val_rx = inst
5733 .add_subscriber(
5734 "VAL",
5735 1,
5736 crate::types::DbFieldType::Double,
5737 EventMask::VALUE.bits(),
5738 )
5739 .expect("VAL subscriber");
5740 let _rbv_rx = inst
5741 .add_subscriber(
5742 "RBV",
5743 2,
5744 crate::types::DbFieldType::Double,
5745 EventMask::VALUE.bits(),
5746 )
5747 .expect("RBV subscriber");
5748 let names = |snap: &ProcessSnapshot| {
5749 snap.changed_fields
5750 .iter()
5751 .map(|(n, _, _)| n.clone())
5752 .collect::<Vec<_>>()
5753 };
5754
5755 // Cycle 1 (first publish): RBV fires via the deadband trigger
5756 // (MLST starts at the NaN never-posted sentinel). VAL must NOT
5757 // post: `add_subscriber` seeded `last_posted` with the current
5758 // value (the initial value already went out with EVENT_ADD), and
5759 // C monitor() posts VAL only when MARKED(M_VAL) — nothing marked
5760 // it.
5761 let (snap, _) = inst.process_local().unwrap();
5762 let n = names(&snap);
5763 assert!(n.contains(&"RBV".to_string()), "{n:?}");
5764 assert!(
5765 !n.contains(&"VAL".to_string()),
5766 "VAL unchanged since subscribe must not post: {n:?}"
5767 );
5768
5769 // Cycle 2: RBV moved past MDEL, VAL unchanged → RBV posted,
5770 // VAL not re-posted.
5771 let (snap, _) = inst.process_local().unwrap();
5772 let n = names(&snap);
5773 assert!(n.contains(&"RBV".to_string()), "RBV crossed MDEL: {n:?}");
5774 assert!(
5775 !n.contains(&"VAL".to_string()),
5776 "unchanged VAL must not post: {n:?}"
5777 );
5778
5779 // Cycle 3: widen the deadband — RBV moves within it → throttled.
5780 let _ = inst.record.put_field("MDEL", EpicsValue::Double(1000.0));
5781 let (snap, _) = inst.process_local().unwrap();
5782 let n = names(&snap);
5783 assert!(
5784 !n.contains(&"RBV".to_string()),
5785 "MDEL must throttle RBV: {n:?}"
5786 );
5787
5788 // Cycle 4: setpoint moves while RBV stays inside the deadband →
5789 // VAL posts via change detection, RBV stays throttled.
5790 let _ = inst.record.put_field("VAL", EpicsValue::Double(42.0));
5791 let (snap, _) = inst.process_local().unwrap();
5792 let n = names(&snap);
5793 assert!(
5794 n.contains(&"VAL".to_string()),
5795 "changed VAL must post: {n:?}"
5796 );
5797 assert!(
5798 !n.contains(&"RBV".to_string()),
5799 "MDEL must throttle RBV: {n:?}"
5800 );
5801 }
5802
5803 /// Record that names DIFF in `force_posted_fields` (the motor's C
5804 /// `process_motor_info` unconditional `MARK(M_DIFF)`) while keeping
5805 /// every value constant — a settled axis parked at a fixed non-zero
5806 /// following error. VAL is a control: not force-listed, so it must
5807 /// fall back to change-detection.
5808 struct ForcePostRecord {
5809 diff: f64,
5810 val: f64,
5811 }
5812
5813 impl Record for ForcePostRecord {
5814 fn record_type(&self) -> &'static str {
5815 "ai"
5816 }
5817 fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
5818 // Values never change — the readback already matches; only the
5819 // unconditional MARK should keep DIFF flowing.
5820 Ok(crate::server::record::ProcessOutcome::complete())
5821 }
5822 fn get_field(&self, name: &str) -> Option<EpicsValue> {
5823 match name {
5824 "DIFF" => Some(EpicsValue::Double(self.diff)),
5825 "VAL" => Some(EpicsValue::Double(self.val)),
5826 _ => None,
5827 }
5828 }
5829 fn put_field(&mut self, name: &str, _value: EpicsValue) -> CaResult<()> {
5830 Err(CaError::FieldNotFound(name.to_string()))
5831 }
5832 fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
5833 &[]
5834 }
5835 fn force_posted_fields(&self) -> &'static [&'static str] {
5836 &["DIFF"]
5837 }
5838 }
5839
5840 /// C motorRecord parity: `process_motor_info` MARKs M_DIFF/M_RDIF every
5841 /// CALLBACK_DATA pass and `monitor()` posts them with `DBE_VAL_LOG`
5842 /// regardless of change, so a force-posted field re-posts on an
5843 /// otherwise-idle cycle while an unchanged non-force field does not.
5844 #[test]
5845 fn force_posted_field_reposts_unchanged_value_each_cycle() {
5846 use crate::server::recgbl::EventMask;
5847 let mut inst = RecordInstance::new(
5848 "FP".to_string(),
5849 ForcePostRecord {
5850 diff: 2.5,
5851 val: 1.0,
5852 },
5853 );
5854 let _diff_rx = inst
5855 .add_subscriber(
5856 "DIFF",
5857 1,
5858 crate::types::DbFieldType::Double,
5859 EventMask::VALUE.bits(),
5860 )
5861 .expect("DIFF subscriber");
5862 let _val_rx = inst
5863 .add_subscriber(
5864 "VAL",
5865 2,
5866 crate::types::DbFieldType::Double,
5867 EventMask::VALUE.bits(),
5868 )
5869 .expect("VAL subscriber");
5870 let names = |snap: &ProcessSnapshot| {
5871 snap.changed_fields
5872 .iter()
5873 .map(|(n, _, _)| n.clone())
5874 .collect::<Vec<_>>()
5875 };
5876
5877 // Cycle 1 (first publish): both DIFF and VAL post — last_posted is
5878 // empty so change-detection treats every subscribed field as new.
5879 let (snap1, _) = inst.process_local().unwrap();
5880 assert!(
5881 names(&snap1).contains(&"DIFF".to_string()),
5882 "DIFF posts on first publish: {:?}",
5883 names(&snap1)
5884 );
5885
5886 // Cycle 2: nothing changed. VAL (not force-listed) must NOT re-post;
5887 // DIFF (force-listed) MUST re-post — the C unconditional MARK +
5888 // DBE_VAL_LOG. This is the divergence MOT-1 closes.
5889 let (snap2, _) = inst.process_local().unwrap();
5890 assert!(
5891 names(&snap2).contains(&"DIFF".to_string()),
5892 "force-posted DIFF must re-post when unchanged: {:?}",
5893 names(&snap2)
5894 );
5895 assert!(
5896 !names(&snap2).contains(&"VAL".to_string()),
5897 "an unchanged non-force field must not re-post: {:?}",
5898 names(&snap2)
5899 );
5900 // The forced re-post carries DBE_VALUE|DBE_LOG (no alarm bits this
5901 // cycle), matching C `monitor_mask | DBE_VAL_LOG` with monitor_mask=0.
5902 let diff_mask = snap2
5903 .changed_fields
5904 .iter()
5905 .find(|(n, _, _)| n == "DIFF")
5906 .map(|(_, _, m)| *m)
5907 .expect("DIFF post present");
5908 assert_eq!(
5909 diff_mask.bits(),
5910 (EventMask::VALUE | EventMask::LOG).bits(),
5911 "forced re-post mask is DBE_VAL_LOG"
5912 );
5913 }
5914
5915 /// Record that names S1 in `log_swept_fields` (the scaler's idle
5916 /// `monitor()` DBE_LOG sweep) while keeping every value constant. S2
5917 /// is a control: subscribed but NOT swept, so an unchanged S2 must
5918 /// not re-post. Neither field is the primary `VAL`, so the default
5919 /// deadband field resolves to nothing and does not confound the test.
5920 struct LogSweepRecord {
5921 s1: i32,
5922 s2: i32,
5923 }
5924
5925 impl Record for LogSweepRecord {
5926 fn record_type(&self) -> &'static str {
5927 "scaler"
5928 }
5929 fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
5930 // Counts never change — only the unconditional idle LOG sweep
5931 // should keep S1 flowing to a DBE_LOG (archiver) subscriber.
5932 Ok(crate::server::record::ProcessOutcome::complete())
5933 }
5934 fn get_field(&self, name: &str) -> Option<EpicsValue> {
5935 match name {
5936 "S1" => Some(EpicsValue::Long(self.s1)),
5937 "S2" => Some(EpicsValue::Long(self.s2)),
5938 _ => None,
5939 }
5940 }
5941 fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
5942 match (name, value) {
5943 ("S1", EpicsValue::Long(v)) => {
5944 self.s1 = v;
5945 Ok(())
5946 }
5947 ("S2", EpicsValue::Long(v)) => {
5948 self.s2 = v;
5949 Ok(())
5950 }
5951 _ => Err(CaError::FieldNotFound(name.to_string())),
5952 }
5953 }
5954 fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
5955 &[]
5956 }
5957 fn log_swept_fields(&self) -> &'static [&'static str] {
5958 &["S1"]
5959 }
5960 }
5961
5962 /// C `scalerRecord.c::monitor():757-773` sweeps each active channel with a
5963 /// literal `DBE_LOG` on every cycle it runs, unconditionally — the sweep is
5964 /// INDEPENDENT of the change post, not an alternative to it (R12-62). So an
5965 /// UNCHANGED swept field posts `DBE_LOG` only, and a CHANGED swept field
5966 /// posts TWICE on that one cycle: once by change-detection, and once by the
5967 /// sweep with `DBE_LOG`. (In C's scaler those two are `updateCounts()`'s
5968 /// `DBE_VALUE` at `:582` and `monitor()`'s `DBE_LOG` at `:771`.) A
5969 /// non-swept field never re-posts when unchanged. `add_subscriber` seeds
5970 /// `last_posted` with the current value (the initial value goes out via
5971 /// EVENT_ADD), so a freshly subscribed unchanged field already takes the
5972 /// sweep path on cycle 1.
5973 #[test]
5974 fn log_swept_field_reposts_unchanged_with_log_mask_only() {
5975 use crate::server::recgbl::EventMask;
5976 let mut inst = RecordInstance::new("SW".to_string(), LogSweepRecord { s1: 7, s2: 9 });
5977 let _s1_rx = inst
5978 .add_subscriber(
5979 "S1",
5980 1,
5981 crate::types::DbFieldType::Long,
5982 EventMask::LOG.bits(),
5983 )
5984 .expect("S1 subscriber");
5985 let _s2_rx = inst
5986 .add_subscriber(
5987 "S2",
5988 2,
5989 crate::types::DbFieldType::Long,
5990 EventMask::VALUE.bits(),
5991 )
5992 .expect("S2 subscriber");
5993 let names = |snap: &ProcessSnapshot| {
5994 snap.changed_fields
5995 .iter()
5996 .map(|(n, _, _)| n.clone())
5997 .collect::<Vec<_>>()
5998 };
5999 let count_of = |snap: &ProcessSnapshot, f: &str| {
6000 snap.changed_fields
6001 .iter()
6002 .filter(|(n, _, _)| n == f)
6003 .count()
6004 };
6005 let mask_of = |snap: &ProcessSnapshot, f: &str| {
6006 snap.changed_fields
6007 .iter()
6008 .find(|(n, _, _)| n == f)
6009 .map(|(_, _, m)| *m)
6010 };
6011
6012 // Cycle 1: nothing changed since subscribe. S1 (swept) re-posts
6013 // with DBE_LOG ONLY; S2 (not swept) must NOT re-post.
6014 let (snap1, _) = inst.process_local().unwrap();
6015 assert!(
6016 names(&snap1).contains(&"S1".to_string()),
6017 "log-swept S1 must re-post when unchanged: {:?}",
6018 names(&snap1)
6019 );
6020 assert!(
6021 !names(&snap1).contains(&"S2".to_string()),
6022 "unchanged non-swept S2 must not re-post: {:?}",
6023 names(&snap1)
6024 );
6025 // DBE_LOG, plus the DBE_ALARM of this cycle's transition: a record
6026 // starts UDF/INVALID and its first process clears that, so cycle 1 IS an
6027 // alarm transition (CBUG-B19 — C's sweep drops the alarm bit; this
6028 // assertion used to require a bare DBE_LOG). No DBE_VALUE either way:
6029 // the counts have not moved.
6030 assert_eq!(
6031 mask_of(&snap1, "S1").unwrap().bits(),
6032 (EventMask::LOG | EventMask::ALARM).bits(),
6033 "idle sweep posts DBE_LOG + the alarm transition, never DBE_VALUE"
6034 );
6035
6036 // Cycle 2: S1's count changed. Change-detection delivers it, and the
6037 // sweep delivers it AGAIN with DBE_LOG — the two C `db_post_events`
6038 // calls of the count-completion cycle.
6039 inst.record.put_field("S1", EpicsValue::Long(8)).unwrap();
6040 let (snap2, _) = inst.process_local().unwrap();
6041 assert_eq!(
6042 count_of(&snap2, "S1"),
6043 2,
6044 "a changed swept field posts twice — change post + independent \
6045 DBE_LOG sweep: {:?}",
6046 snap2.changed_fields
6047 );
6048 let s1_masks: Vec<u16> = snap2
6049 .changed_fields
6050 .iter()
6051 .filter(|(n, _, _)| n == "S1")
6052 .map(|(_, _, m)| m.bits())
6053 .collect();
6054 assert_eq!(
6055 s1_masks,
6056 vec![
6057 (EventMask::VALUE | EventMask::LOG).bits(),
6058 EventMask::LOG.bits()
6059 ],
6060 "change post first (VALUE|LOG here — this stub is not a \
6061 value_only_change_fields record), then the sweep's literal DBE_LOG"
6062 );
6063
6064 // Cycle 3: unchanged again — back to the DBE_LOG-only sweep.
6065 let (snap3, _) = inst.process_local().unwrap();
6066 assert_eq!(
6067 mask_of(&snap3, "S1").unwrap().bits(),
6068 EventMask::LOG.bits(),
6069 "unchanged-again S1 returns to the DBE_LOG-only sweep"
6070 );
6071 }
6072
6073 /// A log-swept record that can raise an alarm on demand — the scaler's
6074 /// `do_alarm()` (scalerRecord.c:745-755) in miniature.
6075 struct AlarmingLogSweepRecord {
6076 s1: i32,
6077 alarm: bool,
6078 }
6079
6080 impl Record for AlarmingLogSweepRecord {
6081 fn record_type(&self) -> &'static str {
6082 "scaler"
6083 }
6084 fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
6085 Ok(crate::server::record::ProcessOutcome::complete())
6086 }
6087 fn check_alarms(&mut self, common: &mut crate::server::record::CommonFields) {
6088 if self.alarm {
6089 crate::server::recgbl::rec_gbl_set_sevr(
6090 common,
6091 crate::server::recgbl::alarm_status::UDF_ALARM,
6092 crate::server::record::AlarmSeverity::Invalid,
6093 );
6094 }
6095 }
6096 fn get_field(&self, name: &str) -> Option<EpicsValue> {
6097 match name {
6098 "S1" => Some(EpicsValue::Long(self.s1)),
6099 _ => None,
6100 }
6101 }
6102 fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
6103 match (name, value) {
6104 ("S1", EpicsValue::Long(v)) => {
6105 self.s1 = v;
6106 Ok(())
6107 }
6108 _ => Err(CaError::FieldNotFound(name.to_string())),
6109 }
6110 }
6111 fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
6112 &[]
6113 }
6114 fn log_swept_fields(&self) -> &'static [&'static str] {
6115 &["S1"]
6116 }
6117 fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
6118 Some(self)
6119 }
6120 }
6121
6122 /// CBUG-B19 — the sweep post carries the alarm-transition bits.
6123 ///
6124 /// DEVIATION from C, deliberate. C's scaler `monitor()` computes
6125 /// `monitor_mask = recGblResetAlarms(pscal)` (scalerRecord.c:764), ORs
6126 /// `DBE_VALUE|DBE_LOG` into it (`:766`), and then posts every `Sn` with a
6127 /// LITERAL `DBE_LOG` (`:771`) — `monitor_mask` is assigned, OR-ed, and never
6128 /// read. The alarm bit that `recGblResetAlarms` returns is exactly what every
6129 /// other record ORs into its value posts, so C drops it: a client subscribed
6130 /// to `Sn` with DBE_ALARM receives NOTHING on a severity transition.
6131 ///
6132 /// The DBE_VALUE half of C's dead `|=` is deliberately not resurrected — the
6133 /// sweep is unconditional, so a VALUE bit here would fire a value event on
6134 /// every idle scan whether or not the counts moved. The first assertion pins
6135 /// that.
6136 #[test]
6137 fn b19_log_swept_field_carries_the_alarm_transition_bits() {
6138 use crate::server::recgbl::EventMask;
6139 let mut inst = RecordInstance::new(
6140 "SW".to_string(),
6141 AlarmingLogSweepRecord {
6142 s1: 7,
6143 alarm: false,
6144 },
6145 );
6146 let _s1_rx = inst
6147 .add_subscriber(
6148 "S1",
6149 1,
6150 crate::types::DbFieldType::Long,
6151 (EventMask::LOG | EventMask::ALARM).bits(),
6152 )
6153 .expect("S1 subscriber");
6154 let mask_of = |snap: &ProcessSnapshot, f: &str| {
6155 snap.changed_fields
6156 .iter()
6157 .find(|(n, _, _)| n == f)
6158 .map(|(_, _, m)| *m)
6159 };
6160
6161 // Cycle 1 clears the record's initial UDF/INVALID alarm, which is itself
6162 // a transition; cycle 2 is the quiet baseline. The sweep is then DBE_LOG
6163 // alone — in particular NOT DBE_VALUE, since the counts have not moved.
6164 let _ = inst.process_local().unwrap();
6165 let (snap1, _) = inst.process_local().unwrap();
6166 assert_eq!(
6167 mask_of(&snap1, "S1").unwrap().bits(),
6168 EventMask::LOG.bits(),
6169 "no alarm transition → the sweep is DBE_LOG only"
6170 );
6171
6172 // The alarm fires: severity moves NO_ALARM → INVALID, so this cycle's
6173 // posts carry DBE_ALARM. C posts DBE_LOG here and the alarm subscriber
6174 // learns nothing.
6175 if let Some(r) = inst
6176 .record
6177 .as_any_mut()
6178 .and_then(|a| a.downcast_mut::<AlarmingLogSweepRecord>())
6179 {
6180 r.alarm = true;
6181 }
6182 let (snap2, _) = inst.process_local().unwrap();
6183 assert_eq!(
6184 mask_of(&snap2, "S1").unwrap().bits(),
6185 (EventMask::LOG | EventMask::ALARM).bits(),
6186 "the severity transition must reach the swept field (C drops it)"
6187 );
6188
6189 // Severity stays INVALID: no transition, so no alarm bit — the sweep is
6190 // DBE_LOG again.
6191 let (snap3, _) = inst.process_local().unwrap();
6192 assert_eq!(
6193 mask_of(&snap3, "S1").unwrap().bits(),
6194 EventMask::LOG.bits(),
6195 "a steady severity is not a transition"
6196 );
6197 }
6198
6199 /// Stub record that simulates a record whose process() mutates an
6200 /// internal metadata field. Used to verify that the
6201 /// `Record::took_metadata_change()` hook actually triggers cache
6202 /// invalidation in `process_local()`.
6203 struct MutatingMetaRecord {
6204 val: f64,
6205 egu: String,
6206 took_change: bool,
6207 }
6208
6209 impl Record for MutatingMetaRecord {
6210 fn record_type(&self) -> &'static str {
6211 "ai" // pretend to be ai so populate_display_info populates EGU
6212 }
6213 fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
6214 // Simulate dynamic metadata change inside processing
6215 self.egu = "kV".into();
6216 self.took_change = true;
6217 Ok(crate::server::record::ProcessOutcome::complete())
6218 }
6219 fn get_field(&self, name: &str) -> Option<EpicsValue> {
6220 match name {
6221 "VAL" => Some(EpicsValue::Double(self.val)),
6222 "EGU" => Some(EpicsValue::String(self.egu.clone().into())),
6223 "PREC" => Some(EpicsValue::Short(0)),
6224 "HOPR" => Some(EpicsValue::Double(0.0)),
6225 "LOPR" => Some(EpicsValue::Double(0.0)),
6226 _ => None,
6227 }
6228 }
6229 fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
6230 match (name, value) {
6231 ("VAL", EpicsValue::Double(v)) => {
6232 self.val = v;
6233 Ok(())
6234 }
6235 ("EGU", EpicsValue::String(s)) => {
6236 self.egu = s.as_str_lossy().into_owned();
6237 Ok(())
6238 }
6239 _ => Err(CaError::FieldNotFound(name.to_string())),
6240 }
6241 }
6242 fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
6243 &[]
6244 }
6245 fn took_metadata_change(&mut self) -> bool {
6246 let was = self.took_change;
6247 self.took_change = false; // reset after reporting
6248 was
6249 }
6250 }
6251
6252 #[test]
6253 fn process_local_invalidates_cache_on_took_metadata_change() {
6254 let mut inst = RecordInstance::new(
6255 "MUT".to_string(),
6256 MutatingMetaRecord {
6257 val: 1.0,
6258 egu: "V".to_string(),
6259 took_change: false,
6260 },
6261 );
6262
6263 // Build the cache once with the original EGU
6264 let snap1 = inst.snapshot_for_field("VAL").unwrap();
6265 assert_eq!(snap1.display.unwrap().units, "V");
6266 assert!(inst.metadata_cache.lock().unwrap().is_some());
6267
6268 // Run process_local — the stub record sets took_change inside process()
6269 let _ = inst.process_local();
6270
6271 // Cache should now be invalidated (took_metadata_change returned true)
6272 assert!(
6273 inst.metadata_cache.lock().unwrap().is_none(),
6274 "process_local should invalidate cache when took_metadata_change is true"
6275 );
6276
6277 // Next snapshot picks up the new EGU
6278 let snap2 = inst.snapshot_for_field("VAL").unwrap();
6279 assert_eq!(snap2.display.unwrap().units, "kV");
6280 }
6281
6282 /// Stub record that does NOT mutate metadata fields. Verifies the
6283 /// default `took_metadata_change` returns false and the cache stays.
6284 struct StableMetaRecord {
6285 val: f64,
6286 }
6287 impl Record for StableMetaRecord {
6288 fn record_type(&self) -> &'static str {
6289 "ai"
6290 }
6291 fn process(&mut self) -> CaResult<crate::server::record::ProcessOutcome> {
6292 self.val += 1.0;
6293 Ok(crate::server::record::ProcessOutcome::complete())
6294 }
6295 fn get_field(&self, name: &str) -> Option<EpicsValue> {
6296 match name {
6297 "VAL" => Some(EpicsValue::Double(self.val)),
6298 "EGU" => Some(EpicsValue::String("V".into())),
6299 "PREC" => Some(EpicsValue::Short(0)),
6300 "HOPR" => Some(EpicsValue::Double(0.0)),
6301 "LOPR" => Some(EpicsValue::Double(0.0)),
6302 _ => None,
6303 }
6304 }
6305 fn put_field(&mut self, _: &str, _: EpicsValue) -> CaResult<()> {
6306 Ok(())
6307 }
6308 fn declared_fields(&self) -> &'static [crate::server::record::FieldDesc] {
6309 &[]
6310 }
6311 // took_metadata_change uses default impl (returns false)
6312 }
6313
6314 #[test]
6315 fn process_local_keeps_cache_when_no_metadata_change() {
6316 let mut inst = RecordInstance::new("STABLE".to_string(), StableMetaRecord { val: 0.0 });
6317
6318 let _ = inst.snapshot_for_field("VAL");
6319 assert!(inst.metadata_cache.lock().unwrap().is_some());
6320
6321 // Run process_local several times — cache should remain intact
6322 let _ = inst.process_local();
6323 assert!(inst.metadata_cache.lock().unwrap().is_some());
6324 let _ = inst.process_local();
6325 assert!(inst.metadata_cache.lock().unwrap().is_some());
6326 let _ = inst.process_local();
6327 assert!(inst.metadata_cache.lock().unwrap().is_some());
6328 }
6329
6330 // ── Regression: DBE_PROPERTY event delivery boundaries ──────────────
6331
6332 /// motor `prop(YES)` fields (motorRecord.dbd 154/161/289/361/368)
6333 /// are property-class: a changed write must post DBE_PROPERTY
6334 /// (C dbAccess.c dbPut, `pfldDes->prop`). They feed the
6335 /// live-computed `field_metadata_override`, not the cache, but the
6336 /// posting gate is this same set.
6337 #[test]
6338 fn motor_prop_yes_fields_are_property_class() {
6339 for f in ["VBAS", "VMAX", "MRES", "DHLM", "DLLM"] {
6340 assert!(is_metadata_field(f), "{f} must be property-class");
6341 }
6342 }
6343
6344 /// Boundary 1: metadata field written with a CHANGED value, subscriber
6345 /// mask includes PROPERTY → subscriber receives an event.
6346 /// Mirrors C dbAccess.c:1396-1397 `db_post_events(precord,NULL,DBE_PROPERTY)`.
6347 #[test]
6348 fn r47_property_event_delivered_on_changed_metadata() {
6349 use crate::server::recgbl::EventMask;
6350 let mut inst = ai_instance();
6351 let mut rx = inst
6352 .add_subscriber(
6353 "VAL",
6354 1,
6355 crate::types::DbFieldType::Double,
6356 EventMask::PROPERTY.bits(),
6357 )
6358 .expect("subscriber added");
6359
6360 let prev = inst.record.get_field("EGU"); // "degC"
6361 let _ = inst
6362 .record
6363 .put_field("EGU", EpicsValue::String("kPa".into()));
6364 inst.notify_field_written_if_changed("EGU", prev.as_ref());
6365
6366 assert!(
6367 rx.try_recv().is_ok(),
6368 "PROPERTY subscriber must receive event when metadata field changes"
6369 );
6370 }
6371
6372 /// Boundary 2: same metadata field written with the SAME value → NO event.
6373 /// Matches C suppression at dbAccess.c:1379-1383 and the `prev != now` gate.
6374 #[test]
6375 fn r47_no_event_on_unchanged_metadata() {
6376 use crate::server::recgbl::EventMask;
6377 let mut inst = ai_instance();
6378 let mut rx = inst
6379 .add_subscriber(
6380 "VAL",
6381 1,
6382 crate::types::DbFieldType::Double,
6383 EventMask::PROPERTY.bits(),
6384 )
6385 .expect("subscriber added");
6386
6387 let prev = inst.record.get_field("EGU"); // "degC"
6388 // Write the same value — no change
6389 let _ = inst.record.put_field("EGU", prev.clone().unwrap());
6390 inst.notify_field_written_if_changed("EGU", prev.as_ref());
6391
6392 assert!(
6393 rx.try_recv().is_err(),
6394 "PROPERTY subscriber must NOT receive event when metadata value is unchanged"
6395 );
6396 }
6397
6398 /// Boundary 3: VALUE-only subscriber (no PROPERTY bit) receives NO event
6399 /// from a metadata write, even when the field value changed.
6400 #[test]
6401 fn r47_value_only_subscriber_no_event_on_metadata_write() {
6402 use crate::server::recgbl::EventMask;
6403 let mut inst = ai_instance();
6404 let mut rx = inst
6405 .add_subscriber(
6406 "VAL",
6407 1,
6408 crate::types::DbFieldType::Double,
6409 EventMask::VALUE.bits(),
6410 )
6411 .expect("subscriber added");
6412
6413 let prev = inst.record.get_field("EGU"); // "degC"
6414 let _ = inst
6415 .record
6416 .put_field("EGU", EpicsValue::String("kPa".into()));
6417 inst.notify_field_written_if_changed("EGU", prev.as_ref());
6418
6419 assert!(
6420 rx.try_recv().is_err(),
6421 "VALUE-only subscriber must NOT receive event from a metadata write"
6422 );
6423 }
6424
6425 /// Boundary 4 (took_metadata_change path): PROPERTY subscriber receives
6426 /// event after process_local() when the record reports a metadata change.
6427 #[test]
6428 fn r47_process_local_property_event_on_took_metadata_change() {
6429 use crate::server::recgbl::EventMask;
6430 let mut inst = RecordInstance::new(
6431 "MUT2".to_string(),
6432 MutatingMetaRecord {
6433 val: 1.0,
6434 egu: "V".to_string(),
6435 took_change: false,
6436 },
6437 );
6438 let mut rx = inst
6439 .add_subscriber(
6440 "VAL",
6441 1,
6442 crate::types::DbFieldType::Double,
6443 EventMask::PROPERTY.bits(),
6444 )
6445 .expect("subscriber added");
6446
6447 // process() sets took_change = true and updates egu to "kV"
6448 let _ = inst.process_local();
6449
6450 assert!(
6451 rx.try_recv().is_ok(),
6452 "PROPERTY subscriber must receive event after process_local reports took_metadata_change"
6453 );
6454 }
6455}
6456
6457#[cfg(test)]
6458mod aftc_filter_tests {
6459 //! Tests for the shared AFTC alarm-range filter
6460 //! (`records::alarm_filter::aftc_filter`) as driven by
6461 //! `evaluate_analog_alarm`. Pure-function tests: no record instance
6462 //! needed — the filter is a stateless transform of (raw_alarm, aftc,
6463 //! afvl_in, t_last, t_now). Algorithm provenance: 2009 EPICS
6464 //! Codeathon (epics-base `824d37811`), C `aiRecord.c:355-401`.
6465
6466 use crate::server::records::alarm_filter::aftc_filter;
6467 use std::time::{Duration, SystemTime};
6468
6469 fn at(secs: f64) -> SystemTime {
6470 SystemTime::UNIX_EPOCH + Duration::from_secs_f64(secs)
6471 }
6472
6473 #[test]
6474 fn disabled_when_aftc_le_zero() {
6475 // aftc=0 means filter disabled — pass-through.
6476 let (out, afvl) = aftc_filter(2, 0.0, 0.0, at(0.0), at(1.0));
6477 assert_eq!(out, 2);
6478 assert_eq!(afvl, 0.0);
6479 }
6480
6481 #[test]
6482 fn initial_sample_seeds_state_unchanged_alarm() {
6483 // afvl=0 means first sample after enable — alarm passes through
6484 // and accumulator seeds with the raw severity.
6485 let (out, afvl) = aftc_filter(2, 3.0, 0.0, at(0.0), at(0.5));
6486 assert_eq!(out, 2);
6487 assert_eq!(afvl, 2.0);
6488 }
6489
6490 #[test]
6491 fn raises_alarm_only_after_full_time_constant() {
6492 // Single-step heuristic: with `aftc = 3s` and `dt = 0.1s`, alpha
6493 // ≈ 0.967, so a one-shot raw_alarm=2 against afvl=0.0 should not
6494 // produce alarm=2 yet — the filter must hold off until the
6495 // accumulator crosses the threshold.
6496 // Seed with afvl=0.01 (tiny prior, simulating "almost no alarm
6497 // yet"); the filter must keep alarm at 0 after one short tick.
6498 let (out, afvl) = aftc_filter(2, 3.0, 0.01, at(0.0), at(0.1));
6499 assert_eq!(out, 0, "filter should suppress alarm rise on a 0.1s tick");
6500 assert!(afvl > 0.0 && afvl < 2.0);
6501 }
6502
6503 #[test]
6504 fn dt_zero_is_no_op() {
6505 // Two evaluations at the same instant produce no filter advance.
6506 let (out, afvl) = aftc_filter(2, 3.0, 1.5, at(0.0), at(0.0));
6507 assert_eq!(out, 1); // floor(|1.5|) = 1
6508 assert_eq!(afvl, 1.5);
6509 }
6510
6511 #[test]
6512 fn long_steady_state_converges_to_alarm() {
6513 // After many steps with raw_alarm=2 and dt much smaller than aftc,
6514 // the accumulator must converge towards 2.
6515 let aftc = 1.0;
6516 let mut afvl = 0.0;
6517 let mut last = at(0.0);
6518 let mut alarm = 0;
6519 for i in 1..=100 {
6520 let now = at(i as f64 * 0.05);
6521 let (out, new_afvl) = aftc_filter(2, aftc, afvl, last, now);
6522 alarm = out;
6523 afvl = new_afvl;
6524 last = now;
6525 }
6526 assert_eq!(
6527 alarm, 2,
6528 "after 5 s of steady raw=2 with aftc=1 s, output must reach 2"
6529 );
6530 assert!(afvl.abs() >= 1.99 && afvl.abs() <= 2.0);
6531 }
6532}
6533
6534#[cfg(test)]
6535mod check_deadband_tests {
6536 use super::check_deadband;
6537
6538 /// Sentinel: `oldval=NaN` means "no prior posting", always fire.
6539 #[test]
6540 fn nan_old_value_fires() {
6541 assert!(check_deadband(0.0, f64::NAN, 1.0));
6542 assert!(check_deadband(f64::NAN, f64::NAN, 1.0));
6543 }
6544
6545 /// C path: `delta > deadband` with both finite. delta within deadband
6546 /// must NOT fire.
6547 #[test]
6548 fn within_finite_deadband_does_not_fire() {
6549 assert!(!check_deadband(10.0, 10.5, 1.0));
6550 assert!(!check_deadband(10.0, 9.5, 1.0));
6551 // Boundary: `delta == deadband` is NOT strictly greater.
6552 assert!(!check_deadband(10.0, 11.0, 1.0));
6553 }
6554
6555 /// `delta > deadband` with both finite, beyond → fire.
6556 #[test]
6557 fn beyond_finite_deadband_fires() {
6558 assert!(check_deadband(10.0, 12.0, 1.0));
6559 }
6560
6561 /// Negative deadband acts as "always fire" (C `delta > deadband` is
6562 /// trivially true for any non-negative delta).
6563 #[test]
6564 fn negative_deadband_fires() {
6565 assert!(check_deadband(10.0, 10.0, -1.0));
6566 }
6567
6568 /// C parity bug fix (recGbl.c:355-358): exactly one of {newval,
6569 /// oldval} is NaN — fire. Rust port previously short-circuited only
6570 /// on `oldval=NaN`; `newval=NaN` with `oldval=finite` produced
6571 /// `(NaN - finite).abs() = NaN`, `NaN > deadband = false` →
6572 /// silently dropped the NaN transition. End effect: a record that
6573 /// went UDF (e.g. divide-by-zero in calc) never posted the change
6574 /// to monitors, leaving every camonitor seeing the last valid value.
6575 #[test]
6576 fn newval_nan_with_finite_oldval_fires() {
6577 assert!(check_deadband(f64::NAN, 10.0, 1.0));
6578 }
6579
6580 /// C path case 2 (recGbl.c:355): exactly one infinite, the other
6581 /// finite — fire.
6582 #[test]
6583 fn one_finite_one_infinite_fires() {
6584 assert!(check_deadband(f64::INFINITY, 10.0, 1.0));
6585 assert!(check_deadband(10.0, f64::INFINITY, 1.0));
6586 assert!(check_deadband(f64::NEG_INFINITY, 10.0, 1.0));
6587 }
6588
6589 /// C path case 3 (recGbl.c:360-362): both infinite with opposite
6590 /// signs — fire.
6591 #[test]
6592 fn opposite_signed_infinities_fire() {
6593 assert!(check_deadband(f64::INFINITY, f64::NEG_INFINITY, 1.0));
6594 assert!(check_deadband(f64::NEG_INFINITY, f64::INFINITY, 1.0));
6595 }
6596
6597 /// Same-signed infinity → no fire (C path leaves `delta = 0`,
6598 /// `0 > deadband` is false for any non-negative deadband).
6599 #[test]
6600 fn same_signed_infinity_does_not_fire() {
6601 assert!(!check_deadband(f64::INFINITY, f64::INFINITY, 1.0));
6602 assert!(!check_deadband(f64::NEG_INFINITY, f64::NEG_INFINITY, 1.0));
6603 }
6604}
6605
6606#[cfg(test)]
6607mod common_field_dbload_tests {
6608 use super::*;
6609 use crate::server::records::ai::AiRecord;
6610
6611 /// The db loader feeds every common field to `put_common_field` as an
6612 /// `EpicsValue::String`. Each numeric/menu common field directive must
6613 /// take effect at load — both the integer form (`field(PHAS, "1")`) and
6614 /// the menu-label form (`field(PRIO, "HIGH")`, `field(DISS, "MAJOR")`) —
6615 /// rather than being silently dropped because the arm matched only its
6616 /// typed variant. One assertion per affected common-field arm.
6617 #[test]
6618 fn db_loaded_string_common_fields_take_effect() {
6619 let mut inst = RecordInstance::new("REC".to_string(), AiRecord::default());
6620 let put = |inst: &mut RecordInstance, f: &str, v: &str| {
6621 inst.put_common_field_db_load(f, EpicsValue::String(v.into()))
6622 .unwrap_or_else(|e| panic!("put_common_field_db_load({f}, {v:?}) failed: {e}"));
6623 };
6624
6625 // Integer-valued directives.
6626 put(&mut inst, "PHAS", "1");
6627 assert_eq!(inst.common.phas, 1, "field(PHAS, \"1\")");
6628 put(&mut inst, "TSE", "-2");
6629 assert_eq!(inst.common.tse, -2, "field(TSE, \"-2\")");
6630 put(&mut inst, "DISV", "1");
6631 assert_eq!(inst.common.disv, 1, "field(DISV, \"1\")");
6632 put(&mut inst, "DISA", "1");
6633 assert_eq!(inst.common.disa, 1, "field(DISA, \"1\")");
6634 put(&mut inst, "LCNT", "3");
6635 assert_eq!(inst.common.lcnt, 3, "field(LCNT, \"3\")");
6636 put(&mut inst, "DISP", "1");
6637 assert!(inst.common.disp != 0, "field(DISP, \"1\")");
6638 put(&mut inst, "UDF", "0");
6639 assert!(inst.common.udf == 0, "field(UDF, \"0\")");
6640
6641 // Menu-label directives (resolved via the one menu converter).
6642 put(&mut inst, "PRIO", "HIGH");
6643 assert_eq!(inst.common.prio, 2, "field(PRIO, \"HIGH\")");
6644 put(&mut inst, "DISS", "MAJOR");
6645 assert_eq!(
6646 inst.common.diss,
6647 AlarmSeverity::Major as i16,
6648 "field(DISS, \"MAJOR\")"
6649 );
6650 put(&mut inst, "UDFS", "NO_ALARM");
6651 assert_eq!(
6652 inst.common.udfs,
6653 AlarmSeverity::NoAlarm as i16,
6654 "field(UDFS, \"NO_ALARM\")"
6655 );
6656 put(&mut inst, "ACKT", "NO");
6657 assert!(!inst.common.ackt, "field(ACKT, \"NO\")");
6658
6659 // Numeric form of a menu field still works (field(PRIO, "0")).
6660 put(&mut inst, "PRIO", "0");
6661 assert_eq!(inst.common.prio, 0, "field(PRIO, \"0\")");
6662
6663 // A String-typed common field is untouched by the coercion.
6664 put(&mut inst, "DESC", "a description");
6665 assert_eq!(inst.common.desc.as_str_lossy().as_ref(), "a description");
6666 }
6667}
6668
6669#[cfg(test)]
6670mod declared_override_tests {
6671 use super::*;
6672 use crate::server::records::dfanout::DfanoutRecord;
6673
6674 /// A field `dfanout`'s `.dbd` DECLARES (HOPR/LOPR/PREC/EGU) but the
6675 /// `DfanoutRecord` struct models no storage for: a put must be ACCEPTED and
6676 /// stored (C `dbPut` writes it into record memory), and a later
6677 /// `resolve_field` must serve the written value — not the `.dbd` initial.
6678 #[test]
6679 fn declared_but_unmodeled_field_put_is_stored_and_served() {
6680 let mut inst = RecordInstance::new("DF".to_string(), DfanoutRecord::default());
6681
6682 // Untouched: reads its declared default (initial / type-zero), NOT an
6683 // error, and the override store is empty.
6684 assert_eq!(inst.resolve_field("HOPR"), Some(EpicsValue::Double(0.0)));
6685 assert!(inst.declared_overrides.is_empty());
6686
6687 // DBF_DOUBLE, DBF_SHORT and DBF_STRING declared metadata fields all
6688 // land, coerced to the declared type.
6689 inst.put_common_field("HOPR", EpicsValue::String("10".into()))
6690 .expect("caput dfanout.HOPR 10 must be accepted");
6691 inst.put_common_field("PREC", EpicsValue::String("3".into()))
6692 .expect("caput dfanout.PREC 3 must be accepted");
6693 inst.put_common_field("EGU", EpicsValue::String("volts".into()))
6694 .expect("caput dfanout.EGU volts must be accepted");
6695
6696 assert_eq!(inst.resolve_field("HOPR"), Some(EpicsValue::Double(10.0)));
6697 assert_eq!(inst.resolve_field("PREC"), Some(EpicsValue::Short(3)));
6698 assert_eq!(
6699 inst.resolve_field("EGU"),
6700 Some(EpicsValue::String("volts".into()))
6701 );
6702 // Case-insensitive key: the lower-case read reaches the same slot.
6703 assert_eq!(inst.resolve_field("hopr"), Some(EpicsValue::Double(10.0)));
6704 }
6705
6706 /// The declared type's C range rules apply through the write-side coercion
6707 /// owner: `caput dfanout.PREC 99999` into a `DBF_SHORT` is REFUSED (C
6708 /// `epicsParseInt16` overflow → `S_db_badField`), and the field keeps its
6709 /// prior value — never wraps to a garbage `Short`.
6710 #[test]
6711 fn declared_override_honors_declared_type_range() {
6712 let mut inst = RecordInstance::new("DF".to_string(), DfanoutRecord::default());
6713 inst.put_common_field("PREC", EpicsValue::String("3".into()))
6714 .expect("in-range PREC accepted");
6715 assert!(
6716 inst.put_common_field("PREC", EpicsValue::String("99999".into()))
6717 .is_err(),
6718 "PREC 99999 overflows DBF_SHORT and must be refused"
6719 );
6720 assert!(
6721 inst.put_common_field("PREC", EpicsValue::String("abc".into()))
6722 .is_err(),
6723 "non-numeric PREC must be refused"
6724 );
6725 // The refused puts left the accepted value intact.
6726 assert_eq!(inst.resolve_field("PREC"), Some(EpicsValue::Short(3)));
6727 }
6728
6729 /// An UNDECLARED field name is still `FieldNotFound` — the override store
6730 /// captures only fields with a real `dbFldDes`, so a misspelled field is
6731 /// refused exactly as C's `dbNameToAddr` refuses it.
6732 #[test]
6733 fn undeclared_field_is_still_not_found() {
6734 let mut inst = RecordInstance::new("DF".to_string(), DfanoutRecord::default());
6735 assert!(matches!(
6736 inst.put_common_field("XYZZY", EpicsValue::String("1".into())),
6737 Err(CaError::FieldNotFound(_))
6738 ));
6739 assert!(inst.declared_overrides.is_empty());
6740 }
6741
6742 /// A PARTIALLY modeled field — one the record SERVES via `get_field` but
6743 /// has no `put_field` arm for (`calcout.PVAL` → `self.pval`) — must NOT
6744 /// land in the override map: doing so would place the value where
6745 /// `resolve_field` (which reads `get_field` first) never sees it, a silent
6746 /// write loss. The override is only for fields the record serves nothing
6747 /// for; a partially modeled field's put is the record's own concern.
6748 #[test]
6749 fn partially_modeled_field_is_not_captured_by_override() {
6750 use crate::server::records::calcout::CalcoutRecord;
6751 let mut inst = RecordInstance::new("CO".to_string(), CalcoutRecord::default());
6752 // PVAL is served by the record (its own storage), so it is not stored
6753 // in the override map; the map stays empty and no ghost cell shadows
6754 // the record's read.
6755 let _ = inst.put_common_field("PVAL", EpicsValue::String("1".into()));
6756 assert!(
6757 inst.declared_overrides.is_empty(),
6758 "a field the record serves via get_field must not enter the override map"
6759 );
6760 }
6761}