epics_base_rs/server/record/record_trait.rs
1use crate::error::CaResult;
2use crate::types::{DbFieldType, EpicsValue, PvString, c_parse};
3
4use super::scan::ScanType;
5
6/// Which of a `devXxxSoftRaw` dset's two entry points is delivering a value to
7/// [`Record::raw_soft_input`]. They are not the same function in C, and they do
8/// not agree about `MASK`.
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum RawSoftEntry {
11 /// `devXxxSoftRaw::init_record` — `recGblInitConstantLink(&prec->inp,
12 /// DBF_x, &prec->rval)` (`devAiSoftRaw.c:41`, `devBiSoftRaw.c:42`,
13 /// `devMbbiSoftRaw.c:42`, `devMbbiDirectSoftRaw.c:42`). A CONSTANT `INP`
14 /// (`field(INP,"12")`) is loaded ONCE, at iocInit, straight into `RVAL`.
15 ///
16 /// `recGblInitConstantLink` is a plain typed store — **no MASK**. The mask
17 /// lives in `read_xxx`, which a constant INP never reaches (a constant link
18 /// delivers nothing at process).
19 InitConstant,
20 /// `devXxxSoftRaw::read_xxx` — the per-cycle `dbGetLink(&prec->inp, ...)`
21 /// followed by the dset's own masking (`devBiSoftRaw.c:56-57` `if
22 /// (prec->mask) prec->rval &= prec->mask;`, `devMbbiSoftRaw.c:78-79`
23 /// unconditionally).
24 Read,
25}
26
27/// The `special(SPC_*)` dispatch code a field declares — C `special.h`.
28///
29/// C hands this to the record's `special(DBADDR *, int after)` on every put, and
30/// `dbAccess.c` acts on three of them itself before the record ever sees the
31/// write: `NoMod` refuses it (`S_db_noMod`), `DbAddr` means the field's type and
32/// element count come from the record's `cvt_dbaddr` rather than the `.dbd`, and
33/// `As` re-evaluates access security.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum Special {
36 /// No `special()` declared.
37 None,
38 /// `SPC_NOMOD` (1) — the field must not be modified. Mirrored into
39 /// [`FieldDesc::read_only`], which is the bit the put gate reads.
40 NoMod,
41 /// `SPC_DBADDR` (2) — the record's `cvt_dbaddr` supplies the field's type
42 /// and element count. [`FieldDesc::dbf_type`] carries the type C serves at
43 /// the selector field's default; a record whose type is state-dependent
44 /// (`waveform.VAL` on `FTVL`, `mbbo.VAL` on `SDEF`) overrides it at runtime.
45 DbAddr,
46 /// `SPC_SCAN` (3) — a scan-related field; C re-registers the scan.
47 Scan,
48 /// `SPC_ALARMACK` (5) — an alarm acknowledgement.
49 AlarmAck,
50 /// `SPC_AS` (6) — access security; C re-computes the record's ASG.
51 As,
52 /// `SPC_ATTRIBUTE` (7) — a pseudo (attribute) field.
53 Attribute,
54 /// `SPC_MOD` (100) — the record's own `special()` runs on the put.
55 Mod,
56 /// `SPC_RESET` (101) — the `RES` field is being modified.
57 Reset,
58 /// `SPC_LINCONV` (102) — a linear-conversion field changed; C calls the
59 /// device support's `special_linconv`.
60 LinConv,
61 /// `SPC_CALC` (103) — the `CALC` expression changed; C recompiles it.
62 Calc,
63}
64
65/// A field's access-security level — C `.dbd` `asl(ASL0|ASL1)`.
66///
67/// `ASL1` is the `.dbd` default (`dbLexRoutines.c:570`); `asl(ASL0)` lowers a
68/// field to the level an operator may write.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum Asl {
71 Asl0,
72 Asl1,
73}
74
75/// The `.dbd` declaration of a single record field.
76///
77/// Every one of these is **generated** from the vendored EPICS `.dbd` by
78/// `tools/dbd-codegen` — see [`dbd_generated`](super::dbd_generated). They used
79/// to be hand-copied, which is what made a wrong `dbf_type` or a missed
80/// `special(SPC_NOMOD)` a recurring finding rather than an impossible state.
81///
82/// The struct carries the *whole* declaration, not just the three attributes the
83/// runtime consumes today: dropping the rest at the parser is how the port ended
84/// up unable to answer questions like "is this field `pp(TRUE)`?" without
85/// re-reading the `.dbd`.
86#[derive(Debug, Clone)]
87pub struct FieldDesc {
88 /// The field name, upper-case as declared.
89 pub name: &'static str,
90 /// The `DBF_*` type. This is the *field* type; the CA wire type is derived
91 /// from it by [`DbFieldType::ca_wire_type`], which owns the promotions CA
92 /// has no type for (`ULong`/`Int64`/`UInt64` -> `DBR_DOUBLE`, `UShort` ->
93 /// `DBR_LONG`, `UChar` -> `DBR_CHAR`). Do not pre-promote here: PVA serves
94 /// the native width.
95 ///
96 /// This is what the field is SERVED as, on every delivery path — see
97 /// [`RecordInstance::project_to_declared_type`](super::RecordInstance::project_to_declared_type),
98 /// which projects the stored value onto it. The one exception is a
99 /// [`Self::runtime_typed`] field, where C's `cvt_dbaddr` overrides.
100 pub dbf_type: DbFieldType,
101 /// C's `cvt_dbaddr` re-types this field at name-resolution time from the
102 /// record's own state — `waveform.VAL` from `FTVL`, `aSub.A` from `FTA`,
103 /// `mbbo.VAL` from `SDEF` — so the `.dbd` declaration is a placeholder
104 /// carrying only the selector's default. [`Self::dbf_type`] is therefore
105 /// NOT what such a field is served as; the record's stored variant is this
106 /// port's `cvt_dbaddr` answer, and it wins.
107 ///
108 /// A `special(SPC_DBADDR)` field whose type is nevertheless FIXED
109 /// (`compress.VAL` is always a double array, `histogram.VAL` always
110 /// `epicsUInt32`) is *not* runtime-typed: its row in `cvt_dbaddr.types`
111 /// carries no selector, so the declared type is the true one and it is
112 /// projected like any other field.
113 pub runtime_typed: bool,
114 /// `special(SPC_NOMOD)` — the field is immutable for this record type. The
115 /// static half of the no-modify declaration; see [`Record::field_no_mod`]
116 /// for the half a record decides at runtime.
117 pub read_only: bool,
118 /// The full `special()` code, of which [`Self::read_only`] is one case.
119 pub special: Special,
120 /// `pp(TRUE)` — a put to this field processes the record.
121 pub pp: bool,
122 /// `asl(...)` — the access-security level.
123 pub asl: Asl,
124 /// `size(N)` — the declared byte size of a `DBF_STRING` field, or 0.
125 pub size: u16,
126 /// `menu(...)` choice strings, in index order, for a `DBF_MENU` field. The
127 /// index is the stored value and the strings are what `get_enum_strs` serves,
128 /// so a client sees `"NO CONVERSION"` rather than `0`.
129 pub menu: Option<&'static [&'static str]>,
130 /// `initial("...")` — the value C's dbd loader seeds the field with.
131 pub initial: Option<&'static str>,
132 /// `interest(N)` — the `dbpr` verbosity level at which C prints the field.
133 pub interest: u8,
134 /// `prop(YES)` — the field is a property: a change to it posts a
135 /// `DBE_PROPERTY` event.
136 pub prop: bool,
137}
138
139impl FieldDesc {
140 /// A hand-written descriptor carrying only the three attributes the port
141 /// used to model.
142 ///
143 /// **Transitional.** Every record type is migrating to the generated table
144 /// in [`dbd_generated`](super::dbd_generated), which carries the whole `.dbd`
145 /// declaration; this constructor exists only so the not-yet-migrated records
146 /// keep compiling, and it goes away with the last of them. It does NOT know
147 /// the field's `pp`/`asl`/`size`/`menu`/`initial`, so it reports the neutral
148 /// value for each — a record still on this constructor answers "no menu"
149 /// here and resolves its choices through the
150 /// [`Record::menu_field_choices`] fallback instead.
151 pub const fn new(name: &'static str, dbf_type: DbFieldType, read_only: bool) -> Self {
152 Self {
153 name,
154 dbf_type,
155 // A hand-written table declares a plain field: the type it names is
156 // the type it is served as. The `cvt_dbaddr` records are all on the
157 // generated table, which sets this from `cvt_dbaddr.types`.
158 runtime_typed: false,
159 read_only,
160 special: if read_only {
161 Special::NoMod
162 } else {
163 Special::None
164 },
165 pp: false,
166 asl: Asl::Asl1,
167 size: 0,
168 menu: None,
169 initial: None,
170 interest: 0,
171 prop: false,
172 }
173 }
174}
175
176/// One `recGblInitConstantLink(&prec->LINK, DBF_x, &prec->TARGET)` call from a
177/// record's C `init_record` — the seed of a CONSTANT input link.
178///
179/// Declared by [`Record::constant_init_links`] and applied by the single owner
180/// [`crate::server::database::PvDatabase::rec_gbl_init_constant_links`].
181#[derive(Debug, Clone, Copy, PartialEq, Eq)]
182pub struct ConstantInitLink {
183 /// The link field holding the constant (`INPA`, `NVL`, `SELL`, `DOL1`,
184 /// `SUBL`, `DOL`, ...).
185 pub link_field: &'static str,
186 /// The value field the constant is loaded into (`A`, `SELN`, `DO1`,
187 /// `SNAM`, `VAL`, ...).
188 pub target_field: &'static str,
189 /// Whether a successful seed clears UDF — C's
190 /// `if (recGblInitConstantLink(&prec->dol, ...)) prec->udf = FALSE;`
191 /// (`aoRecord.c:112-113`, `longoutRecord.c:113`, `mbboRecord.c:133`,
192 /// `int64outRecord.c:110`, `dfanoutRecord.c:105`). The multi-input seeders
193 /// (calc/sub/sel/aSub/seq/fanout) do NOT clear UDF: they seed A..L, not
194 /// VAL.
195 pub clears_udf: bool,
196 /// Whether the loaded value is stored as its BOOLEAN — C `boRecord.c:146-148`
197 /// loads the constant into a temporary and stores `prec->val = !!ival`, so
198 /// `field(DOL,"5")` leaves a bo at VAL=1, not 5. The only seed whose stored
199 /// value differs from the loaded one.
200 pub normalize_bool: bool,
201}
202
203impl ConstantInitLink {
204 /// A seed that does not touch UDF — the INPA..L / SELL / NVL / DOLn form.
205 pub const fn new(link_field: &'static str, target_field: &'static str) -> Self {
206 Self {
207 link_field,
208 target_field,
209 clears_udf: false,
210 normalize_bool: false,
211 }
212 }
213
214 /// A DOL→VAL seed, which C follows with `prec->udf = FALSE`.
215 pub const fn dol_to_val(link_field: &'static str, target_field: &'static str) -> Self {
216 Self {
217 link_field,
218 target_field,
219 clears_udf: true,
220 normalize_bool: false,
221 }
222 }
223
224 /// bo's DOL→VAL seed: `prec->val = !!ival; prec->udf = FALSE;`
225 /// (`boRecord.c:146-149`).
226 pub const fn dol_to_bool_val(link_field: &'static str, target_field: &'static str) -> Self {
227 Self {
228 link_field,
229 target_field,
230 clears_udf: true,
231 normalize_bool: true,
232 }
233 }
234}
235
236/// The seed table for a record whose C seeds exactly the input links it
237/// fetches — the `for (i = 0; i < N; i++) recGblInitConstantLink(plink++,
238/// DBF_DOUBLE, pvalue++)` loop of calc / calcout / sub / sel / aSub /
239/// scalcout / acalcout / transform, expressed over the record's own
240/// [`Record::multi_input_links`] table.
241pub fn seed_input_links(pairs: &[(&'static str, &'static str)]) -> Vec<ConstantInitLink> {
242 pairs
243 .iter()
244 .map(|(link, value)| ConstantInitLink::new(link, value))
245 .collect()
246}
247
248/// Resolved metadata of an OUT-link TARGET, as C's soft device support
249/// obtains it before choosing its write buffer.
250///
251/// C's two sources, both mirrored by
252/// [`PvDatabase::resolve_out_target`](crate::server::database::PvDatabase):
253/// - `DB_LINK` — `dbNameToAddr` gives `field_type` and `no_elements`
254/// (`devsCalcoutSoft.c:127-131`, `devaCalcoutSoft.c:78-79`); an
255/// unresolvable name leaves the caller's initializers untouched.
256/// - `CA_LINK` — `dbCaGetLinkDBFtype` / `dbCaGetNelements`
257/// (`dbCa.c:662-704`), which both return `-1` on a disconnected link and
258/// likewise leave the initializers untouched.
259///
260/// A record reproduces its C device support's buffer switch on this in
261/// [`Record::multi_output_buffer`].
262#[derive(Debug, Clone, Copy, PartialEq, Eq)]
263pub struct OutTarget {
264 /// Target field's DBF type. `None` = unresolved (disconnected CA link,
265 /// or a name this IOC cannot resolve) — C's `field_type` initializer.
266 pub field_type: Option<DbFieldType>,
267 /// Target field's element capacity — C `no_elements` / `dbCaGetNelements`.
268 /// `1` when unresolved, matching C's `n_elements = 1` initializer.
269 pub element_count: i64,
270 /// True when C would classify this link as a `CA_LINK`: an explicit
271 /// `ca://`/`pva://` link, or a DB-style name that is not a record of
272 /// this IOC (`dbInitLink` locality). Device support that splits its
273 /// buffer choice on sync-vs-async (`devsCalcoutSoft.c:76`, gated on
274 /// `plink->type == CA_LINK && pscalcout->wait`) reads this.
275 pub is_ca_link: bool,
276 /// True when the target field is one of the seven DBF classes C's soft
277 /// device support puts as `DBR_STRING` — `DBF_STRING`, `DBF_ENUM`,
278 /// `DBF_MENU`, `DBF_DEVICE`, `DBF_INLINK`, `DBF_OUTLINK`, `DBF_FWDLINK`
279 /// (`devsCalcoutSoft.c:83-85`, `:128-130`).
280 ///
281 /// Carried here rather than re-derived from [`Self::field_type`] because
282 /// [`DbFieldType`] is the DBR *wire* type: it has no `Menu` or `Device`
283 /// variant, so a menu target (`PRIO`, `STAT`, `SEVR`, `DISS`, `ACKT`, …)
284 /// or `DTYP` is indistinguishable from a plain numeric/string field by
285 /// type alone. The classification is made once, at resolution, by the
286 /// side that holds the target's field metadata
287 /// (`RecordInstance::field_puts_as_string`); a record's
288 /// [`Record::multi_output_buffer`] just reads the answer.
289 pub puts_as_string: bool,
290}
291
292impl OutTarget {
293 /// C's initializer state: `field_type = 0` is never *used* as a type by
294 /// the port (a `None` type routes to the device support's `default:`
295 /// arm), and `n_elements = 1`. An unresolved target is not in the string
296 /// class — C's `field_type = 0` matches no `case` and falls to `default:`.
297 pub const UNRESOLVED: Self = Self {
298 field_type: None,
299 element_count: 1,
300 is_ca_link: false,
301 puts_as_string: false,
302 };
303}
304
305/// The `dbrType` a record asks an INPUT link for — the second argument of C
306/// `dbGetLink(plink, dbrType, pbuffer, options, pnRequest)` (`dbLink.c:305`).
307///
308/// The READ twin of [`Record::typed_output_buffer`]'s destination switch. C's
309/// input-side switch is on the SOURCE's DBF class (`dbGetLinkDBFtype(&dol)`,
310/// `sseqRecord.c:640-705`) and each arm asks `dbGetLink` for a DIFFERENT
311/// `dbrType`, so the value a record receives is not the source's native one:
312/// a `DBF_ENUM`/`DBF_MENU` source read with `DBR_STRING` delivers its state
313/// LABEL, and a `DBF_CHAR` array read with `DBF_CHAR` delivers bytes, not a
314/// number. The record declares the request
315/// ([`Record::input_link_read_as`]); the framework, which is the side that
316/// can address the source, performs the conversion.
317#[derive(Debug, Clone, Copy, PartialEq, Eq)]
318pub enum LinkReadAs {
319 /// The source's NATIVE value, coerced (or preserved) by the target field's
320 /// own `put_field_internal`. The framework default: every record whose C
321 /// `dbGetLink` request does not switch on the source class (compress `INP`,
322 /// waveform `INP`, sseq `SELL`, epid, motor, table) reads this way.
323 Native,
324 /// C `dbGetLink(..., DBR_STRING, ...)`. An `ENUM`/`MENU` source delivers its
325 /// state LABEL (`dbConvert.c` `getEnumString` → the record's
326 /// `get_enum_str`), never the index; a link/`DTYP` field delivers its text.
327 String,
328 /// C `dbGetLink(..., DBR_DOUBLE, ...)`.
329 Double,
330 /// C `dbGetLink(..., DBF_CHAR|DBF_UCHAR, buf, 0, &n)` — up to `max_elements`
331 /// bytes of the source's char array, taken as the string they spell
332 /// (`sseqRecord.c:682-686`: `n_elements` clamped to the record's 40-byte
333 /// `s` buffer, then `strcmp`/`atof` read it as a C string).
334 CharArrayAsString { max_elements: usize },
335}
336
337/// How C gates a secondary field named by
338/// [`Record::fields_posted_with_value_mask`] *inside* the guard that decides
339/// whether VAL posts at all.
340///
341/// Both variants share the outer guard (the field posts only on a cycle where
342/// VAL's own monitor mask is live, and carries that same mask); they differ in
343/// whether C re-tests the secondary field's own value once inside it. Folding
344/// the two into one rule is what over- or under-posts the field: gating
345/// `timestamp`'s RVAL on its own change silences it (see [`Self::WithValue`]),
346/// and NOT gating `ai`'s RVAL on its own change posts a raw count that never
347/// moved.
348#[derive(Debug, Clone, Copy, PartialEq, Eq)]
349pub enum ValuePostGate {
350 /// C re-tests the field's own previous value inside the guard, and posts
351 /// only if it moved: `ai` `RVAL` — `if (prec->oraw != prec->rval) {
352 /// db_post_events(&prec->rval, monitor_mask); prec->oraw = prec->rval; }`
353 /// (aiRecord.c:460-465).
354 OnChange,
355 /// C posts the field whenever the guard fires, with no test of its own
356 /// value: `timestamp` `RVAL` — `if (strncmp(oval, val, ...)) {
357 /// db_post_events(&val[0], mask); db_post_events(&rval, mask); }`
358 /// (timestampRecord.c:158-162). The VAL-string change is the *only* gate,
359 /// so a cycle that re-renders the same seconds count still re-posts RVAL.
360 WithValue,
361}
362
363/// The event mask ONE per-cycle mark posts with
364/// ([`Record::take_cycle_posted_fields`]).
365///
366/// A record can mark the same field from two different C `db_post_events` call
367/// sites in one cycle, and the two need not agree on the mask. aCalcout does
368/// exactly that with its arrays: `afterCalc` posts the AMASK-flagged ones with a
369/// LITERAL `DBE_VALUE|DBE_LOG` (`aCalcoutRecord.c:296`) while `monitor()` posts
370/// the NEWM-flagged ones with `monitor_mask|DBE_VALUE|DBE_LOG` (`:1034`). An
371/// array in BOTH masks gets BOTH events — the record marks it twice, and the
372/// variant carried with each mark is what keeps them distinguishable.
373#[derive(Debug, Clone, Copy, PartialEq, Eq)]
374pub enum CyclePostMask {
375 /// A literal `DBE_VALUE` — no LOG bit, no alarm bits. C's shape for a
376 /// field the record re-DERIVED from the one it was given: sseq re-renders
377 /// `STRn` after a `DOn` write and posts it with a bare `DBE_VALUE`
378 /// (`sseqRecord.c:679`, `:1115`), while the view actually written carries
379 /// `DBE_VALUE|DBE_LOG`.
380 Value,
381 /// A literal `DBE_VALUE | DBE_LOG` — the alarm-transition bits are NOT
382 /// folded in, because this C call site does not have `monitor_mask` in
383 /// scope (aCalcout `afterCalc`, `aCalcoutRecord.c:296`).
384 ValueLog,
385 /// `monitor_mask | DBE_VALUE | DBE_LOG` — C's usual `monitor()` shape
386 /// (aCalcout `monitor()`, `aCalcoutRecord.c:1034`).
387 MonitorValueLog,
388}
389
390/// The [`ValuePostGate`] a record declared for `field`, or `None` when `field`
391/// is not one of its secondary value-mask fields.
392///
393/// The single lookup for [`Record::fields_posted_with_value_mask`], shared by
394/// every monitor loop (both `process_record_*` paths, the deferred-completion
395/// path, and `RecordInstance::process_local`) so they cannot drift apart on how
396/// a secondary field is gated.
397pub(crate) fn value_gate(
398 value_masked: &'static [(&'static str, ValuePostGate)],
399 field: &str,
400) -> Option<ValuePostGate> {
401 value_masked
402 .iter()
403 .find(|(name, _)| *name == field)
404 .map(|(_, gate)| *gate)
405}
406
407/// The event mask a change-detected AUXILIARY field posts with — the single
408/// owner of that decision, built once per cycle from the record's declarations
409/// and shared by every monitor loop (both `process_record_*` paths, the
410/// deferred-completion path, and `RecordInstance::process_local`), so they
411/// cannot drift apart on what mask a field carries.
412///
413/// C's usual shape for the "post every input/aux field that changed" loop is
414/// `monitor_mask | DBE_VALUE | DBE_LOG` (calcRecord.c:420, subRecord.c:400,
415/// motor `DBE_VAL_LOG`) — that is the default. Three record-declared exceptions
416/// narrow it, and no two are the same narrowing:
417///
418/// * [`Record::value_only_change_fields`] — a literal `DBE_VALUE`
419/// (tableRecord.c:659, scaler `Sn`): alarm bits + `DBE_VALUE`, never `LOG`.
420/// * [`Record::fields_posted_with_monitor_mask`] — `monitor_mask | DBE_VALUE`
421/// (swaitRecord.c:650): VAL's own monitor mask, so `DBE_LOG` rides along
422/// exactly when VAL's ADEL deadband crossed.
423/// * [`Record::fields_posted_without_alarm_bits`] — a literal
424/// `DBE_VALUE | DBE_LOG` (epidRecord.c:376): both value classes, alarm bits
425/// discarded.
426#[derive(Clone, Copy)]
427pub(crate) struct AuxPostMask {
428 value_only: &'static [&'static str],
429 monitor_masked: &'static [&'static str],
430 no_alarm_bits: &'static [&'static str],
431}
432
433impl AuxPostMask {
434 /// Read the record's three declarations once, outside the per-field loop.
435 pub(crate) fn of(record: &dyn Record) -> Self {
436 Self {
437 value_only: record.value_only_change_fields(),
438 monitor_masked: record.fields_posted_with_monitor_mask(),
439 no_alarm_bits: record.fields_posted_without_alarm_bits(),
440 }
441 }
442
443 /// `alarm_bits` is this cycle's `recGblResetAlarms` result; `deadband_mask`
444 /// is VAL's own monitor mask (those alarm bits, plus `DBE_VALUE` when MDEL
445 /// crossed and `DBE_LOG` when ADEL crossed).
446 pub(crate) fn mask_for(
447 &self,
448 field: &str,
449 alarm_bits: crate::server::recgbl::EventMask,
450 deadband_mask: crate::server::recgbl::EventMask,
451 ) -> crate::server::recgbl::EventMask {
452 use crate::server::recgbl::EventMask;
453 if self.value_only.contains(&field) {
454 alarm_bits | EventMask::VALUE
455 } else if self.monitor_masked.contains(&field) {
456 deadband_mask | EventMask::VALUE
457 } else if self.no_alarm_bits.contains(&field) {
458 EventMask::VALUE | EventMask::LOG
459 } else {
460 alarm_bits | EventMask::VALUE | EventMask::LOG
461 }
462 }
463}
464
465/// Outcome of a record's array-style monitor decision, returned by
466/// [`Record::array_monitor_post`] (C waveform/aai/aao `monitor()`,
467/// waveformRecord.c:291-326).
468#[derive(Debug, Clone, Copy)]
469pub struct ArrayMonitorPost {
470 /// Include `DBE_VALUE` on the VAL post this cycle (MPST = Always, or
471 /// MPST = On Change with a changed hash).
472 pub post_value: bool,
473 /// Include `DBE_LOG` on the VAL post this cycle (APST = Always, or
474 /// APST = On Change with a changed hash).
475 pub post_archive: bool,
476 /// The content hash changed this cycle (On Change mode) — the owner
477 /// posts `HASH` with a literal `DBE_VALUE`.
478 pub hash_changed: bool,
479}
480
481/// The record type's RSET metadata slots — which of C's six nullable
482/// `get_*` property functions the record type implements.
483///
484/// This is the port's `rset` property table, transcribed slot by slot
485/// from the `#define get_xxx NULL` lines of each C record's `.c`. It is
486/// what `dbGet` consults to *narrow* the caller's `options` mask
487/// (`dbAccess.c:336-430`), and therefore what decides whether QSRV marks
488/// an NT leaf at all (pvxs `ioc/iocsource.cpp:263-305`). Without it the
489/// port fabricated every leaf it could name and marked it as supplied —
490/// telling the client a made-up `display.precision = 0` on a `longout`,
491/// or `valueAlarm` bands at zero on a `waveform`, were authoritative.
492///
493/// A slot counts as supplied when the C function pointer is non-NULL,
494/// even if the function writes nothing for the field in question — C
495/// leaves the option bit set either way (e.g. `boRecord.c:294-299`,
496/// whose `get_units` writes `"s"` only for `HIGH`, yet `DBR_UNITS`
497/// survives for every `bo` field).
498/// What a record type's C `get_control_double` writes for a field its switch
499/// does not list — the slot's LAST arm.
500///
501/// Independent of [`crate::server::snapshot::PropertySupport::control_double`],
502/// which says whether the slot EXISTS at all (a NULL slot makes
503/// `dbAccess.c:257` fail and clears the option bit, so no leaf is served).
504/// This says what a slot that DOES exist answers when it falls through. The
505/// two genuinely differ: `acalcout` supplies the slot and still writes nothing
506/// for an unlisted field.
507///
508/// Slot-neutral: the two arm SHAPES are the same for `get_control_double` and
509/// `get_graphic_double`, but which one a record type takes is asked per slot —
510/// [`control_default_arm`] and [`graphic_default_arm`] are separate answers.
511/// `aSub` is the type that proves they must be: its `get_control_double` is a
512/// bare `recGblGetControlDouble` (`aSubRecord.c:372-376`) while its
513/// `get_graphic_double` (`:350-368`) has no recGbl call at all.
514#[derive(Debug, Clone, Copy, PartialEq, Eq)]
515pub enum RsetDefaultArm {
516 /// The slot ends in `recGblGetControlDouble` / `recGblGetGraphicDouble` —
517 /// the field TYPE's numeric range (`recGbl.c:146-171`, table at
518 /// `:372-419`).
519 RecGblRange,
520 /// The slot returns without writing, so the `dbAccess.c:256` / `:216`
521 /// `(0.0, 0.0)` seed stands.
522 Seed,
523}
524
525/// The last arm of `rtype`'s C `get_control_double`.
526///
527/// Audited by reading each ported record type's own C rset. Every record in
528/// EPICS base delegates (`aiRecord.c:267`, `aoRecord.c:341`, `calcRecord.c:235`,
529/// `calcoutRecord.c:506`, `aSubRecord.c:372`, `subRecord.c:272`,
530/// `selRecord.c:203`, `seqRecord.c:342`, `dfanoutRecord.c:197`,
531/// `longinRecord.c:217`, `longoutRecord.c:268`, `int64inRecord.c:212`,
532/// `int64outRecord.c:251`, `boRecord.c:310`, `waveformRecord.c:268`,
533/// `aaiRecord.c:293`, `aaoRecord.c:296`, `subArrayRecord.c:262`,
534/// `compressRecord.c:487`, `histogramRecord.c:458`), as do the downstream
535/// types that supply the slot (`motorRecord.cc:3303`, `epidRecord.c:285`,
536/// `tableRecord.c:806`). The rest NULL it outright and never reach here
537/// (`biRecord.c`, `mbbiRecord.c`, `mbboRecord.c`, `mbbiDirectRecord.c`,
538/// `mbboDirectRecord.c`, `stringinRecord.c`, `stringoutRecord.c`,
539/// `lsiRecord.c`, `lsoRecord.c`, `eventRecord.c`, `fanoutRecord.c`,
540/// `permissiveRecord.c`, `printfRecord.c`, `stateRecord.c`,
541/// `sseqRecord.c:141`, `swaitRecord.c`, `transformRecord.c`, `busyRecord.c`,
542/// `asynRecord.c`, `throttleRecord.c:70`, `scalerRecord.c:157`).
543///
544/// Only the synApps calc pair writes nothing: both end `get_control_double`
545/// with a bare `return(0)` after their listed cases, so C serves the seed
546/// where a delegating record serves the type range. Measured on the
547/// differential oracle as 42 `acalcout`/`scalcout` fields.
548pub fn control_default_arm(rtype: &str) -> RsetDefaultArm {
549 match rtype {
550 // aCalcoutRecord.c:793-822, sCalcoutRecord.c:653 — the switch lists
551 // VAL/HIHI/HIGH/LOW/LOLO and the A-L / PA-PL ranges, then falls off
552 // the end into `return(0)` with no recGbl delegation.
553 "acalcout" | "scalcout" => RsetDefaultArm::Seed,
554 _ => RsetDefaultArm::RecGblRange,
555 }
556}
557
558/// The last arm of `rtype`'s C `get_graphic_double` — the twin of
559/// [`control_default_arm`], and NOT the same answer for every type.
560///
561/// Read from each ported type's own rset. `aSubRecord.c:350-368` is the one
562/// that separates the two slots: it tries `get_inlinkNumber` then
563/// `get_outlinkNumber` and, for a field that is neither, falls out of the
564/// function having written nothing — no `default:`, no recGbl call — so the
565/// `dbAccess.c:216` seed stands. Its `get_control_double` (`:372-376`) is a
566/// bare `recGblGetControlDouble` in the same file, which is why one shared bit
567/// could not answer both. Measured: `ASUB.PHAS` serves display 0/0 where
568/// `CALC.PHAS` serves the DBF_SHORT range ±32767.
569///
570/// The synApps calc pair ends the same way — the listed cases return early and
571/// the function ends `return(0)` with no delegation
572/// (`aCalcoutRecord.c:1046-1068`, `sCalcoutRecord.c:906-928`).
573///
574/// Every other ported type that supplies the slot delegates
575/// (`aiRecord.c:244`, `aoRecord.c:316`, `calcRecord.c:187`,
576/// `calcoutRecord.c:452`, `subRecord.c:222`, `selRecord.c:181`,
577/// `seqRecord.c:322`, `dfanoutRecord.c:181`, `longinRecord.c:190`,
578/// `int64inRecord.c:196`, `int64outRecord.c:235`, `longoutRecord.c:252`,
579/// `waveformRecord.c:251`, `aaiRecord.c:276`, `aaoRecord.c:279`,
580/// `subArrayRecord.c:231`, `compressRecord.c:471`, `histogramRecord.c:442`).
581pub fn graphic_default_arm(rtype: &str) -> RsetDefaultArm {
582 match rtype {
583 "aSub" | "acalcout" | "scalcout" => RsetDefaultArm::Seed,
584 _ => RsetDefaultArm::RecGblRange,
585 }
586}
587
588/// How `rtype`'s C `get_alarm_double` answers the fields it lists explicitly
589/// (see [`alarm_explicit_fields`]).
590///
591/// The severity gate is NOT universal, so this bit cannot be inferred from the
592/// base analog shape — it is read from each ported type's own rset.
593#[derive(Debug, Clone, Copy, PartialEq, Eq)]
594pub enum AlarmValArm {
595 /// `pad->upper_alarm_limit = prec->hhsv ? prec->hihi : epicsNAN` — each
596 /// limit is served only when its severity is enabled. The base analog
597 /// shape (`aiRecord.c:290-301`, and ao/longin/longout/calc/calcout/sel/
598 /// sub/dfanout alike).
599 Gated,
600 /// `pad->upper_alarm_limit = prec->hihi` — the four limits verbatim, with
601 /// no severity test at all, so an unset record serves 0 rather than NaN
602 /// (`int64inRecord.c:235-246`, `int64outRecord.c:279-290`,
603 /// `sCalcoutRecord.c:683-696`, `aCalcoutRecord.c:823-836`,
604 /// `motorRecord.cc:3344-3361`, `epidRecord.c:289-301`).
605 Unconditional,
606}
607
608/// The fields `rtype`'s C `get_alarm_double` lists BEFORE its
609/// `recGblGetAlarmDouble` fall-through — the ones that take
610/// [`alarm_val_arm`]'s answer instead of the four NaN.
611///
612/// Empty means the rset lists nothing: even VAL falls to the default arm.
613/// `seqRecord.c:355-367` routes only its `DOn` fields (through their `DOLn`
614/// link), `aSubRecord.c:378-404` only its `INPn`/`OUTn` links, and
615/// `swaitRecord.c:608-612` is a bare `recGblGetAlarmDouble(paddr,pad)` with no
616/// field test whatsoever. A constant link supplies no alarm limits, so the link
617/// arm lands on the same four NaN — which is why only the listed set needs a
618/// per-type answer and the link fields do not.
619///
620/// `motorRecord.cc:3344-3361` is the one type listing a second field: its case
621/// is `fieldIndex == motorRecordVAL || fieldIndex == motorRecordDVAL`, so the
622/// dial-coordinate readback carries the same limits as VAL.
623pub fn alarm_explicit_fields(rtype: &str) -> &'static [&'static str] {
624 match rtype {
625 "seq" | "aSub" | "swait" => &[],
626 "motor" => &["VAL", "DVAL"],
627 _ => &["VAL"],
628 }
629}
630
631/// See [`AlarmValArm`]. Types whose rset lists nothing
632/// ([`alarm_explicit_fields`] empty) never consult this.
633pub fn alarm_val_arm(rtype: &str) -> AlarmValArm {
634 match rtype {
635 "int64in" | "int64out" | "scalcout" | "acalcout" | "motor" | "epid" => {
636 AlarmValArm::Unconditional
637 }
638 _ => AlarmValArm::Gated,
639 }
640}
641
642pub fn default_property_support(rtype: &str) -> crate::server::snapshot::PropertySupport {
643 use crate::server::snapshot::PropertySupport as P;
644 match rtype {
645 // Every numeric slot, no enum strings.
646 // aiRecord.c:68-87, aoRecord.c:67-86, calcRecord.c:63-82,
647 // calcoutRecord.c:67-86, selRecord.c:58-77, subRecord.c:62-81,
648 // dfanoutRecord.c:66-85, seqRecord.c:56-75.
649 "ai" | "ao" | "calc" | "calcout" | "sel" | "sub" | "dfanout" | "seq" => P::NUMERIC,
650
651 // Integer scalars: `#define get_precision NULL`
652 // (longinRecord.c, longoutRecord.c, int64inRecord.c,
653 // int64outRecord.c). This is the measured `longout` case —
654 // pvxs leaves `display.precision` absent, the port sent 0.
655 "longin" | "longout" | "int64in" | "int64out" => P {
656 precision: false,
657 ..P::NUMERIC
658 },
659
660 // Arrays and compress: `#define get_alarm_double NULL`
661 // (waveformRecord.c, aaiRecord.c, aaoRecord.c,
662 // subArrayRecord.c, compressRecord.c, histogramRecord.c).
663 // This is the measured `waveform` case — pvxs leaves all four
664 // `valueAlarm.*Limit` absent, the port sent four zeros.
665 "waveform" | "aai" | "aao" | "subArray" | "compress" | "histogram" => P {
666 alarm_double: false,
667 ..P::NUMERIC
668 },
669
670 // No property slots at all: every `get_*` is `#define`d NULL.
671 // stringinRecord.c:62-81, stringoutRecord.c:64-83,
672 // lsiRecord.c:287-306, lsoRecord.c:328-347,
673 // eventRecord.c:62-81, permissiveRecord.c:56-75,
674 // stateRecord.c:58-77, printfRecord.c:456-475,
675 // fanoutRecord.c:60-79, timestampRecord (std-rs).
676 // This is the measured `stringout` case — pvxs leaves
677 // `display.units` absent, the port sent "".
678 "stringin" | "stringout" | "lsi" | "lso" | "event" | "permissive" | "state" | "printf"
679 | "fanout" | "timestamp" => P::NONE,
680
681 // Enum records. `biRecord.c:61-80` and `mbbiRecord.c:65-84` /
682 // `mbboRecord.c:64-83` NULL every numeric slot and supply only
683 // `get_enum_strs`. `boRecord.c:59-61` keeps `get_units`,
684 // `get_precision` and `get_control_double` (they serve the
685 // `HIGH` field) but NULLs `get_graphic_double` and
686 // `get_alarm_double`.
687 "bi" | "mbbi" | "mbbo" => P {
688 enum_strs: true,
689 ..P::NONE
690 },
691 "bo" => P {
692 units: true,
693 precision: true,
694 control_double: true,
695 enum_strs: true,
696 ..P::NONE
697 },
698 // busyRecord.c (synApps busy): units/graphic/control/alarm NULL,
699 // get_precision and get_enum_strs present.
700 "busy" => P {
701 precision: true,
702 enum_strs: true,
703 ..P::NONE
704 },
705 // mbbiDirectRecord.c:63-81 / mbboDirectRecord.c:63-81 — only
706 // `get_precision` survives, and C's DBF_FLOAT/DOUBLE gate
707 // (`dbAccess.c:388-395`) drops it again for their DBF_ENUM/LONG
708 // value, so nothing is marked. `Snapshot::precision` applies
709 // that gate.
710 "mbbiDirect" | "mbboDirect" => P {
711 precision: true,
712 ..P::NONE
713 },
714
715 // synApps, transcribed the same way.
716 // sCalcoutRecord.c / aCalcoutRecord.c / epidRecord.c /
717 // motorRecord.cc:259-279 (the rset table: get_units, get_precision,
718 // get_graphic_double, get_control_double and get_alarm_double all
719 // supplied, get_enum_strs NULL) / aSubRecord.c: full numeric set, no
720 // enum strings.
721 "scalcout" | "acalcout" | "motor" | "epid" | "aSub" => P::NUMERIC,
722 // scalerRecord.c:147-158 NULLs every property slot but one:
723 // `#define get_units NULL` (:151), `get_enum_strs` (:154),
724 // `get_graphic_double` (:156), `get_control_double` (:157) and
725 // `get_alarm_double` (:158). Only `get_precision` (:152) survives.
726 //
727 // Grouping scaler with the full-numeric synApps types claimed TEN
728 // leaves QSRV2 never serves: `display.units`, the two `display.limit*`,
729 // the two `control.limit*`, the four `valueAlarm.*Limit` — and
730 // `display.precision`, which pvxs assigns only inside its
731 // `DBR_GR_DOUBLE` branch (`iocsource.cpp:288-291`). That nesting is
732 // also why `precision` stays true here and yet marks nothing: it
733 // records what the rset supplies, exactly as `transform`/`sseq` do.
734 "scaler" => P {
735 precision: true,
736 ..P::NONE
737 },
738 // tableRecord.cc (optics): `#define get_alarm_double NULL`.
739 "table" => P {
740 alarm_double: false,
741 ..P::NUMERIC
742 },
743 // swaitRecord.c: get_units and get_control_double are NULL.
744 "swait" => P {
745 units: false,
746 control_double: false,
747 ..P::NUMERIC
748 },
749 // Only `get_precision` survives; the rset NULLs the other five.
750 // transformRecord.c; sseqRecord.c:124-144 (the rset table itself —
751 // `NULL, /* get_units */ get_precision, /* get_precision */ ...
752 // NULL, /* get_graphic_double */ NULL, /* get_control_double */
753 // NULL /* get_alarm_double */`). `sseq` was previously grouped with
754 // the full-numeric synApps types, which marked six leaves per field
755 // that QSRV2 omits entirely.
756 //
757 // `asyn` is NOT here: asyn-rs owns that record and declares its own
758 // row (asynRecord.c:84-91, the same shape) — a downstream crate
759 // cannot reach this table, which is why `Record::property_support`
760 // is the hook and this is only its default.
761 "transform" | "sseq" => P {
762 precision: true,
763 ..P::NONE
764 },
765 "throttle" => P {
766 precision: true,
767 graphic_double: true,
768 ..P::NONE
769 },
770
771 // A record type whose C rset the port has not transcribed keeps
772 // the pre-existing "supplies what it populated" behaviour rather
773 // than silently losing metadata. Add an arm above — with the C
774 // file and line — when porting a new record type.
775 _ => P::NUMERIC,
776 }
777}
778
779/// Per-field metadata deltas returned by
780/// [`Record::field_metadata_override`].
781///
782/// Each `Some` member replaces the corresponding member of the
783/// snapshot's record-level display/control metadata; `None` members
784/// keep the record-level value.
785#[derive(Debug, Clone, Default)]
786pub struct FieldMetadataOverride {
787 /// `display.units` — C RSET `get_units`.
788 pub units: Option<crate::types::PvString>,
789 /// `display.precision` — C RSET `get_precision`.
790 pub precision: Option<i16>,
791 /// `(upper, lower)` display limits — C RSET `get_graphic_double`.
792 pub disp_limits: Option<(f64, f64)>,
793 /// `(upper, lower)` control limits — C RSET `get_control_double`.
794 pub ctrl_limits: Option<(f64, f64)>,
795 /// `(hihi, high, low, lolo)` — C RSET `get_alarm_double`.
796 pub alarm_limits: Option<(f64, f64, f64, f64)>,
797}
798
799/// Side-effect actions that a record requests from the processing framework.
800///
801/// Records return these from `process()` via `ProcessOutcome::actions`.
802/// The framework executes them at the appropriate point in the processing
803/// cycle, keeping records as pure state machines without direct DB access.
804#[derive(Clone, Debug, PartialEq)]
805pub enum ProcessAction {
806 /// Write a value to a DB link. The framework reads `link_field` from the
807 /// record to get the target PV name, then writes `value` to that PV.
808 ///
809 /// Executed after alarm/snapshot, before FLNK.
810 /// Example: scaler writes CNT to COUT/COUTP links.
811 WriteDbLink {
812 link_field: &'static str,
813 value: EpicsValue,
814 },
815
816 /// Resolve an OUT link's TARGET ([`OutTarget`]) and hand it to the record
817 /// through [`Record::set_resolved_out_target`], BEFORE `process()` runs.
818 ///
819 /// **Pre-process action** — the OUT-link twin of [`Self::ReadDbLink`],
820 /// and C's `checkLinks`-cached `lnk_field_type`: a record whose fire-time
821 /// branch depends on the target's DBF class (sseq decides the wire buffer
822 /// AND whether a `WAITn` put-callback is issued from the one switch,
823 /// `sseqRecord.c:714-792`) must have the class in hand when it decides, not
824 /// after the framework's put path has already been entered.
825 ResolveOutTarget { link_field: &'static str },
826
827 /// Read a value from a DB link into a record field. The framework reads
828 /// `link_field` from the record to get the source PV name, reads that PV,
829 /// and writes the result into `target_field` via an internal put that
830 /// bypasses read-only checks.
831 ///
832 /// The value delivered is the link target's **native** [`EpicsValue`] — it
833 /// is NOT coerced to a numeric type on the way in. The record coerces (or
834 /// preserves) it at its own `put_field`/`put_field_internal` boundary, so a
835 /// string-class source can reach a string field byte-exact (the `sseq`
836 /// `DOLn`→`STRn` path, C `sseqRecord.c:643-705`). Records whose
837 /// `target_field` is numeric simply convert there, exactly as before.
838 ///
839 /// **Pre-process action**: executed BEFORE the next process() cycle so
840 /// the value is immediately available. This matches C EPICS `dbGetLink()`
841 /// which is synchronous/immediate.
842 ///
843 /// Example: throttle reads SINP into VAL when SYNC is triggered.
844 ReadDbLink {
845 link_field: &'static str,
846 target_field: &'static str,
847 },
848
849 /// Schedule a re-process of this record after the given duration.
850 /// The framework spawns `tokio::spawn(sleep(d) + process_record(name))`.
851 /// The current cycle's OUT/FLNK/notify proceed normally.
852 ///
853 /// Equivalent to C EPICS `callbackRequestDelayed()` + `scanOnce()`.
854 ReprocessAfter(std::time::Duration),
855
856 /// C `scanOnce(precord)` — queue ONE process of this record, now.
857 ///
858 /// A record's `special()` emits this when a put changed state the record
859 /// must act on but the put itself will not process the record. C guards
860 /// every such call with `if (precord->scan)` — scaler `special()`
861 /// (scalerRecord.c:655 CNT, :667 CONT), whose comment is exactly the
862 /// contract: *"Scan record if it's not Passive. (If it's Passive, it'll
863 /// get scanned automatically, since .cnt is a Process-Passive field.)"*
864 ///
865 /// The FRAMEWORK owns that gate, not the record: the framework owns SCAN
866 /// and owns the `pp(TRUE)` reprocess decision (`dbPutField`,
867 /// dbAccess.c:1265-1268), and a record's `special()` cannot see either. So
868 /// a record emits `ScanOnce` unconditionally wherever C calls `scanOnce`,
869 /// and the executor drops it for a Passive record — where the put's own
870 /// process already covers it and a second one would double-process.
871 ///
872 /// Queued, not inline: C's `scanOnce` hands the record to the scan-once
873 /// thread, which takes `dbScanLock` — so the process lands after the
874 /// putting thread leaves `dbPutField`.
875 ScanOnce,
876
877 /// Send a named command to the device support driver.
878 /// The framework calls `DeviceSupport::handle_command()` with this data.
879 /// Used by scaler to request reset/arm/write_preset operations
880 /// without the record holding a direct driver reference.
881 DeviceCommand {
882 command: &'static str,
883 args: Vec<EpicsValue>,
884 },
885
886 /// Write a value to a DB link as a put-*with-completion*, then re-enter
887 /// THIS record's `process()` when the downstream operation completes.
888 ///
889 /// The framework arms a put-notify wait-set (C `dbProcessNotify`),
890 /// writes `link_field`'s target through it, releases the initiator's
891 /// own count, and wires the completion to an async re-entry of this
892 /// record (`mint_async_token` + `reprocess_on_notify`). The record
893 /// returns [`RecordProcessResult::AsyncPending`] alongside this action
894 /// and is re-entered once the downstream record (and its FLNK/OUT
895 /// chain) finishes — the synApps `sseq` `WAITn` "wait for the put
896 /// callback" dependency (`sseqRecord.c::processNextLink`,
897 /// `dbCaPutLinkCallback`). Built on the same `new_put_notify` +
898 /// `reprocess_on_notify` primitive an out-of-band
899 /// [`crate::server::database::AsyncDbHandle`] caller uses.
900 ///
901 /// Executed before FLNK, like [`Self::WriteDbLink`].
902 WriteDbLinkNotify {
903 link_field: &'static str,
904 value: EpicsValue,
905 },
906
907 /// (Re)arm this record's monitor watchdog — C `histogramRecord.c::wdogInit`
908 /// (:126-152), whose `callbackRequestDelayed(&pcallback->callback,
909 /// prec->sdel)` starts (or restarts) the periodic
910 /// [`Record::watchdog_fire`] tick.
911 ///
912 /// Emitted from a record's `special()` when the put changed the watchdog's
913 /// period (histogram SDEL is `special(SPC_RESET)` precisely so it can
914 /// re-arm, `histogramRecord.c:266-268`). The framework also arms every
915 /// record's watchdog once at `iocInit`, which is C's other `wdogInit` call
916 /// site (`init_record` pass 1, `:168`).
917 ///
918 /// Arming supersedes any tick already pending for the record, exactly as
919 /// C's `callbackRequestDelayed` replaces an outstanding delayed callback.
920 ArmWatchdog,
921
922 /// Cancel this record's outstanding async re-entry (C
923 /// `callbackCancelDelayed`): the framework advances the record's
924 /// re-entry generation so any pending `ReprocessAfter` timer or
925 /// `WriteDbLinkNotify` completion re-entry becomes a structural no-op
926 /// (the `AsyncToken` gate), with no runtime "is-aborted" check on the
927 /// re-entry path. Used by `sseq` `ABORT` to drop a pending `DLYn`
928 /// delay or `WAITn` wait; the record resets its own sequence state in
929 /// the same `process()` cycle that emits this.
930 CancelReprocess,
931}
932
933/// Result of a record's process() call.
934///
935/// Determines how the framework handles the current processing cycle.
936/// Side-effect actions (link writes, delayed reprocess, etc.) are expressed
937/// separately in `ProcessOutcome::actions`.
938#[derive(Clone, Debug, PartialEq)]
939pub enum RecordProcessResult {
940 /// Processing completed synchronously this cycle.
941 /// Framework proceeds with alarm/timestamp/snapshot/OUT/FLNK.
942 Complete,
943 /// Processing started but not yet complete (PACT stays set).
944 /// Current cycle skips alarm/timestamp/snapshot/OUT/FLNK.
945 /// ProcessActions (if any) are still executed.
946 AsyncPending,
947 /// Async pending, but notify these intermediate field changes immediately.
948 /// Used by motor records to flush DMOV=0 before the move completes.
949 AsyncPendingNotify(Vec<(String, EpicsValue)>),
950 /// Completed synchronously (PACT cleared, unlike `AsyncPending`), but the
951 /// record produced no new value to publish this cycle — the framework must
952 /// skip the value-publication epilogue (UDF clear / timestamp / monitor /
953 /// FLNK). C parity `compressRecord.c:365` `if (status != 1)`: a compress
954 /// record still accumulating toward its next compressed sample runs none of
955 /// `recGblGetTimeStamp` / `monitor` / `recGblFwdLink` on that cycle.
956 CompleteNoEmit,
957 /// Ran the value-publication epilogue NOW (UDF clear / timestamp / monitor —
958 /// VAL and the alarm fields are posted this cycle), but the OUTPUT side (OUT
959 /// link write / OEVT / forward link) is deferred to a scheduled
960 /// reprocess, with PACT held across the wait. C parity `swaitRecord.c::process`
961 /// (lines 425-481): when `schedOutput` arms the ODLY watchdog it sets
962 /// `async=TRUE`, so `process` still runs `monitor()` (line 475) — posting the
963 /// value side at the START of the delay — but skips the `if(!async)
964 /// {recGblFwdLink; pact=FALSE;}` tail; the deferred `execOutput` (watchdog,
965 /// at delay-END) does the OUT write + OEVT + forward link and posts no
966 /// monitors. Unlike the calcout/scalcout/acalcout family, whose C `process`
967 /// `return`s BEFORE `monitor()` (calcoutRecord.c:282, only `dlya` posted), so
968 /// they defer the value side too and use `AsyncPendingNotify`. The deferral
969 /// must carry a [`ProcessAction::ReprocessAfter`] — that scheduled reprocess
970 /// is the continuation that releases the held PACT (same by-construction
971 /// invariant as the `AsyncPendingNotify` ODLY defer).
972 CompleteDeferOutput,
973 /// Completed synchronously (PACT cleared), and the framework runs the ALARM
974 /// epilogue ONLY: the UDF update, `check_alarms`, `recGblResetAlarms`
975 /// (committing SEVR/STAT/AMSG and posting those fields with their C masks)
976 /// and the timestamp. The VALUE side is skipped entirely — no `monitor()`
977 /// value posts (so the last-posted trackers stay put and the next publishing
978 /// cycle re-detects the change, exactly as C leaves `LA..LP` un-updated), no
979 /// OUT / OEVT write, no process actions, no forward link.
980 ///
981 /// C parity `transformRecord.c:554-560`: an INVALID input severity with
982 /// `IVLA == transformIVLA_DO_NOTHING` makes `process()` run
983 /// `recGblGetTimeStamp` + `checkAlarms` + `recGblResetAlarms`, clear `pact`
984 /// and `return` — skipping the calc loop, all 16 OUTx `dbPutLink` writes,
985 /// `monitor()` and `recGblFwdLink()`.
986 ///
987 /// Distinct from [`RecordProcessResult::CompleteNoEmit`], which skips the
988 /// alarm commit and the timestamp too (C `compressRecord.c:365` returns
989 /// before `checkAlarms`).
990 CompleteAlarmOnly,
991}
992
993/// Complete outcome of a record's process() call.
994///
995/// Contains the processing result (Complete, AsyncPending, etc.) and a list
996/// of side-effect actions for the framework to execute.
997#[derive(Clone, Debug)]
998pub struct ProcessOutcome {
999 pub result: RecordProcessResult,
1000 pub actions: Vec<ProcessAction>,
1001 /// Set by the framework when device support's read() returned
1002 /// `did_compute: true`. The record's process() can check this to
1003 /// skip its built-in computation (e.g., PID). Replaces the `pid_done`
1004 /// flag pattern.
1005 pub device_did_compute: bool,
1006}
1007
1008impl ProcessOutcome {
1009 /// Shorthand for a simple Complete with no actions.
1010 pub fn complete() -> Self {
1011 Self {
1012 result: RecordProcessResult::Complete,
1013 actions: Vec::new(),
1014 device_did_compute: false,
1015 }
1016 }
1017
1018 /// Shorthand for Complete with actions.
1019 pub fn complete_with(actions: Vec<ProcessAction>) -> Self {
1020 Self {
1021 result: RecordProcessResult::Complete,
1022 actions,
1023 device_did_compute: false,
1024 }
1025 }
1026
1027 /// Completed synchronously, but no new value was emitted this cycle, so
1028 /// the framework skips the value-publication epilogue (UDF clear /
1029 /// timestamp / monitor / FLNK). See `RecordProcessResult::CompleteNoEmit`.
1030 pub fn complete_no_emit() -> Self {
1031 Self {
1032 result: RecordProcessResult::CompleteNoEmit,
1033 actions: Vec::new(),
1034 device_did_compute: false,
1035 }
1036 }
1037
1038 /// Completed synchronously with the alarm epilogue only — no value posts,
1039 /// no output, no forward link. See `RecordProcessResult::CompleteAlarmOnly`.
1040 pub fn complete_alarm_only() -> Self {
1041 Self {
1042 result: RecordProcessResult::CompleteAlarmOnly,
1043 actions: Vec::new(),
1044 device_did_compute: false,
1045 }
1046 }
1047
1048 /// Shorthand for AsyncPending with no actions.
1049 pub fn async_pending() -> Self {
1050 Self {
1051 result: RecordProcessResult::AsyncPending,
1052 actions: Vec::new(),
1053 device_did_compute: false,
1054 }
1055 }
1056}
1057
1058impl Default for ProcessOutcome {
1059 fn default() -> Self {
1060 Self::complete()
1061 }
1062}
1063
1064/// Result of setting a common field, indicating what scan index updates are needed.
1065#[derive(Clone, Debug, PartialEq, Eq)]
1066pub enum CommonFieldPutResult {
1067 NoChange,
1068 ScanChanged {
1069 old_scan: ScanType,
1070 new_scan: ScanType,
1071 phas: i16,
1072 },
1073 PhasChanged {
1074 scan: ScanType,
1075 old_phas: i16,
1076 new_phas: i16,
1077 },
1078}
1079
1080/// Read-only snapshot of framework-owned `CommonFields` state that a
1081/// record's `process()` or device support's `read()` needs to see
1082/// *during* the processing cycle.
1083///
1084/// The framework owns `RecordInstance.common`; a record `process()`
1085/// receives only `&mut self` (the concrete record) and device support
1086/// `read()` receives only `&mut dyn Record`. Neither can reach
1087/// `CommonFields`. C records, by contrast, see `dbCommon` directly —
1088/// e.g. `epidRecord.c:195` reads `pepid->udf`, `timestampRecord.c:90`
1089/// reads `ptimestamp->tse`, `devTimeOfDay.c:122` reads `psi->phas`.
1090///
1091/// The framework builds a `ProcessContext` from `common` and pushes it
1092/// onto the record (via [`Record::set_process_context`]) and onto the
1093/// device support (via
1094/// [`crate::server::device_support::DeviceSupport::set_process_context`])
1095/// immediately before the respective call. This mirrors the existing
1096/// `set_device_did_compute` framework-set-hook pattern: additive,
1097/// no `process()` / `read()` signature change.
1098#[derive(Clone, Debug, PartialEq)]
1099pub struct ProcessContext {
1100 /// `dbCommon.udf` — value is undefined. C records check this at the
1101 /// top of `process()` (e.g. `epidRecord.c:195`).
1102 pub udf: bool,
1103 /// `dbCommon.udfs` — alarm severity raised for a UDF record.
1104 pub udfs: crate::server::record::AlarmSeverity,
1105 /// `dbCommon.nsev` — the *pending* (new) alarm severity this cycle has
1106 /// accumulated so far, BEFORE the record body runs. C `dbGetLink` folds an
1107 /// `MS`-class input link's severity into `nsev` at fetch time, so a record
1108 /// body that branches on the input severity reads it here — e.g.
1109 /// `transformRecord.c:554` `if ((ptran->nsev >= INVALID_ALARM) && (ptran->ivla
1110 /// == transformIVLA_DO_NOTHING))`. The framework folds every input-link alarm
1111 /// into `common.nsev` before building this snapshot, so `nsev` is the single
1112 /// source of truth; the record never re-derives it from the links.
1113 pub nsev: crate::server::record::AlarmSeverity,
1114 /// `dbCommon.phas` — phase. Used by device support for format
1115 /// selection (`devTimeOfDay.c:122`).
1116 pub phas: i16,
1117 /// `dbCommon.tse` — time-stamp event. `timestampRecord.c:90`
1118 /// branches on `tse == epicsTimeEventDeviceTime`.
1119 pub tse: i16,
1120 /// `dbCommon.time` — the record's current resolved time stamp at the
1121 /// start of this cycle (the previous cycle's stamp, or `UNIX_EPOCH`
1122 /// before the first process). Device support that has to format the
1123 /// record's time during `read()` — the std module's `devTimeOfDay.c`
1124 /// `recGblGetTimeStamp(psi)` call, which runs *before* the framework's
1125 /// per-cycle timestamp application — resolves the stamp with
1126 /// [`crate::server::recgbl::get_time_stamp`]`(tse, time)`. The `time`
1127 /// member is the device-provided value that helper returns verbatim on
1128 /// the `TSE == epicsTimeEventDeviceTime (-2)` branch.
1129 pub time: std::time::SystemTime,
1130 /// `dbCommon.tsel` — time-stamp event link string.
1131 pub tsel: String,
1132 /// `dbCommon.dtyp` — device-support type name. A record's
1133 /// `process()` / pre-process hooks can branch on the DTYP to mirror
1134 /// C device support that lives in a separate DSET (e.g. the epid
1135 /// record's `devEpidSoftCallback` callback DSET drives the TRIG
1136 /// readback link, whereas `devEpidSoft` does not).
1137 pub dtyp: String,
1138}
1139
1140/// C `epicsTime.h`: `epicsTimeEventDeviceTime` — the `TSE` sentinel
1141/// meaning "device support provides the time stamp". `timestampRecord.c`
1142/// uses it to take the OS-clock branch instead of `recGblGetTimeStamp`.
1143pub const EPICS_TIME_EVENT_DEVICE_TIME: i16 = -2;
1144
1145/// Snapshot of changes from a process cycle, used for notify outside lock.
1146pub struct ProcessSnapshot {
1147 /// `(field, value, mask)` — every posted field carries its own
1148 /// `DBE_*` posting mask, mirroring C's per-field
1149 /// `db_post_events(prec, &field, mask)`. One process cycle posts
1150 /// different classes per field: a deadband-gated readback narrows
1151 /// to the deadbands that actually crossed (MDEL → `DBE_VALUE`,
1152 /// ADEL → `DBE_LOG`; motorRecord.cc `monitor()` 3477-3507,
1153 /// aiRecord.c `monitor()`), while a change-detected auxiliary
1154 /// field posts `DBE_VALUE | DBE_LOG` (motorRecord.cc 3522-3645
1155 /// `DBE_VAL_LOG`; calcRecord.c:420). A single record-wide mask
1156 /// collapses that granularity — an archive-only deadband crossing
1157 /// would wrongly reach `DBE_VALUE` subscribers whenever any other
1158 /// field changed in the same pass.
1159 pub changed_fields: Vec<(String, EpicsValue, crate::server::recgbl::EventMask)>,
1160}
1161
1162/// What C's `fetch_values()` does when one of the record's input links fails
1163/// to read, and whether that failure gates the record body.
1164///
1165/// Every C record with an INPA..INPx block has a `fetch_values()` helper, but
1166/// they do not share a failure shape, so the framework cannot pick one rule
1167/// for all of them — each record declares its own via
1168/// [`Record::input_fetch_policy`].
1169///
1170/// The two dimensions C varies are "does the loop stop at the first failure"
1171/// and "does a failure gate the record body", and it uses three of the four
1172/// combinations. Whichever variant a record picks, the framework reduces the
1173/// cycle to ONE outcome — C's `fetch_values()` return status, zero or not —
1174/// and delivers it through a single owner: [`Record::set_fetch_gate_failed`]
1175/// for records that compute in their own `process()`, and
1176/// `RecordInstance::suppress_subroutine_run` for the two whose body is a
1177/// framework-dispatched subroutine (sub/aSub).
1178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1179pub enum InputFetchPolicy {
1180 /// Read every configured link; a failed read neither stops the loop nor
1181 /// gates the record body. C `transformRecord.c::process` (531-545) reads
1182 /// on through a failed `dbGetLink` and computes anyway.
1183 ReadAll,
1184 /// Read every configured link — a failure does NOT stop the loop, so the
1185 /// inputs behind it still refresh — but the body is skipped this cycle.
1186 ///
1187 /// C `calcRecord.c::fetch_values` (427-443) keeps the FIRST failing status
1188 /// while looping to the end (`if (status == 0) status = newStatus;`), and
1189 /// `calcRecord.c::process` (120) runs `calcPerform` only
1190 /// `if (fetch_values(prec) == 0)` — so VAL and UDF freeze, no CALC_ALARM is
1191 /// raised, and everything after the calc (timestamp, alarms, monitors,
1192 /// forward link) still runs. `calcoutRecord.c` (694-709 fetch, 237 gate) is
1193 /// the same shape, and its OOPT decision then runs against the frozen VAL.
1194 ReadAllGateOnFailure,
1195 /// Stop at the FIRST failed link and skip the record body this cycle.
1196 ///
1197 /// C `subRecord.c::fetch_values` (407-418) `return -1`s on the first
1198 /// failing `dbGetLink`, so the inputs behind it are never read and keep
1199 /// their previous values; `subRecord.c::process` (145-146) then runs
1200 /// `do_sub` only `if (status == 0)`, freezing VAL/UDF and raising none of
1201 /// the subroutine's alarms. `aSubRecord.c` (277-289 fetch, 216-218
1202 /// process), `sCalcoutRecord.c` (885-887 fetch, 356 gate),
1203 /// `aCalcoutRecord.c` (1068-1071 fetch, 399 gate) and
1204 /// `swaitRecord.c` (686-705 fetch, 408 gate) are the same shape.
1205 AbortOnFirstFailure,
1206}
1207
1208/// **The** field declaration of a record type, and the only way to obtain one.
1209///
1210/// Not implementable: the blanket `impl` below covers every [`Record`], so a
1211/// second `impl FieldDeclaration for MyRecord` is a coherence error. A record
1212/// type therefore cannot *supply* a field list — it can only be *asked* for
1213/// one, and the answer is resolved here:
1214///
1215/// * a record type **base's** vendored `.dbd` set covers is declared by the
1216/// table generated from that `.dbd` ([`dbd_generated::record_fields`]);
1217/// * any other record type is asked for its own declaration,
1218/// [`Record::declared_fields`] — which for the downstream record types is the
1219/// table generated from the `.dbd` *their* crate vendors, and for a synthetic
1220/// record type (tests) is a hand-written table.
1221///
1222/// The two are mutually exclusive by construction, which is what closes the
1223/// invariant *one declaration per record type*. It used to be closed by luck:
1224/// both tables were live, `field_desc_of` merely happened to consult the
1225/// generated one first, and every consumer that reached for `field_list()`
1226/// directly (`dbpr`, the `dbpf` typo hint, `motor`'s field gate) read the
1227/// hand-written one — which is how `waveform.FTVL` was declared `DBF_SHORT`
1228/// with no menu while `waveformRecord.dbd` said `DBF_MENU`/`menu(menuFtype)`.
1229pub trait FieldDeclaration {
1230 /// The record type's field descriptors, in `.dbd` declaration order.
1231 fn field_list(&self) -> &'static [FieldDesc];
1232}
1233
1234impl<R: Record + ?Sized> FieldDeclaration for R {
1235 fn field_list(&self) -> &'static [FieldDesc] {
1236 super::dbd_generated::record_fields(self.record_type())
1237 .unwrap_or_else(|| self.declared_fields())
1238 }
1239}
1240
1241/// Trait that all EPICS record types must implement.
1242pub trait Record: Send + Sync + 'static {
1243 /// Return the record type name (e.g., "ai", "ao", "bi").
1244 fn record_type(&self) -> &'static str;
1245
1246 /// Process the record (scan/compute cycle).
1247 ///
1248 /// Returns a `ProcessOutcome` containing the processing result and any
1249 /// side-effect actions for the framework to execute.
1250 fn process(&mut self) -> CaResult<ProcessOutcome> {
1251 Ok(ProcessOutcome::complete())
1252 }
1253
1254 /// Optional: report whether this record's last `process()` call
1255 /// mutated a metadata-class field (EGU/PREC/HOPR/LOPR/HLM/LLM/
1256 /// alarm limits / DRVH/DRVL / state strings).
1257 ///
1258 /// The framework checks this after every `process()` call and, if
1259 /// true, invalidates the record's metadata cache so the next
1260 /// snapshot rebuilds from the new values.
1261 ///
1262 /// Default: `false` — most records never touch metadata fields
1263 /// during processing. Override only when your record dynamically
1264 /// adjusts limits or unit strings (e.g., a motor that recomputes
1265 /// HLM/LLM after a hardware homing operation).
1266 ///
1267 /// Implementations should reset their internal flag after returning
1268 /// `true` so the next cycle starts clean.
1269 fn took_metadata_change(&mut self) -> bool {
1270 false
1271 }
1272
1273 /// Get a field value by name.
1274 fn get_field(&self, name: &str) -> Option<EpicsValue>;
1275
1276 /// Set a field value by name.
1277 fn put_field(&mut self, name: &str, value: EpicsValue) -> CaResult<()>;
1278
1279 /// The field declaration of a record type **base's** `.dbd` set does not
1280 /// cover — a record type that lives in another crate.
1281 ///
1282 /// C has exactly one declaration per record type: the `.dbd`, read at
1283 /// runtime. The port compiles the vendored `.dbd`s into a generated table,
1284 /// and [`FieldDeclaration::field_list`] — the single resolver every consumer
1285 /// goes through — serves base's
1286 /// [`dbd_generated`](crate::server::record::dbd_generated) table for every
1287 /// record type IT covers and **never falls through to here**. So for a
1288 /// base record type this method is unreachable: it cannot declare one of its
1289 /// fields a second time, whatever it writes here.
1290 ///
1291 /// A record type outside base declares itself here, and the answer is still
1292 /// its `.dbd`: the downstream Tier-3 record types (`motor`, `table`,
1293 /// `scaler`, `epid`, `throttle`, `timestamp`) vendor their upstream `.dbd`
1294 /// into their OWN crate, `tools/dbd-codegen` generates a table into that
1295 /// crate (`tools/dbd-codegen/src/targets.rs`), and this method returns it.
1296 /// Each such crate carries the same ratchet base does
1297 /// (`one_declaration_per_record_type`): the table returned here must BE the
1298 /// generated one, so the `.dbd` stays the single declaration across a crate
1299 /// boundary the generator's output cannot cross on its own.
1300 ///
1301 /// A hand-written table is what is left when a record type has no `.dbd`
1302 /// anywhere — the synthetic record types the tests define. There are no
1303 /// others; a shipped record type has a `.dbd`, and its declaration is that
1304 /// `.dbd`.
1305 ///
1306 /// The declaration is a *spec*: it says what each field's type, menu and
1307 /// `special(SPC_NOMOD)` are. It does NOT say who implements the field. Ask
1308 /// [`Record::implements_field`] for that — see its docs for why the two
1309 /// must not be the same question.
1310 fn declared_fields(&self) -> &'static [FieldDesc] {
1311 &[]
1312 }
1313
1314 /// Does this record type implement `name` in its own `get_field` /
1315 /// `put_field`, as opposed to leaving it to the framework's dbCommon
1316 /// handling?
1317 ///
1318 /// This used to be answered by `field_list()` membership, which conflated
1319 /// two questions: "what is this field?" and "who owns it?". They give
1320 /// different answers for `INP`/`OUT`: every record type *declares* them in
1321 /// the `.dbd`, but only some drive the link themselves
1322 /// (`multi_output_links` for `acalcout`/`scalcout`, device support for
1323 /// `motorRecord`/`scalerRecord`); for the rest the framework arms
1324 /// `parsed_inp`/`parsed_out` and drives it. While `field_list()` was
1325 /// hand-written and incomplete the conflation was invisible, because the
1326 /// hand-written tables happened to omit exactly the fields the framework
1327 /// owns. A complete, spec-derived `field_list()` makes membership true for
1328 /// every record, so ownership needs its own predicate or the framework
1329 /// would stop arming any link at all.
1330 ///
1331 /// The default answers it truthfully — a record implements the fields its
1332 /// own `get_field` can produce. (Verified equivalent to the old
1333 /// `field_list()` membership on all 1,757 fields of all 40 record types at
1334 /// the time of the split, so the split changed no behaviour.)
1335 fn implements_field(&self, name: &str) -> bool {
1336 self.get_field(name).is_some()
1337 }
1338
1339 /// `SPC_NOMOD` that a record's `cvt_dbaddr` decides **at runtime, from
1340 /// record state** — the dynamic half of the no-modify declaration.
1341 ///
1342 /// [`FieldDesc::read_only`] is the static half: it carries the `.dbd`
1343 /// `special(SPC_NOMOD)` of a field that is immutable for the record type,
1344 /// full stop. But C lets a record's `cvt_dbaddr` *raise* SPC_NOMOD per
1345 /// dbAddr, keyed on the record's own fields, and one record does:
1346 ///
1347 /// ```c
1348 /// /* compressRecord.c:398-407 */
1349 /// static long cvt_dbaddr(DBADDR *paddr) {
1350 /// ...
1351 /// if (prec->balg == bufferingALG_LIFO)
1352 /// paddr->special = SPC_NOMOD;
1353 /// }
1354 /// ```
1355 ///
1356 /// A compress VAL is writable under BALG=FIFO and refused under BALG=LIFO —
1357 /// a per-record-state fact no static `FieldDesc` can express. The one gate
1358 /// that owns field immutability (`field_io::check_no_mod`) consults this
1359 /// hook alongside the static set, so the dynamic refusal reaches EVERY put
1360 /// route exactly as the static one does.
1361 ///
1362 /// (C caches `paddr->special` in the DBADDR at name-resolution time, so a
1363 /// CA channel opened while FIFO keeps writing after a switch to LIFO until
1364 /// it reconnects; `dbpf`, which resolves fresh, is refused immediately. The
1365 /// port evaluates live on every put — the invariant C's own `dbpf` path
1366 /// shows, without the stale-cache hole.)
1367 ///
1368 /// `field` is upper-case. Default: no dynamic NOMOD.
1369 fn field_no_mod(&self, _field: &str) -> bool {
1370 false
1371 }
1372
1373 /// Choice strings for a record-specific `DBF_MENU` field served as
1374 /// `DBR_ENUM`, keyed by field name (uppercase, as declared).
1375 ///
1376 /// EPICS dbStaticLib serves a `DBF_MENU` field as `DBR_ENUM`: the value
1377 /// is the menu index and the field carries its `menu()` choice strings,
1378 /// so `caget`/`pvget` present the labels rather than a bare number
1379 /// (`dbStaticLib.c` `dbGetMenuChoices`; `dbAccess.c` `get_enum_str`).
1380 /// A record returns the label table (in index order) for each field it
1381 /// serves as [`DbFieldType::Enum`] from a `menu()`; the framework
1382 /// attaches it to the field snapshot's `EnumInfo` so the CA/PVA enum
1383 /// encoders present the labels — the same mechanism `bi`/`bo`/`mbbi`/
1384 /// `mbbo` already use for their `VAL` state strings, but per field
1385 /// rather than per record (a record can carry several distinct menus).
1386 ///
1387 /// This is the single owner of "menu field -> choice table": a record
1388 /// declares its menu fields here once, and `get_field` returns the menu
1389 /// index as [`EpicsValue::Enum`]. Default: no record-specific menu
1390 /// fields. The dbCommon menu fields (`SCAN`, etc.) are handled
1391 /// separately by the framework, not here.
1392 ///
1393 /// INVARIANT — answering here is a claim that the field is `DBF_MENU`, so
1394 /// [`Self::field_list`] MUST declare it [`DbFieldType::Enum`]: C's
1395 /// `mapDBFToDBR` serves every `DBF_MENU` as `DBR_ENUM`, and the DECLARED
1396 /// type is what goes on the wire
1397 /// ([`RecordInstance::project_to_declared_type`](super::RecordInstance::project_to_declared_type)).
1398 /// A field with choices but a `Short` declaration is a self-contradictory
1399 /// declaration: it would be served as a bare `DBR_SHORT` index while
1400 /// claiming to have labels for it. `menu_choices_are_served_as_dbr_enum`
1401 /// (`tests/menu_fields_serve_enum_choices.rs`) fails on any record type
1402 /// that breaks it — the storage may be a short, the declaration may not.
1403 fn menu_field_choices(&self, _field: &str) -> Option<&'static [&'static str]> {
1404 None
1405 }
1406
1407 /// Per-field override of the record-level display/control metadata
1408 /// for a GET / monitor snapshot of `field`.
1409 ///
1410 /// C record support serves metadata PER FIELD: the RSET functions
1411 /// `get_units` / `get_precision` / `get_graphic_double` /
1412 /// `get_control_double` / `get_alarm_double` all key on
1413 /// `dbGetFieldIndex(paddr)` and fall back to the `recGbl*` defaults
1414 /// for unlisted fields. The framework's metadata cache is per
1415 /// record (built by `populate_display_info` /
1416 /// `populate_control_info` from the VAL-class fields); a record
1417 /// whose RSET serves different metadata for non-VAL fields
1418 /// overrides this hook to patch the cached values for that field
1419 /// (e.g. the motor record: VELO's display range is VMAX/VBAS, not
1420 /// HLM/LLM — `motorRecord.cc:3247-3250`).
1421 ///
1422 /// Applied on both the GET path (`snapshot_for_field`) and the
1423 /// monitor path (`make_monitor_snapshot`), AFTER the cached
1424 /// record-level metadata — and computed live on each call, so an
1425 /// override derived from non-cached fields can never go stale.
1426 /// `field` is uppercase, as declared in [`Record::field_list`].
1427 /// Default: `None` — record-level metadata serves every field.
1428 fn field_metadata_override(&self, _field: &str) -> Option<FieldMetadataOverride> {
1429 None
1430 }
1431
1432 /// Which of C's six nullable `rset` `get_*` property slots THIS record
1433 /// type implements — the record's own `#define get_xxx NULL` lines.
1434 ///
1435 /// `dbGet` consults the rset to *narrow* the caller's options mask
1436 /// (`dbAccess.c:336-430`): a NULL slot clears the option bit, so the leaf
1437 /// never reaches the client. That is what decides whether QSRV marks an NT
1438 /// leaf at all (pvxs `ioc/iocsource.cpp:263-305`). A slot counts as
1439 /// supplied when the C function pointer is non-NULL **even if the function
1440 /// writes nothing for the field in question** — C leaves the option bit
1441 /// set either way (`boRecord.c:294-299` writes units only for `HIGH`, yet
1442 /// `DBR_UNITS` survives for every `bo` field).
1443 ///
1444 /// The record type owns this answer because the record type owns its C
1445 /// rset. A central table keyed on the record-type *string* cannot: a
1446 /// record implemented in a downstream crate (`asyn-rs`'s `asynRecord`,
1447 /// the motor/scaler/optics types) has no way to add a row to it, so it
1448 /// silently inherited a default that marked every leaf it could name —
1449 /// telling clients a fabricated `display.units` of `""` and
1450 /// `valueAlarm` bands of zero were authoritative.
1451 ///
1452 /// The default answers from [`default_property_support`], the
1453 /// transcription of the record types epics-base-rs implements itself.
1454 /// Override it in the record's own file, citing the C rset lines.
1455 fn property_support(&self) -> crate::server::snapshot::PropertySupport {
1456 default_property_support(self.record_type())
1457 }
1458
1459 /// Field names this record serves as a *long string*: a `DBF_CHAR`
1460 /// array field that semantically holds a NUL-terminated string.
1461 ///
1462 /// In EPICS such a field is declared `DBF_NOACCESS` (or carries a `$`
1463 /// modifier) and is accessed through a `DBR_CHAR` array view whose
1464 /// `form` is `"String"`; pvxs maps that view to a scalar `pvString`
1465 /// rather than an `int8[]` (`ioc/channel.cpp:58-68`,
1466 /// `ioc/iocsource.cpp:619-643`). QSRV uses this list to serve those
1467 /// fields as scalar-string NTScalar values instead of byte scalars.
1468 ///
1469 /// The record keeps its `CharArray` storage; the QSRV boundary does
1470 /// the `CharArray <-> String` conversion. Default empty — only
1471 /// long-string record types (`lsi`/`lso` VAL/OVAL, `printf` VAL)
1472 /// override this. Names are matched case-insensitively.
1473 fn long_string_fields(&self) -> &'static [&'static str] {
1474 &[]
1475 }
1476
1477 /// Field names declared `pp(TRUE)` in this record type's DBD (empty if
1478 /// none, e.g. `event`/`histogram`, or if the type is unmodeled).
1479 ///
1480 /// Drives the `dbPutField` processing gate: C `dbAccess.c:1263`
1481 /// re-processes a record on a put only when the put field is `PROC` or it
1482 /// is `pp(TRUE)` **and** `SCAN == Passive`. The table is total and
1483 /// fail-safe — an unmodeled type returns `&[]` (and warns once), so its
1484 /// field puts never auto-process (only `PROC` does). The default consults
1485 /// the central DBD-sourced table keyed by [`Record::record_type`]; record
1486 /// types can override.
1487 fn process_passive_fields(&self) -> &'static [&'static str] {
1488 super::process_passive::pp_fields_for(self.record_type())
1489 }
1490
1491 /// Whether a put to `field` should reprocess this Passive record.
1492 ///
1493 /// The default is pure `pp(TRUE)` membership — the put gate's
1494 /// `field in process_passive_fields()` test. A record type overrides this
1495 /// when its C `special()` conditionally returns ERROR to suppress the
1496 /// reprocess for a `pp(TRUE)` field on certain values (e.g. motor STUP:
1497 /// only a `STUP == ON` put runs the status-update process; any other value
1498 /// is clamped to OFF and C returns ERROR so no process runs). Modeling that
1499 /// here keeps the suppression at the same gate as the pp test, with no
1500 /// per-put one-shot state — the post-clamp field value is deterministic.
1501 fn processes_after_put(&self, field: &str) -> bool {
1502 self.process_passive_fields()
1503 .iter()
1504 .any(|f| f.eq_ignore_ascii_case(field))
1505 }
1506
1507 /// The record's `DBF_ENUM` state strings — the C rset slot pair
1508 /// `get_enum_strs` / `put_enum_str`, which in C read the same fields and
1509 /// are therefore ONE table here.
1510 ///
1511 /// It is what a client reads as the `DBR_ENUM` choice list AND the set of
1512 /// names a `DBR_STRING` put to the record's `DBF_ENUM` `VAL` may name
1513 /// (`dbConvert.c::putStringEnum` → [`resolve_enum_state_string`]). Taking
1514 /// both from one table is the point: a name the record advertises is a name
1515 /// a client may put, by construction — the two cannot drift.
1516 ///
1517 /// The table is already trimmed to C's `no_str`: `bi`/`bo`/`busy` drop
1518 /// `ONAM` when `ZNAM` is set and `ONAM` is empty (`boRecord.c:342-352`);
1519 /// `mbbi`/`mbbo` cut at the last non-empty state (`mbbiRecord.c:262-269`).
1520 ///
1521 /// `None` — the record type leaves both rset slots NULL. That is every
1522 /// record whose `VAL` is not `DBF_ENUM`, and `mbbiDirect`/`mbboDirect`
1523 /// (`mbbiDirectRecord.c:58` `#define put_enum_str NULL`), whose `VAL` is
1524 /// `DBF_LONG`. C then fails a `DBR_STRING` put with `S_db_noRSET`.
1525 fn enum_state_strings(&self) -> Option<Vec<PvString>> {
1526 None
1527 }
1528
1529 /// The record's `get_enum_str` rset slot — how a `DBR_STRING` READ of its
1530 /// `DBF_ENUM` `VAL` renders. A THIRD slot, distinct from the pair above:
1531 /// C's `get_enum_str` (singular) is not `get_enum_strs` (plural), and
1532 /// serving the read from the plural table is what made an undefined `mbbi`
1533 /// state come out as its index.
1534 ///
1535 /// The difference is the trimming. `get_enum_strs` reports `no_str`, so the
1536 /// label list stops at the last non-empty state; `get_enum_str` indexes the
1537 /// state array *untrimmed* (`mbbiRecord.c:246-250`: any `val <= 15` reads
1538 /// `zrst + val * sizeof(zrst)`, empty or not) and only an index past the
1539 /// array reaches the sentinel. Verified on the compiled C `softIoc`: an
1540 /// `mbbi` with `ZRST`/`ONST` set answers `caget -t` with `""` at `VAL=5` and
1541 /// `"Illegal Value"` at `VAL=20`.
1542 ///
1543 /// `None` — the record leaves the rset slot NULL (`#define get_enum_str
1544 /// NULL`), which is every record but `bi`/`bo`/`mbbi`/`mbbo`. A field on
1545 /// such a record renders from its menu instead; see
1546 /// [`RecordInstance::enum_string_form_for`](super::RecordInstance::enum_string_form_for),
1547 /// the single owner that picks between the two.
1548 fn enum_string_form(&self) -> Option<crate::server::snapshot::EnumStringForm> {
1549 None
1550 }
1551
1552 /// Validate a put before it is applied. Return Err to reject.
1553 fn validate_put(&self, _field: &str, _value: &EpicsValue) -> CaResult<()> {
1554 Ok(())
1555 }
1556
1557 /// Hook called after a successful put_field.
1558 fn on_put(&mut self, _field: &str) {}
1559
1560 /// Whether a put to `field` names a subroutine that must resolve in the
1561 /// function registry — C `special(SPC_MOD)` → `registryFunctionFind`
1562 /// (`aSubRecord.c::special`, `subRecord.c::special`). C stores the name in
1563 /// `dbPut`, then `special(after)` looks it up and returns `S_db_BadSub`
1564 /// (→ rsrv `ECA_PUTFAIL`) when the name is non-empty and unregistered, so
1565 /// the client's write is REFUSED while the field keeps the value it was
1566 /// given. An empty name names no routine and is accepted.
1567 ///
1568 /// The record's `special()` has no database handle and so cannot reach the
1569 /// registry itself (the registry is the DB's single owner); this hook only
1570 /// says "a put to `field` is a subroutine name that must be resolved". The
1571 /// put owner — which holds the registry — extracts the name from the write,
1572 /// performs the lookup, and applies the `S_db_BadSub` refusal at the point
1573 /// C's `dbPut` returns the after-put `special()` status. Returns `false`
1574 /// for any field/mode C accepts without a lookup (a non-SNAM field, or an
1575 /// aSub in `LFLG=READ` where the name comes from the SUBL link at process
1576 /// time and a SNAM put is not validated).
1577 fn is_subroutine_name_field(&self, _field: &str) -> bool {
1578 false
1579 }
1580
1581 /// Primary field name (default "VAL"). Override for waveform etc.
1582 fn primary_field(&self) -> &'static str {
1583 "VAL"
1584 }
1585
1586 /// Whether a put to `field` directly defines the record — clears UDF
1587 /// exactly like a primary-value-field put. C `dbAccess.c::dbPut`
1588 /// (`:1409-1411`) clears `udf` synchronously only when the put target is
1589 /// `dbIsValueField` (i.e. `field == primary_field()`); this hook is where
1590 /// a record type says its own `special()` ALSO clears UDF for a
1591 /// non-value field, independent of `dbIsValueField`.
1592 ///
1593 /// `mbboDirect` is the case this exists for: `mbboDirectRecord.c::special`
1594 /// (`after==1`, B0..B1F, line 290) sets `prec->udf = FALSE` on a bit-field
1595 /// put — the bit write is a second value source alongside a VAL put and
1596 /// the closed-loop DOL fetch. Default: only the primary field.
1597 fn is_udf_defining_put(&self, field: &str) -> bool {
1598 field == self.primary_field()
1599 }
1600
1601 /// Get the primary value.
1602 fn val(&self) -> Option<EpicsValue> {
1603 self.get_field(self.primary_field())
1604 }
1605
1606 /// Set the primary value.
1607 ///
1608 /// Matches C EPICS `dbPut` behavior: if the value type doesn't match
1609 /// the field type, it is automatically coerced (e.g., Long→Double for
1610 /// ai, Long→Enum for bi/mbbi). This prevents silent failures when
1611 /// asyn device support provides Int32 values to Enum-typed records.
1612 fn set_val(&mut self, value: EpicsValue) -> CaResult<()> {
1613 // Soft-channel INP/DOL delivery into the record's value field is
1614 // internal delivery, so it takes the same single owner every other
1615 // link target takes — `put_field_internal`. It was a parallel path
1616 // (put_field, then a `TypeMismatch`-triggered `convert_to` off the
1617 // *current* value's type), which silently dropped a shape the typed
1618 // arm rejected and `convert_to` could not fix: an array source into a
1619 // scalar VAL stayed an array and never landed. C's link layer asks for
1620 // one element (`dbGetLink(..., nRequest = NULL)`), so a waveform INP
1621 // into an `ai.VAL` delivers `wf[0]`.
1622 let field = self.primary_field();
1623 self.put_field_internal(field, value)
1624 }
1625
1626 /// Whether this record's `INP` is read by DEVICE SUPPORT (a C `DSET`), as
1627 /// opposed to by the record body itself.
1628 ///
1629 /// The init-time load of a CONSTANT `INP` into the record's value field is
1630 /// soft device support's `init_record` (`devAiSoft.c`, `devLonginSoft.c`,
1631 /// … each call `recGblInitConstantLink(&prec->inp, …)`), so it exists only
1632 /// where a DSET exists. `compress` has no device support at all
1633 /// (`compressRecord.c` declares no `dset`; its `process` calls `dbGetLink`
1634 /// on `INP` itself), which is why C leaves a `field(INP,"5")` compress with
1635 /// an EMPTY circular buffer — the constant is loaded nowhere and delivers
1636 /// nothing at process (`dbConstGetValue`). Seeding it anyway put a phantom
1637 /// sample in the buffer before the first scan.
1638 fn input_read_by_device_support(&self) -> bool {
1639 true
1640 }
1641
1642 /// The rest of the soft INPUT device support's `init_record`, once the
1643 /// constant-INP load above has (or has not) landed.
1644 ///
1645 /// Most soft dsets are exactly `recGblInitConstantLink()` and stop there —
1646 /// a link they could not load leaves the record's own init state alone. The
1647 /// ARRAY dsets do not: `devWfSoft.c:39-51` runs `dbLoadLinkArray` on every
1648 /// waveform and sets `prec->nord = 0` when it fails (a real link, or none —
1649 /// `dbLoadLinkArray` has no `loadArray` lset outside a constant), which is
1650 /// why C serves `NORD = 0` on a `record(waveform,"X"){}` even though the
1651 /// record's own `init_record` seeded `nord = (nelm == 1)` a moment earlier.
1652 ///
1653 /// `loaded` is whether a constant INP reached the value field. Defaulted to
1654 /// a no-op: a dset that only seeds does not need this half.
1655 fn soft_input_dset_init(&mut self, loaded: bool) {
1656 let _ = loaded;
1657 }
1658
1659 /// The `DTYP="Raw Soft Channel"` INPUT dset — C's four `devXxxSoftRaw.c`
1660 /// read supports (`devAiSoftRaw`, `devBiSoftRaw`, `devMbbiSoftRaw`,
1661 /// `devMbbiDirectSoftRaw`).
1662 ///
1663 /// The value read from the INP link goes to **`RVAL`**, not `VAL`: the
1664 /// record's own `RVAL → VAL` convert then runs (that is the whole
1665 /// difference from `"Soft Channel"`, whose `read_xxx` returns 2 and writes
1666 /// `VAL` directly).
1667 ///
1668 /// **`Some`/`None` IS the dset table.** A record type that implements this
1669 /// is one for which C ships a SoftRaw input dset; a record type that does
1670 /// not, C has no such dset for, so `DTYP="Raw Soft Channel"` on it is a
1671 /// configuration C rejects at iocInit. There is no separate boolean saying
1672 /// whether the record "accepts" raw input — that boolean existed, defaulted
1673 /// to `false`, had ONE override in the workspace, and silently sent the
1674 /// other three input records' raw values into `VAL`, where their own convert
1675 /// then overwrote them from an unseeded `RVAL=0` (R19-66). A capability
1676 /// answer that can disagree with the implementation is the bug.
1677 fn raw_soft_input(&mut self, entry: RawSoftEntry, value: EpicsValue) -> Option<CaResult<()>> {
1678 let _ = (entry, value);
1679 None
1680 }
1681
1682 /// The `DTYP="Raw Soft Channel"` OUTPUT dset — C's four `devXxxSoftRaw.c`
1683 /// write supports: the value `write_xxx()` puts to the OUT link.
1684 ///
1685 /// `devAoSoftRaw.c` / `devBoSoftRaw.c` put `RVAL` (`dbPutLink(&prec->out,
1686 /// DBR_LONG, &prec->rval, 1)`); `devMbboSoftRaw.c` /
1687 /// `devMbboDirectSoftRaw.c` put `RVAL & MASK` as `DBR_ULONG`. All four
1688 /// write the RAW word — never the engineering `OVAL` that
1689 /// [`Record::output_link_value`] (the `"Soft Channel"` dset) puts.
1690 ///
1691 /// Same rule as [`Record::raw_soft_input`]: `Some`/`None` IS the dset
1692 /// table. Before this hook existed, a `DTYP="Raw Soft Channel"` output
1693 /// record matched neither the soft-OUT arm (which tests for `"Soft
1694 /// Channel"`) nor the device arm (it has no device), so it wrote **nothing
1695 /// at all** to OUT.
1696 fn raw_soft_output_value(&self) -> Option<EpicsValue> {
1697 None
1698 }
1699
1700 /// Apply a raw device value read *back* from an output record's device
1701 /// support (the asyn init seed and driver readback callback), the output
1702 /// analogue of [`Record::apply_raw_input`]. An output record whose
1703 /// `convert()` is forward (engineering → raw) must invert it here — store
1704 /// the raw value into `RVAL` and compute the engineering `VAL` — because
1705 /// the framework's forward convert would otherwise recompute `RVAL` from
1706 /// the stale `VAL` and discard the readback (C `processAo`/`initAo` set
1707 /// `rval`/`val` directly, devAsynInt32.c:955-957/:973-994).
1708 ///
1709 /// Returns `true` when the record fully produced `VAL` from the raw value
1710 /// (the asyn store path then reports `computed` so the forward convert is
1711 /// skipped). The default returns `false`: records whose own `convert()` is
1712 /// already `raw → eng` (`ai`) or that need no conversion (`longout`,
1713 /// `mbbo`, whose `set_val` re-derives from the raw value) keep the legacy
1714 /// raw → `RVAL` / direct-`VAL` path.
1715 fn apply_raw_readback(&mut self, _raw: i32) -> bool {
1716 false
1717 }
1718
1719 /// Apply a float64 device value read *back* from an output record's asyn
1720 /// device support — the `asynFloat64` analogue of
1721 /// [`Record::apply_raw_readback`]. A float64 output (`ao`) whose device
1722 /// value carries an `ASLO`/`AOFF` linear scaling must seed the engineering
1723 /// `VAL` here (`VAL = value * ASLO + AOFF`), because the asyn store path
1724 /// would otherwise write the raw device value straight into `VAL` and drop
1725 /// the scaling. Sets `VAL` only (a float64 `ao` carries no `RVAL`); the
1726 /// reverse scaling `(OVAL - AOFF) / ASLO` is applied on the device-write
1727 /// side. Mirrors C `initAo`/`processAo` (devAsynFloat64.c:627-629/:646-649).
1728 ///
1729 /// Returns `true` when the record produced `VAL` from the raw value (the
1730 /// asyn store path then reports `computed`, skipping the forward convert).
1731 /// The default returns `false`: records with no float64 readback scaling
1732 /// keep the raw `set_val` path.
1733 fn apply_float64_readback(&mut self, _raw: f64) -> bool {
1734 false
1735 }
1736
1737 /// Hand the record the database's breakpoint-table registry so an `ai`/`ao`
1738 /// with `LINR >= 3` can resolve and cache the table its `LINR` selects.
1739 /// Called once at iocInit, before the first `process`/`convert`. The record
1740 /// resolves the table lazily on the first conversion (and re-resolves when
1741 /// `LINR` changes at runtime), mirroring C `cvtRawToEngBpt`'s
1742 /// `init || *ppbrk == NULL` cache. The default is a no-op: only `ai`/`ao`
1743 /// carry `LINR`.
1744 fn install_breaktable_registry(
1745 &mut self,
1746 _registry: std::sync::Arc<crate::server::cvt_bpt::BreakTableRegistry>,
1747 ) {
1748 }
1749
1750 /// Apply IVOA=2 ("set outputs to IVOV") semantics: copy the
1751 /// IVOV value into whatever output staging field the OUT
1752 /// writeback consumes for this record type. Mirrors the
1753 /// per-record C `recXxx.c` behaviour:
1754 ///
1755 /// - `ao`/`lso`: `OVAL = IVOV; VAL = OVAL`
1756 /// - `bo`/`busy`/`mbbo`/`mbboDirect`: `RVAL = IVOV; VAL = IVOV`
1757 /// - `calcout`/`scalcout`: `OVAL = IVOV` (VAL is calc input, not
1758 /// touched on invalid-output)
1759 /// - `dfanout`: `VAL = IVOV` (the broadcast value)
1760 ///
1761 /// Default uses [`Record::set_val`] for records whose OUT path
1762 /// reads VAL only.
1763 fn apply_invalid_output_value(&mut self, ivov: EpicsValue) -> CaResult<()> {
1764 self.set_val(ivov)
1765 }
1766
1767 /// Whether this record type supports device write (output records only).
1768 /// `aao` is included here even though it's served by the same
1769 /// concrete struct as `waveform`/`aai`/`subArray` — the
1770 /// WaveformRecord's `can_device_write` override picks the right
1771 /// answer per [`ArrayKind`], but this default matters for code that
1772 /// only has the record-type string.
1773 fn can_device_write(&self) -> bool {
1774 matches!(
1775 self.record_type(),
1776 "ao" | "bo"
1777 | "longout"
1778 | "int64out"
1779 | "mbbo"
1780 | "mbboDirect"
1781 | "stringout"
1782 | "lso"
1783 | "printf"
1784 | "aao"
1785 )
1786 }
1787
1788 /// Whether async processing has completed and put_notify can respond.
1789 /// Records that return AsyncPendingNotify should return false while
1790 /// async work is in progress, and true when done.
1791 /// Default: true (synchronous records are always complete).
1792 fn is_put_complete(&self) -> bool {
1793 true
1794 }
1795
1796 /// Whether this record should fire its forward link after processing.
1797 fn should_fire_forward_link(&self) -> bool {
1798 true
1799 }
1800
1801 /// C parity: a record whose completion restamps `TIME` AFTER the VAL
1802 /// monitor post and the forward link, not before the value post like
1803 /// every standard record (`aoRecord.c:190` stamps ahead of `writeValue`).
1804 ///
1805 /// Only sseq's `asyncFinish` (`sseqRecord.c`) has this ordering: it posts
1806 /// VAL at `:474`, runs `recGblFwdLink` at `:499`, and only then calls
1807 /// `recGblGetTimeStamp` at `:501`. So the first VAL monitor event carries
1808 /// the record's pre-update timestamp, and `TIME` advances only for the
1809 /// following BUSY post and the next cycle — the VAL timestamp always lags
1810 /// one completion behind. The framework's synchronous `Complete` tail
1811 /// consults this to skip the pre-output restamp and apply it after the
1812 /// forward-link tail instead. Default false: every other record (including
1813 /// the base `seq`, whose `seqRecord.c:224` restamps BEFORE the `:229` VAL
1814 /// post) stamps before the value post.
1815 fn restamps_time_after_completion(&self) -> bool {
1816 false
1817 }
1818
1819 /// Whether this record's OUT link should be written after processing.
1820 /// Defaults to true. Override in calcout / longout to implement OOPT
1821 /// conditional output (epics-base 7.0.8).
1822 fn should_output(&self) -> bool {
1823 true
1824 }
1825
1826 /// Notify the record that the OUT-link / device write completed
1827 /// successfully on this cycle. The framework calls this right after
1828 /// the actual write so transition-detection state (e.g.
1829 /// `longout.pval`) can update for the next cycle's
1830 /// [`Self::should_output`] check. Default: no-op.
1831 fn on_output_complete(&mut self) {}
1832
1833 /// Whether this record uses MDEL/ADEL deadband for monitor posting.
1834 /// Binary records (bi, bo, busy, mbbi, mbbo) return false because
1835 /// C EPICS always posts monitors for these record types regardless
1836 /// of whether the value changed.
1837 fn uses_monitor_deadband(&self) -> bool {
1838 true
1839 }
1840
1841 /// Whether this record's process cycle posts its primary value (`VAL`)
1842 /// as a value monitor (`DBE_VALUE` / `DBE_LOG`).
1843 ///
1844 /// Default `true`: for most records C `monitor()` posts `VAL` whenever the
1845 /// value moved (deadband, change-gate, or always).
1846 ///
1847 /// `false` for the "trigger" records `fanout` and `seq`. Their `VAL` is
1848 /// `field(VAL,DBF_LONG){ pp(TRUE) }` — "Used to trigger" — and their C
1849 /// `process()` posts `VAL` ONLY with the alarm events `recGblResetAlarms`
1850 /// returns: `if (events) db_post_events(prec, &prec->val, events)`
1851 /// (fanoutRecord.c:148-150, seqRecord.c:227-229), never `DBE_VALUE` /
1852 /// `DBE_LOG`. Writing `VAL` fans out the forward links / sequences the
1853 /// `DOn`→`LNKn` writes; the value itself is not a monitored quantity, so a
1854 /// run of `caput VAL` posts no per-put value event (only the initial
1855 /// subscription snapshot fires). The alarm bits still reach `VAL` through
1856 /// the deadband post's `alarm_bits`, so an alarm transition posts `VAL`
1857 /// with `DBE_ALARM` exactly as C's `if (events)` does.
1858 fn process_posts_value_monitor(&self) -> bool {
1859 true
1860 }
1861
1862 /// Per-record VALUE/LOG monitor gate for record types that post a
1863 /// monitor *only when the value actually changed* — and have no
1864 /// MDEL/ADEL deadband to express that.
1865 ///
1866 /// `Some(changed)` makes the framework post the VALUE and LOG
1867 /// monitors iff `changed`; `None` (the default) leaves the decision
1868 /// to the deadband / always-post path.
1869 ///
1870 /// C `lsiRecord.c`/`lsoRecord.c` `monitor()` raise `DBE_VALUE |
1871 /// DBE_LOG` only when `len != olen || memcmp(oval, val, len)`. Those
1872 /// records return [`Self::uses_monitor_deadband`]`== false`, which
1873 /// otherwise routes them to the unconditional always-post path
1874 /// (correct for binary records, wrong for lsi/lso). Because the
1875 /// framework posts monitors *after* `process()` — by which point the
1876 /// record has already committed `oval`/`olen` — the implementation
1877 /// captures the comparison result during `process()` and returns the
1878 /// captured flag here, not a live re-comparison.
1879 fn monitor_value_changed(&self) -> Option<bool> {
1880 None
1881 }
1882
1883 /// `menuPost` "Always" override for the VALUE / LOG monitor masks.
1884 ///
1885 /// Returns `(post_value_always, post_archive_always)`. The framework
1886 /// ORs these into the change-gated mask from
1887 /// [`Self::monitor_value_changed`], so an *unchanged* process cycle
1888 /// still posts `DBE_VALUE` (resp. `DBE_LOG`) when the record's MPST
1889 /// (resp. APST) menu field is set to `Always`.
1890 ///
1891 /// C `lsiRecord.c`/`lsoRecord.c` `monitor()` compute the VAL post
1892 /// mask from three independent inputs:
1893 ///
1894 /// * the change test `len != olen || memcmp(oval, val, len)` →
1895 /// `DBE_VALUE | DBE_LOG`,
1896 /// * `if (mpst == menuPost_Always) events |= DBE_VALUE;`,
1897 /// * `if (apst == menuPost_Always) events |= DBE_LOG;`.
1898 ///
1899 /// [`Self::monitor_value_changed`] carries the first input; this hook
1900 /// carries the other two. Records without a `menuPost` field keep the
1901 /// default `(false, false)`, which leaves the change gate unchanged.
1902 fn monitor_always_post(&self) -> (bool, bool) {
1903 (false, false)
1904 }
1905
1906 /// The value the MDEL/ADEL deadband is evaluated against.
1907 ///
1908 /// For most records C `monitor()` applies the value deadband to
1909 /// `VAL`, so the default is [`Self::val`]. A record whose monitored
1910 /// quantity is not its primary value must override this: the motor
1911 /// record, for instance, has `VAL` as the setpoint and applies
1912 /// MDEL/ADEL to `RBV` (the readback) — its C `monitor()` deadbands
1913 /// `RBV`, not `VAL`. Such a record returns its readback field here.
1914 ///
1915 /// Default is `val()`, so existing records are unaffected.
1916 fn monitor_deadband_value(&self) -> Option<EpicsValue> {
1917 self.val()
1918 }
1919
1920 /// The FIELD whose VALUE/LOG monitor delivery the MDEL/ADEL
1921 /// deadband gates — the field [`Self::monitor_deadband_value`]
1922 /// reads. A record overriding one must override both consistently.
1923 ///
1924 /// For most records the deadband gates the primary value itself,
1925 /// so the default returns [`Self::primary_field`] and nothing
1926 /// changes. The motor record deadbands RBV: C `monitor()`
1927 /// (motorRecord.cc:3468-3507) throttles the RBV post with
1928 /// MDEL/ADEL, while VAL is posted only when an actual setpoint
1929 /// change marked it (M_VAL). When this returns a non-primary
1930 /// field, the framework's snapshot builders:
1931 ///
1932 /// * deliver THIS field on the deadband triggers (instead of raw
1933 /// change-detection), and
1934 /// * route the primary field through generic change-detection, so
1935 /// an unchanged setpoint is not re-posted on every readback
1936 /// poll.
1937 fn monitor_deadband_field(&self) -> &'static str {
1938 self.primary_field()
1939 }
1940
1941 /// Fields the record's C `monitor()` posts on every cycle whose
1942 /// alarm transition fired, even when their value did not change.
1943 ///
1944 /// C motorRecord.cc `monitor()` (3513-3645) computes
1945 /// `local_mask = monitor_mask | (MARKED(x) ? DBE_VAL_LOG : 0)`
1946 /// for each field in its posting list — when the alarm moved
1947 /// (`monitor_mask != 0`), `local_mask` is non-zero for UNMARKED
1948 /// fields too, so every listed field posts with `DBE_ALARM` and a
1949 /// `DBE_ALARM`-only subscriber observes the alarm moment on any of
1950 /// them. The framework's change-detection loop posts a listed,
1951 /// subscribed, unchanged field with the cycle's alarm bits when
1952 /// this list names it.
1953 ///
1954 /// Default: empty — most C record types post only their value
1955 /// field(s) on an alarm transition (aiRecord.c `monitor()` posts
1956 /// VAL with `monitor_mask` and RVAL only when it changed), which
1957 /// the deadband-field post already covers.
1958 fn alarm_cycle_monitored_fields(&self) -> &'static [&'static str] {
1959 &[]
1960 }
1961
1962 /// Fields the record's C `monitor()` re-posts with `DBE_VAL_LOG` on
1963 /// every cycle that recomputed them, even when the value did not
1964 /// change — the analogue of an unconditional `MARK(field)` in C.
1965 ///
1966 /// Unlike [`Self::alarm_cycle_monitored_fields`] (which posts unchanged
1967 /// fields only on a cycle whose alarm transition fired), these post on
1968 /// any cycle the record names them, with `DBE_VALUE | DBE_LOG` (plus the
1969 /// cycle's alarm bits when one fired). The framework's change-detection
1970 /// loop posts a listed, subscribed, unchanged field with that mask.
1971 ///
1972 /// C motorRecord `process_motor_info` (motorRecord.cc:3764-3767)
1973 /// `MARK`s `M_DIFF`/`M_RDIF` unconditionally on every `CALLBACK_DATA`
1974 /// pass, and `monitor()` (3522-3531) posts them with `monitor_mask |
1975 /// DBE_VAL_LOG`; a `camonitor DIFF` on an axis parked at a constant
1976 /// non-zero following error thus gets an event every poll. The record
1977 /// returns the fields ONLY on the cycles it actually re-marked them (it
1978 /// reads its own per-cycle state), so a pass that did not recompute them
1979 /// does not over-post.
1980 ///
1981 /// Default: empty — most record types post a field only when it
1982 /// changed (or on an alarm transition), which the existing gates cover.
1983 fn force_posted_fields(&self) -> &'static [&'static str] {
1984 &[]
1985 }
1986
1987 /// Fields this cycle's C `monitor()` posted UNCONDITIONALLY, chosen per
1988 /// cycle from record state — the DYNAMIC sibling of
1989 /// [`Self::force_posted_fields`].
1990 ///
1991 /// Some records decide which fields to post from a per-cycle BIT MASK
1992 /// rather than from a fixed list. aCalcout has two of them, and neither
1993 /// consults the value: `afterCalc` posts exactly the AMASK-flagged array
1994 /// fields — the ones the expression STORED into
1995 /// (`aCalcoutRecord.c:293-297`) — and `monitor()` posts exactly the
1996 /// NEWM-flagged ones — the input arrays whose link delivered a CHANGED
1997 /// value (`:1031-1036`). `AA := AA` therefore still posts AA.
1998 ///
1999 /// Neither existing gate can express that. The change-detection loop posts
2000 /// only what moved, so it drops the store-the-same-value case;
2001 /// [`Self::force_posted_fields`] is `&'static`, so it cannot name a set
2002 /// that varies per cycle (twelve arrays, 2^12 combinations) without
2003 /// over-posting every one of them every cycle.
2004 ///
2005 /// Each entry is ONE C `db_post_events` call, with the mask THAT call site
2006 /// uses ([`CyclePostMask`]) — not one entry per field. The two aCalcout call
2007 /// sites disagree on the mask (`afterCalc` posts a literal `DBE_VALUE|
2008 /// DBE_LOG`, `monitor()` posts `monitor_mask|DBE_VALUE|DBE_LOG`), and an
2009 /// array in BOTH masks is posted TWICE by C, once from each. So a field may
2010 /// legitimately appear twice, and the framework emits an event per entry.
2011 ///
2012 /// TAKE semantics: called exactly once per process cycle, and the record
2013 /// clears whatever state it answered from — C's `pcalc->newm = 0` (`:1036`)
2014 /// is part of the same step.
2015 ///
2016 /// Default: empty — and `Vec::new()` does not allocate.
2017 fn take_cycle_posted_fields(&mut self) -> Vec<(&'static str, CyclePostMask)> {
2018 Vec::new()
2019 }
2020
2021 /// Fields whose ONLY post path is the record's own per-cycle mark — C never
2022 /// change-detects them, so a value change alone must post nothing.
2023 ///
2024 /// aCalcout's arrays AA..LL are the case. C's `monitor()` compares scalar
2025 /// A..L against their PA..PL previous values (`aCalcoutRecord.c:1023-1029`)
2026 /// and OVAL against POVL (`:1039`), but it keeps NO previous copy of an
2027 /// array and runs no array comparison anywhere: an array posts if and only
2028 /// if the expression stored into it (AMASK, `afterCalc` `:293-297`) or its
2029 /// input link delivered a changed value (NEWM, `:1031-1036`) — both reported
2030 /// by [`Self::take_cycle_posted_fields`].
2031 ///
2032 /// So the change-detection arm must not see these fields at all. It is not
2033 /// merely redundant with the marks: a client `caput` to AA posts the put's
2034 /// value without advancing the subscriber's `last_posted`, and the next
2035 /// process — which stored nothing into AA and fetched nothing into it —
2036 /// then found AA "changed" and emitted a post C has no counterpart for.
2037 ///
2038 /// Default: empty — every other record's auxiliary fields post on change.
2039 fn fields_posted_only_when_marked(&self) -> &'static [&'static str] {
2040 &[]
2041 }
2042
2043 /// Fields the record's C `monitor()` re-posts with `DBE_LOG` ONLY on
2044 /// every cycle it names them, regardless of change — the analogue of
2045 /// an unconditional `db_post_events(field, DBE_LOG)` sweep.
2046 ///
2047 /// Distinct from [`Self::force_posted_fields`], which posts with
2048 /// `DBE_VALUE | DBE_LOG`: these post with `DBE_LOG` alone, so only a
2049 /// `DBE_LOG` (archiver) subscriber receives the event.
2050 ///
2051 /// The sweep is an INDEPENDENT post, NOT an alternative to the
2052 /// change-detected post. C's `db_post_events` calls compose: on the
2053 /// scaler's count-completion cycle `updateCounts()` posts each changed
2054 /// `Sn` with `DBE_VALUE` (scalerRecord.c:582) and then `monitor()` —
2055 /// reached because the done-interrupt set `ss = IDLE` (`:367`,
2056 /// `:510`) — posts the SAME `Sn` again with a literal `DBE_LOG`
2057 /// (`:757-773`). Two events, one field, one cycle. So the framework
2058 /// emits the sweep post in addition to whatever the change detection
2059 /// produced; gating it on "did not change" would silently drop the
2060 /// `DBE_LOG` half on exactly the cycle that carries the final counts.
2061 ///
2062 /// For a field that is ALSO a [`Self::value_only_change_fields`]
2063 /// member (scaler `Sn`) the change post carries `DBE_VALUE` only, so
2064 /// this sweep is the sole source of its `DBE_LOG` events, matching C.
2065 ///
2066 /// The record returns the names ONLY on the cycles whose C `monitor()`
2067 /// runs — the scaler reads its own `ss` state and returns `S1..Snch`
2068 /// while idle, empty while counting (a counting cycle never reaches C
2069 /// `monitor()`).
2070 ///
2071 /// The sweep post carries `DBE_LOG` plus the cycle's ALARM-transition bits
2072 /// (`recGblResetAlarms`). C's scaler computes that mask and then posts with a
2073 /// literal `DBE_LOG`, dropping the alarm bit — CBUG-B19, a deliberate
2074 /// deviation; see the post site in `collect_subscriber_posts`.
2075 ///
2076 /// Default: empty — most record types have no LOG-only sweep.
2077 fn log_swept_fields(&self) -> &'static [&'static str] {
2078 &[]
2079 }
2080
2081 /// Fields whose change-detected monitor post must carry `DBE_VALUE`
2082 /// only — the LOG bit is stripped — instead of the framework default
2083 /// `DBE_VALUE | DBE_LOG`.
2084 ///
2085 /// The generic change-detection post (and the deadband post for a
2086 /// deadband field named here) normally bundles `DBE_LOG` so an
2087 /// archiver subscribed `DBE_LOG` sees every value change. A record
2088 /// whose C `db_post_events` calls pass a literal `DBE_VALUE` for
2089 /// these fields names them here so the framework drops the LOG bit;
2090 /// the cycle's alarm bits are still OR'd in (alarm posting is a
2091 /// separate per-field contract, unaffected by this hook).
2092 ///
2093 /// C `scalerRecord.c` posts CNT/T/VAL/PR1/TP/FREQ and each active
2094 /// channel `S1..Snch` with a literal `DBE_VALUE` on a value change
2095 /// (scalerRecord.c:372,478,582,588 et al.); `DBE_LOG` appears ONLY in
2096 /// the idle `monitor()` sweep ([`Self::log_swept_fields`],
2097 /// scalerRecord.c:771). The two hooks are complementary: a `DBE_LOG`
2098 /// subscriber on `Sn` is served by the idle sweep, never by a
2099 /// counting-cycle value change — matching C.
2100 ///
2101 /// Default: empty — most record types post changes with
2102 /// `DBE_VALUE | DBE_LOG` (C `monitor_mask | DBE_VALUE | DBE_LOG`,
2103 /// calcRecord.c:420, subRecord.c:400).
2104 fn value_only_change_fields(&self) -> &'static [&'static str] {
2105 &[]
2106 }
2107
2108 /// Secondary value fields a record posts with the *primary VAL
2109 /// monitor mask*, from INSIDE the same guard C wraps its VAL post in —
2110 /// never with a forced `DBE_VALUE | DBE_LOG` on every change.
2111 ///
2112 /// Mirrors C records that drive a raw secondary field with the shared
2113 /// `monitor_mask` rather than `monitor_mask | DBE_VALUE | DBE_LOG`. Each
2114 /// entry pairs the field with the gate C applies to it *inside* that
2115 /// guard — see [`ValuePostGate`], which is the whole reason this is a
2116 /// pair and not a bare name: `ai` re-tests the raw value
2117 /// (`if (prec->oraw != prec->rval)`) while `timestamp` does not.
2118 ///
2119 /// Distinct from the default change-detected aux post (which carries
2120 /// `DBE_VALUE | DBE_LOG` unconditionally): ao `RVAL`/`RBV`, mbbo/
2121 /// mbboDirect/mbbiDirect `RVAL`/`RBV`, sel `SELN` and compress `NUSE`
2122 /// are all posted by C with the `DBE_VALUE | DBE_LOG`-forced mask, so
2123 /// they stay on the default path and must NOT be named here.
2124 ///
2125 /// Default: empty.
2126 fn fields_posted_with_value_mask(&self) -> &'static [(&'static str, ValuePostGate)] {
2127 &[]
2128 }
2129
2130 /// Change-detected auxiliary fields this record posts with C's
2131 /// `monitor_mask | DBE_VALUE` — VAL's monitor mask ORed with `DBE_VALUE`,
2132 /// and NOT the framework default `monitor_mask | DBE_VALUE | DBE_LOG`.
2133 ///
2134 /// The difference is the forced `DBE_LOG`. For a field named here the LOG
2135 /// bit is present only when it is already in VAL's monitor mask — i.e. only
2136 /// when VAL's own ADEL deadband crossed this cycle — so a `DBE_LOG`
2137 /// subscriber (an archiver) receives the field exactly on the cycles C
2138 /// sends it, instead of on every change.
2139 ///
2140 /// `swaitRecord.c::monitor` (646-653) is this shape for its A..L inputs:
2141 ///
2142 /// ```c
2143 /// if (*pnew != *pprev)
2144 /// db_post_events(pwait, pnew, monitor_mask | DBE_VALUE);
2145 /// ```
2146 ///
2147 /// while `calcRecord.c:420` — the same loop, one module over — writes
2148 /// `monitor_mask | DBE_VALUE | DBE_LOG`. The two records genuinely differ,
2149 /// so the mask is a per-record property, not a framework-wide rule.
2150 ///
2151 /// Distinct from [`Self::value_only_change_fields`] (a literal `DBE_VALUE`,
2152 /// which drops the ADEL LOG bit as well) and from
2153 /// [`Self::fields_posted_with_value_mask`] (posted from INSIDE C's
2154 /// `if (monitor_mask)` guard, so they do not post at all on a cycle where
2155 /// VAL itself does not). The fields named here post on every change,
2156 /// guard or no guard.
2157 ///
2158 /// Default: empty.
2159 fn fields_posted_with_monitor_mask(&self) -> &'static [&'static str] {
2160 &[]
2161 }
2162
2163 /// Fields whose change post carries a LITERAL `DBE_VALUE | DBE_LOG` — this
2164 /// cycle's alarm bits DISCARDED.
2165 ///
2166 /// C's fourth mask shape, and the only one that *drops* information the
2167 /// record already computed. `epidRecord.c::monitor` builds VAL's mask from
2168 /// `recGblResetAlarms` (`:350`) and posts VAL with it, then REASSIGNS
2169 /// (not `|=`) before the secondaries:
2170 ///
2171 /// ```c
2172 /// monitor_mask = DBE_LOG|DBE_VALUE; /* :376 */
2173 /// if (pepid->ovlp != pepid->oval) db_post_events(pepid, &pepid->oval, monitor_mask);
2174 /// ... /* P, I, D, CT, DT, ERR, CVAL */
2175 /// ```
2176 ///
2177 /// so on an alarm-transition cycle a `DBE_ALARM`-only subscriber to one of
2178 /// those fields is sent NOTHING, while the generic aux mask
2179 /// (`alarm_bits | DBE_VALUE | DBE_LOG`) would send it an event.
2180 ///
2181 /// Distinct from the three narrower shapes: [`Self::value_only_change_fields`]
2182 /// (literal `DBE_VALUE`), [`Self::fields_posted_with_monitor_mask`]
2183 /// (`monitor_mask | DBE_VALUE` — keeps the alarm bits AND VAL's ADEL LOG bit)
2184 /// and [`Self::fields_posted_with_value_mask`] (VAL's mask, posted from inside
2185 /// C's `if (monitor_mask)` guard). A field named here posts on every change,
2186 /// with both value classes and no alarm class, whatever the cycle's alarms did.
2187 ///
2188 /// Resolved for every change-detected field by [`aux_change_mask`], the single
2189 /// owner of the aux-post mask.
2190 ///
2191 /// Default: empty.
2192 fn fields_posted_without_alarm_bits(&self) -> &'static [&'static str] {
2193 &[]
2194 }
2195
2196 /// The array-style monitor decision (C waveform/aai/aao `monitor()`,
2197 /// waveformRecord.c:291-326). `None` (the default) means the record has
2198 /// no MPST/APST/HASH mechanism and the generic MDEL/ADEL deadband
2199 /// decision applies. `Some(_)` lets the record replace that with its
2200 /// "Always vs On Change" rule: it hashes the array content, compares to
2201 /// the stored `HASH`, updates it, and reports whether `DBE_VALUE` /
2202 /// `DBE_LOG` should be on the VAL post this cycle and whether the hash
2203 /// changed (so the owner posts `HASH` with `DBE_VALUE`). Called by
2204 /// `check_deadband_ext` (the single owner of the VAL-mask decision).
2205 ///
2206 /// The hook is the VAL mask, not the MPST/APST rule specifically: any
2207 /// record whose C `monitor()` decides the mask by its own rule implements
2208 /// it. `histogram` is the other implementor — its rule is the MDEL COUNT
2209 /// deadband (`mcnt > mdel`, histogramRecord.c:287-291), and like waveform's
2210 /// it updates the state it keys on (there, `MCNT = 0`; here, `HASH`).
2211 fn array_monitor_post(&mut self) -> Option<ArrayMonitorPost> {
2212 None
2213 }
2214
2215 /// Fields the record posts itself via an event-driven, individually
2216 /// masked path rather than the generic change-detection loop. The
2217 /// framework excludes these from that loop so they are neither
2218 /// double-posted nor spuriously posted on a cycle the event did not
2219 /// fire. C waveform/aai/aao `monitor()` posts `HASH` this way —
2220 /// `db_post_events(prec, &prec->hash, DBE_VALUE)` only when the content
2221 /// hash changed (waveformRecord.c:317-319), never via VAL's change.
2222 ///
2223 /// The CLOSED set of fields a process cycle of this record may post —
2224 /// the record's C `process()` + `monitor()` `db_post_events` calls,
2225 /// enumerated.
2226 ///
2227 /// `None` (the default) leaves the framework's generic rule in force:
2228 /// every subscribed field that changed since its last post is posted.
2229 /// That rule is right for a record whose C `monitor()` walks its fields
2230 /// and posts whatever moved (calc, sub, ai …). It is WRONG for a record
2231 /// whose C `monitor()` posts a fixed list and leaves every other field it
2232 /// wrote silent — the framework then invents events C never sends:
2233 ///
2234 /// * a field the record WRITES during `process()` but C never posts
2235 /// (scaler's gate→direction copy, `scalerRecord.c:413-414`: `pdir[i] =
2236 /// pgate[i]` with no `db_post_events` — C posts `Dn` only from
2237 /// `special()`).
2238 ///
2239 /// (A field a PUT already posted is NOT in that category: the put's own
2240 /// post advances `last_posted` — see the `RecordInstance::last_posted`
2241 /// contract — so the next process cycle does not change-detect it. This
2242 /// hook must not be used to paper over a framework double post.)
2243 ///
2244 /// `Some(list)` closes it by construction: a field outside the list is
2245 /// never posted by a process cycle — its only monitors come from its own
2246 /// put and from [`Self::monitor_side_effect_fields`]. The list is a
2247 /// whitelist, not a blacklist, so a field added to the record later stays
2248 /// silent unless C posts it.
2249 ///
2250 /// Fields inside the list keep their normal treatment (change detection,
2251 /// [`Self::value_only_change_fields`] mask, deadband, `log_swept_fields`).
2252 fn process_posted_fields(&self) -> Option<&'static [&'static str]> {
2253 None
2254 }
2255
2256 /// Fields the record posts itself via an event-driven, individually
2257 /// masked path rather than the generic change-detection loop. The
2258 /// framework excludes these from that loop so they are neither
2259 /// double-posted nor spuriously posted on a cycle the event did not
2260 /// fire. C waveform/aai/aao `monitor()` posts `HASH` this way —
2261 /// `db_post_events(prec, &prec->hash, DBE_VALUE)` only when the content
2262 /// hash changed (waveformRecord.c:317-319), never via VAL's change.
2263 ///
2264 /// Default: empty.
2265 fn event_posted_fields(&self) -> &'static [&'static str] {
2266 &[]
2267 }
2268
2269 /// Initialize record (pass 0: field defaults; pass 1: dependent init).
2270 fn init_record(&mut self, _pass: u8) -> CaResult<()> {
2271 Ok(())
2272 }
2273
2274 /// Did `init_record` leave the record PERMANENTLY ACTIVE — C's
2275 /// `prec->pact = TRUE` inside `init_record`, which is how a record type
2276 /// disables itself when it cannot possibly process?
2277 ///
2278 /// `subRecord.c:119-123` is the live case: an empty `SNAM` has no
2279 /// subroutine to call, so C prints `"%s.SNAM is empty"`, sets `pact = TRUE`
2280 /// and returns 0. The record exists and serves its fields, but `dbProcess`
2281 /// takes the PACT-active branch on every scan from then on — it never runs
2282 /// record support again. `caget X.PACT` on a bare `record(sub,"X"){}` reads
2283 /// 1 on a C IOC.
2284 ///
2285 /// PACT is a `dbCommon` field with a single owner
2286 /// ([`RecordInstance::enter_pact`] / [`leave_pact`]), so a record cannot
2287 /// park it from `init_record`. It reports the fact here and the owner
2288 /// performs the transition, once, at the end of the init passes.
2289 ///
2290 /// [`leave_pact`]: crate::server::record::RecordInstance::leave_pact
2291 fn init_record_parks_pact(&self) -> bool {
2292 false
2293 }
2294
2295 /// Post-init finalisation hook with mutable access to the
2296 /// framework's UDF flag. Called once after both `init_record`
2297 /// passes complete. Default implementation is a no-op.
2298 ///
2299 /// epics-base PR `dabcf89` (mbboDirect): when VAL is undefined
2300 /// at init time but the user populated B0..B1F bits, the bits
2301 /// should be folded into VAL and UDF cleared. The framework
2302 /// owns `common.udf`, so the record cannot mutate it from
2303 /// `init_record` alone — this hook is the controlled point of
2304 /// access.
2305 fn post_init_finalize_undef(&mut self, _udf: &mut bool) -> CaResult<()> {
2306 Ok(())
2307 }
2308
2309 /// Whether this record type's C `init_record` resets the record to a
2310 /// defined, no-alarm state — `prec->udf = 0; recGblResetAlarms(prec)` — so
2311 /// a freshly loaded, never-processed record reads `UDF=0`,
2312 /// `STAT=NO_ALARM`, `SEVR=NO_ALARM` instead of the born `UDF`/`INVALID`/`1`.
2313 ///
2314 /// Almost no record does this: a not-yet-processed record is normally left
2315 /// `UDF` so an `MS` consumer inherits `INVALID` at IOC startup (see
2316 /// [`RecordInstance::run_init_passes`]). The asyn record is the exception —
2317 /// `asynRecord.c` `init_record` pass 0 does `pasynRec->udf = 0;
2318 /// recGblResetAlarms(pasynRec)` unconditionally, because a device-config
2319 /// record is defined the moment it loads, even against a disconnected port.
2320 /// `UDF` is a common field `init_record` cannot reach, so the record
2321 /// declares the fact here and the init owner performs the reset. Default
2322 /// `false`.
2323 fn init_resets_alarms(&self) -> bool {
2324 false
2325 }
2326
2327 /// The channel's native (maximum) element count for `field`, when it
2328 /// differs from the count of the field's current value.
2329 ///
2330 /// C's `cvt_dbaddr` fixes a channel's `no_elements` at the field's buffer
2331 /// capacity, while `get_array_info` reports the current valid length — so a
2332 /// client's `ca_element_count` is the capacity even though a GET returns
2333 /// fewer elements. Return `Some(capacity)` for such a field; `None`
2334 /// (default) means the channel count is the value's own count.
2335 ///
2336 /// - waveform `VAL` → `NELM` (buffer capacity; the value serves `NORD`).
2337 /// - asyn `BOUT` → `OMAX`, `BINP` → `IMAX` (the `SPC_DBADDR` octet buffers;
2338 /// the value serves the transferred byte count `NOWT`/`NORD`).
2339 fn field_native_count(&self, _field: &str) -> Option<u32> {
2340 None
2341 }
2342
2343 /// Seed the monitor/archive/alarm deadband trackers (MLST/ALST/LALM)
2344 /// from the initial value at iocInit, called once by the builder after
2345 /// both `init_record` passes and `post_init_finalize_undef`.
2346 ///
2347 /// Every C value record's `init_record` ends with
2348 /// `prec->mlst = prec->alst = prec->lalm = prec->val`
2349 /// (e.g. `longinRecord.c:120-122`, `aiRecord.c`), so the first
2350 /// `monitor()` evaluates `DELTA(mlst, val) > mdel` with `mlst == val`
2351 /// (= 0) and posts no DBE_VALUE/DBE_LOG event when the value is
2352 /// unchanged from its initial state. Records expose MLST/ALST/LALM as
2353 /// plain `f64` fields default-initialised to `0.0`; that default
2354 /// conflates "never published" with "published 0", so a record
2355 /// initialised to a *nonzero* value (constant DOL, initial VAL) used
2356 /// to post a spurious first-cycle update that C does not.
2357 ///
2358 /// The default seeds whichever of MLST/ALST/LALM the record actually
2359 /// serves from its monitor-deadband value (`val` for most records),
2360 /// making the invariant hold by construction for every record rather
2361 /// than per-type `init_record` code. It is idempotent for the record
2362 /// types that already seed inside `init_record`, and a no-op for
2363 /// records that serve none of these fields.
2364 fn seed_deadband_tracking(&mut self) {
2365 let seed = match self.monitor_deadband_value().and_then(|v| v.to_f64()) {
2366 Some(v) if v.is_finite() => v,
2367 _ => return,
2368 };
2369 for field in ["MLST", "ALST", "LALM"] {
2370 if self.get_field(field).is_some() {
2371 let _ = self.put_field(field, EpicsValue::Double(seed));
2372 }
2373 }
2374 }
2375
2376 /// Called by the framework immediately after applying this cycle's
2377 /// [`Record::multi_input_links`] fetches, before `process()`.
2378 ///
2379 /// `resolved` lists the `link_field` names (the first element of
2380 /// each `multi_input_links` pair) whose fetch SUCCEEDED this cycle —
2381 /// C's `RTN_SUCCESS(dbGetLink(...))`, i.e. status 0. That includes a
2382 /// CONSTANT link, which returns success having delivered nothing
2383 /// (`dbConstGetValue`, `dbConstLink.c:219-225`) — `epidRecord.c:191`
2384 /// clears UDF on exactly that. A link field absent from the slice
2385 /// either had no link configured or its DB/CA fetch FAILED.
2386 ///
2387 /// This is the framework analogue of C device support inspecting
2388 /// `RTN_SUCCESS(dbGetLink(...))` — e.g. `epidRecord.c:191-193`
2389 /// clears `udf` only when `dbGetLink(&prec->stpl, ...)` returns
2390 /// success. A record's `process()` cannot otherwise observe whether
2391 /// an input link's fetch succeeded, because a failed fetch simply
2392 /// leaves the target field unwritten.
2393 ///
2394 /// Additive, framework-set-hook pattern (same shape as
2395 /// [`Record::set_process_context`]). Default: ignore.
2396 fn set_resolved_input_links(&mut self, _resolved: &[&'static str]) {}
2397
2398 /// Report this cycle's `fetch_values()` outcome: `failed == true` means C's
2399 /// helper would have returned a non-zero status, so the record body — the
2400 /// `calcPerform` / `do_sel` the C `process()` wraps in
2401 /// `if (fetch_values(prec) == 0)` — must NOT run, and VAL/UDF freeze.
2402 ///
2403 /// This is the single delivery point for that outcome, whichever
2404 /// [`InputFetchPolicy`] produced it (a failed link read) and whichever
2405 /// record-specific rule did (sel's `Specified`-mode selected-input read).
2406 /// Records that gate: calc (calcRecord.c:120), calcout (:237), sCalcout
2407 /// (sCalcoutRecord.c:356), aCalcout (aCalcoutRecord.c:399), swait
2408 /// (swaitRecord.c:408 — which additionally raises READ_ALARM/INVALID on the
2409 /// failure) and sel (selRecord.c:114). sub/aSub gate the same outcome, but
2410 /// their body is the framework-dispatched subroutine, so they consume it
2411 /// through `RecordInstance::suppress_subroutine_run` instead.
2412 ///
2413 /// Default: ignore (records with no fetch gate). Same framework-set hook
2414 /// pattern as [`Record::set_resolved_input_links`].
2415 fn set_fetch_gate_failed(&mut self, _failed: bool) {}
2416
2417 /// Report this cycle's subroutine status — C `process`'s `status` variable
2418 /// for `sub`/`aSub`:
2419 ///
2420 /// ```c
2421 /// status = fetch_values(prec);
2422 /// if (!status) { status = do_sub(prec); prec->val = status; }
2423 /// ...
2424 /// if (!status) /* aSubRecord.c:232-239 */
2425 /// for (i = 0; i < NUM_ARGS; i++)
2426 /// dbPutLink(&(&prec->outa)[i], (&prec->ftva)[i], (&prec->vala)[i],
2427 /// (&prec->neva)[i]);
2428 /// ```
2429 ///
2430 /// so `0` — and only `0` — means the input fetch succeeded AND `do_sub` ran
2431 /// and returned success. It is the gate on aSub's OUT-link pushes.
2432 ///
2433 /// Delivered by `RecordInstance::run_registered_subroutine`, the single
2434 /// owner of the `do_sub` call, on every one of its exit paths (the
2435 /// suppressed cycle, no bound routine, the routine's own return).
2436 ///
2437 /// Default: ignore (records with no subroutine).
2438 fn set_subroutine_status(&mut self, _status: i64) {}
2439
2440 /// Called before/after a field put for side-effect processing.
2441 fn special(&mut self, _field: &str, _after: bool) -> CaResult<()> {
2442 Ok(())
2443 }
2444
2445 /// The period of this record's monitor watchdog, or `None` when it has
2446 /// none — C `histogramRecord.c::wdogInit` (:126-152):
2447 ///
2448 /// ```c
2449 /// static void wdogInit(histogramRecord *prec) {
2450 /// if (prec->sdel > 0) { ... callbackRequestDelayed(&pcallback->callback, prec->sdel); }
2451 /// }
2452 /// ```
2453 ///
2454 /// A watchdog is NOT a process cycle: it posts monitors for a record whose
2455 /// value is changing but whose deadband (histogram MDEL) is holding the
2456 /// posts back, so a slow accumulation still reaches a display. The
2457 /// framework re-reads this on every tick, so clearing SDEL stops the
2458 /// watchdog at the next fire without any separate cancel.
2459 ///
2460 /// histogram is the only base record with one. Default: no watchdog.
2461 fn watchdog_interval(&self) -> Option<std::time::Duration> {
2462 None
2463 }
2464
2465 /// One watchdog tick — C `histogramRecord.c::wdogCallback` (:102-124):
2466 ///
2467 /// ```c
2468 /// if (prec->mcnt > 0) {
2469 /// dbScanLock(prec);
2470 /// recGblGetTimeStamp(prec);
2471 /// db_post_events(prec, &prec->val, DBE_VALUE | DBE_LOG);
2472 /// prec->mcnt = 0;
2473 /// dbScanUnlock(prec);
2474 /// }
2475 /// ```
2476 ///
2477 /// The record performs its own state change (histogram: zero MCNT) and
2478 /// returns the fields whose monitors the framework must post — the
2479 /// `db_post_events` half, which a record cannot do itself. An empty slice
2480 /// means "nothing changed since the last tick": no timestamp, no post. The
2481 /// framework holds the record lock across the call (C `dbScanLock`) and
2482 /// re-arms afterwards from [`Self::watchdog_interval`].
2483 ///
2484 /// Default: nothing to post.
2485 fn watchdog_fire(&mut self) -> &'static [&'static str] {
2486 &[]
2487 }
2488
2489 /// Whether this record type's support reads SIML through the `recGbl`
2490 /// simulation helpers (`recGblGetSimm`/`recGblInitSimm`, and therefore
2491 /// `recGblSaveSimm`/`recGblCheckSimm`) rather than a bare `dbGetLink`.
2492 ///
2493 /// ONE C fact, two consequences — which is why it is one predicate:
2494 ///
2495 /// - **The SCAN swap.** The helpers take `&prec->sscn` and `&prec->oldsimm`,
2496 /// so only a record that declares those fields can call them, and only
2497 /// such a record swaps SCAN with SSCN on a SIMM transition
2498 /// (`recGblCheckSimm`, `recGbl.c:427-437`).
2499 /// - **The alarm on a failed SIML read.** `recGblGetSimm` reads SIML with
2500 /// `dbTryGetLink` — which does NOT call `setLinkAlarm` — and then raises
2501 /// the alarm itself, by writing `nsta` DIRECTLY:
2502 /// `if (status && !pcommon->nsev) pcommon->nsta = LINK_ALARM;`
2503 /// (`recGbl.c:454`). SEVR is left alone. A record reading SIML with a
2504 /// plain `dbGetLink` (`busyRecord.c:399`, `swaitRecord.c:402`) instead
2505 /// gets `setLinkAlarm` (`dbLink.c:319-323`) →
2506 /// `recGblSetSevrMsg(LINK_ALARM, INVALID_ALARM)`, a full severity raise.
2507 ///
2508 /// The 21 base records that declare SSCN answer `true`; `busy` and `swait`
2509 /// carry SIMM/SIML/SIOL but neither SSCN nor OLDSIMM. Records with no
2510 /// simulation block answer `false` trivially.
2511 ///
2512 /// The default consults [`record_type_has_sscn`](crate::server::recgbl::simm::record_type_has_sscn),
2513 /// which is enumerated from the C dbd files, so no record has to restate it.
2514 fn uses_recgbl_simm_helpers(&self) -> bool {
2515 crate::server::recgbl::simm::record_type_has_sscn(self.record_type())
2516 }
2517
2518 /// The record's `readValue`/`writeValue` ABORTS when the SIML read fails —
2519 /// it returns before performing any I/O, so the cycle does no device write,
2520 /// no SIOL redirect, and raises no SIMM_ALARM.
2521 ///
2522 /// `busy` is the only record that does this (busyRecord.c:397-400):
2523 ///
2524 /// ```c
2525 /// status = dbGetLink(&prec->siml, DBR_USHORT, &prec->simm, 0, 0);
2526 /// if (status)
2527 /// return(status); /* <-- before write_busy AND before dbPutLink */
2528 /// ```
2529 ///
2530 /// The LINK_ALARM that `dbGetLink`'s `setLinkAlarm` already raised is the
2531 /// cycle's only simulation alarm.
2532 ///
2533 /// The other two families do NOT abort, for different reasons:
2534 ///
2535 /// - The 21 [`Self::uses_recgbl_simm_helpers`] records look like they do —
2536 /// `readValue` has `status = recGblGetSimm(...); if (status) return status;`
2537 /// (longinRecord.c:403-405) — but `recGblGetSimm` ends with an
2538 /// unconditional `return 0` (recGbl.c:456), so that branch is DEAD and the
2539 /// record always proceeds to its `switch (prec->simm)`.
2540 /// - `swait` reads SIML with a plain `dbGetLink` and simply never tests the
2541 /// status (swaitRecord.c:402), so it proceeds too.
2542 ///
2543 /// Default: `false`.
2544 fn aborts_on_failed_siml_read(&self) -> bool {
2545 false
2546 }
2547
2548 /// The record joined (`true`) or left (`false`) the `SCAN="I/O Intr"` list.
2549 ///
2550 /// C parity: `dbScan.c::scanAdd` calls the record's device support
2551 /// `get_ioint_info(0, precord, &iopvt)` when SCAN becomes `I/O Intr`, and
2552 /// `scanDelete` calls `get_ioint_info(1, ...)` when it leaves. Device
2553 /// support that registers driver interrupt callbacks does so there —
2554 /// `asynRecord.c:582-597` registers/cancels its per-interface interrupt
2555 /// users in exactly those two calls, and clears its `gotValue` cell on the
2556 /// register.
2557 ///
2558 /// The port's device supports own their subscription through
2559 /// [`crate::server::device_support::DeviceSupport::io_intr_receiver`],
2560 /// which the framework asks for once at `iocInit`. This hook is the
2561 /// *runtime* half: a record whose own state decides what to subscribe to
2562 /// (asynRecord's PORT/IFACE/UI32MASK/REASON) must (re)register when the
2563 /// operator moves SCAN in or out of `I/O Intr` after `iocInit`.
2564 ///
2565 /// Called from the single owner of the SCAN transition
2566 /// (`RecordInstance::put_common_field*`, and the `scanAdd`-failure demotion
2567 /// in `ioc_app`) only when I/O Intr membership actually changes, so it is
2568 /// never invoked twice for the same state. Default: ignore.
2569 fn set_io_intr_scan(&mut self, _active: bool) {}
2570
2571 /// The link writes a C `special()` performs *itself*, inside `dbPut`.
2572 ///
2573 /// `special()` takes the record alone — it has no database handle — so a
2574 /// record whose C `special()` calls `dbPutLink` cannot make that write from
2575 /// `special()`. It queues the write here instead, and the put owner
2576 /// (`field_io`'s `dbPut` paths) drains the queue immediately after
2577 /// `special(field, true)` returns and executes the actions BEFORE the put's
2578 /// `pp(TRUE)` process cycle. That is C's order: `dbPutField` → `dbPut` →
2579 /// `dbPutSpecial(paddr, 1)` — which runs the `dbPutLink` to completion,
2580 /// target processing included — → `dbProcess`.
2581 ///
2582 /// The scaler is the case this exists for: `scalerRecord.c:623-624` puts
2583 /// `CNT` to `COUTP` inside `special()`, so a record wired to `.COUTP` is
2584 /// processed while the scaler is still IDLE, before the count is armed. The
2585 /// port deferred that write to the head of the CNT-triggered process cycle,
2586 /// where the target saw an already-COUNTING scaler.
2587 ///
2588 /// This is neither the record's "should the link fire" state nor part of the
2589 /// process cycle's action list: a `special()` put and a `process()` put to
2590 /// the same link (scaler `COUTP` again, `:463`) are independent writes.
2591 ///
2592 /// The drain is unconditional — it runs even when `special()` returned an
2593 /// error — so a queued action can never survive the put that queued it and
2594 /// fire against a later, unrelated put.
2595 ///
2596 /// Default: none (a `special()` that writes no link).
2597 fn take_special_actions(&mut self) -> Vec<ProcessAction> {
2598 Vec::new()
2599 }
2600
2601 /// Other fields whose monitors must be posted because a put to
2602 /// `put_field` changed them as a side effect, without driving a full
2603 /// process cycle.
2604 ///
2605 /// Mirrors the explicit `db_post_events` calls a C `special()` makes:
2606 /// e.g. `compressRecord.c::reset` (invoked on a `SPC_RESET` write to
2607 /// `RES`) posts `NUSE` and `VAL` even though `RES` is not `pp(TRUE)`
2608 /// and so does not process. The framework posts a `VALUE|LOG` monitor
2609 /// for each returned field after the put. Default: none.
2610 fn monitor_side_effect_fields(&self, _put_field: &str) -> &'static [&'static str] {
2611 &[]
2612 }
2613
2614 /// True iff the C `special()` for a put to `put_field` runs the record's
2615 /// own `monitor()` — whose first act is `recGblResetAlarms(prec)`, which
2616 /// commits `nsta`/`nsev` into `stat`/`sevr` and clears the born-UDF alarm.
2617 ///
2618 /// `compress` is the case this exists for: `compressRecord.c::special`
2619 /// (:385-388) calls `reset(prec); monitor(prec);` on any SPC_RESET write
2620 /// (RES/ALG/PBUF/BALG/N), and `compressRecord.c::monitor` (:103) opens with
2621 /// `recGblResetAlarms`. A born-UDF compress record therefore transitions to
2622 /// NO_ALARM the moment one of those fields is put, with no process cycle.
2623 ///
2624 /// The framework already posts the `db_post_events` half of that `monitor()`
2625 /// through [`Record::monitor_side_effect_fields`]; this hook is the
2626 /// `recGblResetAlarms` half. When it returns true, the put owner
2627 /// (`field_io`'s `dbPut` paths) runs `rec_gbl_reset_alarms` and posts the
2628 /// resulting STAT/SEVR/AMSG/ACKS transition. Default: false (a `special()`
2629 /// that does not run the record's `monitor()`).
2630 fn special_commits_alarms(&self, _put_field: &str) -> bool {
2631 false
2632 }
2633
2634 /// True iff the C `special()` for a put to `put_field` runs code that
2635 /// writes `stat`/`sevr` DIRECTLY (not `nsta`/`nsev`) with NO `monitor()` /
2636 /// `recGblResetAlarms` after it — so the write STICKS and a later `caget`
2637 /// observes it, unlike the process path where `recGblResetAlarms` erases it.
2638 ///
2639 /// `histogram` is the case this exists for: a `.SGNL` caput is C's SPC_MOD
2640 /// `special()` → `add_count`, which writes `prec->stat = SOFT_ALARM` on
2641 /// inverted limits (histogramRecord.c:329-334) and returns with no monitor.
2642 /// When true, the put owner (`field_io`) runs
2643 /// [`Record::check_alarms`] after the store — the same direct write the
2644 /// process path makes, but here it persists because no process cycle
2645 /// follows. Default: false (no direct special-path alarm write).
2646 fn special_checks_alarms(&self, _put_field: &str) -> bool {
2647 false
2648 }
2649
2650 /// Downcast to concrete type for device support init injection.
2651 /// Override in record types that need device support to inject state (e.g., MotorRecord).
2652 fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
2653 None
2654 }
2655
2656 /// Whether processing this record should clear UDF.
2657 /// Override to return false for record types that don't produce a valid value every cycle.
2658 fn clears_udf(&self) -> bool {
2659 true
2660 }
2661
2662 /// Whether this record's C `process()` clears UDF regardless of the read's
2663 /// status — i.e. even when `readValue` failed.
2664 ///
2665 /// Most records gate the clear on the read: `if (status == 0) prec->udf =
2666 /// FALSE;` inside `readValue`'s SIOL branch (`longinRecord.c:418`), so a
2667 /// failed simulation read leaves the record undefined. The array records do
2668 /// NOT: their `process()` clears UDF itself, unconditionally, on the line
2669 /// after `readValue` returns — `prec->pact = TRUE; prec->udf = FALSE;`
2670 /// (`waveformRecord.c:143-144`, `aaiRecord.c:173-174`) and
2671 /// `if (!pact) { prec->udf = FALSE; ... }` (`aaoRecord.c:164-165`) — whatever
2672 /// status came back, including the `-1` of an illegal SIMM. (waveform's
2673 /// readValue also clears UDF on a good SIOL read, `:353`, but the
2674 /// process-level clear runs after it and dominates.)
2675 ///
2676 /// Consulted by the simulation tail, which otherwise gates the clear on the
2677 /// SIOL fetch status. Default `false` — the status-gated majority.
2678 fn clears_udf_unconditionally(&self) -> bool {
2679 false
2680 }
2681
2682 /// Whether this record type's `.dbd` declares an `INP` field at all.
2683 ///
2684 /// The port keeps INP on `CommonFields` for every record, which is right for
2685 /// the input records (`aiRecord.dbd.pod` … all declare it) but wrong for the
2686 /// ones whose C `.dbd` has no INP: C's dbd is the gate there, and
2687 /// `field(INP,...)` on such a record is a load error ("field not found"),
2688 /// leaving the record inert.
2689 ///
2690 /// `histogram` is the case this exists for: `histogramRecord.dbd.pod`
2691 /// declares NO INP — its DBF_INLINK is `SVL` (:212), read into SGNL by
2692 /// `devHistogramSoft.c` — so a histogram driven from INP is a database that
2693 /// no C IOC can load. Default `true`.
2694 ///
2695 /// This is the whole namespace gate, not just the loader's: in C the dbd
2696 /// also decides which `.FIELD` channels exist, so a histogram's INP is not
2697 /// resolvable at all (`dbgf HI.INP` → `PV 'HI.INP' not found`). Both
2698 /// [`RecordInstance::get_common_field`] and
2699 /// [`RecordInstance::put_common_field`] consult this, so the field cannot
2700 /// be readable on one route while refused on the other.
2701 ///
2702 /// [`RecordInstance::get_common_field`]: crate::server::record::RecordInstance::get_common_field
2703 /// [`RecordInstance::put_common_field`]: crate::server::record::RecordInstance::put_common_field
2704 fn declares_inp_link(&self) -> bool {
2705 true
2706 }
2707
2708 /// Process-time INP read when the INP link is CONSTANT (or unset) — the
2709 /// per-record exception to the load-once rule.
2710 ///
2711 /// Nearly every soft input device support skips a constant INP at process:
2712 /// `devWfSoft.c::read_wf` and `devAaiSoft.c::read_aai` open with
2713 /// `if (dbLinkIsConstant(pinp)) return 0;`, and the scalar ones call
2714 /// `dbGetLink`, whose `dbConstGetValue` (`dbConstLink.c:219-225`) writes
2715 /// nothing. The constant reaches such a record ONCE, at init, through
2716 /// `recGblInitConstantLink` / `dbLoadLinkArray`
2717 /// (`PvDatabase::rec_gbl_init_constant_inp`), so a client's caput to VAL is
2718 /// never clobbered by a re-delivered constant.
2719 ///
2720 /// `devSASoft.c::read_sa` (92-123) is the documented exception: it re-runs
2721 /// `dbLoadLinkArray` on a constant INP EVERY process, and on an EMPTY INP
2722 /// (`S_db_badField`) it sets `nRequest = prec->nord` and still subsets — so
2723 /// the record re-slices the client-written VAL by INDX each cycle. C draws
2724 /// that line at the device-support layer (`devSASoft` vs `devAaiSoft`), and
2725 /// so does this hook.
2726 ///
2727 /// Called by the framework on a soft-DTYP cycle whose INP is constant, with
2728 /// `value = Some(constant)` for a non-empty constant and `None` for an
2729 /// empty/unset INP. Returns whether the record consumed the input stage.
2730 /// Default `false` — the load-once rule.
2731 fn read_constant_inp(&mut self, _value: Option<EpicsValue>) -> bool {
2732 false
2733 }
2734
2735 /// Whether this record type raises UDF_ALARM at all.
2736 ///
2737 /// C has no framework-level UDF alarm: every record that reports one does
2738 /// it itself, with the guard at the top of its own `checkAlarms` —
2739 /// `if (prec->udf) { recGblSetSevr(prec, UDF_ALARM, prec->udfs); return; }`
2740 /// (`aiRecord.c:319-323`, `calcRecord.c:300-304`, …). A record whose
2741 /// support has no such guard NEVER reports UDF_ALARM, no matter what its
2742 /// `UDF` field says — `swaitRecord.c` is the case in point: its two only
2743 /// `udf` statements are `udf = FALSE` (`:411`, `:419`); it has no
2744 /// `checkAlarms` and never names UDF_ALARM.
2745 ///
2746 /// The framework raises UDF_ALARM centrally (`rec_gbl_check_udf`), so this
2747 /// hook is where a record type says C does not. Default `true` — the base
2748 /// analog/binary/string records all carry the guard.
2749 fn raises_udf_alarm(&self) -> bool {
2750 true
2751 }
2752
2753 /// Whether this record's C `checkAlarms` tests the UDF byte with
2754 /// `if (prec->udf == TRUE)` (EXACT-ONE) rather than `if (prec->udf)`
2755 /// (truthy). See [`crate::server::recgbl::udf_alarm_active`]: exact-one
2756 /// records (`boRecord.c:371`, `stringoutRecord.c:146`, `biRecord.c:225`,
2757 /// `busyRecord.c:337`) do NOT raise UDF_ALARM for a `udf` byte that is
2758 /// neither 0 nor 1.
2759 ///
2760 /// This only changes behavior for a record whose `udf` byte can actually
2761 /// hold such a value at `checkAlarms` time — one that does NOT re-derive
2762 /// `udf` every cycle ([`Record::clears_udf`] `== false`), reached via a
2763 /// direct `caput .UDF 255` (or `-1`, stored as `255` in the `DBF_UCHAR`
2764 /// field). For the re-deriving records (`clears_udf() == true`, e.g.
2765 /// `bi`/`busy`/the calc family) the byte is always 0/1 here, so exact-one
2766 /// and truthy agree and the flag is left at its default. Default `false`.
2767 fn udf_alarm_on_exact_one(&self) -> bool {
2768 false
2769 }
2770
2771 /// The alarm message C attaches when raising `UDF_ALARM`.
2772 ///
2773 /// Almost every base record raises UDF with plain
2774 /// `recGblSetSevr(prec, UDF_ALARM, prec->udfs)` — and `recGblSetSevr`
2775 /// forwards a NULL message to `recGblSetSevrMsg`, which sets
2776 /// `namsg[0] = '\0'` (`recGbl.c:249-251,258-261`). So the C amsg for a
2777 /// UDF record is EMPTY, and pvxs then serves the `"UDF"` condition
2778 /// string for `alarm.message` (`iocsource.cpp:230-236`). Default `""`
2779 /// models exactly that.
2780 ///
2781 /// The sole exception in base is `mbboDirectRecord.c:191`, which raises
2782 /// `recGblSetSevrMsg(prec, UDF_ALARM, prec->udfs, "UDFS")` — a bespoke
2783 /// literal. That record overrides this to `"UDFS"`.
2784 fn udf_alarm_message(&self) -> &str {
2785 ""
2786 }
2787
2788 /// Whether the record's current `VAL` is undefined (UDF must
2789 /// stay set).
2790 ///
2791 /// C parity: `aiRecord.c:285` / `calcRecord.c::checkAlarms` /
2792 /// `int64inRecord.c:144` clear `UDF` **only** when the computed /
2793 /// read value is valid — `if (status == 0)` and, for floating
2794 /// records, only when `VAL` is not NaN. The framework owns
2795 /// `common.udf`; it calls `clears_udf()` to decide whether this
2796 /// record type clears UDF at all, then this method to decide
2797 /// whether the *value produced this cycle* is actually defined.
2798 ///
2799 /// Default: a floating `VAL` that is NaN (e.g. a calc
2800 /// divide-by-zero, or a soft input whose link read failed and
2801 /// left VAL un-updated) is undefined; everything else is defined.
2802 /// A record whose `val()` yields `None` (no primary value) is
2803 /// also treated as undefined.
2804 fn value_is_undefined(&self) -> bool {
2805 match self.val() {
2806 Some(EpicsValue::Double(v)) => v.is_nan(),
2807 Some(EpicsValue::Float(v)) => v.is_nan(),
2808 Some(_) => false,
2809 None => true,
2810 }
2811 }
2812
2813 /// Per-record alarm hook — evaluate record-type-specific alarms
2814 /// (STATE / COS / analog limit / SOFT) and accumulate them into
2815 /// `nsta`/`nsev` via `recGblSetSevr`.
2816 ///
2817 /// The framework centralises the generic alarm machinery (UDF
2818 /// check, `recGblResetAlarms` transfer, MS/MSI/MSS link-alarm
2819 /// inheritance). The record-type-specific severity logic that C
2820 /// puts in each record's `checkAlarms()` belongs here so a record
2821 /// can raise its own alarms without the framework hardcoding a
2822 /// per-type `match` on `record_type()`.
2823 ///
2824 /// `common` is the record's [`CommonFields`]; implementations
2825 /// raise alarms with [`crate::server::recgbl::rec_gbl_set_sevr`]
2826 /// / [`crate::server::recgbl::rec_gbl_set_sevr_msg`].
2827 ///
2828 /// Default: no-op — records that have not yet migrated their
2829 /// `checkAlarms` logic here are still covered by the framework's
2830 /// legacy centralised `evaluate_alarms` match.
2831 fn check_alarms(&mut self, _common: &mut crate::server::record::CommonFields) {}
2832
2833 /// Return multi-input link field pairs: (link_field, value_field).
2834 /// Override in calc, calcout, sel, sub to return INPA..INPL → A..L mappings.
2835 fn multi_input_links(&self) -> &[(&'static str, &'static str)] {
2836 &[]
2837 }
2838
2839 /// The `(link_field, value_field)` pairs whose CONSTANT value this record's
2840 /// C `special()` RE-SEEDS on a runtime put to the link field —
2841 /// `recGblInitConstantLink(plink, DBF_DOUBLE, pvalue)` +
2842 /// `db_post_events(prec, pvalue, DBE_VALUE)` + `INAV = CON`
2843 /// (`calcoutRecord.c:367-378`, `sCalcoutRecord.c:512-517`,
2844 /// `aCalcoutRecord.c:534-540`).
2845 ///
2846 /// Without it a constant link is load-once dead state: `caput CO.INPB 7`
2847 /// stores the link text, the link layer then delivers nothing at process
2848 /// time (a constant link is not read), and `B` keeps its `.db`-load value
2849 /// forever.
2850 ///
2851 /// Declaring the pair is all a record does — the put path
2852 /// (`database::field_io::special_after_put`, the one `special(field, true)`
2853 /// owner) runs the load through
2854 /// [`crate::server::record::rec_gbl_init_constant_link`], the same owner the
2855 /// init seed uses, and posts the value field. A record cannot declare the
2856 /// pair and forget to implement the re-seed.
2857 ///
2858 /// Default: EMPTY — and that is the correct answer for every record whose C
2859 /// `special()` does NOT re-seed. `recGblInitConstantLink` appears inside a
2860 /// `special()` body in exactly FOUR record types across base and synApps
2861 /// calc — calcout, sCalcout, aCalcout, transform. Everywhere else (calc,
2862 /// sub, sel, aSub, seq, fanout, dfanout, swait, sseq, ao/bo/longout/…) it is
2863 /// called only from `init_record`, so those records seed once and never
2864 /// again, and they inherit this empty default.
2865 ///
2866 /// The overriding records list only the inputs C actually re-seeds:
2867 /// sCalcout/aCalcout guard with `fieldIndex <= INPL` (their string/array
2868 /// inputs are init-load only) and transform with
2869 /// `fieldIndex < transformRecordOUTA` (its OUT half is not an input).
2870 fn special_reseed_input_links(&self) -> &[(&'static str, &'static str)] {
2871 &[]
2872 }
2873
2874 /// The event mask of the `db_post_events` call in that record's `special()`
2875 /// re-seed arm — the C call sites do not agree:
2876 ///
2877 /// * calcout (`calcoutRecord.c:376`), sCalcout (`:516`), aCalcout (`:537`)
2878 /// post a literal `DBE_VALUE`.
2879 /// * transform (`transformRecord.c:718`) posts `DBE_VALUE | DBE_LOG`.
2880 ///
2881 /// Default: `DBE_VALUE`, the majority shape. Only consulted for the fields
2882 /// named by [`Self::special_reseed_input_links`].
2883 fn special_reseed_post_mask(&self) -> crate::server::recgbl::EventMask {
2884 crate::server::recgbl::EventMask::VALUE
2885 }
2886
2887 /// Every CONSTANT input link this record seeds ONCE, at `init_record` —
2888 /// the record's own `recGblInitConstantLink` / `dbLoadLinkArray` table,
2889 /// transcribed from its C.
2890 ///
2891 /// This is the OTHER half of the one rule the link layer enforces: a
2892 /// constant link delivers NOTHING at process time (`dbConstGetValue`,
2893 /// `dbConstLink.c:219-225`), so the ONLY way a `field(INPA,"5")` ever
2894 /// reaches `A` is this table, applied by the single init-seed owner
2895 /// [`crate::server::database::PvDatabase::rec_gbl_init_constant_links`].
2896 /// A record that fetches an input link but declares no seed for it (swait,
2897 /// whose C uses `recDynLink` and seeds nothing) simply never sees the
2898 /// constant — which is what its C does.
2899 ///
2900 /// Default: none.
2901 fn constant_init_links(&self) -> Vec<ConstantInitLink> {
2902 Vec::new()
2903 }
2904
2905 /// The link field this record loads into its long-string VAL at init through
2906 /// C's `dbLoadLinkLS` — `"DOL"` for `lso` (`lsoRecord.c:82`), `"INP"` for
2907 /// `lsi` (its soft device support, `devLsiSoft.c:24`). `loadLS` is a lset
2908 /// entry of its own, so this is a SEPARATE table from
2909 /// [`Self::constant_init_links`], not a variant of it; the same init-seed
2910 /// owner runs both.
2911 ///
2912 /// Default: none — a record with no long-string VAL has no `loadLS` seed.
2913 fn constant_ls_link(&self) -> Option<&'static str> {
2914 None
2915 }
2916
2917 /// Apply the [`Self::constant_ls_link`] load, and return the resulting LEN.
2918 /// The record clamps the text at its own `SIZV` and runs C's init tail
2919 /// (`if (prec->len) { strcpy(prec->oval, prec->val); prec->olen = prec->len; }`,
2920 /// lsoRecord.c:92-95 / lsiRecord.c:85-88); the owner turns a non-zero LEN
2921 /// into `udf = FALSE`.
2922 fn apply_ls_load(&mut self, _load: crate::server::record::LsLoad) -> u32 {
2923 0
2924 }
2925
2926 /// Whether this record's CONSTANT input links deliver their value on
2927 /// EVERY process cycle instead of only at init.
2928 ///
2929 /// `false` for every record that fetches with a plain `dbGetLink`. `printf`
2930 /// is the one exception in the whole database: its `GET_PRINT` macro
2931 /// (`printfRecord.c:49-52`) tests `dbLinkIsConstant` and re-runs
2932 /// `recGblInitConstantLink` on every `doPrintf`, so a constant INP0..9
2933 /// really is re-read each cycle.
2934 fn constant_inputs_deliver_at_process(&self) -> bool {
2935 false
2936 }
2937
2938 /// The subset of [`Self::multi_input_links`] the framework should
2939 /// actually fetch this cycle, given an optional externally-resolved
2940 /// selector index (sel's NVL→SELN value, or `None` when no NVL link
2941 /// drove it). Default `None` = fetch every input link.
2942 ///
2943 /// C `selRecord.c::fetch_values` (lines 421-431) fetches ONLY INP[SELN]
2944 /// in `Specified` mode and all inputs otherwise; sel returns
2945 /// `Some(vec![INP[SELN]])` so the non-selected inputs are never read and
2946 /// raise no monitors or link-alarm SEVR.
2947 fn select_input_links(
2948 &self,
2949 _selector: Option<u16>,
2950 ) -> Option<Vec<(&'static str, &'static str)>> {
2951 None
2952 }
2953
2954 /// A `SIMM != NO` cycle substitutes only this record's INPUT STAGE — the
2955 /// rest of its `process()` still runs.
2956 ///
2957 /// C's SIML/SIMM/SIOL group has three shapes, and this hook names the third:
2958 ///
2959 /// * `readValue` (ai, bi, longin, …): the simulated read replaces the device
2960 /// read, which is the whole of the record's input; the framework performs
2961 /// the SIOL read and completes the cycle itself.
2962 /// * `writeValue` (ao, bo, …): the simulated write replaces the device write
2963 /// at the END of the body, so the body runs and only the output is
2964 /// redirected to SIOL.
2965 /// * swait (`swaitRecord.c:401-421`): the simulated read replaces
2966 /// `fetch_values()` **and** `calcPerform()` and nothing else — VAL comes
2967 /// from SIOL through SVAL, and the OOPT switch, `execOutput`, the monitors
2968 /// and the forward link all still run from the record's own `process()`.
2969 ///
2970 /// A record that returns `true` gets, on a simulated cycle: SIMM resolved
2971 /// from SIML, SIOL read into SVAL, `VAL = SVAL` and `UDF = FALSE` when that
2972 /// read succeeded (C `:417-420` — a failed read changes neither), SIMM_ALARM
2973 /// raised at SIMS *before* the body so it maximizes against whatever the
2974 /// body raises (C `:421`), no input-link fetch, and
2975 /// [`Self::set_simulation_active`] pushed before `process()`.
2976 fn simulation_substitutes_input_stage(&self) -> bool {
2977 false
2978 }
2979
2980 /// Land the scalar a simulated cycle read from SIOL (through SVAL, where
2981 /// the record has one) — C `readValue`'s assignment plus whatever the
2982 /// record's `process()` body then does with it, under the same
2983 /// `status == 0` gate the framework applies before calling this.
2984 ///
2985 /// The base records assign the value straight to VAL — `longinRecord.c:417`
2986 /// `prec->val = prec->sval;` — which is the default (`set_val`).
2987 ///
2988 /// `histogram` does NOT: `histogramRecord.c:385-386` lands it in SGNL
2989 /// (`prec->sgnl = prec->sval;`), and `process()` (`:218-219`,
2990 /// `if (status == 0) add_count(prec);`) bins that signal into the VAL
2991 /// bin-count array. Its VAL is the array, so a `set_val` of the scalar
2992 /// no-ops and the simulated record is frozen. It overrides.
2993 fn land_simulated_value(&mut self, value: EpicsValue) -> CaResult<()> {
2994 self.set_val(value)
2995 }
2996
2997 /// Whether the record's C `switch (prec->simm)` carries a `default:` arm
2998 /// that REFUSES a SIMM value outside its own menu:
2999 ///
3000 /// ```c
3001 /// default:
3002 /// recGblSetSevr(prec, SOFT_ALARM, INVALID_ALARM);
3003 /// status = -1;
3004 /// ```
3005 ///
3006 /// Every record in the framework has it — all 21 base records
3007 /// (`longinRecord.c:436-438` and its twins; `aaiRecord.c:381-384` writes the
3008 /// same arm as an `else if (prec->simm != menuYesNoNO)`) and `busy`
3009 /// (`busyRecord.c:409-413`, the `else` of its YES test).
3010 ///
3011 /// `swait` is the sole exception: `swaitRecord.c:407-421` is a plain
3012 /// `if (pwait->simm == menuYesNoNO) { … } else { /* SIMULATION MODE */ … }`,
3013 /// so every non-NO value — legal or not — simulates. It overrides to
3014 /// `false`.
3015 ///
3016 /// Consumed by [`resolve_sim_mode`](crate::server::recgbl::simm::resolve_sim_mode),
3017 /// the single owner of the SIMM dispatch.
3018 fn rejects_illegal_sim_mode(&self) -> bool {
3019 true
3020 }
3021
3022 /// This cycle's simulation state, pushed by the framework before
3023 /// `process()` — the twin of [`Self::set_fetch_gate_failed`], and only for a
3024 /// record that declares [`Self::simulation_substitutes_input_stage`].
3025 ///
3026 /// It is pushed on EVERY cycle of such a record (`false` included), so the
3027 /// flag cannot survive the cycle it belongs to. The record uses it to skip
3028 /// exactly what C's simulation branch skips — for swait, `fetch_values()`
3029 /// (through [`Self::select_input_links`]) and `calcPerform()`.
3030 fn set_simulation_active(&mut self, _active: bool) {}
3031
3032 /// How C's `fetch_values()` for this record type reacts to a link read
3033 /// that fails. Drives the framework's [`Self::multi_input_links`] fetch
3034 /// loop; see [`InputFetchPolicy`]. Default: [`InputFetchPolicy::ReadAll`].
3035 ///
3036 /// It governs the [`Self::multi_input_links`] loop ONLY.
3037 /// [`Self::string_input_links`] is C's *second*, separately-gated fetch
3038 /// loop and never participates in this policy.
3039 fn input_fetch_policy(&self) -> InputFetchPolicy {
3040 InputFetchPolicy::ReadAll
3041 }
3042
3043 /// String-valued input links: `(link_field, value_field)` pairs read as
3044 /// DBR_STRING, C `sCalcoutRecord.c::fetch_values` (890-941) — the SECOND
3045 /// loop of that function, over `INAA`..`INLL` → `AA`..`LL`:
3046 ///
3047 /// ```c
3048 /// for (i=0, plink=&pcalc->inaa, psvalue=pcalc->strs; i<STRING_MAX_FIELDS; ...) {
3049 /// ...
3050 /// if (((field_type==DBR_CHAR) || (field_type==DBR_UCHAR)) && nelm>1) {
3051 /// status = dbGetLink(plink, field_type, tmpstr, 0, &nelm);
3052 /// epicsStrSnPrintEscaped(*psvalue, STRING_SIZE-1, tmpstr, strlen(tmpstr));
3053 /// } else {
3054 /// status = dbGetLink(plink, DBR_STRING, *psvalue, 0, 0);
3055 /// }
3056 /// if (!RTN_SUCCESS(status))
3057 /// epicsSnprintf(*psvalue, STRING_SIZE-1, "%s:fetch(%s) failed", pcalc->name, sFldnames[i]);
3058 /// }
3059 /// return(0);
3060 /// ```
3061 ///
3062 /// Three properties this loop does NOT share with [`Self::multi_input_links`],
3063 /// which is why it is a separate list rather than more entries in that one:
3064 ///
3065 /// 1. **Ungated.** It ends in `return(0)` — a failing string link never
3066 /// makes `fetch_values` non-zero, so it cannot suppress the record body.
3067 /// The record's single [`Self::input_fetch_policy`] describes the numeric
3068 /// loop (`AbortOnFirstFailure` for scalcout) and cannot also describe this
3069 /// one.
3070 /// 2. **A failed read still writes the field** — with the diagnostic text
3071 /// `"<record>:fetch(<FIELD>) failed"`, not with the previous value.
3072 /// 3. **A `DBF_CHAR`/`DBF_UCHAR` array source is read as text**, C-escaped
3073 /// (`epicsStrSnPrintEscaped`), which is how a >40-char string reaches a
3074 /// string calc; every other source type converts as DBR_STRING.
3075 ///
3076 /// The value is delivered through [`Self::put_field_internal`], so the
3077 /// target field's declared `DbFieldType` performs the final coercion.
3078 fn string_input_links(&self) -> &'static [(&'static str, &'static str)] {
3079 &[]
3080 }
3081
3082 /// Input links this record reads at OUTPUT time instead of during the
3083 /// input-fetch phase: `(link_name_field, value_field)` pairs. The framework
3084 /// reads each configured link immediately before the OUT write, and ONLY on
3085 /// a cycle where the output actually fires ([`Self::should_output`] and no
3086 /// IVOA veto), then writes the value into `value_field` via
3087 /// [`Self::put_field`]; a failed read leaves the field alone.
3088 ///
3089 /// C `swaitRecord.c::execOutput` (763-772) does exactly this for `DOL`:
3090 ///
3091 /// ```c
3092 /// if (pwait->dopt) { /* DOPT = "Use DOL" */
3093 /// if (!pwait->dolv) { /* DOL PV connected */
3094 /// oldDold = pwait->dold;
3095 /// recDynLinkGet(&pcbst->caLinkStruct[DOL_INDEX], &(pwait->dold), ...);
3096 /// if (pwait->dold != oldDold)
3097 /// db_post_events(pwait, &pcbst->pwait->dold, DBE_VALUE);
3098 /// }
3099 /// outValue = pwait->dold;
3100 /// }
3101 /// ```
3102 ///
3103 /// The timing is the point: the value written out is the one the link holds
3104 /// at output time (ODLY delay-end included), and a cycle whose output does
3105 /// not fire never refreshes — or posts — the field. Fetching such a link in
3106 /// the normal input phase would do both. Default: none.
3107 fn output_time_input_links(&self) -> &'static [(&'static str, &'static str)] {
3108 &[]
3109 }
3110
3111 /// The value the framework writes to the OUT link. The single owner of
3112 /// "what goes out", shared by the soft-OUT write, the async-completion
3113 /// write and the simulated SIOL redirect.
3114 ///
3115 /// The default is the C staging convention: the record computed the output
3116 /// into `OVAL` during `process()` (`calcout`/`ao`/`bo`/...), falling back to
3117 /// `VAL` for records that have no `OVAL`. Override when the record's C
3118 /// composes the output value at *output* time rather than staging it — e.g.
3119 /// swait, whose `execOutput` (`swaitRecord.c:763-772`) picks between `VAL`
3120 /// and the just-fetched `DOLD` and whose `OVAL` field is C's "Old Value"
3121 /// (the previous VAL, used only by the OOPT test), not an output stage.
3122 fn output_link_value(&self) -> Option<EpicsValue> {
3123 self.get_field("OVAL").or_else(|| self.val())
3124 }
3125
3126 /// Return multi-output link field pairs: (link_field, value_field).
3127 /// Override in transform to return OUTA..OUTP → A..P mappings.
3128 fn multi_output_links(&self) -> &[(&'static str, &'static str)] {
3129 &[]
3130 }
3131
3132 /// The record's C soft device support write-buffer switch for a
3133 /// multi-output pair: given the pair's staged value (the value field
3134 /// named by [`Self::multi_output_links`]) and the RESOLVED TARGET
3135 /// metadata, return the buffer C would actually put.
3136 ///
3137 /// C's soft device supports do not blindly write one field: they read
3138 /// the target's DBF type and element count and pick a buffer from them —
3139 /// `devaCalcoutSoft.c::write_acalcout` (75-87) picks
3140 /// `nelm == 1 ? &scalar : array`, `devsCalcoutSoft.c::write_scalcout`
3141 /// (66-144) routes a string-class target to the computed string, a
3142 /// `CHAR`/`UCHAR` array to the string's bytes, and everything else to
3143 /// the numeric. The framework resolves the target
3144 /// ([`PvDatabase::resolve_out_target`](crate::server::database::PvDatabase))
3145 /// and hands it here; the record reproduces its device support's switch.
3146 ///
3147 /// Default: write the staged value unchanged (no device-support switch).
3148 fn multi_output_buffer(
3149 &self,
3150 link_field: &str,
3151 staged: EpicsValue,
3152 target: &OutTarget,
3153 ) -> EpicsValue {
3154 let _ = (link_field, target);
3155 staged
3156 }
3157
3158 /// The buffer to put on an OUT link the record drives itself, chosen from
3159 /// the RESOLVED TARGET — the no-staged-value sibling of
3160 /// [`Self::multi_output_buffer`].
3161 ///
3162 /// C `sseqRecord.c::processCallback` (706-793) is the case: the value a
3163 /// step forwards is not one field but a *switch on the destination*
3164 /// (`dbGetLinkDBFtype(&lnk)` / `dbGetNelements(&lnk)`), taken at fire
3165 /// time — the string view `s` for a string-class target, the double view
3166 /// `dov` for a numeric one, `s`'s bytes for a `CHAR`/`UCHAR` array, and
3167 /// **no put at all** for a target whose type does not resolve (C's
3168 /// `default: break`). `None` is that no-put: the caller issues no write.
3169 ///
3170 /// The record calls this ITSELF, on the target
3171 /// [`ProcessAction::ResolveOutTarget`] handed it before `process()` — one
3172 /// decision, made before anything is issued, because the same switch
3173 /// decides more than the buffer (sseq: whether a `WAITn` put-callback goes
3174 /// out, and hence whether `WTGn` is raised). See
3175 /// [`Self::set_resolved_out_target`].
3176 ///
3177 /// Default: `None`. Only a record that resolves its own OUT target reaches
3178 /// this, and it must override.
3179 fn typed_output_buffer(&self, link_field: &str, target: &OutTarget) -> Option<EpicsValue> {
3180 let _ = (link_field, target);
3181 None
3182 }
3183
3184 /// Receive the RESOLVED target of an OUT link the record asked to have
3185 /// resolved before this cycle's `process()`
3186 /// ([`ProcessAction::ResolveOutTarget`]).
3187 ///
3188 /// C resolves an OUT link's DBF class OUTSIDE the put — `checkLinks` caches
3189 /// it in the record (`sseqRecord.c:202-250`) — so `processCallback` can make
3190 /// ONE decision from it: which view goes on the wire, AND whether a
3191 /// put-callback is issued (hence whether `waiting` is raised). Its
3192 /// `default:` arm (`:790`) does neither. A record that learns the class only
3193 /// from inside the framework's put path cannot keep those two halves
3194 /// together: it has to raise `waiting` first and find out afterwards that no
3195 /// put was made. This hook is that cached class — the record decides, then
3196 /// acts.
3197 ///
3198 /// Default: no-op. Only a record that emits the action reaches this.
3199 fn set_resolved_out_target(&mut self, link_field: &str, target: OutTarget) {
3200 let _ = (link_field, target);
3201 }
3202
3203 /// The `dbrType` this record's [`ProcessAction::ReadDbLink`] on
3204 /// `link_field` asks the SOURCE for — the READ twin of
3205 /// [`Self::typed_output_buffer`], and C's `dbGetLink` second argument.
3206 ///
3207 /// `source` is the far end of the input link as C's
3208 /// `dbGetLinkDBFtype`/`dbGetNelements` report it (the same lset accessors
3209 /// the OUT side uses — sseq asks them of `dol` at `sseqRecord.c:641` and of
3210 /// `lnk` at `:709`), resolved by the framework
3211 /// ([`PvDatabase::resolve_out_target`](crate::server::database::PvDatabase)).
3212 ///
3213 /// `None` means C's `default: break` — **no read at all**, the arm a source
3214 /// class the record's switch does not name falls to (an unresolvable /
3215 /// constant / disconnected source, and sseq's un-cased `DBF_INT64`). The
3216 /// link is left untouched and no LINK alarm is raised, exactly as C's
3217 /// skipped `dbGetLink` call leaves `status` alone.
3218 ///
3219 /// Default: [`LinkReadAs::Native`] — the source's native value, coerced at
3220 /// the target field's own put boundary.
3221 fn input_link_read_as(&self, link_field: &str, source: &OutTarget) -> Option<LinkReadAs> {
3222 let _ = (link_field, source);
3223 Some(LinkReadAs::Native)
3224 }
3225
3226 /// Return the name of the output event (`OEVT`) to post this cycle, or
3227 /// `None`. The event-subsystem twin of the OUT write: a downstream
3228 /// `SCAN="Event"` / `EVNT="<name>"` record is woken each time the record
3229 /// drives output. Mirrors C `calcout`/`sCalcout`/`aCalcout` `execOutput`,
3230 /// which calls `postEvent(epvt)` / `post_event(oevt)` immediately after
3231 /// `writeValue` in every OUT-driving branch.
3232 ///
3233 /// The override MUST fold in the record's own output-fire decision
3234 /// (`should_output()` for `calcout`; the cached OOPT/calc-fail/ODLY
3235 /// decision for `sCalcout`/`aCalcout`) and return `None` when output did
3236 /// not fire or when `OEVT` is unset. The framework adds the only gate the
3237 /// record cannot see — the IVOA `Don't_drive` veto on an INVALID cycle —
3238 /// so the post fires on exactly the cycles the OUT write does. Numeric
3239 /// `OEVT` (DBF_USHORT) stringifies to match the `EVNT` ingest; a string
3240 /// `OEVT` (DBF_STRING) is the event name verbatim.
3241 fn output_event(&self) -> Option<String> {
3242 None
3243 }
3244
3245 /// Internal field write that bypasses read-only checks.
3246 /// Used by the framework to write values from ReadDbLink actions
3247 /// into fields that are normally read-only (e.g., epid.CVAL).
3248 /// Default implementation delegates to put_field().
3249 ///
3250 /// On the `ReadDbLink` path this is also where a pvalink NTEnum
3251 /// carrier ([`EpicsValue::EnumWithChoices`]) is resolved. The
3252 /// dbrType-blind link resolver produces it for an NTEnum source;
3253 /// pvxs `pvaGetValue` (`pvalink_lset.cpp:330-360`) picks
3254 /// label-vs-index by the TARGET field's dbrType — only a DBR_STRING
3255 /// target gets the `choices[index]` label, every other type takes
3256 /// the numeric index. Route it through [`EpicsValue::convert_to`]
3257 /// (the single value-coercion owner) against the target field's
3258 /// `db_field_type`, so the transient carrier is consumed before any
3259 /// record `put_field` / storage / wire path can see it. The
3260 /// single-INP→VAL apply path reaches the same `convert_to` via
3261 /// `set_val`'s `TypeMismatch` auto-coerce.
3262 fn put_field_internal(&mut self, name: &str, value: EpicsValue) -> CaResult<()> {
3263 put_field_internal_default(self, name, value)
3264 }
3265
3266 /// Return pre-process actions (ReadDbLink) that the framework should
3267 /// execute BEFORE calling process(). This is called once per cycle.
3268 /// Default returns empty. Override in records that need link reads
3269 /// to be available during process().
3270 fn pre_process_actions(&mut self) -> Vec<ProcessAction> {
3271 Vec::new()
3272 }
3273
3274 /// Return actions the framework must execute BEFORE the input-link
3275 /// (`multi_input_links`, INP -> value-field) fetch for this cycle.
3276 ///
3277 /// This is strictly earlier than [`Self::pre_process_actions`]: the
3278 /// framework resolves input links *before* it calls
3279 /// `pre_process_actions`, so an action that must affect what an
3280 /// input link reads cannot be expressed there.
3281 ///
3282 /// The motivating case is the epid record's `devEpidSoftCallback`
3283 /// DB-type TRIG link: C `devEpidSoftCallback.c:120-132` writes the
3284 /// readback-trigger link with `dbPutLink` — which synchronously
3285 /// processes the triggered source chain — and only *then*
3286 /// (`devEpidSoftCallback.c:151`) does `dbGetLink(&pepid->inp, ...)`
3287 /// read `CVAL`. The trigger write therefore has to land before the
3288 /// `INP -> CVAL` fetch, in the same process pass.
3289 ///
3290 /// Called once per cycle, while a record write lock is held; the
3291 /// framework executes the returned actions (currently `WriteDbLink`
3292 /// and `ReadDbLink`) and then performs the input-link fetch.
3293 /// Default returns empty.
3294 fn pre_input_link_actions(&mut self) -> Vec<ProcessAction> {
3295 Vec::new()
3296 }
3297
3298 /// Called by the framework immediately before `process()` to push a
3299 /// read-only snapshot of framework-owned [`CommonFields`] state
3300 /// ([`ProcessContext`]) that the record's `process()` needs to see.
3301 ///
3302 /// The framework owns `RecordInstance.common`; a record `process()`
3303 /// only gets `&mut self`. C records read `dbCommon` directly — e.g.
3304 /// `epidRecord.c:195` checks `pepid->udf` at the top of `process()`,
3305 /// `timestampRecord.c:90` branches on `ptimestamp->tse`. This hook
3306 /// is the controlled equivalent: a record that needs `udf`/`phas`/
3307 /// `tse`/`tsel` during `process()` overrides this to stash the
3308 /// values into its own fields.
3309 ///
3310 /// Additive, framework-set-hook pattern (same shape as
3311 /// [`Record::set_device_did_compute`]). Default: ignore — most
3312 /// records never need common state during `process()`.
3313 fn set_process_context(&mut self, _ctx: &ProcessContext) {}
3314
3315 /// Called once by the framework when the record is registered
3316 /// (`add_record`), delivering the record its own canonical name plus a
3317 /// cycle-free [`crate::server::database::AsyncDbHandle`] for driving
3318 /// async-side updates from OUTSIDE a `process()` cycle.
3319 ///
3320 /// The handle wraps a `Weak` reference to the database, so a record
3321 /// that stashes it creates no ownership cycle (the database owns the
3322 /// record; a stored strong handle would leak it). It is the controlled
3323 /// equivalent of C device support capturing `precord` plus the
3324 /// dbCommon scan lock for an out-of-band `db_post_events` /
3325 /// `callbackRequest`: e.g. the asyn TRACE/exception callback posts
3326 /// trace-flag fields immediately from the driver thread, and AQR
3327 /// cancels a queued I/O re-entry — neither happens inside `process()`.
3328 ///
3329 /// The in-band counterpart for a record's *own* process cycle is the
3330 /// completion-driven [`ProcessAction`] family
3331 /// ([`ProcessAction::WriteDbLinkNotify`],
3332 /// [`ProcessAction::CancelReprocess`],
3333 /// [`ProcessAction::ReprocessAfter`]); this hook exists for the
3334 /// out-of-band path that has no `process()` return to ride on.
3335 ///
3336 /// Additive, framework-set-hook pattern (same shape as
3337 /// [`Self::set_process_context`]). Default: ignore — most records do
3338 /// no out-of-band async posting.
3339 fn set_async_context(&mut self, _name: String, _db: crate::server::database::AsyncDbHandle) {}
3340
3341 /// Framework init hook: called once at record load *after* the common
3342 /// link fields (`INP`/`OUT`/`FLNK`/...) have been resolved and the
3343 /// `init_record` passes have run, with the record's resolved
3344 /// [`CommonFields`](crate::server::record::CommonFields).
3345 ///
3346 /// This is the seam for records that classify their links into status
3347 /// diagnostics at init the way C `init_record` does (e.g. calcout's
3348 /// `INAV..INUV`/`OUTV` `menu(calcoutINAV)` checkLinks loop): a record's
3349 /// *common* link strings (`OUT` is a common field, not a record field)
3350 /// are invisible to [`Self::set_async_context`] — which runs at
3351 /// `add_record`, *before* the common fields are applied — and to
3352 /// `init_record`, which carries no `CommonFields`. The record captures
3353 /// whichever common links it needs here so a passive, never-processed
3354 /// record already exposes its link status. Records whose links are all
3355 /// record-owned (e.g. sseq DOLn/LNKn) do not need this hook.
3356 ///
3357 /// Additive, framework-set-hook pattern. Default: ignore.
3358 fn init_links(&mut self, _common: &crate::server::record::CommonFields) {}
3359
3360 /// Called by the framework before process() to indicate whether device
3361 /// support's read() already performed the record's compute step.
3362 /// Override in records that have a built-in compute (e.g., epid PID)
3363 /// to skip it when device support already ran it.
3364 /// Default: ignore.
3365 fn set_device_did_compute(&mut self, _did_compute: bool) {}
3366
3367 /// Whether this record has a raw-to-engineering (`RVAL → VAL`)
3368 /// `convert()` step that must be skipped on a `Soft Channel` input.
3369 ///
3370 /// C `devAiSoft.c:65` `read_ai` (and the other soft-channel input
3371 /// `read_xxx`) always returns 2 ("don't convert"), so `aiRecord.c`'s
3372 /// `if (status==0) convert(prec)` is bypassed for a `Soft Channel`
3373 /// input record. The framework expresses this by calling
3374 /// [`Record::set_device_did_compute(true)`] on the record before
3375 /// `process()`.
3376 ///
3377 /// This hook exists so the framework only suppresses `convert()` —
3378 /// NOT a record's entire built-in compute. Records like `epid` also
3379 /// override `set_device_did_compute` but interpret it as "skip the
3380 /// whole compute step" (the PID loop); those records have no
3381 /// `RVAL → VAL` convert and MUST keep the default `false` so a
3382 /// `Soft Channel` `epid` still runs `do_pid()` in `process()`.
3383 ///
3384 /// Default `false`: a record is only opted into the soft-channel
3385 /// convert-skip when it explicitly returns `true`.
3386 fn soft_channel_skips_convert(&self) -> bool {
3387 false
3388 }
3389
3390 /// Whether this output record's forward `VAL → RVAL` `convert()` must be
3391 /// SKIPPED on a process cycle where VAL is still undefined (`UDF != 0`) and
3392 /// no value source ran.
3393 ///
3394 /// C's output records take an early `goto CONTINUE` before `convert()` when
3395 /// the record is undefined and no value was sourced this cycle:
3396 ///
3397 /// ```c
3398 /// /* mbboRecord.c:199-217 (and ao/bo/mbboDirect alike) */
3399 /// if (!pact) {
3400 /// if (!dbLinkIsConstant(&prec->dol) && omsl == closed_loop) {
3401 /// ... prec->val = <DOL>; /* value sourced -> udf cleared */
3402 /// }
3403 /// else if (prec->udf) {
3404 /// recGblSetSevr(prec, UDF_ALARM, prec->udfs);
3405 /// goto CONTINUE; /* skip udf=FALSE AND convert() */
3406 /// }
3407 /// prec->udf = FALSE;
3408 /// convert(prec); /* VAL -> RVAL */
3409 /// }
3410 /// ```
3411 ///
3412 /// So a `caput REC.RVAL 1` on a bare `record(mbbo,"M"){}` (UDF still 1, no
3413 /// VAL put, no closed-loop DOL) leaves RVAL at the client value: `convert`
3414 /// never runs to recompute `RVAL = VAL(=0)`. Verified on the compiled
3415 /// softIoc — bare RVAL put reads back the put value; after a VAL put clears
3416 /// UDF, the next RVAL put IS overwritten by `convert`.
3417 ///
3418 /// The framework consults this before `process()`: an opted-in output record
3419 /// with `UDF != 0` and no value source this cycle is told
3420 /// [`Self::set_device_did_compute(true)`] so its `process()` skips the
3421 /// forward convert. A VAL put (UDF cleared in `field_io`) or a closed-loop
3422 /// DOL fetch (UDF cleared at the DOL-apply site) leaves `UDF == 0`, so the
3423 /// convert runs exactly as C's fall-through does.
3424 ///
3425 /// Default `false`. The rest of C's output family (ao/bo/mbboDirect) shares
3426 /// the same `goto CONTINUE`; they are a separate change and stay opted out
3427 /// here.
3428 fn skips_forward_convert_when_undefined(&self) -> bool {
3429 false
3430 }
3431
3432 /// C `mbboRecord.c:210-221` / `mbboDirectRecord.c:190-202` — the same
3433 /// `else if (prec->udf) goto CONTINUE` that skips the forward `convert()`
3434 /// ALSO jumps past the pre-output `recGblGetTimeStampSimm` call. So a soft
3435 /// (synchronous) mbbo/mbboDirect that is still UNDEFINED never stamps TIME
3436 /// on the first-pass output stage: the only other stamp after `CONTINUE:`
3437 /// is guarded by `if (pact)` (mbboRecord.c:256-258), which fires on
3438 /// ASYNCHRONOUS completion re-entry only. A sync UDF record therefore keeps
3439 /// TIME at the EPICS epoch ("never processed") until a VAL put clears UDF.
3440 ///
3441 /// Contrast ao/bo/longout/int64out/stringout: their `if (!pact)` block
3442 /// calls `recGblGetTimeStampSimm` UNCONDITIONALLY (aoRecord.c:192,
3443 /// boRecord.c:215), so they stamp even while undefined and do NOT opt in.
3444 ///
3445 /// The framework consults this at the synchronous output-stage stamp
3446 /// (`processing.rs` `process_record_with_links_inner`, the pre-output
3447 /// `apply_timestamp`): an opted-in record with `UDF != 0` skips that stamp,
3448 /// mirroring C's `goto CONTINUE`. The async-completion stamp
3449 /// (`complete_async_record_inner`) stays unconditional, matching C's
3450 /// `if (pact)` re-stamp on async devices.
3451 ///
3452 /// This is a SEPARATE hook from [`Self::skips_forward_convert_when_undefined`]:
3453 /// mbboDirect's VAL is bit-derived and does NOT opt into the convert-skip,
3454 /// yet it DOES share this timestamp-skip. Do not conflate the two.
3455 ///
3456 /// Default `false`. Only mbbo/mbboDirect carry the `goto CONTINUE`
3457 /// timestamp-skip in C; every other record stays opted out.
3458 fn skips_timestamp_when_undefined(&self) -> bool {
3459 false
3460 }
3461}
3462
3463/// The body of [`Record::put_field_internal`] — the framework's internal write
3464/// path — as a free function, so a record that needs to observe an internal
3465/// write can WRAP it instead of re-implementing it.
3466///
3467/// A record overriding `put_field_internal` and ending in `self.put_field(..)`
3468/// silently drops the coercion below for every field it does not special-case.
3469/// Calling this instead keeps the one owner of that coercion.
3470///
3471/// Input-link / internal delivery coerces the source to the target field's
3472/// stored type before `put_field`, mirroring C `dbGetLink(DBF_<target>)`: the
3473/// link layer converts any numeric source to the requested type, so a record's
3474/// typed `put_field` arm never sees a mismatched type. This covers every
3475/// `ReadDbLink` target by construction (e.g. a `compress` INP from a `DBF_LONG`
3476/// record delivers a `Long`/`LongArray` that must become `Double`/`DoubleArray`
3477/// for the Double-only VAL arm, which otherwise drops it and never advances the
3478/// buffer). An `EnumWithChoices` carrier is always collapsed to a bare index by
3479/// `convert_to`, even when the target is already `Enum`.
3480pub fn put_field_internal_default<R: Record + ?Sized>(
3481 record: &mut R,
3482 name: &str,
3483 value: EpicsValue,
3484) -> CaResult<()> {
3485 // Coerce to the type the record STORES, not the type it SERVES. The two are
3486 // the same for most fields, but a `menu()` field is declared `DBF_MENU` and
3487 // served as `DBR_ENUM` with its choices (`promote_menu_value`) while the
3488 // record stores the bare choice index as a `Short` — and `put_field`'s arms
3489 // match on what is stored. Coercing to the served type would hand every
3490 // `put_field` an `Enum` its `Short` arm cannot match. This is the inverse of
3491 // `promote_menu_value`, and asking the record what it holds keeps the rule
3492 // uniform instead of special-casing menus here.
3493 //
3494 // The `.dbd` type is the fallback for a field the record cannot currently
3495 // produce a value for (an uninitialised array, a port-internal field).
3496 let target_type = record
3497 .get_field(name)
3498 .map(|v| v.db_field_type())
3499 .or_else(|| crate::server::record::record_instance::declared_field_type_of(record, name));
3500 // An array source into a SCALAR destination delivers element 0. C's link
3501 // layer asks for exactly one element (`dbGetLink(..., nRequest = NULL)`), so
3502 // `dbGet` converts the field at offset 0 and the record sees a scalar — a
3503 // waveform INP into an `ai.VAL` lands `wf[0]`, it is not dropped. Without the
3504 // reduction the array reached the record's typed `put_field` arm, which
3505 // rejected it and left the field at its stale value. Same clamp as
3506 // `field_io::dbput_request` (C `dbPut` `nRequest -> no_elements`), through the
3507 // same primitive; a `CharArray` into a `DBF_STRING` field is likewise exempt —
3508 // that shape is the dbChannel `$` char view of a string field, decoded by
3509 // `convert_to`.
3510 let dest_is_array = record.get_field(name).is_some_and(|v| v.is_array());
3511 let is_char_string_view =
3512 matches!(value, EpicsValue::CharArray(_)) && target_type == Some(DbFieldType::String);
3513 let value = if !dest_is_array && value.is_array() && !is_char_string_view {
3514 value.first_element().unwrap_or(value)
3515 } else {
3516 value
3517 };
3518 let is_enum_carrier = matches!(value, EpicsValue::EnumWithChoices { .. });
3519 let value = match target_type {
3520 // A String target routes through the converter even on a type match: C's
3521 // `putStringString` truncates to `field_size - 1` (see `coerce_put_value`).
3522 Some(target)
3523 if is_enum_carrier
3524 || ((value.db_field_type() != target || target == DbFieldType::String)
3525 && !value.is_empty_array()) =>
3526 {
3527 coerce_put_value(record, name, target, value)?
3528 }
3529 // Carrier with no known target field: collapse to a bare index (the prior
3530 // fallback) rather than letting it reach storage.
3531 None if is_enum_carrier => value.convert_to(DbFieldType::Long),
3532 _ => value,
3533 };
3534 record.put_field(name, value)
3535}
3536
3537/// Coerce a written value to a field's stored type — the single owner of C
3538/// `dbConvert.c`'s `dbFastPutConvertRoutine[dbrType][field_type]` table, shared
3539/// by the two paths a value can enter a record's field through: a client
3540/// `dbPut` ([`crate::server::database::field_io`]) and an internal link /
3541/// device-support delivery ([`put_field_internal_default`]).
3542///
3543/// Every `DBR_STRING` row of C's put table is a converter that can FAIL, and
3544/// none of them is `EpicsValue::convert_to`:
3545///
3546/// * `DBF_MENU` → `putStringMenu` — exact label, else an index below `nChoice`
3547/// ([`resolve_menu_field_string`]).
3548/// * `DBF_ENUM` → `putStringEnum` — the record's state strings, else an index
3549/// below `no_str` ([`resolve_enum_state_string`]).
3550/// * `DBF_STRING` → `putStringString` — a byte copy, the one row that cannot
3551/// fail.
3552/// * every numeric width → `putStringChar` … `putStringDouble`, i.e.
3553/// `epicsParse*`, which refuses the put on overflow and on unparseable text
3554/// ([`c_parse::put_string`]).
3555///
3556/// `convert_to` cannot express any of the failures — it is field-blind and
3557/// total, mapping unparseable text to `0` and an out-of-range number to the
3558/// nearest representable one. That is how `caput MY:VALVE Open` became a silent
3559/// no-op that drove `VAL` to state 0, and how `caput REC.PREC 32768` — which the
3560/// compiled softIoc REFUSES — stored 32767.
3561///
3562/// An ARRAY destination keeps the coercion path. C reaches it through the same
3563/// `putString*` routine (`nRequest` elements, parsed one at a time), but this
3564/// port's array records carry their own element-type conversion, so the row is
3565/// theirs to own; routing a string here would break the string→`DBF_CHAR[]`
3566/// carry that `convert_to` provides for them.
3567pub fn coerce_put_value<R: Record + ?Sized>(
3568 record: &R,
3569 field: &str,
3570 target: DbFieldType,
3571 value: EpicsValue,
3572) -> CaResult<EpicsValue> {
3573 if let EpicsValue::String(s) = &value {
3574 // DTYP (DBF_DEVICE) validates against the record type's FULL device
3575 // menu — static `device()` lines PLUS runtime-contributed device
3576 // support — the same set the read/announce path exposes via
3577 // `RecordInstance::device_choices`. `menu_choices_of`'s DTYP branch
3578 // returns only the static half, so a contributed device-support name
3579 // (asyn's `asynInt32`, scaler-rs's `Asyn Scaler`, ...) would wrongly
3580 // fail this put even though a client can read it in the DTYP choices.
3581 // Resolve DTYP against the merged menu to keep put and read symmetric.
3582 if field.eq_ignore_ascii_case("DTYP") {
3583 let choices = super::merged_device_menu(record.record_type());
3584 if !choices.is_empty() {
3585 return super::resolve_menu_field_string(
3586 field,
3587 &choices,
3588 target,
3589 &s.as_str_lossy(),
3590 );
3591 }
3592 // No device menu declared or contributed for this record type: fall
3593 // through to the generic handling below (unchanged behavior).
3594 } else if let Some(choices) = super::record_instance::menu_choices_of(record, field) {
3595 return super::resolve_menu_field_string(field, choices, target, &s.as_str_lossy());
3596 }
3597 if target == DbFieldType::Enum {
3598 return super::resolve_enum_state_string(
3599 field,
3600 record.enum_state_strings().as_deref(),
3601 s,
3602 );
3603 }
3604 let dest_is_array = record.get_field(field).is_some_and(|v| v.is_array());
3605 if !dest_is_array {
3606 if let Some(numeric) = c_parse::NumericField::of(target) {
3607 return c_parse::put_string(field, numeric, &s.as_str_lossy());
3608 }
3609 if target == DbFieldType::String {
3610 // C `putStringString` (dbConvert.c:916-925): `strncpy(pdst, psrc,
3611 // field_size); pdst[field_size-1] = 0` — the DBF_STRING put
3612 // truncates to `field_size - 1` bytes. The row is NOT a no-op even
3613 // for a String source, so it must run even when source and stored
3614 // type match (the two gates that call this converter skip it on a
3615 // type match; both route a String target here regardless). The CA
3616 // wire already caps a DBR_STRING at `MAX_STRING_SIZE - 1` (39), so
3617 // this only bites a field whose `.dbd` `size(N)` is under 40 —
3618 // dbCommon `ASG` `size(29)` → 28, and the like.
3619 return Ok(EpicsValue::String(cap_string_to_field_size(
3620 record, field, s,
3621 )));
3622 }
3623 }
3624 }
3625 Ok(value.convert_to(target))
3626}
3627
3628/// C `putStringString`'s truncation: a `DBF_STRING` field stores at most
3629/// `field_size - 1` bytes (its `.dbd` `size(N)` less the forced NUL). A field
3630/// with no declared size (`0` — a Tier 3 hand table, or a field with no
3631/// declaration) is left uncapped beyond the wire's own `MAX_STRING_SIZE - 1`.
3632fn cap_string_to_field_size<R: Record + ?Sized>(record: &R, field: &str, s: &PvString) -> PvString {
3633 match super::record_instance::field_desc_of(record, field) {
3634 Some(desc) if desc.size > 0 => {
3635 let cap = (desc.size as usize).saturating_sub(1);
3636 let bytes = s.as_bytes();
3637 if bytes.len() > cap {
3638 PvString::from_bytes(bytes[..cap].to_vec())
3639 } else {
3640 s.clone()
3641 }
3642 }
3643 _ => s.clone(),
3644 }
3645}
3646
3647/// Subroutine function type for `sub`/`aSub` records.
3648///
3649/// The return value is the subroutine's C `long` status
3650/// (`subRecord.c::do_sub` / `aSubRecord.c::do_sub`): `< 0` raises
3651/// `SOFT_ALARM` at the record's `BRSV` severity, and for `aSub` the status
3652/// is published as `VAL` (`aSubRecord.c:223`). Return `Ok(0)` for the
3653/// normal no-alarm path. `Err(..)` is reserved for an infrastructure
3654/// failure inside the closure (e.g. a field write error), which aborts
3655/// processing — it is distinct from a negative status.
3656pub type SubroutineFn = Box<dyn Fn(&mut dyn Record) -> CaResult<i64> + Send + Sync>;