ridl_rt/contract.rs
1//! Identity, and the interaction descriptors generated code writes.
2//!
3//! A descriptor is a zero-sized marker type with constants. The descriptors
4//! are the per-member form of the ordinal table of ADR-0013 decision 3,
5//! extended with the interface number and the catalog hash.
6//!
7//! Two computations read the descriptors: a member's call deadline
8//! ([`Member::call_deadline`]) and the in-flight byte budget
9//! ([`Member::reservation`], [`table_budget`]).
10
11use crate::encoding::Encoding;
12use crate::sample::Duration;
13
14/// A member's ordinal: its position in the interface body, counted from 1
15/// (ridl §11). An ordinal is never 0.
16#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub struct Ordinal(pub u32);
18
19/// An interface's number in its catalog: the number the lock file froze, or a
20/// provisional number. An interface number is never 0.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
22pub struct InterfaceNo(pub u32);
23
24/// The catalog hash: SHA-256 over the catalog's interfaces, their numbers, and
25/// the types they reach.
26#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
27pub struct CatalogHash(pub [u8; 32]);
28
29/// A catalog: one package's interfaces.
30///
31/// Two `CatalogRef`s are equal only when both the names and the hashes are
32/// equal, because two packages with the same contents can have the same hash.
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct CatalogRef {
35 /// The package name.
36 pub name: &'static str,
37 /// The catalog hash.
38 pub hash: CatalogHash,
39}
40
41/// The five interaction kinds of the language.
42#[repr(u8)]
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
44pub enum Kind {
45 /// A `signal`.
46 Signal = 1,
47 /// An `event`.
48 Event = 2,
49 /// A `command`.
50 Command = 3,
51 /// A `query`.
52 Query = 4,
53 /// A `fixed`.
54 Fixed = 5,
55}
56
57/// An interface's descriptor.
58pub trait Interface {
59 /// The catalog the interface belongs to.
60 const CATALOG: &'static CatalogRef;
61 /// The interface number in that catalog.
62 const NUMBER: InterfaceNo;
63 /// `true` when the number is provisional, not yet frozen in the lock file.
64 const PROVISIONAL: bool;
65 /// The interface name.
66 const NAME: &'static str;
67 /// The members, in ordinal order. A reserved ordinal has no row, so the
68 /// index of a row is not its ordinal minus one.
69 const MEMBERS: &'static [Member];
70}
71
72/// An interaction's descriptor: the part every kind has.
73pub trait Interaction {
74 /// The interface that declares the interaction.
75 type Iface: Interface;
76 /// The interaction's row in `Iface::MEMBERS`.
77 const MEMBER: &'static Member;
78}
79
80/// A `signal` (ridl §4).
81pub trait Signal: Interaction {
82 /// The value type.
83 type Payload;
84 /// The channel's init value (ridl §4.4).
85 fn init() -> Self::Payload;
86}
87
88/// An `event` (ridl §5).
89pub trait Event: Interaction {
90 /// The occurrence type.
91 type Payload;
92}
93
94/// A `fixed` (ridl §8).
95pub trait Fixed: Interaction {
96 /// The provisioned value type.
97 type Payload;
98}
99
100/// A `command` (ridl §6).
101pub trait Command: Interaction {
102 /// The argument type.
103 type Args;
104 /// Evaluates the command's `require` clauses. `Ok` when every clause is
105 /// true or the command declares none. `Err` when a clause is false, which
106 /// the provider reports as
107 /// [`Contract::PreconditionFailed`](crate::error::Contract::PreconditionFailed).
108 #[allow(
109 clippy::result_unit_err,
110 reason = "the failing method decides the contract error, so the error carries no value"
111 )]
112 fn require(args: &Self::Args) -> Result<(), ()>;
113}
114
115/// A `query` (ridl §7).
116pub trait Query: Interaction {
117 /// The argument type.
118 type Args;
119 /// The reply type.
120 type Reply;
121 /// Evaluates the query's `require` clauses. `Ok` when every clause is
122 /// true or the query declares none. `Err` when a clause is false, which
123 /// the provider reports as
124 /// [`Contract::PreconditionFailed`](crate::error::Contract::PreconditionFailed).
125 #[allow(
126 clippy::result_unit_err,
127 reason = "the failing method decides the contract error, so the error carries no value"
128 )]
129 fn require(args: &Self::Args) -> Result<(), ()>;
130 /// Evaluates the query's `ensure` clauses. `Ok` when every clause is true
131 /// or the query declares none. `Err` when a clause is false, which the
132 /// provider reports as
133 /// [`Contract::ContractBroken`](crate::error::Contract::ContractBroken).
134 #[allow(
135 clippy::result_unit_err,
136 reason = "the failing method decides the contract error, so the error carries no value"
137 )]
138 fn ensure(args: &Self::Args, reply: &Self::Reply) -> Result<(), ()>;
139}
140
141/// One member of an interface.
142#[derive(Clone, Copy, Debug, PartialEq, Eq)]
143pub struct Member {
144 /// The member's ordinal.
145 pub ordinal: Ordinal,
146 /// The member's kind.
147 pub kind: Kind,
148 /// The member's name.
149 pub name: &'static str,
150 /// The member's timing, as the IR resolved it. `None` when the IR carries
151 /// no timing: a `command` or a `query` with no timing annotation, or a
152 /// `fixed`.
153 pub timing: Option<Timing>,
154 /// One entry per payload: two for a `query` (the request, then the
155 /// reply), one for every other kind.
156 pub payloads: &'static [PayloadInfo],
157}
158
159impl Member {
160 /// The call deadline: the `max` of the member's `timing`, which on a
161 /// `command` or a `query` is the response bound (ridl §9.3).
162 ///
163 /// `None` when `timing` is `None` — a `command` or a `query` with no
164 /// timing annotation, which is never given a default (ridl §9.1) — or
165 /// when the timing has no `max`, as under `@[20ms..]`. This function
166 /// takes no position on what a caller does with `None`.
167 ///
168 /// The function reads `max` whatever the member's `kind`. On a `signal`
169 /// `max` is the staleness bound and on an `event` the time to live
170 /// (ridl §9), neither of which is a call deadline, so call it on a
171 /// `command` or a `query`.
172 pub fn call_deadline(&self) -> Option<Duration> {
173 self.timing.and_then(|timing| timing.max)
174 }
175
176 /// The bytes one in-flight instance of this member reserves in encoding
177 /// `E`: the sum of `PayloadInfo::max_size` for `E` over its `payloads` —
178 /// one payload for most kinds, two for a `query`, the request and then the
179 /// reply.
180 ///
181 /// No specification defines this budget. It is derived from the
182 /// descriptors alone, so that every runtime sizing a table of calls in
183 /// flight computes the same number.
184 ///
185 /// # Errors
186 ///
187 /// [`Unsized`], naming this member and the first payload whose size for
188 /// `E` is `None`. A missing size is reported, never replaced by an
189 /// estimate.
190 pub fn reservation<E: Encoding>(&self) -> Result<u64, Unsized> {
191 let mut total: u64 = 0;
192 for payload in self.payloads {
193 let size = E::max_size(&payload.max_size).ok_or(Unsized {
194 ordinal: self.ordinal,
195 member: self.name,
196 type_name: payload.type_name,
197 })?;
198 total = total.saturating_add(u64::from(size));
199 }
200 Ok(total)
201 }
202}
203
204/// The in-flight byte budget of a table of members in encoding `E`: the sum of
205/// [`Member::reservation`] over `members`. Pass an interface's
206/// `Interface::MEMBERS`; a table serving several interfaces adds the budget of
207/// each.
208///
209/// No specification defines this budget. It is derived from the descriptors
210/// alone, and it counts every member it is given, whatever its kind.
211///
212/// # Errors
213///
214/// [`Unsized`] for the first member, in the order given, whose reservation has
215/// a payload with no size for `E`.
216pub fn table_budget<E: Encoding>(members: &[Member]) -> Result<u64, Unsized> {
217 let mut total: u64 = 0;
218 for member in members {
219 total = total.saturating_add(member.reservation::<E>()?);
220 }
221 Ok(total)
222}
223
224/// A payload with no size in the encoding a budget was asked for: its
225/// `EncodedSizes` field for that encoding is `None`. The budget is not
226/// computed, because a missing size is not estimated.
227#[derive(Clone, Copy, Debug, PartialEq, Eq)]
228#[non_exhaustive]
229pub struct Unsized {
230 /// The member's ordinal.
231 pub ordinal: Ordinal,
232 /// The member's name.
233 pub member: &'static str,
234 /// The name of the payload type that has no size.
235 pub type_name: &'static str,
236}
237
238/// The form of a timing annotation (ridl §9).
239#[derive(Clone, Copy, Debug, PartialEq, Eq)]
240pub enum TimingMode {
241 /// `@Xms`: a strict period, on a signal only (ridl §9.2).
242 StrictPeriodic,
243 /// `@[min..max]`, where either side may be absent.
244 Range,
245}
246
247/// A member's timing (ridl §9).
248///
249/// `max` is the staleness bound of a signal, the time to live of an event, and
250/// the response bound of a call.
251///
252/// Under `StrictPeriodic`, `min` and `max` both hold the period.
253#[derive(Clone, Copy, Debug, PartialEq, Eq)]
254pub struct Timing {
255 /// The form of the annotation.
256 pub mode: TimingMode,
257 /// The lower bound. `None` when the IR leaves it unset.
258 pub min: Option<Duration>,
259 /// The upper bound. `None` when the IR leaves it unset.
260 pub max: Option<Duration>,
261}
262
263/// One payload of a member.
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
265pub struct PayloadInfo {
266 /// The payload type's name.
267 pub type_name: &'static str,
268 /// The payload's largest encoded size in each core encoding.
269 pub max_size: EncodedSizes,
270}
271
272/// A payload's largest encoded size in bytes, one field per core encoding.
273///
274/// A field is `None` when the toolchain cannot size the payload for that
275/// encoding. That covers two cases the reader does not have to tell apart: the
276/// encoding cannot carry the payload at all, and the encoding can carry it but
277/// the size is not derivable yet, because the story that defines the layout has
278/// not landed. The `repr(C)` column is `None` for every payload until E11.12
279/// defines the C-representable layout, and a backend that emits descriptors
280/// before its codec exists writes `None` for that codec's column too.
281///
282/// So a consumer reads `None` as "no size is available here", never as "this
283/// payload cannot be encoded this way", and asks the catalog descriptor rather
284/// than this field when it needs to know which encodings a payload has.
285#[derive(Clone, Copy, Debug, PartialEq, Eq)]
286pub struct EncodedSizes {
287 /// The proto3 size.
288 pub proto3: Option<u32>,
289 /// The FlatBuffers size.
290 pub flatbuffers: Option<u32>,
291 /// The `repr(C)` size.
292 pub repr_c: Option<u32>,
293}
294
295#[cfg(test)]
296mod tests {
297 use super::{CatalogHash, CatalogRef, Kind};
298
299 #[test]
300 fn catalog_refs_are_equal_only_when_name_and_hash_are_equal() {
301 let base = CatalogRef {
302 name: "vehicle",
303 hash: CatalogHash([1; 32]),
304 };
305 let same = CatalogRef {
306 name: "vehicle",
307 hash: CatalogHash([1; 32]),
308 };
309 let other_hash = CatalogRef {
310 name: "vehicle",
311 hash: CatalogHash([2; 32]),
312 };
313 let other_name = CatalogRef {
314 name: "cabin",
315 hash: CatalogHash([1; 32]),
316 };
317 assert_eq!(base, same);
318 assert_ne!(base, other_hash);
319 assert_ne!(base, other_name);
320 }
321
322 #[test]
323 fn kind_values_are_the_language_order_from_one() {
324 assert_eq!(Kind::Signal as u8, 1);
325 assert_eq!(Kind::Event as u8, 2);
326 assert_eq!(Kind::Command as u8, 3);
327 assert_eq!(Kind::Query as u8, 4);
328 assert_eq!(Kind::Fixed as u8, 5);
329 }
330}