ridl_loopback/lib.rs
1//! `ridl-loopback` — the in-process reference runtime.
2//!
3//! This crate implements the twelve port traits of
4//! [`ridl_rt::port`](https://docs.rs/ridl-rt) over one in-memory store. It is
5//! the first runtime in this workspace (ADR-0020 decision 6, which names the
6//! crate and fixes `ridl-rt` as its only dependency), and it is what the
7//! generated interaction face runs against in a test, an example or a
8//! single-process application.
9//!
10//! What it is not:
11//!
12//! - **Not a transport.** It carries no frame, opens no socket and has no wire
13//! format. A value published here is read here, in the same process.
14//! - **Not the engine.** The store below is a map and a queue, not the seqlock
15//! store, the sans-IO session, the platform traits and the scheduler, which
16//! are outside this repository.
17//! - **Not a checker.** Payload bytes are opaque to it: it carries them and
18//! never verifies one. `Payload::verify` is the generated face's, on both
19//! sides.
20//!
21//! # The handles
22//!
23//! A runtime presents one handle type per port role rather than one type
24//! implementing them all, and may also offer an aggregate handle covering the
25//! port set one interface's face needs (ADR-0021 decision 12). This crate
26//! offers both. Its six handles group eleven roles the way that decision
27//! derives the threading split: a handle each for the five roles with a
28//! `&mut self` method, and one handle for the six whose methods all take
29//! `&self`, which are exactly the roles several threads may hold at once. The
30//! twelfth port trait, `Wakeable`, is implemented on every handle, because
31//! each handle wakes its own waiters (see "Waking" below).
32//! [`Loopback`] is the aggregate: it implements all twelve port traits by
33//! delegating to the six role handles it holds, and it is what a generated
34//! `Client`, `Publisher` or `dispatch` is normally built over.
35//!
36//! ```
37//! use ridl_loopback::Loopback;
38//! use ridl_rt::contract::{CatalogHash, CatalogRef, InterfaceNo, Ordinal};
39//! use ridl_rt::port::{SignalReader, SignalWriter};
40//!
41//! let catalog = CatalogRef { name: "face.demo", hash: CatalogHash([0u8; 32]) };
42//! let mut rt = Loopback::new(catalog);
43//!
44//! rt.set(InterfaceNo(1), Ordinal(1), &[42]).expect("staged");
45//! rt.commit();
46//!
47//! let mut out = [0u8; 8];
48//! let sample = rt.read(InterfaceNo(1), Ordinal(1), &mut out).expect("read");
49//! assert_eq!(&out[..sample.len], &[42]);
50//! ```
51//!
52//! [`Loopback::split`] hands out the six role handles for a program that wants
53//! them apart — one thread reading while another publishes, or two callers on
54//! one provider. [`ReaderHandle`] is `Send + Sync`; the other five are `Send`
55//! and driven by one thread each. Nothing here declares either: both follow
56//! from the fields, and the assertions at the bottom of this file pin them.
57//!
58//! # What it reports, and what it cannot
59//!
60//! The loopback holds no catalog descriptor — the descriptor and the catalog
61//! hash arrive with story E16.2 (driftsys/ridl#378) — so it has no member
62//! table, and there is no ordinal it can call unknown, no member it can call
63//! unowned, and no timing annotation it can measure a value's freshness or a
64//! call's remaining time against. What it therefore never returns:
65//! `WriteError::NotOwner`, `RaiseError::NotOwner`, `ServeError::NotOwner`, any
66//! port error's `Contract` variant except
67//! [`FixedReader::read_fixed`](ridl_rt::port::FixedReader::read_fixed)'s, and
68//! `Freshness::Fresh` or `Freshness::Stale`. Nothing detaches, because every
69//! handle holds the store alive, so `Detached` never appears either. The one
70//! bound is the call table's [`Loopback::SLOTS`]: a send with every slot
71//! taken answers `SendError::Busy`. Nothing else is bounded, so `TooLarge`
72//! appears only from [`Loopback::fail_next_settle`], and `Transport::Busy`
73//! reaches a caller only when a provider settles a call with it.
74//!
75//! # Waking
76//!
77//! Every handle implements [`Wakeable`], and a handle stores a waker only
78//! under a kind of key one of its roles observes: a caller handle under
79//! `Interest::Outcome`, kept with each call, and one waker under
80//! `Interest::Slot`, a source handle one waker under `Interest::Event`, and a
81//! handler handle one waker under `Interest::Claim`.
82//! For `Event` and `Claim` the rule is one waker per kind, and a change to
83//! any key of the kind wakes the stored waker, whatever interface it was
84//! registered under (ADR-0021 decision 13); an `Outcome` waker is per call,
85//! and no change but that call's settlement, its `forget`, or the drop of the
86//! caller handle that sent it wakes it (a displacement by another task does,
87//! as for every kind). A settlement wakes the
88//! call's waiter, a raise wakes each source it queues the occurrence for, and
89//! a send wakes each handler that serves the member, and a reclaimed slot of
90//! the call table wakes every caller's `Slot` waiter. A registration whose key
91//! already holds — the outcome is known, an occurrence or a call is waiting, a
92//! slot is free — is woken at once, and so is one under a kind the handle does
93//! not observe. A registration of the waker already stored refreshes it
94//! without waking it. No waker is woken while the store is locked.
95//!
96//! [`Attached::catalog`](ridl_rt::port::Attached::catalog) returns the
97//! `CatalogRef` the runtime was built with, unexamined. ADR-0021 decision 3
98//! places a check of it against the interface's own `CATALOG` in a generated
99//! face's constructor, once, when the face is built; the constructor the Rust
100//! backend emits today performs no such check (driftsys/ridl#448). Either way
101//! it is the face's check and not the runtime's: the loopback carries the
102//! value and compares nothing.
103//!
104//! The crate's as-built design record, with the reasoning behind each of these
105//! choices, is `docs/design/ridl-loopback.md` in this repository.
106
107use std::sync::{Arc, Mutex};
108use std::task::Waker;
109
110use ridl_rt::contract::{CatalogRef, InterfaceNo, Ordinal};
111use ridl_rt::error::CallError;
112use ridl_rt::port::{
113 Attached, Caller, Changed, Claim, ClaimId, Clock, CoherentSignals, Correlation, EventSink,
114 EventSource, FixedReader, Handler, Interest, RaiseError, RawOccurrence, RawSample, ReadError,
115 ScannableSignals, SendError, ServeError, SettleError, SignalReader, SignalWriter,
116 SubscribeError, Wakeable, Watermark, WriteError,
117};
118use ridl_rt::sample::{Duration, Timestamp};
119
120mod handle;
121mod store;
122
123pub use handle::{
124 CallerHandle, HandlerHandle, ReaderHandle, SinkHandle, SourceHandle, WriterHandle,
125};
126
127use handle::{Shared, lock};
128use store::Store;
129
130/// The six role handles of one runtime, as [`Loopback::split`] hands them out.
131pub struct Handles {
132 /// `Attached`, `Clock`, `SignalReader`, `FixedReader`, `ScannableSignals`
133 /// and `CoherentSignals`.
134 pub reader: ReaderHandle,
135 /// `SignalWriter`.
136 pub writer: WriterHandle,
137 /// `EventSource`.
138 pub source: SourceHandle,
139 /// `EventSink`.
140 pub sink: SinkHandle,
141 /// `Caller`.
142 pub caller: CallerHandle,
143 /// `Handler`.
144 pub handler: HandlerHandle,
145}
146
147/// The aggregate handle: one value implementing all twelve port traits by
148/// delegating to the six role handles it holds.
149///
150/// A face is built over one value implementing at least the port traits its
151/// interface needs, and a generated `Client` is commonly bound over
152/// `SignalReader + EventSource + Caller` at once, which no single role handle
153/// satisfies. That is what an aggregate is for (ADR-0021 decision 12). Pass it
154/// by value, or as `&mut` under the forwarding impls of ADR-0021 decision 11.
155pub struct Loopback {
156 shared: Shared,
157 catalog: CatalogRef,
158 handles: Handles,
159}
160
161impl Loopback {
162 /// The number of calls the runtime holds at once. A call holds its slot
163 /// from its send until one of these reclaims it:
164 ///
165 /// - [`Caller::forget`], or the drop of the caller handle that sent it,
166 /// while it is settled or still waiting for a handler;
167 /// - its settlement, when it was forgotten while a handler held it;
168 /// - the drop of the handler that held it unsettled, when it was
169 /// forgotten.
170 ///
171 /// So a settled call keeps its slot until it is forgotten, and a claimed
172 /// call keeps its slot after its `forget` until it is settled or its
173 /// handler is dropped. With every slot taken, [`Caller::command`] and
174 /// [`Caller::query`] answer [`SendError::Busy`], on every caller handle,
175 /// because the table is the runtime's.
176 ///
177 /// Sixteen is a small bound, chosen so that a test reaches it in a few
178 /// sends and a program that never forgets a call finds out at once rather
179 /// than after its memory grows. The loopback has no catalog descriptor to
180 /// size a byte budget from (story E16.2), so the slot count is its only
181 /// bound (note F-9 of the async face design).
182 ///
183 /// The generated async client's future (story E11.21) forgets its call
184 /// when it leaves the waiting phase: in the poll that takes the outcome,
185 /// at the call's deadline, and on drop while the call is still waiting.
186 /// So a program that calls through the generated face holds one slot per
187 /// call in flight. A program that sends through the `Caller` port
188 /// directly must forget each correlation itself once it has read the
189 /// outcome, or drop the caller handle, which forgets that handle's calls;
190 /// otherwise it gets `SendError::Busy` from its seventeenth call on.
191 pub const SLOTS: usize = 16;
192
193 /// A runtime attached to `catalog`, with an empty store and its clock at
194 /// [`Timestamp`] 0.
195 ///
196 /// The catalog is carried, not checked: see the crate documentation.
197 #[must_use]
198 pub fn new(catalog: CatalogRef) -> Self {
199 let shared: Shared = Arc::new(Mutex::new(Store::new()));
200 let handles = Handles {
201 reader: ReaderHandle::new(Arc::clone(&shared), catalog),
202 writer: WriterHandle::new(Arc::clone(&shared), catalog),
203 source: SourceHandle::new(Arc::clone(&shared), catalog),
204 sink: SinkHandle::new(Arc::clone(&shared), catalog),
205 caller: CallerHandle::new(Arc::clone(&shared), catalog),
206 handler: HandlerHandle::new(Arc::clone(&shared), catalog),
207 };
208 Loopback {
209 shared,
210 catalog,
211 handles,
212 }
213 }
214
215 /// Hands out the six role handles this aggregate holds. Every one of them
216 /// keeps the same store, so a value published through `writer` is read
217 /// through `reader`.
218 #[must_use]
219 pub fn split(self) -> Handles {
220 self.handles
221 }
222
223 /// An additional reader handle on the same store.
224 #[must_use]
225 pub fn reader(&self) -> ReaderHandle {
226 ReaderHandle::new(Arc::clone(&self.shared), self.catalog)
227 }
228
229 /// An additional writer handle on the same store, with its own staging
230 /// area and its own per channel sequence counters.
231 #[must_use]
232 pub fn writer(&self) -> WriterHandle {
233 WriterHandle::new(Arc::clone(&self.shared), self.catalog)
234 }
235
236 /// An additional event source on the same store, with its own
237 /// subscription set and its own queue.
238 #[must_use]
239 pub fn source(&self) -> SourceHandle {
240 SourceHandle::new(Arc::clone(&self.shared), self.catalog)
241 }
242
243 /// An additional event sink on the same store, with its own sequence
244 /// counter.
245 #[must_use]
246 pub fn sink(&self) -> SinkHandle {
247 SinkHandle::new(Arc::clone(&self.shared), self.catalog)
248 }
249
250 /// An additional caller on the same store, with its own sequence counter.
251 /// Two callers on one provider therefore never collide on a sequence
252 /// number (driftsys/ridl#308).
253 #[must_use]
254 pub fn caller(&self) -> CallerHandle {
255 CallerHandle::new(Arc::clone(&self.shared), self.catalog)
256 }
257
258 /// An additional handler on the same store.
259 ///
260 /// Every handler draws from the one queue of waiting calls, filtered by
261 /// what it has served: a handler that has served nothing is presented
262 /// every waiting call, and one that has served members is presented only
263 /// those. A claim belongs to the handler it was presented to.
264 #[must_use]
265 pub fn handler(&self) -> HandlerHandle {
266 HandlerHandle::new(Arc::clone(&self.shared), self.catalog)
267 }
268
269 /// Advances the clock by `by`.
270 ///
271 /// The clock is a counter this method moves and nothing else moves. It
272 /// never reads wall-clock time, so a round trip over this runtime produces
273 /// the same timestamps on every run and on every machine. It saturates
274 /// rather than overflowing.
275 ///
276 /// # Panics
277 ///
278 /// When `by` is negative. A clock that ran backwards would stamp an
279 /// envelope before one already stamped.
280 pub fn advance(&mut self, by: Duration) {
281 lock(&self.shared).advance(by);
282 }
283
284 /// Supplies the value of a `fixed` (ridl §8), which is provisioned into a
285 /// runtime rather than published by application code.
286 ///
287 /// Until a `fixed` is provisioned, reading it answers
288 /// `ReadError::Contract(Contract::UnknownInteraction)`: the loopback holds
289 /// no value and, having no member table, cannot say anything narrower.
290 pub fn provision_fixed(&mut self, iface: InterfaceNo, ord: Ordinal, bytes: &[u8]) {
291 lock(&self.shared).provision_fixed(iface, ord, bytes);
292 }
293
294 /// Makes the next `Handler::settle` on this runtime fail with
295 /// `SettleError::TooLarge` and record no outcome.
296 ///
297 /// This is the one fault this runtime injects, and the one place a
298 /// `SettleError` other than `UnknownClaim` comes from. It exists because
299 /// the generated `dispatch` counts a claim only once the handler has
300 /// accepted its settlement, and nothing else in an in-process runtime can
301 /// make that path fail.
302 pub fn fail_next_settle(&mut self) {
303 lock(&self.shared).fail_next_settle();
304 }
305}
306
307// ---------------------------------------------------------------------------
308// The aggregate's twelve port implementations, each one a delegation.
309// ---------------------------------------------------------------------------
310
311impl Attached for Loopback {
312 fn catalog(&self) -> &CatalogRef {
313 self.handles.reader.catalog()
314 }
315}
316
317impl Clock for Loopback {
318 fn now(&self) -> Timestamp {
319 self.handles.reader.now()
320 }
321}
322
323impl SignalReader for Loopback {
324 fn read(
325 &self,
326 iface: InterfaceNo,
327 ord: Ordinal,
328 out: &mut [u8],
329 ) -> Result<RawSample, ReadError> {
330 self.handles.reader.read(iface, ord, out)
331 }
332}
333
334impl FixedReader for Loopback {
335 fn read_fixed(
336 &self,
337 iface: InterfaceNo,
338 ord: Ordinal,
339 out: &mut [u8],
340 ) -> Result<usize, ReadError> {
341 self.handles.reader.read_fixed(iface, ord, out)
342 }
343}
344
345impl ScannableSignals for Loopback {
346 fn generation(&self, iface: InterfaceNo) -> u64 {
347 self.handles.reader.generation(iface)
348 }
349
350 fn scan(&self, marks: &mut [Watermark], out: &mut [Changed]) -> usize {
351 self.handles.reader.scan(marks, out)
352 }
353}
354
355impl CoherentSignals for Loopback {
356 fn read_coherent(
357 &self,
358 iface: InterfaceNo,
359 ords: &[Ordinal],
360 out: &mut [u8],
361 samples: &mut [RawSample],
362 ) -> Result<usize, ReadError> {
363 self.handles.reader.read_coherent(iface, ords, out, samples)
364 }
365}
366
367impl SignalWriter for Loopback {
368 fn set(&mut self, iface: InterfaceNo, ord: Ordinal, bytes: &[u8]) -> Result<(), WriteError> {
369 self.handles.writer.set(iface, ord, bytes)
370 }
371
372 fn invalidate(&mut self, iface: InterfaceNo, ord: Ordinal) -> Result<(), WriteError> {
373 self.handles.writer.invalidate(iface, ord)
374 }
375
376 fn touch(&mut self, iface: InterfaceNo, ord: Ordinal) -> Result<(), WriteError> {
377 self.handles.writer.touch(iface, ord)
378 }
379
380 fn commit(&mut self) {
381 self.handles.writer.commit();
382 }
383}
384
385impl EventSource for Loopback {
386 fn subscribe(&mut self, iface: InterfaceNo, ords: &[Ordinal]) -> Result<(), SubscribeError> {
387 self.handles.source.subscribe(iface, ords)
388 }
389
390 fn unsubscribe(&mut self, iface: InterfaceNo, ords: &[Ordinal]) {
391 self.handles.source.unsubscribe(iface, ords);
392 }
393
394 fn next(&mut self, out: &mut [u8]) -> Result<Option<RawOccurrence>, ReadError> {
395 self.handles.source.next(out)
396 }
397}
398
399impl EventSink for Loopback {
400 fn raise(&mut self, iface: InterfaceNo, ord: Ordinal, bytes: &[u8]) -> Result<(), RaiseError> {
401 self.handles.sink.raise(iface, ord, bytes)
402 }
403}
404
405impl Caller for Loopback {
406 fn command(
407 &mut self,
408 iface: InterfaceNo,
409 ord: Ordinal,
410 args: &[u8],
411 ) -> Result<Correlation, SendError> {
412 self.handles.caller.command(iface, ord, args)
413 }
414
415 fn query(
416 &mut self,
417 iface: InterfaceNo,
418 ord: Ordinal,
419 args: &[u8],
420 ) -> Result<Correlation, SendError> {
421 self.handles.caller.query(iface, ord, args)
422 }
423
424 fn ack(&mut self, c: Correlation) -> Option<Result<(), CallError>> {
425 self.handles.caller.ack(c)
426 }
427
428 fn reply(
429 &mut self,
430 c: Correlation,
431 out: &mut [u8],
432 ) -> Result<Option<Result<usize, CallError>>, ReadError> {
433 self.handles.caller.reply(c, out)
434 }
435
436 fn forget(&mut self, c: Correlation) {
437 self.handles.caller.forget(c);
438 }
439}
440
441impl Handler for Loopback {
442 fn serve(&mut self, iface: InterfaceNo, ords: &[Ordinal]) -> Result<(), ServeError> {
443 self.handles.handler.serve(iface, ords)
444 }
445
446 fn next_claim(&mut self, out: &mut [u8]) -> Result<Option<Claim>, ReadError> {
447 self.handles.handler.next_claim(out)
448 }
449
450 fn settle(
451 &mut self,
452 claim: ClaimId,
453 outcome: Result<&[u8], CallError>,
454 ) -> Result<(), SettleError> {
455 self.handles.handler.settle(claim, outcome)
456 }
457}
458
459/// Each key goes to the handle that observes it: `Outcome` and `Slot` to the
460/// caller, `Event` to the source, and `Claim` to the handler.
461impl Wakeable for Loopback {
462 fn wake_on(&self, what: Interest, waker: &Waker) {
463 match what {
464 Interest::Outcome(_) | Interest::Slot => self.handles.caller.wake_on(what, waker),
465 Interest::Event(_) => self.handles.source.wake_on(what, waker),
466 Interest::Claim(_) => self.handles.handler.wake_on(what, waker),
467 }
468 }
469}
470
471// ---------------------------------------------------------------------------
472// The threading model, asserted rather than documented (ADR-0021 decision 12).
473// ---------------------------------------------------------------------------
474
475const _: () = {
476 const fn assert_sync<T: Sync>() {}
477 const fn assert_send<T: Send>() {}
478
479 // Several threads may read one store at once.
480 assert_sync::<ReaderHandle>();
481 assert_send::<ReaderHandle>();
482
483 // One thread drives each of the rest.
484 assert_send::<WriterHandle>();
485 assert_send::<SourceHandle>();
486 assert_send::<SinkHandle>();
487 assert_send::<CallerHandle>();
488 assert_send::<HandlerHandle>();
489
490 // The aggregate is as `Send` as the handles it holds.
491 assert_send::<Loopback>();
492};