Skip to main content

epics_base_rs/server/database/
link_set.rs

1//! [`LinkSet`] — pluggable backend for `pva://` / `ca://` link
2//! resolution.
3//!
4//! Mirrors the C EPICS `lset` (link set) abstraction used by libdbCore
5//! to delegate link operations to a pluggable backend. We expose a
6//! pure-Rust trait so the bridge crate can wire up `pvalink` /
7//! `calink` without epics-base-rs having to know about either
8//! protocol.
9//!
10//! At runtime [`super::PvDatabase`] holds a registry keyed by URL
11//! scheme (`"pva"`, `"ca"`); each entry is an `Arc<dyn LinkSet>`.
12//! Record-link reads dispatch through the matching lset before
13//! falling back to the legacy `ExternalPvResolver` closure.
14//!
15//! The trait is **split by thread**, mirroring the C `dbCa` split
16//! between the record-processing thread and the `dbCaTask`
17//! (`dbCa.c:1093-1260`):
18//!
19//! * **Synchronous methods** are the ones record processing calls while
20//!   it holds the record's advisory write gate (C `dbScanLock`). They
21//!   answer from cached, monitor-fed state and MUST NOT perform I/O —
22//!   C `dbCaGetLink` copies out of `pca->pgetNative` and never touches
23//!   the wire (`dbCa.c:419-506`). Their signature is what enforces
24//!   that: a `fn` cannot await, so it cannot suspend the record thread.
25//! * **Async methods** ([`LinkSet::get_value`],
26//!   [`LinkSet::connect_link`], [`LinkSet::put_value`],
27//!   [`LinkSet::flush_puts`]) are the `dbCaTask` half. They run on the
28//!   database's link work owner, never on a record-processing thread,
29//!   and MAY block on the network.
30//!
31//! Before this split the "MUST NOT perform I/O" rule was a doc comment
32//! on an `async fn`, so nothing stopped a new lset from suspending
33//! record processing inside the gate. It is now a type-level property.
34//!
35//! # Adding a new lset
36//!
37//! ```ignore
38//! struct MyLset { /* ... */ }
39//! #[epics_base_rs::async_trait]
40//! impl LinkSet for MyLset {
41//!     fn is_connected(&self, name: &str) -> bool { /* cached */ }
42//!     fn get_cached_value(&self, name: &str) -> Option<EpicsValue> { /* cached */ }
43//!     async fn get_value(&self, name: &str) -> Option<EpicsValue> { /* may do I/O */ }
44//!     /* etc. */
45//! }
46//! db.register_link_set("pva", Arc::new(MyLset { ... })).await;
47//! ```
48
49use std::sync::Arc;
50
51use crate::types::EpicsValue;
52
53/// DBF field type a link's value maps to — the Rust counterpart of
54/// the C `DBF_*` codes pvxs `pvaGetDBFtype` returns.
55///
56/// Mirrors `pvxs/ioc/pvalink_lset.cpp:199` (`pvaGetDBFtype`), which
57/// maps the cached NT value's `TypeCode` to a `DBF_*` constant; an
58/// NT `enum_t` structure maps to `DBF_ENUM`.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60pub enum LinkDbfType {
61    Char,
62    UChar,
63    Short,
64    UShort,
65    Long,
66    ULong,
67    Int64,
68    UInt64,
69    Float,
70    Double,
71    String,
72    Enum,
73}
74
75/// How an external OUT-link write should be delivered to the lset.
76///
77/// Mirrors the C dbCore split between a plain link put and a
78/// put-notify-aware put: `dbPutLink` (synchronous, no completion
79/// callback) vs `dbPutLinkAsync` (issued from `dbNotify`, where the
80/// source record's processing is held until the downstream put
81/// completes). pvxs's pvalink lset realises the same split as
82/// `pvaPutValue` (plain, `wait=false`) vs `pvaPutValueAsync`
83/// (`wait=true`, which sets `record._options.block` so the PUT
84/// request carries the block option and the source record is parked
85/// in `after_put` until the server acknowledges completion) —
86/// `pvxs/ioc/pvalink_lset.cpp` `putValue` / `putValueAsync`.
87///
88/// The database selects the op from the write context: a write that
89/// originates inside a put-notify / blocking-put chain (the source
90/// record carries a completion wait-set) uses [`Async`]; a plain
91/// record-processing OUT write uses [`Plain`].
92///
93/// [`Async`]: LinkPutOp::Async
94/// [`Plain`]: LinkPutOp::Plain
95#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
96pub enum LinkPutOp {
97    /// Plain put — fire-and-forget from the lset's perspective. Maps to
98    /// pvxs `pvaPutValue` (`wait=false`) / C `dbPutLink`.
99    #[default]
100    Plain,
101    /// Completion-aware put — the originating record is part of a
102    /// put-notify / blocking-put chain. Maps to pvxs `pvaPutValueAsync`
103    /// (`wait=true`, `record._options.block`) / C `dbPutLinkAsync`.
104    Async,
105}
106
107/// Whether an external OUT link will accept a staged write right now —
108/// the answer to C `dbCaPutLinkCallback`'s first gate:
109///
110/// ```c
111/// if (!pca->isConnected || !pca->hasWriteAccess) {
112///     epicsMutexUnlock(pca->lock);
113///     return -1;
114/// }
115/// ```
116/// (`dbCa.c:529-532`).
117///
118/// Answered from cached state only: it runs on a record-processing thread
119/// inside the record's advisory write gate, which is exactly where C never
120/// touches the network.
121#[derive(Clone, Copy, Debug, PartialEq, Eq)]
122pub enum PutAdmission {
123    /// The lset tracks this link and its channel is up — stage the write.
124    /// C's fall-through to `addAction` (`dbCa.c:593`).
125    Connected,
126    /// The lset tracks this link and will not take the write — the channel
127    /// is down, or it is up but the server denies write access. One variant
128    /// for both because C has one outcome for both: `-1`, stage nothing
129    /// (`dbCa.c:529-532`). The caller raises the owning record's
130    /// LINK/INVALID through `dbPutLink`'s `setLinkAlarm`
131    /// (`dbLink.c:434-448`).
132    ///
133    /// Named for the answer rather than for one of its two causes: the
134    /// earlier name `Disconnected` was why an implementation of this trait
135    /// answered `is_connected()` alone and admitted every write-denied link.
136    Refused,
137    /// The lset has never opened this link, so it cannot answer. C cannot
138    /// reach this state: `dbCaAddLink` opens every CA link at record-init
139    /// time (`dbCa.c` `addAction(pca, CA_CONNECT)`), so by the first
140    /// `dbCaPutLink` the `caLink` always exists. Our lsets open lazily on
141    /// first use instead, so the write is staged and the lset's own
142    /// `put_value` performs the open — dropping it would mean an OUT link
143    /// that never opens and therefore never connects.
144    Unopened,
145}
146
147/// One external link's report state — the `caLink` fields `dbcar` prints
148/// per link (`dbCaTest.c:95-133`).
149///
150/// C reads them off one `caLink` struct because dbCa owns the channel, the
151/// staged out-value and the connection callback together. Here those belong
152/// to two owners — the lset owns the channel and the connection edge, the
153/// database's link-put queue owns the staged out-value — so this type
154/// carries only the lset's half and `dbcar` joins it with
155/// [`PvDatabase::external_link_puts_coalesced_for`], C's `nNoWrite`.
156///
157/// [`PvDatabase::external_link_puts_coalesced_for`]: super::PvDatabase::external_link_puts_coalesced_for
158#[derive(Clone, Debug, Default, PartialEq, Eq)]
159pub struct LinkDiagnostics {
160    /// C's `pca->chid && ca_field_type(pca->chid) != TYPENOTCONN`
161    /// (`dbCaTest.c:95-97`) — the channel is up. Not
162    /// [`LinkSet::is_connected`], which is the *readable-cache* gate
163    /// `dbCaGetLink` applies; a channel that has connected but has yet to
164    /// deliver a monitor event counts as connected to `dbcar` and as
165    /// unreadable to a record.
166    pub connected: bool,
167    /// C `ca_host_name(pca->chid)` — the server's name with its port.
168    pub host: String,
169    /// C `ca_read_access(pca->chid)`.
170    pub read_access: bool,
171    /// C `ca_write_access(pca->chid)`.
172    pub write_access: bool,
173    /// C `pca->nDisconnect` (`dbCa.c:822`) — connect→disconnect edges since
174    /// the link was opened.
175    pub n_disconnect: u64,
176    /// `pvlOptInpNative`: the link has served a native input transfer
177    /// (`dbCa.c:456`, set on the first `dbCaGetLink` that needs the native
178    /// monitor).
179    pub input_native: bool,
180    /// `pvlOptInpString`: the link has served a *string* input transfer,
181    /// which C reaches only for a `DBR_ENUM` channel read as `DBR_STRING`
182    /// (`dbCa.c:441`).
183    pub input_string: bool,
184    /// `pvlOptOutNative` (`dbCa.c:557`). Dead at the pin: the assignment is
185    /// inside a `/* Disabled by ANJ ... */` comment, so C never sets it and
186    /// `dbcar` always prints the column blank.
187    pub output_native: bool,
188    /// `pvlOptOutString` (`dbCa.c:541`), disabled by the same ANJ comment.
189    pub output_string: bool,
190}
191
192/// Remote display / control / valueAlarm metadata snapshot for a
193/// link, as exposed by pvxs's pvalink lset metadata getters.
194///
195/// Mirrors the `pvxs/ioc/pvalink_lset.cpp` metadata getter set installed
196/// at `pvxs/ioc/pvalink_lset.cpp:706-732`:
197/// `pvaGetDBFtype`, `pvaGetElements`, `pvaGetControlLimits`,
198/// `pvaGetGraphicLimits`, `pvaGetAlarmLimits`, `pvaGetPrecision`,
199/// `pvaGetUnits`.
200///
201/// Every field is optional: pvxs's getters read the cached NT
202/// structure with `Value::as`, which leaves the caller's buffer
203/// unchanged when the sub-field is absent. `None` here means the
204/// remote NT value carried no such metadata — the record support
205/// then keeps its local/default metadata, exactly as the C path does.
206/// The link-backed metadata resolved for **one snapshot build** — the single
207/// channel through which a link's target metadata can reach a served
208/// [`Snapshot`](crate::server::snapshot::Snapshot).
209///
210/// The invariant it makes true by construction is *a served snapshot's
211/// link-backed metadata was resolved during THIS build*. Three things enforce
212/// it, none of them a runtime check:
213///
214/// * the field is private and [`LinkBacking::resolved`] is `pub(crate)`, so a
215///   crate outside `epics-base-rs` cannot make one and must go through
216///   [`PvDatabase::channel_snapshot_for_field`](crate::server::database::PvDatabase::channel_snapshot_for_field);
217/// * it borrows the resolve's own output, so it cannot outlive the resolve and
218///   there is nowhere to *store* it — a stale value is unrepresentable;
219/// * `RecordInstance` keeps no link-metadata map, so the consumer has no second
220///   source to read.
221///
222/// C needs no equivalent. `dbLock.c:725-760` merges every DB_LINK-connected
223/// record into one lock set behind one recursive mutex, so `get_units` and its
224/// siblings call `dbGetUnits`/`dbGetPrecision`/... inline under the target's
225/// lock (`dbDbLink.c:240-261`). The port has one `RwLock` per record and no
226/// lock sets, so it must resolve with no record lock held and hand the answer
227/// in; this type is that hand-off.
228#[derive(Clone, Copy)]
229pub struct LinkBacking<'a>(Option<&'a std::collections::HashMap<String, LinkMetadata>>);
230
231impl<'a> LinkBacking<'a> {
232    /// Nothing was resolved for this build: the record backs no field's
233    /// metadata with a link, or the caller is a path that serves only
234    /// non-link-backed fields. Every lookup answers `None`, which serves each
235    /// rset slot's C seed — the same answer C's untouched buffer gives for a
236    /// CONSTANT link, an unresolvable target, or a link its
237    /// `DBLINK_FLAG_VISITED` guard refused.
238    pub const fn none() -> Self {
239        Self(None)
240    }
241
242    /// What the links this record's metadata is backed by resolved to, keyed
243    /// by link field (`INPA`, `INPB`, ...), resolved with no record lock held.
244    pub const fn resolved(resolved: &'a std::collections::HashMap<String, LinkMetadata>) -> Self {
245        Self(Some(resolved))
246    }
247
248    /// The metadata behind one link field. The *predicate* — whether this
249    /// served field is link-backed at all — stays with
250    /// `Record::link_backed_metadata_field`, so this type answers only the
251    /// value and carries one meaning.
252    pub(crate) fn metadata(&self, link_field: &str) -> Option<&'a LinkMetadata> {
253        self.0.and_then(|m| m.get(link_field))
254    }
255
256    /// True for [`Self::none`] — the caller resolved nothing. Distinct from a
257    /// resolve that came back empty, and the difference is what the monitor
258    /// poster's `debug_assert` reads: a link-backed field posted through an
259    /// unresolved backing is a poster that skipped its resolve, whereas the
260    /// same field posted through an empty resolve is a link that genuinely
261    /// answered nothing and correctly serves its C seed.
262    pub(crate) const fn is_unresolved(&self) -> bool {
263        self.0.is_none()
264    }
265}
266
267#[derive(Clone, Debug, Default, PartialEq)]
268pub struct LinkMetadata {
269    /// DBF type the remote value maps to (`pvaGetDBFtype`). A connected
270    /// link always reports a type — an unmappable value shape falls back
271    /// to `Long`, the `default:` arm of pvxs `pvaGetDBFtype`
272    /// (`pvxs/ioc/pvalink_lset.cpp:199-236`). `None` therefore means "not
273    /// connected" (no cached value), never "connected but unmappable".
274    pub dbf_type: Option<LinkDbfType>,
275    /// Element count: array length, or `1` for a scalar / any connected
276    /// non-array shape (`pvaGetElements`, `pvxs/ioc/pvalink_lset.cpp:242-257`).
277    /// As with `dbf_type`, `None` means "not connected".
278    pub element_count: Option<i64>,
279    /// `display.limitLow` / `display.limitHigh` (`pvaGetGraphicLimits`).
280    pub graphic_limits: Option<(f64, f64)>,
281    /// `control.limitLow` / `control.limitHigh` (`pvaGetControlLimits`).
282    pub control_limits: Option<(f64, f64)>,
283    /// `valueAlarm.{lowAlarmLimit,lowWarningLimit,highWarningLimit,
284    /// highAlarmLimit}` as `(lolo, lo, hi, hihi)` (`pvaGetAlarmLimits`).
285    pub alarm_limits: Option<(f64, f64, f64, f64)>,
286    /// `display.precision` (`pvaGetPrecision`).
287    pub precision: Option<i16>,
288    /// `display.units` (`pvaGetUnits`).
289    pub units: Option<String>,
290    /// `display.description` — carried so a link snapshot is complete;
291    /// pvxs exposes it through the same `fld_meta` cache.
292    pub description: Option<String>,
293    /// ENUM state labels of the remote channel, when it has any. The label
294    /// table a `DBR_STRING`-requesting reader (stringin/lsi INP, printf
295    /// `%s`) renders a remote enum index through — C `dbCa` keeps a second
296    /// `DBR_STRING` monitor (`pgetString`) for that read; here the labels
297    /// ride the same attribute fetch as the limits (CA: `DBR_CTRL_ENUM`).
298    pub enum_choices: Option<Vec<String>>,
299}
300
301/// Ungated remote alarm snapshot for a link — the remote
302/// `(severity, status, message)` the upstream PV carried at the last
303/// successful value read, WITHOUT the maximize-severity
304/// (`MS`/`NMS`/`MSI`) gate that [`LinkSet::alarm_severity`] applies for
305/// owning-record propagation.
306///
307/// This is the DB-link inspection counterpart pvxs exposes through
308/// `dbGetAlarm` / `dbGetAlarmMsg` — `pvaGetAlarmMsg` returns the cached
309/// `snap_severity` / `snap_message` directly and never consults the
310/// link's `sevr` mode (`pvxs/ioc/pvalink_lset.cpp:542-569`; `pvaGetAlarm`
311/// `:571-575` is the thin wrapper that calls it with no message buffer).
312/// A default
313/// `NMS` link must still report its remote severity here even though it
314/// does not maximize the owning record's severity.
315#[derive(Clone, Debug, Default, PartialEq)]
316pub struct RemoteAlarm {
317    /// Remote alarm severity (`0 = NO_ALARM` … `3 = INVALID`), the raw
318    /// cached `alarm.severity` — never gated by the link's `sevr` mode.
319    pub severity: i32,
320    /// Remote alarm status code, derived from `severity` exactly as
321    /// pvxs `pvaGetAlarmMsg` does (`LINK_ALARM` when severity is
322    /// non-`NO_ALARM`, else `NO_ALARM` — `pvxs/ioc/pvalink_lset.cpp:554`). See
323    /// [`RemoteAlarm::from_severity_message`].
324    pub status: i32,
325    /// Remote `alarm.message`. Empty when the remote carried none or
326    /// the severity is `NO_ALARM` (pvxs clears `snap_message` unless
327    /// `snap_severity != 0` — `pvxs/ioc/pvalink_lset.cpp:418-422`).
328    pub message: String,
329}
330
331impl RemoteAlarm {
332    /// Build a snapshot whose `status` is derived from `severity`
333    /// exactly as pvxs `pvaGetAlarmMsg` (`pvxs/ioc/pvalink_lset.cpp:554`):
334    /// `LINK_ALARM` when the remote severity is non-`NO_ALARM`, else
335    /// `NO_ALARM`. status and severity cannot disagree by construction.
336    pub fn from_severity_message(severity: i32, message: String) -> Self {
337        let status = if severity != 0 {
338            crate::server::recgbl::alarm_status::LINK_ALARM as i32
339        } else {
340            crate::server::recgbl::alarm_status::NO_ALARM as i32
341        };
342        Self {
343            severity,
344            status,
345            message,
346        }
347    }
348}
349
350/// Pluggable backend for one URL scheme's link operations.
351///
352/// All methods take `&self` so the implementation must use interior
353/// mutability for any cached state. None / false is the
354/// "unavailable" sentinel — the database falls back to a generic
355/// LINK/INVALID alarm when an lset returns None.
356#[async_trait::async_trait]
357pub trait LinkSet: Send + Sync {
358    /// True iff a fresh value is available for `name` without
359    /// blocking. Used by the record processing loop to decide
360    /// whether to mark the record's STAT as LINK_ALARM.
361    ///
362    /// Synchronous: asked on the record-processing thread inside the
363    /// record's advisory write gate. MUST NOT perform I/O.
364    fn is_connected(&self, name: &str) -> bool;
365
366    /// True iff `name` has completed every post-connect init action
367    /// iocInit's external-link wait holds for — C `testInitReady`
368    /// (`dbCa.c:835-845` at `ef4829829`, epics-base #856 "dbCa: iocInit
369    /// wait for all conditions" — post-`R7.0.10` and in no tag, so this
370    /// is the one citation here that is not pin-relative): connected with
371    /// the first monitor event cached AND
372    /// the attribute (metadata) fetch complete. Distinct from
373    /// [`Self::is_connected`], which is C's lset `isConnected` and keeps
374    /// its readable-cache semantics.
375    ///
376    /// Synchronous and non-blocking like `is_connected`; polled only by
377    /// the iocInit wait. Default: `is_connected` — right for an lset
378    /// with no post-connect init actions.
379    fn init_ready(&self, name: &str) -> bool {
380        self.is_connected(name)
381    }
382
383    /// Read the current value of `name`. Returns None when the
384    /// upstream isn't yet connected or the lset has no cache for
385    /// this name.
386    ///
387    /// MAY perform I/O (open the channel, issue a one-shot GET). It is
388    /// therefore called only from the database's link work owner task —
389    /// the record-processing path uses [`Self::get_cached_value`].
390    async fn get_value(&self, name: &str) -> Option<EpicsValue>;
391
392    /// Read `name` from cached, monitor-fed state ONLY — the
393    /// record-processing read. C `dbCaGetLink` (`dbCa.c:419-506`) copies
394    /// out of `pca->pgetNative`, the buffer the CA monitor callback
395    /// (`eventCallback`, `dbCa.c:891-967`, the fill at `:941-944`)
396    /// keeps fresh on the `dbCaTask`; it never opens a channel and never
397    /// waits on the wire. Returns None
398    /// when the link has no cached value yet, which is C returning -1 for
399    /// `!pca->isConnected` (`dbCa.c:430-435`) — the reading record takes
400    /// LINK/INVALID for that cycle.
401    ///
402    /// MUST NOT perform I/O — which is why this is a `fn` and
403    /// [`Self::get_value`] is an `async fn`.
404    ///
405    /// Default: `None`, i.e. "this lset keeps no cache". That is C's
406    /// `!pca->isConnected` arm verbatim: the reading record takes
407    /// LINK/INVALID for the cycle and the database stages the link's
408    /// open on the link work owner ([`Self::connect_link`]), which is
409    /// what warms the cache for the next cycle. An lset that CAN answer
410    /// from memory MUST override, or its links never read.
411    fn get_cached_value(&self, name: &str) -> Option<EpicsValue> {
412        let _ = name;
413        None
414    }
415
416    /// Open (subscribe / connect) `name` so later
417    /// [`Self::get_cached_value`] reads have a cache to serve — C
418    /// `dbCaAddLink` (`dbCa.c:397-401`), which stages a `CA_CONNECT`
419    /// action whose `ca_create_channel` +
420    /// `ca_add_array_event` run on the `dbCaTask`, not on the caller.
421    ///
422    /// **Called from the database's link work owner task**, so it MAY
423    /// block on the network. Idempotent: the owner may call it again for
424    /// a link that is already open or still connecting.
425    ///
426    /// More precisely, it is called on the tokio runtime the database
427    /// captured at construction, so `tokio::net` is usable here — and that
428    /// is the *only* place it is usable. A database built with no runtime
429    /// entered anywhere captured none, and there is no second executor that
430    /// could stand in: the process-global background executor deliberately
431    /// carries no `tokio::net` reactor. Such a database therefore never
432    /// calls this method at all; it refuses the link instead
433    /// (`PvDatabase::external_put_gate`). Do not read the absence of a
434    /// runtime as a reason to open the channel synchronously on the
435    /// caller — there is no caller thread that may block that way.
436    ///
437    /// Default: drive the lset's own lazy open by reading through
438    /// [`Self::get_value`] and discarding the result — correct for every
439    /// existing lset, and it runs off the record-processing thread.
440    async fn connect_link(&self, name: &str) {
441        let _ = self.get_value(name).await;
442    }
443
444    /// Non-blocking admission gate for an OUT-link write, asked on the
445    /// record-processing thread *before* the write is staged onto the
446    /// database's link-put queue — C `dbCaPutLinkCallback`'s
447    /// `if (!pca->isConnected || !pca->hasWriteAccess) return -1;`
448    /// (`db/dbCa.c:529-532` (`dbCaPutLinkCallback`); epics-base R7.0.10).
449    ///
450    /// MUST NOT perform I/O. It is the one lset call left inside the
451    /// record's advisory write gate, and the whole point of the queue is
452    /// that nothing there touches the network.
453    ///
454    /// Default: derive from [`Self::is_connected`], which the trait already
455    /// documents as answerable "without blocking" — i.e. only C's FIRST
456    /// operand. An lset whose protocol also carries a write right MUST
457    /// override and test both, because the default cannot see the second
458    /// one; so MUST an lset whose OUT links live in a different cache than
459    /// its INP links (pvalink keys its registry on direction), or every OUT
460    /// write to a perfectly healthy channel is refused.
461    fn put_admission(&self, name: &str) -> PutAdmission {
462        if self.is_connected(name) {
463            PutAdmission::Connected
464        } else {
465            PutAdmission::Refused
466        }
467    }
468
469    /// Write `value` to `name` with the delivery semantics named by
470    /// `op` ([`LinkPutOp::Plain`] for a fire-and-forget put,
471    /// [`LinkPutOp::Async`] for a put that is part of a put-notify /
472    /// blocking-put chain). Returns Err with a human-readable reason
473    /// on failure (denied, type-mismatch, no-such-pv, etc.). Default
474    /// impl rejects all writes — read-only lsets keep the default.
475    ///
476    /// **Called from the database's link-put owner task, never from a
477    /// record-processing thread** — this is the `dbCaTask` half of the
478    /// split (`db/dbCa.c:1161-1183` (`dbCaTask`); epics-base R7.0.10), so it
479    /// may block on the network.
480    ///
481    /// As with [`Self::connect_link`], "may block on the network" means "on
482    /// the tokio runtime the database captured", which is where the owner
483    /// dispatches it. A database that captured no runtime never reaches this
484    /// method: the write is refused at `PvDatabase::external_put_gate` with
485    /// nothing staged, C's shape for a put it cannot deliver
486    /// (`db/dbCa.c:529-532` (`dbCaPutLinkCallback`); R7.0.10).
487    async fn put_value(&self, name: &str, value: EpicsValue, op: LinkPutOp) -> Result<(), String> {
488        let _ = (name, value, op);
489        Err("link set is read-only".into())
490    }
491
492    /// Fire `name`'s forward link (FLNK): trigger the remote target to
493    /// process, transferring no value.
494    ///
495    /// The lset counterpart of C `dbScanFwdLink` → `lset->scanForward`
496    /// (`dbLink.c:475`), realised by the pvalink lset as `pvaScanForward`
497    /// (`pvxs/ioc/pvalink_lset.cpp:672-688`). A forward link is never
498    /// deferred ("FWD_LINK is never deferred, and always results in a
499    /// Put") and carries no staged value: it forces the remote record to
500    /// process when the source record fires its FLNK.
501    ///
502    /// The lset applies the same non-retry validity gate pvxs does
503    /// (`pvxs/ioc/pvalink_lset.cpp:677`): on a non-retry link that is not currently
504    /// connected it performs NO trigger and returns `Err`, so the caller
505    /// raises LINK/INVALID on the owning record — pvxs calls
506    /// `recGblSetSevrMsg(LINK_ALARM, INVALID_ALARM, "Disconn")` there.
507    ///
508    /// Default impl: `Ok(())` no-op. A read-only or DB-local lset
509    /// forwards nothing through this hook — a DB FLNK target is processed
510    /// directly by the database's `scanOnce` path (the DB lset's
511    /// `scanForward`), not through an external link set.
512    fn scan_forward(&self, name: &str) -> Result<(), String> {
513        let _ = name;
514        Ok(())
515    }
516
517    /// Flush any OUT-link writes the lset has queued but not yet sent —
518    /// the production drain trigger for an async OUT channel owner.
519    ///
520    /// Two queued states this drains: a write deferred for sibling
521    /// coalescing, and a write that failed mid-disconnect and is held
522    /// for replay once the upstream reconnects (`retry`). The database
523    /// calls this after every external OUT-link write so the
524    /// "retry on connect" path has a production caller from record
525    /// processing — not only test code. Default no-op: a synchronous
526    /// lset (DB links, a read-only lset) queues nothing.
527    ///
528    /// Mirrors the role of pvxs's shared `pvaLinkChannel::put()` being
529    /// driven from record processing rather than left to manual calls
530    /// (`pvxs/ioc/pvalink_lset.cpp:653`, `pvxs/ioc/pvalink_channel.cpp:220-280`).
531    async fn flush_puts(&self) {}
532
533    /// Most recent alarm message string from the upstream PV, when
534    /// available. None means no alarm or no cache.
535    fn alarm_message(&self, _name: &str) -> Option<String> {
536        None
537    }
538
539    /// Alarm severity (`0 = NO_ALARM` … `3 = INVALID`) to fold into
540    /// the owning record's `LINK_ALARM`, when the link should
541    /// propagate one.
542    ///
543    /// `None` means "do not propagate" — either the upstream has no
544    /// alarm, the lset has no cache, or the link's maximize-severity
545    /// mode (`NMS`/`MS`/`MSI`) suppresses it. The lset is expected to
546    /// apply that mode gate itself (the `pva://X?sevr=MS` modifier is
547    /// stripped before epics-base-rs sees the link, so only the lset
548    /// retains it). A returned `Some(sev)` is therefore already
549    /// gated and the record processing loop propagates it verbatim
550    /// as a maximize-severity contribution. Mirrors pvxs
551    /// `pvxs/ioc/pvalink_lset.cpp` `pvaGetAlarm` feeding `recGblSetSevr`.
552    fn alarm_severity(&self, _name: &str) -> Option<i32> {
553        None
554    }
555
556    /// Remote alarm *status* code (the EPICS `alarm_status` enum:
557    /// `0 = NO_ALARM`, `1 = READ`, … `17 = COMM`, …) from the upstream
558    /// PV, when available.
559    ///
560    /// used to honour the `MSS` (maximize-severity-and-
561    /// status) link modifier — the owning record then adopts the remote
562    /// STAT instead of the generic `LINK_ALARM`. `None` means the lset
563    /// cannot report a remote status (no cache, or the link set does not
564    /// track it); the caller falls back to `LINK_ALARM`, which is the
565    /// behaviour for every non-`MSS` modifier and for lsets that leave
566    /// this default. Mirrors `pvxs/ioc/pvalink_lset.cpp` `pvaGetAlarm`
567    /// surfacing the remote `alarm.status` to `recGblSetSevrMsg`.
568    fn alarm_status(&self, _name: &str) -> Option<i32> {
569        None
570    }
571
572    /// Ungated remote alarm snapshot — the remote `(severity, status,
573    /// message)` after a successful value read, WITHOUT the
574    /// maximize-severity (`MS`/`NMS`/`MSI`) gate that
575    /// [`LinkSet::alarm_severity`] applies.
576    ///
577    /// This is the split pvxs draws between two operations: `pvaGetValue`
578    /// applies the `sevr` gate only when raising the *owning record's*
579    /// `LINK_ALARM` (`pvxs/ioc/pvalink_lset.cpp:424-431` — surfaced here
580    /// through [`LinkSet::alarm_severity`]), whereas `pvaGetAlarmMsg`
581    /// returns the cached `snap_severity` / `snap_message` snapshot
582    /// directly and never consults `sevr`
583    /// (`pvxs/ioc/pvalink_lset.cpp:542-569`, with `pvaGetAlarm` `:571-575`
584    /// its no-message-buffer wrapper — surfaced here). A caller
585    /// inspecting the DB link's alarm (`dbGetAlarm` / `dbGetAlarmMsg`)
586    /// therefore sees the remote severity even on a default `NMS` link
587    /// that leaves the owning record unraised.
588    ///
589    /// `None` means the lset cannot report a snapshot: no cache, the
590    /// link is not connected (pvxs `CHECK_VALID` — `pvxs/ioc/pvalink_lset.cpp:548`),
591    /// or the link set does not track remote alarms. Default: none.
592    fn remote_alarm(&self, _name: &str) -> Option<RemoteAlarm> {
593        None
594    }
595
596    /// `(seconds_past_epoch, nanoseconds, userTag)` from the upstream
597    /// PV's timestamp slot, when available. The `userTag` is the remote
598    /// `timeStamp.userTag` widened to the 64-bit `epicsUTag` tag without
599    /// sign extension, or `0` when the source carries none (CA links, or
600    /// a PVA source whose timeStamp omits the field).
601    fn time_stamp(&self, _name: &str) -> Option<(i64, i32, u64)> {
602        None
603    }
604
605    /// Remote display / control / valueAlarm metadata for `name`, as
606    /// a single snapshot.
607    ///
608    /// The Rust counterpart of pvxs's pvalink lset metadata getter
609    /// set (`pvaGetDBFtype`, `pvaGetElements`, `pvaGetControlLimits`,
610    /// `pvaGetGraphicLimits`, `pvaGetAlarmLimits`, `pvaGetPrecision`,
611    /// `pvaGetUnits` — installed at `pvxs/ioc/pvalink_lset.cpp:706-732`).
612    /// A structured snapshot is used instead of seven separate trait
613    /// methods so the lset reads its cache once and record support
614    /// gets every linked-metadata field together.
615    ///
616    /// `None` means the lset has no cached value for `name` (not yet
617    /// connected); a `Some(LinkMetadata)` with individual `None`
618    /// fields means the remote NT value simply did not carry that
619    /// piece of metadata — the record then keeps its local default,
620    /// matching the C getters that leave the caller's buffer
621    /// untouched on a missing sub-field. Default impl: no metadata.
622    fn link_metadata(&self, _name: &str) -> Option<LinkMetadata> {
623        None
624    }
625
626    /// Enumerate every PV name this lset has *opened* (i.e., is
627    /// actively tracking). Used by `dbpvxr` to dump per-record
628    /// link state without forcing the caller to know the full
629    /// name list up-front.
630    fn link_names(&self) -> Vec<String> {
631        Vec::new()
632    }
633
634    /// This link's `dbcar` report state, or `None` when the lset has never
635    /// opened `name` — C's `pca == NULL`, which `dbcar` prints as a
636    /// not-connected link with zero counters (`dbCaTest.c:127-132`).
637    ///
638    /// Async because C's host field is `ca_host_name(pca->chid)`, and this
639    /// port's twin (`CaChannel::host_name`) resolves the peer's PTR record
640    /// on a blocking thread exactly as libca's `hostNameCache` does. That
641    /// makes this the one `LinkSet` method neither half of the C split owns:
642    /// it is a diagnostic, called from iocsh, never from record processing
643    /// and never from the link work owner.
644    ///
645    /// Default: `None`, i.e. "this lset has no per-link report state".
646    /// Such an lset's links are invisible to `dbcar`, which is right — C's
647    /// `dbcar` walks `plink->type == CA_LINK` and no other link flavour.
648    async fn link_diagnostics(&self, _name: &str) -> Option<LinkDiagnostics> {
649        None
650    }
651}
652
653/// Type-erased lset reference held by the [`LinkSetRegistry`].
654pub type DynLinkSet = Arc<dyn LinkSet>;
655
656/// Per-scheme registry. Held in a snapshot cell inside
657/// [`super::PvDatabase`]: readers take an `Arc` of the whole registry with no
658/// lock, and `register` rebuilds and republishes under the cell's writer gate.
659/// `Clone` is what makes that rebuild possible; it is a per-scheme `Arc`
660/// clone, not a deep copy.
661#[derive(Clone, Default)]
662pub struct LinkSetRegistry {
663    inner: std::collections::HashMap<String, DynLinkSet>,
664}
665
666impl LinkSetRegistry {
667    pub fn new() -> Self {
668        Self {
669            inner: std::collections::HashMap::new(),
670        }
671    }
672
673    /// Register `lset` under `scheme`. Subsequent calls for the same
674    /// scheme replace the previous binding.
675    pub fn register(&mut self, scheme: &str, lset: DynLinkSet) {
676        self.inner.insert(scheme.to_string(), lset);
677    }
678
679    /// Look up the lset for `scheme`. Returns `None` when nothing is
680    /// registered under that scheme.
681    pub fn get(&self, scheme: &str) -> Option<DynLinkSet> {
682        self.inner.get(scheme).cloned()
683    }
684
685    /// Names of every registered scheme (`["pva", "ca", ...]`).
686    pub fn schemes(&self) -> Vec<String> {
687        self.inner.keys().cloned().collect()
688    }
689
690    /// Number of registered schemes.
691    pub fn len(&self) -> usize {
692        self.inner.len()
693    }
694
695    pub fn is_empty(&self) -> bool {
696        self.inner.is_empty()
697    }
698}
699
700#[cfg(test)]
701mod tests {
702    use super::*;
703
704    struct StubLset;
705    #[async_trait::async_trait]
706    impl LinkSet for StubLset {
707        fn is_connected(&self, _: &str) -> bool {
708            true
709        }
710        fn get_cached_value(&self, _: &str) -> Option<EpicsValue> {
711            Some(EpicsValue::Long(42))
712        }
713        async fn get_value(&self, name: &str) -> Option<EpicsValue> {
714            self.get_cached_value(name)
715        }
716    }
717
718    #[epics_macros_rs::epics_test]
719    async fn register_and_lookup() {
720        let mut reg = LinkSetRegistry::new();
721        assert!(reg.is_empty());
722        reg.register("pva", Arc::new(StubLset));
723        assert_eq!(reg.len(), 1);
724        let lset = reg.get("pva").expect("registered");
725        assert!(lset.is_connected("anything"));
726        assert_eq!(lset.get_value("anything").await, Some(EpicsValue::Long(42)));
727    }
728
729    #[test]
730    fn unknown_scheme_returns_none() {
731        let reg = LinkSetRegistry::new();
732        assert!(reg.get("missing").is_none());
733    }
734}