epics_base_rs/server/pv.rs
1use std::sync::Arc;
2use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
3
4use crate::runtime::sync::PriorityInheritanceMutex;
5
6use crate::error::CaError;
7use crate::server::event_queue::{EventReader, EventSink, EventUser, PostOutcome, TryRecvError};
8use crate::server::snapshot::{ControlInfo, DisplayInfo, EnumInfo, PropertySupport, Snapshot};
9use crate::types::{DbFieldType, EpicsValue, WallTime};
10
11/// Per-PV subscriber cap. Default 1024 — comfortably above
12/// any realistic dashboard fan-out, small enough to bound the
13/// per-PV `Vec<Subscriber>` under abuse. Override via
14/// `EPICS_CAS_MAX_SUBSCRIBERS_PER_PV`.
15pub(crate) fn max_subscribers_per_pv() -> usize {
16 crate::runtime::env::get("EPICS_CAS_MAX_SUBSCRIBERS_PER_PV")
17 .and_then(|s| s.parse::<usize>().ok())
18 .unwrap_or(1024)
19 .max(8)
20}
21
22/// Process-global counter of monitor events the subscriber never observed
23/// because a later post replaced them in the event queue — C `evSubscrip
24/// ::nreplace` (`dbEvent.c:821`), summed over every monitor. Covers both
25/// `ProcessVariable` and `RecordInstance` posts, because both reach the queue
26/// through the single [`EventSink::post`] owner. Mirrors the pattern of
27/// `dropped_monitors` on the client side (subscribe_with_deadband).
28///
29/// read via [`dropped_monitor_events`]. That reader is not yet
30/// wired to a live scrape surface — the `/queues` admin endpoint
31/// currently renders configured limits only, not this counter — so do
32/// not assume the value is observable through an endpoint until that
33/// wiring lands.
34static DROPPED_MONITOR_EVENTS: AtomicU64 = AtomicU64::new(0);
35
36/// Read the cumulative count of dropped monitor events. Intended for
37/// introspection / metrics; see `DROPPED_MONITOR_EVENTS` for the
38/// current wiring status.
39pub fn dropped_monitor_events() -> u64 {
40 DROPPED_MONITOR_EVENTS.load(Ordering::Relaxed)
41}
42
43/// Identity of the client driving a `WriteHook` invocation. Carries
44/// the user/host/peer fields the CA TCP handler already tracks for
45/// audit + access security, so a proxy hook (gateway, ACL filter,
46/// putlog) can make decisions without re-deriving them.
47#[derive(Debug, Clone, Default)]
48pub struct WriteContext {
49 /// CA `CLIENT_NAME` username, or empty if unknown.
50 pub user: String,
51 /// CA `HOST_NAME` hostname (or peer IP fallback), used for ACF
52 /// matching against `HAG(...)` groups.
53 pub host: String,
54 /// Raw `peer.ip():peer.port()` string, retained for audit/log use.
55 pub peer: String,
56}
57
58/// Async hook invoked by client-originated writes (CA `caput`, CA
59/// `WRITE_NOTIFY`) before the PV's local value is set. Used by the CA
60/// gateway and similar proxies to forward writes upstream instead of
61/// landing them in the local `ProcessVariable`.
62///
63/// The hook receives the proposed new value plus a [`WriteContext`]
64/// identifying the client, and must return either:
65/// * `Ok(())` — the write was accepted (e.g. forwarded to upstream).
66/// The caller does NOT update the local `value` field — the
67/// subsequent upstream-monitor event is expected to do that. This
68/// matches CA-gateway semantics where the cached value reflects
69/// reality after the round-trip.
70/// * `Err(CaError)` — the write was rejected. The caller surfaces
71/// the error to the CA client (`WRITE_NOTIFY` carries the ECA
72/// status). The hook itself decides whether to update local state
73/// on rejection.
74///
75/// The hook is consulted only on the client → server path. Internal
76/// callers (`ProcessVariable::set`, `put_pv_and_post`) bypass it so
77/// the upstream-monitor forwarder can update local state without
78/// recursing into itself.
79///
80/// ## Stale-local hazard
81///
82/// "Hook returns `Ok` → caller does NOT update local value" assumes
83/// the upstream will emit a monitor event reflecting the new value.
84/// EPICS records can violate that assumption: PP=NO fields,
85/// PUT-only fields (e.g. `.PROC`), and records configured to suppress
86/// monitor events on identical values. In those cases the shadow
87/// PV remains at its pre-put value indefinitely — caput appears to
88/// succeed but `caget` afterwards returns the old value.
89///
90/// Hook implementors who target such records SHOULD update the local
91/// `ProcessVariable` themselves on `Ok` — typically by invoking
92/// `pv.set(new_value).await` AFTER the upstream put-ack, accepting
93/// the cost of one local mutation per put. The base hook contract
94/// stays "do nothing on Ok" because most monitor-driven shadows
95/// (the CA gateway's primary use case) WILL receive a monitor event
96/// and updating locally would race with it.
97///
98/// ## Reentrancy
99///
100/// The TCP write path clones the hook `Arc` and releases the read
101/// guard BEFORE invoking it, so a hook that calls
102/// `pv.set_write_hook(...)` to swap itself does not deadlock. A hook
103/// that calls `pv.set(...)` reentrantly is allowed but defeats the
104/// "let the upstream-monitor update local state" contract — the
105/// reentrant `set` will be silently overwritten by the next
106/// upstream event.
107pub type WriteHook = Arc<
108 dyn Fn(
109 EpicsValue,
110 WriteContext,
111 )
112 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), CaError>> + Send>>
113 + Send
114 + Sync,
115>;
116
117/// read/write access decision for a gateway shadow PV,
118/// evaluated for a specific downstream `(user, host)`. Mirrors the CA
119/// access-rights model the server reports to the client and gates
120/// reads on.
121#[derive(Debug, Clone, Copy)]
122pub struct AccessDecision {
123 /// Client may GET / MONITOR (`EVENT_ADD`) the PV.
124 pub read: bool,
125 /// Client may PUT (`WRITE` / `WRITE_NOTIFY`) the PV.
126 pub write: bool,
127}
128
129/// per-PV access hook installed by a proxy (the CA
130/// gateway) so the CA server routes a shadow PV's access-rights
131/// decision through the proxy's own ACF instead of the server's.
132/// Given the downstream client's `(user, host)`, it returns the
133/// [`AccessDecision`].
134///
135/// Symmetric to [`WriteHook`]: the gateway captures its single
136/// `ArcSwap<AccessConfig>` and the PV's `.pvlist` ASG/ASL in the
137/// closure, so `compute_access` reports access rights and gates reads
138/// with the same `can_read` / `can_write` the write hook uses — one
139/// ACF authority, no second copy to keep in sync. The hook is
140/// synchronous (it only reads an in-memory `ArcSwap`, no `.await`); the
141/// server consults it at `CREATE_CHAN` and on access-rights
142/// re-evaluation.
143pub type AccessHook = Arc<dyn Fn(&str, &str) -> AccessDecision + Send + Sync>;
144
145/// per-PV read hook consulted by the CA server's one-shot GET path
146/// (`CA_PROTO_READ` / `CA_PROTO_READ_NOTIFY`) when set. A bare PV serves
147/// reads straight from its stored value cell; a proxy (the CA gateway in
148/// its no-cache mode) installs this hook so each downstream GET is
149/// satisfied by a *fresh* upstream fetch instead of the last cached
150/// value. Mirrors C ca-gateway `-no_cache`, where a connected channel
151/// with caching disabled forwards every read as a fresh
152/// `ca_array_get_callback()` to the IOC (`gateVc.cc:1361-1369`) rather
153/// than returning `vc->eventData()`.
154///
155/// The hook returns a full [`Snapshot`], not a bare value: C `-no_cache`
156/// reads issue `ca_array_get_callback(eventType(), ...)` with `eventType()`
157/// a `DBR_TIME_*` class, and `getTimeCB` decodes the event's status,
158/// severity, and timestamp into `setEventData` before the GET completes
159/// (`gatePv.cc:976`, `:1789-1794`). The hook therefore owns producing the
160/// fresh value *together with* its upstream alarm/timestamp so the read
161/// path never synthesizes metadata by grafting a fresh value onto an
162/// unrelated cached snapshot. Property metadata (display/control/enum) is
163/// not carried by a `DBR_TIME_*` event in either C or here; the consumer
164/// overlays the shadow's last-known property metadata for those fields
165/// (a separate upstream path feeds them, as C splits value/time from the
166/// property monitor).
167///
168/// The hook is async (it performs an upstream get) and fallible: on
169/// `Err` the server surfaces the failure to the client (`ECA_GETFAIL`)
170/// exactly as the IOC's own get-callback error would propagate. Only the
171/// GET path consults it ([`ProcessVariable::read_snapshot`]); monitor
172/// fan-out, the initial monitor event, and access-rights re-posts keep
173/// serving the stored snapshot, so a no-cache PV still backs a downstream
174/// monitor with its upstream subscription's events.
175///
176/// `None` (the default) leaves the read path byte-for-byte unchanged for
177/// every record-backed and cached PV — the hook is purely additive.
178pub type ReadHook = Arc<
179 dyn Fn()
180 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<Snapshot, CaError>> + Send>>
181 + Send
182 + Sync,
183>;
184
185/// A monitor event sent to subscribers when a PV value changes.
186/// Carries a full Snapshot so GR/CTRL metadata (PREC, EGU, limits) is available.
187#[derive(Debug, Clone)]
188pub struct MonitorEvent {
189 pub snapshot: Snapshot,
190 /// Origin writer ID. When non-zero, subscribers with the same
191 /// `ignore_origin` can filter out self-triggered events.
192 /// Used to prevent sequencer write-back loops.
193 ///
194 /// **Scope**: tagged explicitly by the `put_*_post` tier
195 /// (`put_pv_and_post_with_origin`, records and simple PVs alike), and
196 /// inherited by every post inside the `put_*_process` tier's
197 /// synchronous put+process cascade through the thread-local ambient
198 /// write origin (`AmbientWriteOriginScope`) — both record funnels
199 /// (`notify_field_with_origin`, `notify_from_snapshot`) and the
200 /// simple-PV funnel (`ProcessVariable::deliver`) apply the same
201 /// inheritance rule. Posts from work a cascade merely spawned (async
202 /// record completions, driver pollers) run outside any scope and stay
203 /// origin 0.
204 pub origin: u64,
205 /// The `DBE_*` event class(es) this post carries — C attaches the
206 /// posting mask to each event's field log (`db_field_log.mask`,
207 /// dbEvent.c) and pvxs narrows per event from `pDbFieldLog->mask`
208 /// (`groupsource.cpp:331-337`). Producer-side it was already used to
209 /// gate delivery (`Subscriber::accepts`); carrying it on the event
210 /// lets subscribers narrow what they decode (e.g. a QSRV group
211 /// monitor updating only alarm leaves on a `DBE_ALARM`-only event).
212 /// When events coalesce under a slow consumer, masks accumulate by
213 /// OR — the surviving snapshot is the newest, the mask reports every
214 /// class that changed since the last delivered event.
215 pub mask: crate::server::recgbl::EventMask,
216}
217
218/// A subscriber waiting for PV value updates — C `evSubscrip`'s producer-side
219/// view. Its pending events live in the shared event queue
220/// ([`crate::server::event_queue`]), reached only through `sink`.
221pub struct Subscriber {
222 pub sid: u32,
223 pub data_type: DbFieldType,
224 pub mask: u16,
225 /// Producer half of this monitor's slot in the circuit's event queue.
226 /// `pub(crate)` so no code outside this crate can enqueue past the
227 /// append-vs-replace rule the queue owns.
228 pub(crate) sink: EventSink,
229 /// Server-side channel filter chain (epics-base 3.15.7).
230 /// Defaults to empty — every event passes unchanged. Populated
231 /// by the subscription path when the channel name carries a
232 /// `.{filter:opts}` JSON suffix (`dbnd`, `arr`, `ts`, ...).
233 pub filters: crate::server::database::filters::FilterChain,
234 /// Delivery gate. `true` (the default) delivers events normally;
235 /// `false` suppresses every post to this subscriber at the source —
236 /// nothing reaches the event queue, no filter is evaluated — so a
237 /// paused monitor stops the record-event work entirely, not just the
238 /// downstream frame. Mirrors EPICS `db_event_disable` / pvxs
239 /// `onStart(false)` (singlesource.cpp:151-173, groupsource.cpp:151-281):
240 /// the subscription object survives, only its event flow is gated, so
241 /// the same subscriber resumes on re-enable. Flipped only under the
242 /// owner's write lock via [`super::record::record_instance::RecordInstance::set_subscriber_active`]
243 /// (records) — the post paths read it under the matching read lock.
244 pub active: bool,
245}
246
247impl Subscriber {
248 /// a monitor delivery is gated on the requested `DBE_*`
249 /// mask. Returns true only when the post's event class intersects
250 /// this subscriber's mask — the single rule C rsrv enforces with
251 /// `caEventMask & pevent->select` (`dbEvent.c:892-900`) and the
252 /// same intersection the record-field monitor path applies. An
253 /// empty post class (no specific class) delivers unconditionally.
254 fn accepts(&self, post: crate::server::recgbl::EventMask) -> bool {
255 post.is_empty() || crate::server::recgbl::EventMask::from_bits(self.mask).intersects(post)
256 }
257
258 /// The single post path for both event sources (`ProcessVariable` value /
259 /// alarm / property posts and `RecordInstance` field monitors): hand the
260 /// event to this monitor's event queue, which owns C's append-vs-replace
261 /// decision (`db_queue_event_log`), and apply the one piece of accounting
262 /// that lives outside the queue — the counter for a value that a later post
263 /// displaced before the consumer ever saw it (C `nreplace`).
264 pub(crate) fn post(&self, event: MonitorEvent) {
265 if self.sink.post(event) == PostOutcome::Replaced {
266 DROPPED_MONITOR_EVENTS.fetch_add(1, Ordering::Relaxed);
267 }
268 }
269
270 /// The consumer for this monitor is gone; the producer row can be reaped.
271 pub(crate) fn is_closed(&self) -> bool {
272 self.sink.is_closed()
273 }
274}
275
276/// Shadow `DBR_GR_*` / `DBR_CTRL_*` / enum metadata for a
277/// non-record-backed PV.
278///
279/// A bare [`ProcessVariable`] has no record engine to derive units /
280/// precision / display+alarm+control limits / enum labels from, so a
281/// proxy that fronts an upstream IOC (the CA / PVA gateway) fetches the
282/// upstream's control metadata and installs it here via
283/// [`ProcessVariable::set_metadata`]. Every snapshot the PV emits —
284/// the GET path ([`ProcessVariable::snapshot`]) and every monitor
285/// event ([`ProcessVariable::post_property`], value, alarm, and
286/// gateway snapshot posts) — then carries it, so a downstream client
287/// that requested a `DBR_GR_*` / `DBR_CTRL_*` type receives the
288/// upstream metadata instead of zeroed limits.
289///
290/// Mirrors the C ca-gateway, where `gatePvData` subscribes to
291/// `DBE_PROPERTY` and issues a control-type `ca_array_get_callback`
292/// (`gatePv.cc:850-934`) then copies units / precision / graphic +
293/// control limits into the gateway's gdd attributes
294/// (`gatePv.cc:1916-2007`).
295#[derive(Debug, Clone, Default)]
296pub struct PvMetadata {
297 pub display: Option<DisplayInfo>,
298 pub control: Option<ControlInfo>,
299 pub enums: Option<EnumInfo>,
300}
301
302/// Metadata of the most recent full-snapshot write to a bare PV:
303/// alarm + acquisition timestamp + userTag. A bare `ProcessVariable`
304/// has no alarm engine, so without this it would forget everything a
305/// full-value write carried beyond the raw value. pvxs mailbox
306/// `SharedPV::post()` assigns the *whole* posted value to the current
307/// value (`sharedpv.cpp:417-432`); to match that, a PV that received a
308/// full posted Value must reflect its alarm/time on every later GET,
309/// not just to the monitor subscribers that saw the post live.
310#[derive(Clone)]
311struct PostedMeta {
312 alarm: crate::server::snapshot::AlarmInfo,
313 timestamp: WallTime,
314 user_tag: i32,
315}
316
317/// A process variable hosted by the server.
318pub struct ProcessVariable {
319 pub name: String,
320 /// The stored value. A synchronous `parking_lot::RwLock` (matching the
321 /// sibling `posted_meta` / `metadata` / hook locks): every access is a
322 /// single-expression read-or-write with no `.await` held across the
323 /// guard, so the value-read path (`get`, `snapshot`) is pure lock work
324 /// with no reactor dependency — the sans-io READ path. The write side
325 /// (`set` / `set_snapshot`) still `.await`s the monitor fan-out, but
326 /// drops this guard first.
327 pub value: parking_lot::RwLock<EpicsValue>,
328 /// Monitor fan-out list — **L7** of `doc/rtems-priority-locks-design.md`
329 /// §3.
330 ///
331 /// A BLOCKING mutex, not the async one: every emission path runs from a
332 /// record-processing thread with the record's advisory gate (L1) held, and
333 /// C's `db_post_events` likewise takes `evUser->lock` from inside
334 /// `dbScanLock` (`dbEvent.c::db_post_events`). Holding an async mutex here
335 /// would put a suspension point inside that window. Every critical section
336 /// below is bounded list work (`retain` / `push` / `sub.post`), with no
337 /// I/O and no `.await` inside it.
338 ///
339 /// Specifically a [`PriorityInheritanceMutex`] rather than a plain
340 /// `parking_lot::Mutex`, because `evUser->lock` is an `epicsMutex` and on
341 /// the RTEMS arm every `epicsMutex` is a `PTHREAD_PRIO_INHERIT` pthread
342 /// mutex (`os/posix/osdMutex.c:71-88`, compiled for RTEMS via
343 /// `os/RTEMS-posix/osdMutex.c:8`). It is taken from banded IOC threads on
344 /// both sides — the emitting record-processing thread and a `CAS-client`
345 /// thread running `remove_subscriber` — so a plain mutex here reintroduces
346 /// the inversion L1 was converted to remove. Off the PI targets this is
347 /// `parking_lot::Mutex`, i.e. exactly what it was.
348 ///
349 /// A leaf of the acquisition order (`record_lock.rs` module doc): no other
350 /// lock is taken while it is held.
351 pub subscribers: PriorityInheritanceMutex<Vec<Subscriber>>,
352 /// Sticky metadata of the last full-snapshot write. `None` until a
353 /// [`Self::set_snapshot`] lands; a value-only [`Self::set`] clears it
354 /// back to `None` (a plain value write carries no explicit
355 /// alarm/time, so it reverts to NO_ALARM + wall-clock-now). When
356 /// `Some`, [`Self::snapshot`] serves these instead of the defaults.
357 /// Single meaning: the served snapshot reflects the most recent
358 /// write — value always current, metadata from that write.
359 posted_meta: parking_lot::RwLock<Option<PostedMeta>>,
360 /// Shadow DBR_GR_*/DBR_CTRL_*/enum metadata, installed by a proxy
361 /// (CA / PVA gateway) via [`Self::set_metadata`]. Empty for a plain
362 /// local PV. Stored under the same sync `parking_lot::RwLock` slot
363 /// rationale as the hooks: every snapshot builder reads it without
364 /// an `.await`. See [`PvMetadata`].
365 metadata: parking_lot::RwLock<PvMetadata>,
366 /// Optional hook consulted on client-originated writes. When set,
367 /// the CA TCP write path delegates to the hook instead of doing a
368 /// local `pv.set()`. See [`WriteHook`].
369 ///
370 /// Stored under `parking_lot::RwLock` (sync) rather than the
371 /// async `tokio::sync::RwLock` so the hot put-path can read it
372 /// without an `.await` round-trip — `write_hook()` is now a
373 /// constant-time clone of the optional `Arc`. The hook itself
374 /// is async (returns a `Future`); only the slot is sync.
375 write_hook: parking_lot::RwLock<Option<WriteHook>>,
376 /// optional access hook consulted by the CA server's
377 /// `compute_access` to decide a downstream client's read/write
378 /// rights for this PV. When set, it overrides the server's own ACF
379 /// for this PV — the gateway uses it to enforce `.pvlist` ASG-based
380 /// `can_read` / `can_write`, symmetric to [`Self::write_hook`].
381 /// Same sync `parking_lot::RwLock` slot rationale as `write_hook`.
382 access_hook: parking_lot::RwLock<Option<AccessHook>>,
383 /// optional read hook consulted by the CA server's one-shot GET path
384 /// ([`Self::read_snapshot`]) to fetch a fresh value instead of the
385 /// stored cell. Used by the CA gateway's no-cache mode to forward
386 /// each downstream GET to upstream. `None` (the default) keeps the
387 /// read path serving the stored value, identical to before. Same
388 /// sync slot rationale as [`Self::write_hook`]: the GET path clones
389 /// the optional `Arc` without an `.await`, then awaits the hook
390 /// outside any lock. See [`ReadHook`].
391 read_hook: parking_lot::RwLock<Option<ReadHook>>,
392}
393
394impl ProcessVariable {
395 pub fn new(name: String, initial: EpicsValue) -> Self {
396 Self {
397 name,
398 value: parking_lot::RwLock::new(initial),
399 subscribers: PriorityInheritanceMutex::new(Vec::new()),
400 metadata: parking_lot::RwLock::new(PvMetadata::default()),
401 posted_meta: parking_lot::RwLock::new(None),
402 write_hook: parking_lot::RwLock::new(None),
403 access_hook: parking_lot::RwLock::new(None),
404 read_hook: parking_lot::RwLock::new(None),
405 }
406 }
407
408 /// Install (or replace) the shadow DBR_GR_*/DBR_CTRL_*/enum
409 /// metadata served on this PV's snapshots. Used by the CA / PVA
410 /// gateway after fetching the upstream IOC's control metadata. See
411 /// [`PvMetadata`]. To publish the change to downstream property
412 /// monitors, follow with [`Self::post_property`].
413 pub fn set_metadata(&self, metadata: PvMetadata) {
414 *self.metadata.write() = metadata;
415 }
416
417 /// Snapshot (clone) of the installed shadow metadata; empty
418 /// (`Default`) for a plain local PV.
419 pub fn metadata(&self) -> PvMetadata {
420 self.metadata.read().clone()
421 }
422
423 /// Fill any metadata field the snapshot leaves `None` from the
424 /// installed shadow metadata. A field the caller already populated
425 /// (e.g. a gateway snapshot that carried its own metadata) wins —
426 /// this only supplies what is otherwise absent, so every emission
427 /// path serves the upstream metadata uniformly without clobbering a
428 /// richer source.
429 fn apply_metadata(&self, snap: &mut Snapshot) {
430 let meta = self.metadata.read();
431 if snap.display.is_none() {
432 snap.display = meta.display.clone();
433 }
434 if snap.control.is_none() {
435 snap.control = meta.control.clone();
436 }
437 if snap.enums.is_none() {
438 snap.enums = meta.enums.clone();
439 }
440 // A bare PV has no `rset`, so "which properties does this channel
441 // supply" is answered by what metadata it actually HAS: a proxy that
442 // shadowed an upstream IOC's display/control/enum info supplies those
443 // properties, a mailbox PV that nobody gave metadata to supplies none.
444 // Assigned here, in the one owner of a bare PV's metadata, so the mask
445 // and the values it describes cannot disagree.
446 // See [`crate::server::snapshot::PropertySupport`].
447 snap.properties = PropertySupport {
448 units: snap.display.is_some(),
449 precision: snap.display.is_some(),
450 graphic_double: snap.display.is_some(),
451 alarm_double: snap.display.is_some(),
452 control_double: snap.control.is_some(),
453 enum_strs: snap.enums.is_some(),
454 }
455 .narrowed_to_field(snap.value.db_field_type(), false);
456 }
457
458 /// Install an access hook. Replaces any previously
459 /// installed hook.
460 pub fn set_access_hook(&self, hook: AccessHook) {
461 *self.access_hook.write() = Some(hook);
462 }
463
464 /// Snapshot of the installed access hook (clone of the `Arc`), or
465 /// `None`. Consulted by the CA server's `compute_access`; cheap and
466 /// non-async, like [`Self::write_hook`].
467 pub fn access_hook(&self) -> Option<AccessHook> {
468 self.access_hook.read().clone()
469 }
470
471 /// Install a read hook. Replaces any previously-installed hook.
472 /// Used by the CA gateway's no-cache mode so each downstream GET is
473 /// served by a fresh upstream fetch. See [`ReadHook`].
474 pub fn set_read_hook(&self, hook: ReadHook) {
475 *self.read_hook.write() = Some(hook);
476 }
477
478 /// Snapshot of the installed read hook (clone of the `Arc`), or
479 /// `None`. Cheap and non-async, like [`Self::write_hook`]: the read
480 /// lock is released before the cloned `Arc` returns, so the caller's
481 /// subsequent `await` on the hook holds no lock.
482 pub fn read_hook(&self) -> Option<ReadHook> {
483 self.read_hook.read().clone()
484 }
485
486 /// Install a write hook. Replaces any previously-installed hook.
487 pub fn set_write_hook(&self, hook: WriteHook) {
488 *self.write_hook.write() = Some(hook);
489 }
490
491 /// Remove any installed write hook.
492 pub fn clear_write_hook(&self) {
493 *self.write_hook.write() = None;
494 }
495
496 /// Snapshot of the installed write hook (clone of the `Arc`), or
497 /// `None` if none. Used by the CA TCP write path; cheap and
498 /// non-async — the read lock is released before the cloned `Arc`
499 /// returns, so the caller's subsequent `await` on the hook does
500 /// not hold any lock.
501 pub fn write_hook(&self) -> Option<WriteHook> {
502 self.write_hook.read().clone()
503 }
504
505 /// Get the current value.
506 ///
507 /// Synchronous: a single-expression read-lock clone with no `.await`,
508 /// so the value-read path carries no reactor dependency (sans-io).
509 pub fn get(&self) -> EpicsValue {
510 self.value.read().clone()
511 }
512
513 /// Build a Snapshot for this bare PV.
514 ///
515 /// A `ProcessVariable` is a non-record-backed channel: it has no
516 /// alarm engine, no DESC/EGU/PREC metadata and no timestamp user
517 /// tag of its own. The snapshot is therefore value + `NO_ALARM` +
518 /// wall-clock now, with `user_tag` = 0. Display / control / enum
519 /// metadata is `None` *unless* a proxy installed it via
520 /// [`Self::set_metadata`] (the CA / PVA gateway shadowing an
521 /// upstream IOC) — see `Self::apply_metadata`. Record-backed
522 /// channels build their snapshot via
523 /// `RecordInstance::snapshot_for_field`, which carries the record's
524 /// own alarm/metadata. The only path that injects a non-zero alarm
525 /// onto a bare PV is [`Self::post_alarm`] (used by the gateway
526 /// adapter to surface upstream disconnect).
527 pub fn snapshot(&self) -> Snapshot {
528 let value = self.value.read().clone();
529 // Serve the sticky metadata of the last full-snapshot write if
530 // one landed (pvxs mailbox parity: a posted full Value stays the
531 // current value, alarm/time included); otherwise the bare-PV
532 // default of NO_ALARM + wall-clock-now.
533 let mut snap = match self.posted_meta.read().clone() {
534 Some(m) => {
535 let mut s = Snapshot::new(value, m.alarm.status, m.alarm.severity, m.timestamp);
536 s.alarm.ackt = m.alarm.ackt;
537 s.alarm.acks = m.alarm.acks;
538 s.user_tag = m.user_tag;
539 s
540 }
541 None => Snapshot::new(value, 0, 0, crate::runtime::time::now_wall()),
542 };
543 self.apply_metadata(&mut snap);
544 snap
545 }
546
547 /// Build the snapshot served on a one-shot client GET
548 /// (`CA_PROTO_READ` / `CA_PROTO_READ_NOTIFY`).
549 ///
550 /// When a [`ReadHook`] is installed (the CA gateway's no-cache mode),
551 /// the snapshot is fetched fresh through the hook — value *and* its
552 /// upstream alarm status/severity and IOC timestamp together — and the
553 /// shadow's last-known property metadata (display/control/enum) is
554 /// overlaid for the fields a `DBR_TIME_*` event does not carry; on hook
555 /// error the failure propagates so the server can answer `ECA_GETFAIL`,
556 /// matching C ca-gateway forwarding each read to the IOC under
557 /// `-no_cache` (`gateVc.cc:1361-1369`, `gatePv.cc:976`/`:1789-1794`).
558 /// Without a hook this is exactly [`Self::snapshot`] wrapped in `Ok`,
559 /// so the GET path is unchanged for every record-backed and cached PV.
560 ///
561 /// Only the GET path calls this; monitor fan-out, the initial monitor
562 /// event, and access-rights re-posts keep using [`Self::snapshot`]
563 /// (the stored value), so a no-cache PV still backs a downstream
564 /// monitor with its upstream subscription's events rather than a
565 /// per-event upstream get.
566 pub async fn read_snapshot(&self) -> Result<Snapshot, CaError> {
567 match self.read_hook() {
568 Some(hook) => {
569 // The hook issues a metadata-bearing upstream GET
570 // (`DbrClass::Time`), so the returned snapshot already
571 // carries the fresh value WITH its upstream alarm
572 // status/severity and IOC timestamp — mirroring C
573 // `getTimeCB` decoding the `DBR_TIME_*` event before
574 // `setEventData`. A `DBR_TIME_*` event does not carry
575 // display/control/enum metadata, so overlay the shadow's
576 // last-known property metadata for those absent fields only
577 // (a separate upstream path feeds it, exactly as C splits
578 // the value/time path from the property monitor). Never
579 // graft the fresh value onto the stored snapshot's
580 // alarm/time, which may be stale or the bare-PV default.
581 let mut snap = hook().await?;
582 self.apply_metadata(&mut snap);
583 Ok(snap)
584 }
585 None => Ok(self.snapshot()),
586 }
587 }
588
589 /// Synchronous companion to [`Self::read_snapshot`] for the one-shot GET
590 /// path (`CA_PROTO_READ` / `CA_PROTO_READ_NOTIFY`).
591 ///
592 /// `Some(snapshot)` when NO read hook is installed — the sans-io GET that
593 /// every record-backed and cached PV takes: [`Self::snapshot`] of the
594 /// stored value, produced with no `.await` and no reactor dependency.
595 /// `None` when a gateway no-cache [`ReadHook`] IS installed, whose `hook()`
596 /// is a genuine upstream network GET; the caller must then take the async
597 /// [`Self::read_snapshot`] instead. This keeps the hook / no-hook decision
598 /// in one owner, in lockstep with `read_snapshot` — the only difference is
599 /// that the async fallible upstream fetch is surfaced to the caller as
600 /// `None` rather than performed here.
601 pub fn read_snapshot_local(&self) -> Option<Snapshot> {
602 match self.read_hook() {
603 Some(_) => None,
604 None => Some(self.snapshot()),
605 }
606 }
607
608 /// Set a new value and notify all subscribers.
609 pub fn set(&self, new_value: EpicsValue) {
610 self.set_with_origin(new_value, 0);
611 }
612
613 /// [`Self::set`] tagged with the writer's origin: the value post carries
614 /// `origin` so an origin-aware consumer can recognise (and skip) the
615 /// writer's own event — the simple-PV side of the
616 /// `put_pv_and_post_with_origin` self-write contract. Origin 0 is the
617 /// untagged default (never filtered).
618 pub fn set_with_origin(&self, new_value: EpicsValue, origin: u64) {
619 {
620 let mut val = self.value.write();
621 *val = new_value.clone();
622 }
623 // A plain value write carries no explicit alarm/time — revert to
624 // the bare-PV default so a stale full-snapshot's metadata does
625 // not linger on a value the client never stamped.
626 *self.posted_meta.write() = None;
627 self.notify_subscribers(new_value, origin);
628 }
629
630 /// Set value from a full snapshot (value + alarm + timestamp) and notify
631 /// all subscribers. Used by the CA gateway forwarding task to propagate
632 /// the upstream alarm status/severity and IOC timestamp to downstream
633 /// monitors. Mirrors `gateVcData::setEventData` + `vcPostEvent` in the
634 /// C ca-gateway: the incoming `dbr_time_xxx` GDD carries all three fields.
635 pub fn set_snapshot(&self, snapshot: Snapshot) {
636 {
637 let mut val = self.value.write();
638 *val = snapshot.value.clone();
639 }
640 // Persist the posted alarm/time/userTag so a later GET reflects
641 // the full posted value, not just the live monitor fan-out.
642 *self.posted_meta.write() = Some(PostedMeta {
643 alarm: snapshot.alarm.clone(),
644 timestamp: snapshot.timestamp,
645 user_tag: snapshot.user_tag,
646 });
647 self.notify_subscribers_from_snapshot(snapshot);
648 }
649
650 /// Single delivery owner: emit `snapshot` to every live subscriber
651 /// whose `DBE_*` mask intersects `post`.
652 ///
653 /// Every emission path ([`Self::notify_subscribers`] value posts,
654 /// [`Self::post_alarm`], [`Self::notify_subscribers_from_snapshot`]
655 /// gateway posts, [`Self::post_property`]) routes through here so the
656 /// mask gate (`caEventMask & pevent->select`, `dbEvent.c:892-900`),
657 /// the per-subscriber channel-filter chain, and the slow-consumer
658 /// coalesce-overflow accounting are applied identically — one event
659 /// class differs per caller, nothing else. The snapshot is built once
660 /// by the caller (one timestamp per logical event) and cloned per
661 /// subscriber.
662 fn deliver(&self, post: crate::server::recgbl::EventMask, snapshot: Snapshot, origin: u64) {
663 use crate::server::database::filters::FilteredMonitorEvent;
664 // Same ambient-origin inheritance as the record funnels
665 // (`notify_field_with_origin` / `notify_from_snapshot`): a post
666 // carrying no origin of its own inherits the current thread's
667 // ambient write origin, so a simple PV written from inside an
668 // in-process writer's synchronous put cascade tags its event
669 // with the writer's origin too. 0 outside any scope.
670 let origin = if origin != 0 {
671 origin
672 } else {
673 crate::server::record::ambient_write_origin()
674 };
675 let mut subs = self.subscribers.lock();
676 // Remove subscribers whose consumer has been dropped.
677 subs.retain(|sub| !sub.is_closed());
678 for sub in subs.iter() {
679 // Paused subscribers (`db_event_disable`) receive nothing —
680 // skip before any work so a disabled monitor stops the event
681 // flow at the source.
682 if !sub.active {
683 continue;
684 }
685 // Skip subscribers whose requested class does not intersect
686 // this post's event class.
687 if !sub.accepts(post) {
688 continue;
689 }
690 let event = MonitorEvent {
691 snapshot: snapshot.clone(),
692 origin,
693 mask: post,
694 };
695 // The channel-filter chain may suppress this event (e.g.
696 // `dbnd` deadband not crossed); the event's mask tells value
697 // filters whether to pass through (446e0d4a).
698 let filtered = if sub.filters.is_empty() {
699 Some(event)
700 } else {
701 sub.filters
702 .apply(FilteredMonitorEvent::new(event))
703 .map(|fe| fe.event)
704 };
705 let Some(event) = filtered else {
706 continue;
707 };
708 // C `db_queue_event_log`: the queue appends, or replaces this
709 // monitor's last entry in place when it is in flow control or
710 // nearly full. Earlier distinct entries are never discarded.
711 sub.post(event);
712 }
713 }
714
715 /// Push a fresh monitor event holding the current value but with
716 /// the supplied alarm severity/status. Used by the PVA / CA
717 /// gateway adapter to surface upstream-disconnect to downstream
718 /// monitor subscribers without dropping the simple PV (which
719 /// would force every downstream client into ECA_DISCONN +
720 /// reconnect storms when the upstream is just briefly
721 /// unreachable). Mirrors gatePvData::death's "alarm-post"
722 /// alternative discussed in the C++ ca-gateway audit.
723 pub fn post_alarm(&self, severity: u16, status: u16) {
724 use crate::server::recgbl::EventMask;
725 let value = self.value.read().clone();
726 let mut snapshot = Snapshot::new(value, status, severity, crate::runtime::time::now_wall());
727 self.apply_metadata(&mut snapshot);
728 // ALARM|LOG so DBE_LOG (archiver) subscribers receive alarm events.
729 self.deliver(EventMask::ALARM | EventMask::LOG, snapshot, 0);
730 }
731
732 /// Post a `DBE_PROPERTY` monitor event carrying the decoded upstream
733 /// CTRL event `snapshot` — its value plus the upstream status /
734 /// severity and timestamp — overlaid with the installed shadow
735 /// metadata, so downstream property-change monitors re-read the units /
736 /// precision / limits / enum labels with the *upstream* alarm state.
737 ///
738 /// Used by the CA / PVA gateway when an upstream `DBE_PROPERTY` event
739 /// fires (metadata changed) after it has refreshed the shadow PV via
740 /// [`Self::set_metadata`]. The caller supplies the snapshot rather than
741 /// this method synthesising one: C ca-gateway decodes the upstream
742 /// `DBR_CTRL_*` callback and re-posts the value with `setStatSevr()`
743 /// status/severity preserved (`gatePv.cc:2413-2438`,
744 /// `runValueDataCB`), leaving the timestamp as the control DBR carries
745 /// none — it must NOT be replaced with a fresh `NO_ALARM` /
746 /// wall-clock-now snapshot just because metadata changed. Pass the
747 /// timestamp the upstream value carried (the control event has none of
748 /// its own); pass `status`/`severity` from the upstream CTRL payload.
749 /// Property events are a distinct class from value/alarm: only
750 /// `DBE_PROPERTY` subscribers receive them.
751 pub async fn post_property(&self, mut snapshot: Snapshot) {
752 use crate::server::recgbl::EventMask;
753 self.apply_metadata(&mut snapshot);
754 self.deliver(EventMask::PROPERTY, snapshot, 0);
755 }
756
757 /// Notify all subscribers of a new value, tagged with the writer's
758 /// `origin` (0 = untagged).
759 fn notify_subscribers(&self, value: EpicsValue, origin: u64) {
760 use crate::server::recgbl::EventMask;
761 let mut snapshot = Snapshot::new(value, 0, 0, crate::runtime::time::now_wall());
762 self.apply_metadata(&mut snapshot);
763 // VALUE|LOG so DBE_LOG (archiver) subscribers receive value events.
764 self.deliver(EventMask::VALUE | EventMask::LOG, snapshot, origin);
765 }
766
767 /// Notify all subscribers using a pre-built Snapshot (value + alarm +
768 /// timestamp). Used by `set_snapshot` to propagate the upstream alarm
769 /// and IOC timestamp without synthesising a new zero-alarm local-time
770 /// snapshot. Installed shadow metadata fills any metadata field the
771 /// gateway snapshot left absent (see [`Self::apply_metadata`]).
772 fn notify_subscribers_from_snapshot(&self, mut snapshot: Snapshot) {
773 use crate::server::recgbl::EventMask;
774 self.apply_metadata(&mut snapshot);
775 // C gateway fires postEvent(VALUE|ALARM|LOG) for every
776 // upstream event (gateVc.cc:374-376); match it so DBE_LOG
777 // archivers and DBE_ALARM-only monitors receive gateway snapshot posts.
778 self.deliver(
779 EventMask::VALUE | EventMask::LOG | EventMask::ALARM,
780 snapshot,
781 0,
782 );
783 }
784
785 /// Add an in-process subscriber, attached to an event queue of its own.
786 ///
787 /// C `db_add_event(ctx, ...)` puts a monitor on the queue chain of the
788 /// `event_user` (client) that owns it. An in-process consumer is its own
789 /// client, so it gets its own [`EventUser`] — nothing else shares its
790 /// queue, and flow control (a CA circuit concept) never engages on it.
791 /// The CA server, whose subscriptions DO share one circuit-wide queue, uses
792 /// [`Self::add_subscriber_on`].
793 pub fn add_subscriber(
794 &self,
795 sid: u32,
796 data_type: DbFieldType,
797 mask: u16,
798 ) -> Option<EventReader> {
799 self.add_subscriber_on(&EventUser::new(), sid, data_type, mask)
800 }
801
802 /// Add a subscriber whose events are queued on `user`'s event queue —
803 /// C `db_add_event` with the circuit's `event_user` as context. Every
804 /// subscription on one CA circuit shares that queue, and therefore its
805 /// `nDuplicates`: a duplicate queued for one of them releases the
806 /// EVENTS_OFF drain for all of them (`dbEvent.c:947`).
807 ///
808 /// Returns `None` when the per-PV subscriber cap is reached (defends
809 /// against a misbehaving client opening many MONITOR ops against one shared
810 /// PV; the per-channel cap limits channels but not subscriber rows on a
811 /// single PV). Operators override it via `EPICS_CAS_MAX_SUBSCRIBERS_PER_PV`.
812 pub fn add_subscriber_on(
813 &self,
814 user: &EventUser,
815 sid: u32,
816 data_type: DbFieldType,
817 mask: u16,
818 ) -> Option<EventReader> {
819 let cap = max_subscribers_per_pv();
820 let mut subs = self.subscribers.lock();
821 // Reap rows whose consumer is gone BEFORE counting
822 // against the cap. `notify_subscribers` / `post_alarm`
823 // already retain-filter on every emission, but a PV with
824 // no value changes (e.g. a static catalog entry that
825 // dashboards latch onto and drop) never triggered the
826 // reaper — a long-lived subscribe / disconnect storm could
827 // pin the Vec at `cap` worth of dead rows and lock
828 // out genuine new subscribers with a false-positive cap-
829 // reached warning. Same defect class as the
830 // NDPluginPva subscribe reaper (qsrv/pva_adapter.rs:247).
831 subs.retain(|s| !s.is_closed());
832 if subs.len() >= cap {
833 tracing::warn!(
834 pv = %self.name,
835 live = subs.len(),
836 cap,
837 "PV subscriber cap reached, refusing add_subscriber"
838 );
839 return None;
840 }
841 let (sink, reader) = crate::server::event_queue::attach(user, sid);
842 subs.push(Subscriber {
843 sid,
844 data_type,
845 mask,
846 sink,
847 filters: crate::server::database::filters::FilterChain::new(),
848 active: true,
849 });
850 Some(reader)
851 }
852
853 /// attach a channel-filter chain to an already-added
854 /// subscriber (looked up by `sid`). The CA server first
855 /// `add_subscriber`s, then attaches the chain parsed from the
856 /// channel's `.{...}` suffix — symmetric with the record-field
857 /// `RecordInstance::attach_filter_to_last_subscriber` path, so a
858 /// `SimplePv` monitor runs the SAME filter chain as a record-field
859 /// monitor instead of the empty default `FilterChain` that
860 /// `add_subscriber` installs. Update delivery
861 /// (`Self::notify_subscribers` / [`Self::post_alarm`]) already
862 /// applies `sub.filters`; this is the missing wiring that populates
863 /// it.
864 ///
865 /// The caller passes a FRESH chain per subscriber so stateful
866 /// filters (`dbnd` last-value, `dec` counter, `sync` state) stay
867 /// isolated across subscribers. An empty chain is a no-op (keeps the
868 /// default). No-op when no subscriber matches `sid` (e.g. it was
869 /// reaped between add and attach).
870 pub fn attach_filters_to_subscriber(
871 &self,
872 sid: u32,
873 filters: crate::server::database::filters::FilterChain,
874 ) {
875 if filters.is_empty() {
876 return;
877 }
878 let mut subs = self.subscribers.lock();
879 if let Some(sub) = subs.iter_mut().find(|s| s.sid == sid) {
880 sub.filters = filters;
881 }
882 }
883
884 /// Remove a subscriber by subscription ID.
885 pub fn remove_subscriber(&self, sid: u32) {
886 let mut subs = self.subscribers.lock();
887 subs.retain(|s| s.sid != sid);
888 }
889}
890
891/// Subscriber-id source for in-process [`PvSubscription`] monitors on a
892/// [`ProcessVariable`]. A `ProcessVariable`'s subscriber `Vec` is disjoint
893/// from any `RecordInstance`'s, so this is independent of the record-side
894/// allocator; it only has to stay unique among the simple-PV subscribers
895/// competing for one PV. Seeded at 1_000_000 for the same reason the
896/// record allocator is — keep in-process sids clear of the low,
897/// client-assigned wire subscription ids the CA server also registers on
898/// the same PV.
899static NEXT_PV_SUB_SID: AtomicU32 = AtomicU32::new(1_000_000);
900
901fn next_pv_sub_sid() -> u32 {
902 NEXT_PV_SUB_SID.fetch_add(1, Ordering::Relaxed)
903}
904
905/// In-process value-change monitor on a simple [`ProcessVariable`], the
906/// counterpart of the record-side `DbSubscription`.
907///
908/// The PUT path (`ProcessVariable::set` / `set_snapshot`) calls
909/// `notify_subscribers`, which fans the new value out to every registered
910/// subscriber, so a consumer holding a `PvSubscription` observes every
911/// later PUT — not just the connect-time snapshot. This mirrors pvxs
912/// `SharedPV::post()` delivering a cloned update to each stored subscriber
913/// (`sharedpv.cpp:417-440`).
914///
915/// The handle owns its `Subscriber` slot: `Drop` removes it, so a dropped
916/// consumer cannot leave a dead subscriber row in
917/// `ProcessVariable.subscribers` — the same leak `DbSubscription`'s `Drop`
918/// closes for records.
919pub struct PvSubscription {
920 reader: EventReader,
921 pv: Arc<ProcessVariable>,
922 sid: u32,
923}
924
925impl PvSubscription {
926 /// Register a value-change monitor on `pv`. Returns `None` when the
927 /// per-PV subscriber cap is reached. The caller emits the initial
928 /// snapshot itself (pvxs `SharedPV::attach` posts the current value
929 /// before storing the subscriber); registering the subscriber *before*
930 /// reading that snapshot is the miss-free ordering — a PUT racing the
931 /// two is then delivered through the stream rather than lost.
932 pub async fn subscribe(pv: Arc<ProcessVariable>) -> Option<Self> {
933 use crate::server::recgbl::EventMask;
934 // VALUE|LOG matches the record-side `DbSubscription` default so
935 // simple-PV and record-backed monitors gate identically; a
936 // pure-alarm `post_alarm` (ALARM|LOG) still intersects via LOG.
937 let mask = (EventMask::VALUE | EventMask::LOG).bits();
938 let sid = next_pv_sub_sid();
939 // `data_type` is nominal for snapshot consumers: `deliver` ships
940 // the full `Snapshot` and gates only on mask/filters, never on the
941 // stored type — `DbSubscription` likewise registers as `Double`.
942 let reader = pv.add_subscriber(sid, DbFieldType::Double, mask)?;
943 Some(Self { reader, pv, sid })
944 }
945
946 /// Await the next value change as a full `Snapshot`. A consumer that falls
947 /// behind sees the same thing a C monitor does: its earlier distinct queued
948 /// updates, and then — once the queue ran short of room — a tail entry
949 /// carrying the latest value, because further posts replaced that entry in
950 /// place rather than appending (`db_queue_event_log`, `dbEvent.c:812-820`).
951 pub async fn recv_snapshot(&mut self) -> Option<Snapshot> {
952 Some(self.reader.recv().await?.snapshot)
953 }
954
955 /// Non-blocking [`Self::recv_snapshot`]. Delegates to
956 /// [`EventReader::try_recv`] (`event_queue.rs:570`) — same queue, same
957 /// EVENTS_OFF gate, no suspension.
958 ///
959 /// Lets a PVA monitor source that adapts this stream be polled from a
960 /// blocking drain loop with no reactor present
961 /// (`doc/rtems-runtime-portability-design.md` §9 phase 6).
962 pub fn try_recv_snapshot(&mut self) -> Result<Snapshot, TryRecvError> {
963 self.reader.try_recv().map(|e| e.snapshot)
964 }
965
966 /// Await the next change as the full [`MonitorEvent`] — snapshot plus the
967 /// per-event `DBE_*` mask. The mask-carrying counterpart of
968 /// [`recv_snapshot`](Self::recv_snapshot), matching
969 /// `DbSubscription::recv_event` so a consumer can treat a simple-PV and a
970 /// record subscription through one shape.
971 pub async fn recv_event(&mut self) -> Option<MonitorEvent> {
972 self.reader.recv().await
973 }
974
975 /// Non-blocking [`Self::recv_event`].
976 pub fn try_recv_event(&mut self) -> Result<MonitorEvent, TryRecvError> {
977 self.reader.try_recv()
978 }
979}
980
981impl Drop for PvSubscription {
982 fn drop(&mut self) {
983 let pv = self.pv.clone();
984 let sid = self.sid;
985 // Mirror `DbSubscription::drop`: `remove_subscriber` needs an async
986 // lock, so remove the slot off-thread. No current runtime means no
987 // live subscription to clean up.
988 if tokio::runtime::Handle::try_current().is_ok() {
989 crate::runtime::task::spawn(async move {
990 pv.remove_subscriber(sid);
991 });
992 }
993 }
994}
995
996#[cfg(test)]
997mod mask_gate_tests {
998 use super::*;
999
1000 // CA DBE_* monitor mask bits (db_access.h).
1001 const DBE_VALUE: u16 = 1;
1002 const DBE_LOG: u16 = 2;
1003 const DBE_ALARM: u16 = 4;
1004
1005 fn pv() -> ProcessVariable {
1006 ProcessVariable::new("test:pv".into(), EpicsValue::Double(0.0))
1007 }
1008
1009 /// A full-snapshot write must persist alarm + timestamp + userTag so
1010 /// a later `snapshot()` (the GET path) reflects them — not just the
1011 /// live monitor fan-out. A subsequent value-only `set()` carries no
1012 /// explicit metadata and must revert the snapshot to NO_ALARM.
1013 #[epics_macros_rs::epics_test]
1014 async fn set_snapshot_metadata_persists_then_value_set_clears() {
1015 let pv = pv();
1016
1017 // 42 ns exact: a `SystemTime` rounds this to 0 on Windows, so the
1018 // round-trip is built from `WallTime` integers to actually exercise
1019 // sub-100 ns persistence through `PostedMeta`.
1020 let posted_time = WallTime::from_unix(1_600_000_000, 42);
1021 let mut snap = Snapshot::new(EpicsValue::Double(7.0), 3, 2, posted_time);
1022 snap.user_tag = 9;
1023 pv.set_snapshot(snap);
1024
1025 let got = pv.snapshot();
1026 assert_eq!(got.value, EpicsValue::Double(7.0), "value persisted");
1027 assert_eq!(got.alarm.status, 3, "alarm.status persisted to GET");
1028 assert_eq!(got.alarm.severity, 2, "alarm.severity persisted to GET");
1029 assert_eq!(got.user_tag, 9, "userTag persisted to GET");
1030 assert_eq!(got.timestamp, posted_time, "timestamp persisted to GET");
1031
1032 // A plain value write reverts to the bare-PV default.
1033 pv.set(EpicsValue::Double(8.0));
1034 let after = pv.snapshot();
1035 assert_eq!(after.value, EpicsValue::Double(8.0));
1036 assert_eq!(after.alarm.status, 0, "value set clears posted alarm");
1037 assert_eq!(after.alarm.severity, 0, "value set clears posted severity");
1038 assert_eq!(after.user_tag, 0, "value set clears posted userTag");
1039 assert_ne!(
1040 after.timestamp, posted_time,
1041 "value set must restamp the timestamp, not keep the posted one"
1042 );
1043 }
1044
1045 /// a `DBE_ALARM`-only subscriber must not receive a plain
1046 /// value set, but must receive an alarm post.
1047 #[epics_macros_rs::epics_test]
1048 async fn alarm_only_subscriber_skips_value_post() {
1049 let pv = pv();
1050 let mut rx = pv
1051 .add_subscriber(1, DbFieldType::Double, DBE_ALARM)
1052 .expect("subscriber added");
1053 pv.set(EpicsValue::Double(1.0));
1054 assert!(
1055 rx.try_recv().is_err(),
1056 "DBE_ALARM-only subscriber must not receive a value post"
1057 );
1058 pv.post_alarm(2, 3);
1059 assert!(
1060 rx.try_recv().is_ok(),
1061 "DBE_ALARM subscriber must receive an alarm post"
1062 );
1063 }
1064
1065 /// a `DBE_VALUE`-only subscriber must not receive a
1066 /// `post_alarm`, but must receive value sets.
1067 #[epics_macros_rs::epics_test]
1068 async fn value_only_subscriber_skips_alarm_post() {
1069 let pv = pv();
1070 let mut rx = pv
1071 .add_subscriber(1, DbFieldType::Double, DBE_VALUE)
1072 .expect("subscriber added");
1073 pv.post_alarm(2, 3);
1074 assert!(
1075 rx.try_recv().is_err(),
1076 "DBE_VALUE-only subscriber must not receive an alarm post"
1077 );
1078 pv.set(EpicsValue::Double(1.0));
1079 assert!(
1080 rx.try_recv().is_ok(),
1081 "DBE_VALUE subscriber must receive a value post"
1082 );
1083 }
1084
1085 // --- Regression: set_snapshot must reach DBE_LOG and DBE_ALARM-only subs ---
1086
1087 fn snapshot() -> Snapshot {
1088 Snapshot::new(
1089 EpicsValue::Double(2.0),
1090 0,
1091 0,
1092 std::time::SystemTime::UNIX_EPOCH,
1093 )
1094 }
1095
1096 /// A DBE_LOG (archiver) subscriber must receive a set_snapshot post.
1097 #[epics_macros_rs::epics_test]
1098 async fn log_subscriber_receives_snapshot_post() {
1099 let pv = pv();
1100 let mut rx = pv
1101 .add_subscriber(1, DbFieldType::Double, DBE_LOG)
1102 .expect("subscriber added");
1103 pv.set_snapshot(snapshot());
1104 assert!(
1105 rx.try_recv().is_ok(),
1106 "DBE_LOG subscriber must receive a set_snapshot post"
1107 );
1108 }
1109
1110 /// A DBE_ALARM-only subscriber must receive a set_snapshot post.
1111 #[epics_macros_rs::epics_test]
1112 async fn alarm_only_subscriber_receives_snapshot_post() {
1113 let pv = pv();
1114 let mut rx = pv
1115 .add_subscriber(1, DbFieldType::Double, DBE_ALARM)
1116 .expect("subscriber added");
1117 pv.set_snapshot(snapshot());
1118 assert!(
1119 rx.try_recv().is_ok(),
1120 "DBE_ALARM-only subscriber must receive a set_snapshot post"
1121 );
1122 }
1123
1124 /// A DBE_VALUE subscriber must still receive a set_snapshot post.
1125 #[epics_macros_rs::epics_test]
1126 async fn value_subscriber_receives_snapshot_post() {
1127 let pv = pv();
1128 let mut rx = pv
1129 .add_subscriber(1, DbFieldType::Double, DBE_VALUE)
1130 .expect("subscriber added");
1131 pv.set_snapshot(snapshot());
1132 assert!(
1133 rx.try_recv().is_ok(),
1134 "DBE_VALUE subscriber must receive a set_snapshot post"
1135 );
1136 }
1137
1138 /// A `DBE_VALUE | DBE_ALARM` subscriber receives both event classes.
1139 #[epics_macros_rs::epics_test]
1140 async fn both_classes_receive_both_posts() {
1141 let pv = pv();
1142 let mut rx = pv
1143 .add_subscriber(1, DbFieldType::Double, DBE_VALUE | DBE_ALARM)
1144 .expect("subscriber added");
1145 pv.set(EpicsValue::Double(1.0));
1146 assert!(rx.try_recv().is_ok(), "value post delivered to VALUE|ALARM");
1147 pv.post_alarm(2, 3);
1148 assert!(rx.try_recv().is_ok(), "alarm post delivered to VALUE|ALARM");
1149 }
1150
1151 /// A DBE_LOG-only subscriber (archiver) must receive both value
1152 /// events and alarm events. Pre-fix: VALUE-only / ALARM-only post masks
1153 /// never intersected DBE_LOG(2), so archivers received silence.
1154 #[epics_macros_rs::epics_test]
1155 async fn br_r52_log_subscriber_receives_value_and_alarm_events() {
1156 const DBE_LOG: u16 = 2;
1157 let pv = pv();
1158 let mut rx = pv
1159 .add_subscriber(1, DbFieldType::Double, DBE_LOG)
1160 .expect("subscriber added");
1161 pv.set(EpicsValue::Double(1.0));
1162 assert!(
1163 rx.try_recv().is_ok(),
1164 "DBE_LOG subscriber must receive a value post"
1165 );
1166 pv.post_alarm(2, 3);
1167 assert!(
1168 rx.try_recv().is_ok(),
1169 "DBE_LOG subscriber must receive an alarm post"
1170 );
1171 }
1172
1173 /// Every delivered event carries its post's `DBE_*` class — the
1174 /// per-event mask C attaches to the field log (`db_field_log.mask`)
1175 /// and pvxs narrows monitor decoding with (`groupsource.cpp:331-337`).
1176 #[epics_macros_rs::epics_test]
1177 async fn monitor_event_carries_post_class_mask() {
1178 use crate::server::recgbl::EventMask;
1179 let pv = pv();
1180 let mut rx = pv
1181 .add_subscriber(1, DbFieldType::Double, DBE_VALUE | DBE_LOG | DBE_ALARM)
1182 .expect("subscriber added");
1183 pv.set(EpicsValue::Double(1.0));
1184 assert_eq!(
1185 rx.try_recv().expect("value event").mask,
1186 EventMask::VALUE | EventMask::LOG,
1187 "value post carries VALUE|LOG"
1188 );
1189 pv.post_alarm(2, 3);
1190 assert_eq!(
1191 rx.try_recv().expect("alarm event").mask,
1192 EventMask::ALARM | EventMask::LOG,
1193 "alarm post carries ALARM|LOG"
1194 );
1195 }
1196
1197 /// When the queue runs short of room and a post replaces this monitor's
1198 /// last entry in place, the surviving entry's mask is the OR of the
1199 /// displaced event's class and its own: the displaced *value* is gone (C
1200 /// frees the field log), but a narrow consumer must still learn that an
1201 /// ALARM-class change happened inside the coalesced tail.
1202 #[epics_macros_rs::epics_test]
1203 async fn in_place_replacement_accumulates_event_class_masks() {
1204 use crate::server::event_queue::{event_que_size, events_per_que};
1205 use crate::server::recgbl::EventMask;
1206 let pv = Arc::new(ProcessVariable::new(
1207 "coalesce:mask".into(),
1208 EpicsValue::Double(0.0),
1209 ));
1210 let mut reader = pv
1211 .add_subscriber(7, DbFieldType::Double, DBE_VALUE | DBE_LOG | DBE_ALARM)
1212 .expect("subscriber added");
1213 // Append VALUE|LOG posts until the ring space reaches the replace
1214 // threshold; from here every post overwrites the tail entry.
1215 let appended = event_que_size() - events_per_que();
1216 for i in 1..=appended {
1217 pv.set(EpicsValue::Double(i as f64));
1218 }
1219 // Replaces the tail: its class (ALARM|LOG) must not be lost.
1220 pv.post_alarm(2, 3);
1221 // Replaces it again with a value post — both classes fold into the
1222 // survivor.
1223 pv.set(EpicsValue::Double(99.0));
1224
1225 let mut last = None;
1226 while let Ok(event) = reader.try_recv() {
1227 last = Some(event);
1228 }
1229 let delivered = last.expect("the tail entry is delivered");
1230 assert_eq!(
1231 delivered.snapshot.value.to_f64(),
1232 Some(99.0),
1233 "the tail entry carries the newest value"
1234 );
1235 assert!(
1236 delivered
1237 .mask
1238 .contains(EventMask::VALUE | EventMask::ALARM | EventMask::LOG),
1239 "the displaced alarm class survives in the delivered mask (got {:?})",
1240 delivered.mask
1241 );
1242 }
1243
1244 /// R8-22 (simple-PV path): a monitor whose queue runs out of room during a
1245 /// burst must receive its EARLIER DISTINCT queued updates and then a tail
1246 /// entry carrying the latest value — C `db_queue_event_log` replaces only
1247 /// `*pLastLog` (`dbEvent.c:812-820`) and leaves the earlier entries queued.
1248 ///
1249 /// The old primitive parked the newest value in a side coalesce slot, and
1250 /// the consumer, finding it set, discarded the ENTIRE queued backlog and
1251 /// delivered only that newest value — so a 200-post burst came out as a
1252 /// single event instead of {1..107, 200}.
1253 #[epics_macros_rs::epics_test]
1254 async fn r8_22_pv_burst_keeps_earlier_distinct_updates() {
1255 use crate::server::event_queue::{event_que_size, events_per_que};
1256 use std::time::Duration;
1257 let pv = Arc::new(ProcessVariable::new(
1258 "coalesce:pv".into(),
1259 EpicsValue::Double(0.0),
1260 ));
1261 let mut sub = PvSubscription::subscribe(pv.clone())
1262 .await
1263 .expect("subscribe");
1264 // With nothing draining, the first `appended` posts take ring entries
1265 // and every later post replaces the tail entry in place.
1266 let appended = event_que_size() - events_per_que();
1267 let burst = appended + 92;
1268 for i in 1..=burst {
1269 pv.set(EpicsValue::Double(i as f64));
1270 }
1271 let mut seq = Vec::new();
1272 while let Ok(Some(snap)) =
1273 crate::runtime::task::timeout(Duration::from_millis(200), sub.recv_snapshot()).await
1274 {
1275 seq.push(snap.value.to_f64().expect("double value"));
1276 }
1277 let want: Vec<f64> = (1..appended)
1278 .map(|i| i as f64)
1279 .chain(std::iter::once(burst as f64))
1280 .collect();
1281 assert_eq!(
1282 seq, want,
1283 "burst delivery must be {{earlier distinct backlog…, coalesced tail}}"
1284 );
1285 }
1286}
1287
1288#[cfg(test)]
1289mod metadata_tests {
1290 use super::*;
1291
1292 fn meta() -> PvMetadata {
1293 PvMetadata {
1294 display: Some(DisplayInfo {
1295 units: "degC".into(),
1296 precision: 2,
1297 upper_disp_limit: 100.0,
1298 lower_disp_limit: -50.0,
1299 upper_alarm_limit: 90.0,
1300 upper_warning_limit: 80.0,
1301 lower_warning_limit: -20.0,
1302 lower_alarm_limit: -40.0,
1303 ..Default::default()
1304 }),
1305 control: Some(ControlInfo {
1306 upper_ctrl_limit: 95.0,
1307 lower_ctrl_limit: -45.0,
1308 }),
1309 enums: None,
1310 }
1311 }
1312
1313 fn pv() -> ProcessVariable {
1314 ProcessVariable::new("m:pv".into(), EpicsValue::Double(1.0))
1315 }
1316
1317 /// `set_with_origin` tags the value event with the writer's origin,
1318 /// plain `set` stays untagged, and a plain `set` inside an
1319 /// `AmbientWriteOriginScope` inherits the scope's origin — the
1320 /// simple-PV side of the record funnels' inheritance rule.
1321 #[epics_macros_rs::epics_test]
1322 async fn set_with_origin_tags_the_value_event() {
1323 const DBE_VALUE: u16 = 1;
1324 let pv = pv();
1325 let mut rx = pv
1326 .add_subscriber(1, DbFieldType::Double, DBE_VALUE)
1327 .expect("subscriber added");
1328
1329 pv.set(EpicsValue::Double(2.0));
1330 assert_eq!(rx.try_recv().expect("plain set posts").origin, 0);
1331
1332 pv.set_with_origin(EpicsValue::Double(3.0), 77);
1333 assert_eq!(rx.try_recv().expect("tagged set posts").origin, 77);
1334
1335 {
1336 let _scope = crate::server::record::ambient_write_origin_scope(88);
1337 pv.set(EpicsValue::Double(4.0));
1338 }
1339 assert_eq!(
1340 rx.try_recv().expect("ambient-scoped set posts").origin,
1341 88,
1342 "an originless simple-PV post inside an ambient scope must inherit it"
1343 );
1344 }
1345
1346 /// A bare PV serves no metadata until a proxy installs it; after
1347 /// `set_metadata`, the GET snapshot carries the shadow DBR_GR/DBR_CTRL.
1348 #[epics_macros_rs::epics_test]
1349 async fn set_metadata_serves_on_get_snapshot() {
1350 let pv = pv();
1351 assert!(
1352 pv.snapshot().display.is_none(),
1353 "bare PV must carry no metadata before install"
1354 );
1355 pv.set_metadata(meta());
1356 let snap = pv.snapshot();
1357 let d = snap.display.expect("display installed");
1358 assert_eq!(d.units, "degC");
1359 assert_eq!(d.precision, 2);
1360 assert_eq!(
1361 snap.control.expect("control installed").upper_ctrl_limit,
1362 95.0
1363 );
1364 }
1365
1366 /// A CTRL-type monitor must see the installed limits on every value
1367 /// event, not only the initial GET — value posts carry the metadata.
1368 #[epics_macros_rs::epics_test]
1369 async fn installed_metadata_rides_value_posts() {
1370 const DBE_VALUE: u16 = 1;
1371 let pv = pv();
1372 pv.set_metadata(meta());
1373 let mut rx = pv
1374 .add_subscriber(1, DbFieldType::Double, DBE_VALUE)
1375 .expect("subscriber added");
1376 pv.set(EpicsValue::Double(2.0));
1377 let ev = rx.try_recv().expect("value event delivered");
1378 assert_eq!(
1379 ev.snapshot.display.expect("metadata on value post").units,
1380 "degC"
1381 );
1382 }
1383
1384 /// `apply_metadata` only supplies fields the caller left absent: a
1385 /// gateway snapshot that already carries its own display wins.
1386 #[epics_macros_rs::epics_test]
1387 async fn apply_metadata_does_not_clobber_caller_metadata() {
1388 const DBE_VALUE: u16 = 1;
1389 let pv = pv();
1390 pv.set_metadata(meta()); // installed units = degC
1391 let mut rx = pv
1392 .add_subscriber(1, DbFieldType::Double, DBE_VALUE)
1393 .expect("subscriber added");
1394 let mut snap = Snapshot::new(
1395 EpicsValue::Double(3.0),
1396 0,
1397 0,
1398 std::time::SystemTime::UNIX_EPOCH,
1399 );
1400 snap.display = Some(DisplayInfo {
1401 units: "volts".into(),
1402 ..Default::default()
1403 });
1404 pv.set_snapshot(snap);
1405 let ev = rx.try_recv().expect("snapshot delivered");
1406 assert_eq!(
1407 ev.snapshot.display.expect("caller display kept").units,
1408 "volts"
1409 );
1410 }
1411
1412 /// `post_property` reaches DBE_PROPERTY subscribers (carrying the
1413 /// metadata) and not DBE_VALUE-only subscribers.
1414 #[epics_macros_rs::epics_test]
1415 async fn post_property_reaches_only_property_subscribers() {
1416 const DBE_VALUE: u16 = 1;
1417 const DBE_PROPERTY: u16 = 8;
1418 let pv = pv();
1419 pv.set_metadata(meta());
1420 let mut prop_rx = pv
1421 .add_subscriber(1, DbFieldType::Double, DBE_PROPERTY)
1422 .expect("subscriber added");
1423 let mut val_rx = pv
1424 .add_subscriber(2, DbFieldType::Double, DBE_VALUE)
1425 .expect("subscriber added");
1426 pv.post_property(Snapshot::new(
1427 EpicsValue::Double(1.0),
1428 0,
1429 0,
1430 std::time::SystemTime::UNIX_EPOCH,
1431 ))
1432 .await;
1433 let ev = prop_rx
1434 .try_recv()
1435 .expect("DBE_PROPERTY subscriber receives property post");
1436 assert_eq!(
1437 ev.snapshot
1438 .display
1439 .expect("property post carries metadata")
1440 .units,
1441 "degC"
1442 );
1443 assert!(
1444 val_rx.try_recv().is_err(),
1445 "DBE_VALUE-only subscriber must not receive a property post"
1446 );
1447 }
1448
1449 /// A property post
1450 /// must carry the upstream CTRL event's status/severity and timestamp,
1451 /// not a fabricated `NO_ALARM` / wall-clock-now snapshot. C ca-gateway
1452 /// preserves `setStatSevr()` on the property callback
1453 /// (`gatePv.cc:2413-2438`); a downstream `DBE_PROPERTY` monitor must
1454 /// see `severity=MAJOR` and the upstream timestamp, even though only
1455 /// metadata changed.
1456 #[epics_macros_rs::epics_test]
1457 async fn post_property_preserves_upstream_alarm_and_timestamp() {
1458 const DBE_PROPERTY: u16 = 8;
1459 const MAJOR: u16 = 2; // epicsSevMajor
1460 const HIGH: u16 = 3; // epicsAlarmHigh
1461 let pv = pv();
1462 pv.set_metadata(meta());
1463 let mut prop_rx = pv
1464 .add_subscriber(1, DbFieldType::Double, DBE_PROPERTY)
1465 .expect("subscriber added");
1466 // The upstream CTRL event timestamp: a fixed point in the past, so
1467 // it is unmistakably NOT a fresh wall clock minted by the post.
1468 let upstream_ts = WallTime::from_unix(1_000_000, 0);
1469 pv.post_property(Snapshot::new(
1470 EpicsValue::Double(2.0),
1471 HIGH,
1472 MAJOR,
1473 upstream_ts,
1474 ))
1475 .await;
1476 let ev = prop_rx.try_recv().expect("property post delivered");
1477 assert_eq!(
1478 ev.snapshot.alarm.severity, MAJOR,
1479 "property post must carry the upstream MAJOR severity, not NO_ALARM"
1480 );
1481 assert_eq!(ev.snapshot.alarm.status, HIGH, "upstream status preserved");
1482 assert_eq!(
1483 ev.snapshot.timestamp, upstream_ts,
1484 "property post must keep the upstream timestamp, not a fresh wall clock"
1485 );
1486 // Shadow metadata is still overlaid onto the upstream snapshot.
1487 assert_eq!(
1488 ev.snapshot
1489 .display
1490 .expect("property post carries shadow metadata")
1491 .units,
1492 "degC"
1493 );
1494 }
1495}
1496
1497#[cfg(test)]
1498mod read_hook_tests {
1499 use super::*;
1500
1501 fn pv() -> ProcessVariable {
1502 ProcessVariable::new("g:pv".into(), EpicsValue::Double(1.0))
1503 }
1504
1505 /// No hook installed (the default for every record-backed and cached
1506 /// PV): `read_snapshot` is exactly `snapshot` wrapped in `Ok` — the
1507 /// stored value, byte-for-byte unchanged.
1508 #[epics_macros_rs::epics_test]
1509 async fn read_snapshot_without_hook_equals_snapshot() {
1510 let pv = pv();
1511 let read = pv.read_snapshot().await.expect("no-hook read never errors");
1512 let stored = pv.snapshot();
1513 assert_eq!(read.value, stored.value);
1514 assert_eq!(read.value, EpicsValue::Double(1.0));
1515 }
1516
1517 /// With a hook installed (no-cache mode), the GET value comes fresh
1518 /// from the hook, NOT from the stored shadow value — the stored value
1519 /// stays a stale sentinel that the hook overrides.
1520 #[epics_macros_rs::epics_test]
1521 async fn read_snapshot_fires_hook_for_fresh_value() {
1522 let pv = pv();
1523 // Stored shadow value is a sentinel the hook must override.
1524 pv.set(EpicsValue::Double(999.0));
1525 pv.set_read_hook(Arc::new(|| {
1526 Box::pin(async {
1527 Ok(Snapshot::new(
1528 EpicsValue::Double(42.0),
1529 0,
1530 0,
1531 std::time::UNIX_EPOCH,
1532 ))
1533 })
1534 }));
1535 let read = pv.read_snapshot().await.expect("hook returns Ok");
1536 assert_eq!(
1537 read.value,
1538 EpicsValue::Double(42.0),
1539 "GET must serve the hook's fresh value, not the stored sentinel"
1540 );
1541 }
1542
1543 /// A hook failure propagates so the server can answer `ECA_GETFAIL`,
1544 /// matching C ca-gateway forwarding each read to the IOC.
1545 #[epics_macros_rs::epics_test]
1546 async fn read_snapshot_propagates_hook_error() {
1547 let pv = pv();
1548 pv.set_read_hook(Arc::new(|| Box::pin(async { Err(CaError::Disconnected) })));
1549 let err = pv.read_snapshot().await.expect_err("hook error propagates");
1550 assert!(matches!(err, CaError::Disconnected));
1551 }
1552
1553 /// No hook (every record-backed and cached PV): the sync companion
1554 /// `read_snapshot_local` yields `Some(snapshot)`, byte-for-byte the same
1555 /// value as `snapshot` / the async `read_snapshot` — the fully sans-io
1556 /// GET path.
1557 #[test]
1558 fn read_snapshot_local_without_hook_is_some_and_matches_snapshot() {
1559 let pv = pv();
1560 let local = pv
1561 .read_snapshot_local()
1562 .expect("no hook ⇒ sync snapshot is Some");
1563 assert_eq!(local.value, pv.snapshot().value);
1564 assert_eq!(local.value, EpicsValue::Double(1.0));
1565 }
1566
1567 /// A read hook installed (gateway no-cache): the sync companion returns
1568 /// `None`, the signal that the caller must take the async upstream-GET
1569 /// path — `read_snapshot_local` never fires the hook itself.
1570 #[test]
1571 fn read_snapshot_local_with_hook_is_none() {
1572 let pv = pv();
1573 pv.set_read_hook(Arc::new(|| {
1574 Box::pin(async {
1575 Ok(Snapshot::new(
1576 EpicsValue::Double(42.0),
1577 0,
1578 0,
1579 std::time::UNIX_EPOCH,
1580 ))
1581 })
1582 }));
1583 assert!(
1584 pv.read_snapshot_local().is_none(),
1585 "a read hook ⇒ the sync path defers to the async upstream GET"
1586 );
1587 }
1588
1589 /// The read hook is GET-path only: `snapshot` (monitor fan-out, the
1590 /// initial monitor event, access-rights re-posts) keeps serving the
1591 /// stored value even when a hook is installed.
1592 #[epics_macros_rs::epics_test]
1593 async fn snapshot_ignores_read_hook() {
1594 let pv = pv();
1595 pv.set(EpicsValue::Double(7.0));
1596 pv.set_read_hook(Arc::new(|| {
1597 Box::pin(async {
1598 Ok(Snapshot::new(
1599 EpicsValue::Double(42.0),
1600 0,
1601 0,
1602 std::time::UNIX_EPOCH,
1603 ))
1604 })
1605 }));
1606 let snap = pv.snapshot();
1607 assert_eq!(
1608 snap.value,
1609 EpicsValue::Double(7.0),
1610 "snapshot must serve the stored value, never the read hook"
1611 );
1612 }
1613
1614 /// Fresh value + upstream alarm/time ride from the hook; the shadow's
1615 /// installed *property* metadata (display/control/enum) — which a
1616 /// `DBR_TIME_*` event does not carry — is overlaid for those fields.
1617 #[epics_macros_rs::epics_test]
1618 async fn read_snapshot_carries_shadow_metadata() {
1619 let pv = pv();
1620 pv.set_metadata(PvMetadata {
1621 display: Some(DisplayInfo {
1622 units: "mm".into(),
1623 precision: 3,
1624 ..Default::default()
1625 }),
1626 control: None,
1627 enums: None,
1628 });
1629 // The hook returns a Time-class snapshot (value + alarm + time,
1630 // no display/control/enum), exactly as `get_with_metadata(Time)`.
1631 pv.set_read_hook(Arc::new(|| {
1632 Box::pin(async {
1633 Ok(Snapshot::new(
1634 EpicsValue::Double(5.0),
1635 0,
1636 0,
1637 std::time::UNIX_EPOCH,
1638 ))
1639 })
1640 }));
1641 let read = pv.read_snapshot().await.expect("hook returns Ok");
1642 assert_eq!(read.value, EpicsValue::Double(5.0));
1643 assert_eq!(
1644 read.display
1645 .expect("shadow property metadata rides fresh value")
1646 .units,
1647 "mm"
1648 );
1649 }
1650
1651 /// A no-cache GET must report the FRESH upstream alarm and timestamp
1652 /// that travel with the value (C `getTimeCB` decodes the `DBR_TIME_*`
1653 /// event's status/severity/time before `setEventData`,
1654 /// `gatePv.cc:1789-1794`), NOT the shadow's last monitor-posted (or
1655 /// bare-PV default) alarm/time. Before the fix the read hook returned
1656 /// a bare value and `read_snapshot` grafted it onto the stored
1657 /// snapshot, so the GET reported the new value with a stale or default
1658 /// status/severity/timestamp.
1659 #[epics_macros_rs::epics_test]
1660 async fn read_snapshot_carries_upstream_alarm_not_shadow() {
1661 use std::time::{Duration, UNIX_EPOCH};
1662 let pv = pv();
1663 // The shadow's stored snapshot carries one alarm/time (a prior
1664 // monitor post). Make it concrete and DIFFERENT from the upstream
1665 // GET so a graft-onto-shadow regression is observable.
1666 let shadow_time = UNIX_EPOCH + Duration::from_secs(1_000);
1667 pv.set_snapshot(Snapshot::new(EpicsValue::Double(1.0), 7, 1, shadow_time));
1668 // The fresh upstream GET reports a different value, alarm, and time.
1669 let upstream_time = WallTime::from_unix(2_000, 0);
1670 pv.set_read_hook(Arc::new(move || {
1671 Box::pin(
1672 async move { Ok(Snapshot::new(EpicsValue::Double(5.0), 17, 2, upstream_time)) },
1673 )
1674 }));
1675 let read = pv.read_snapshot().await.expect("hook returns Ok");
1676 assert_eq!(read.value, EpicsValue::Double(5.0), "fresh upstream value");
1677 assert_eq!(
1678 read.alarm.status, 17,
1679 "upstream alarm status, not shadow's 7"
1680 );
1681 assert_eq!(read.alarm.severity, 2, "upstream severity, not shadow's 1");
1682 assert_eq!(
1683 read.timestamp, upstream_time,
1684 "upstream timestamp, not shadow's"
1685 );
1686 }
1687}