Skip to main content

zenkey_model/
forms.rs

1//! A call's forms by its operation's types (core §5.1 "The forms", §5.2
2//! "The error form", §7.5, §7.6; #985's C4c): every operation of every
3//! contract travels in them, whatever its types' kind.
4//!
5//! ```text
6//! request, a query's payload       CH · record                  the `request` type's tag, width bit 0
7//! value, a reply's payload         CH · run · seq · record      the `response` type's tag (`summary`'s on a summary)
8//! error, a reply_err's payload     CH · run · seq · error       the `error` type's tag, 0 when it declares none
9//! ```
10//!
11//! [`Forms::of`] reads an operation's four types once: each one's tag
12//! ([`FormType::tag`]), which only a packed type defines (§7.6), and a
13//! packed type's layout, which reads its record under the tag CH carried
14//! ([`FormType::check`]). [`wire`] parses and writes the forms without a
15//! contract; this module adds what the types say:
16//! - **the writers**: [`Forms::request`], [`Forms::value`],
17//!   [`Forms::summary`] and [`Forms::error`], the last refusing a detail on
18//!   an operation that declares no `error` type ([`WriteRefusal::Undeclared`],
19//!   §5.2's MUST NOT) and what §7.5's writer refuses;
20//! - **the owner's read of a request** ([`Forms::read_request`]): §7.5's
21//!   parse, then a packed record under CH's tag, either refusal the
22//!   owner's `invalid_request` (§5.1, "The request").
23//!
24//! A JSON Schema, protobuf or raw record is carried as its bytes: the
25//! runtime encodes and decodes it, on the contract's `encoding` (§7.2).
26//! A record's `time` fields count from the deployment epoch, the writer's
27//! and the reader's to give (§8.6): no form carries one.
28
29use std::sync::Arc;
30
31use crate::contract::{Contract, Operation};
32use crate::envelope::{Cause, Code, ErrorForm};
33use crate::packed::{Layout, ReadRefusal};
34use crate::schema::TypeId;
35use crate::wire::{self, Envelope, Refusal, Request, Stamp, Tag};
36
37/// One of an operation's types as its forms carry it: the tag CH holds,
38/// and a packed type's layout, which reads its record under that tag.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct FormType {
41    tag: Tag,
42    layout: Option<Arc<Layout>>,
43}
44
45impl FormType {
46    /// `ty` of `contract`: a packed type's tag and layout (core §7.6), and
47    /// tag 0 for every other kind, which defines none.
48    ///
49    /// # Errors
50    ///
51    /// A packed type whose artifact the contract does not carry, or whose
52    /// layout does not resolve.
53    pub fn of(contract: &Contract, ty: &TypeId) -> Result<FormType, String> {
54        match contract.packed_layout(ty)? {
55            None => Ok(FormType {
56                tag: Tag::NONE,
57                layout: None,
58            }),
59            Some(l) => Ok(FormType {
60                tag: Tag::new(l.tag()).ok_or_else(|| format!("a tag past 15: {}", l.tag()))?,
61                layout: Some(Arc::new(l)),
62            }),
63        }
64    }
65
66    /// The tag CH carries for a record of this type.
67    #[must_use]
68    pub const fn tag(&self) -> Tag {
69        self.tag
70    }
71
72    /// A packed type's layout; `None` for every other kind.
73    #[must_use]
74    pub fn layout(&self) -> Option<&Layout> {
75        self.layout.as_deref()
76    }
77
78    /// A record CH carried under `tag`, checked as its type reads it (core
79    /// §7.6): a packed record by its layout, `tag` first; any other kind's
80    /// taken as it is, its tag reported and never checked (§7.5), its bytes
81    /// for its own decoder.
82    ///
83    /// # Errors
84    ///
85    /// The packed reader's first refusal ([`ReadRefusal`]), never its
86    /// `epoch`.
87    pub fn check(&self, tag: Tag, record: &[u8]) -> Result<(), ReadRefusal> {
88        match &self.layout {
89            Some(l) => l.check(tag.get(), record),
90            None => Ok(()),
91        }
92    }
93}
94
95/// An operation's types as its forms carry them (core §5.1, §5.2).
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct Forms {
98    pub request: FormType,
99    pub response: FormType,
100    /// `replies = "many"`'s declared summary, if any (O6).
101    pub summary: Option<FormType>,
102    /// The declared `error` type, if any: an `app` error's detail is a value
103    /// of it.
104    pub error: Option<FormType>,
105}
106
107/// What [`Forms::error`] refuses to write.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
109pub enum WriteRefusal {
110    /// A detail on an operation that declares no `error` type, which has
111    /// none to send (core §5.2, "`app`": the owner's MUST NOT).
112    #[error("a detail on an operation that declares no error type")]
113    Undeclared,
114    /// What §7.5's writer refuses: a cause where none goes or none where
115    /// one must, or a detail on a code other than `app`.
116    #[error(transparent)]
117    Form(Refusal),
118}
119
120impl WriteRefusal {
121    /// `spec/conformance/envelope/calls.json`'s token: `detail` for both a
122    /// detail where no `error` type is declared and one on a code other
123    /// than `app`.
124    #[must_use]
125    pub const fn token(&self) -> &'static str {
126        match self {
127            WriteRefusal::Undeclared => "detail",
128            WriteRefusal::Form(r) => r.token(),
129        }
130    }
131}
132
133/// Why an owner refuses a request, `invalid_request` either way (core
134/// §5.1, "The request").
135#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
136pub enum RequestRefusal {
137    /// §7.5's parse refused the query's payload.
138    #[error("no request form: {}", .0.reason())]
139    Form(Refusal),
140    /// A packed request's record, refused under CH's tag (§7.6).
141    #[error("the request's packed record: {}", .0.reason())]
142    Record(ReadRefusal),
143}
144
145impl RequestRefusal {
146    /// The fixtures' token: §7.5's ([`Refusal::token`]) or §7.6's
147    /// ([`ReadRefusal::token`]).
148    #[must_use]
149    pub fn token(&self) -> &'static str {
150        match self {
151            RequestRefusal::Form(r) => r.token(),
152            RequestRefusal::Record(r) => r.token(),
153        }
154    }
155}
156
157impl Forms {
158    /// `op`'s forms, its types read in `contract` ([`FormType::of`]).
159    ///
160    /// # Errors
161    ///
162    /// A packed type of `op` whose layout does not resolve.
163    pub fn of(contract: &Contract, op: &Operation) -> Result<Forms, String> {
164        let of = |ty: &TypeId| FormType::of(contract, ty);
165        Ok(Forms {
166            request: of(&op.request)?,
167            response: of(&op.response)?,
168            summary: op.summary.as_ref().map(of).transpose()?,
169            error: op.error.as_ref().map(of).transpose()?,
170        })
171    }
172
173    /// CH's tag on an error: the `error` type's, 0 when it declares none.
174    #[must_use]
175    pub fn error_tag(&self) -> Tag {
176        self.error.as_ref().map_or(Tag::NONE, FormType::tag)
177    }
178
179    /// A request's bytes, the caller's (§5.1): `CH · record`, its width bit
180    /// 0 and its tag the `request` type's.
181    #[must_use]
182    pub fn request(&self, record: &[u8]) -> Vec<u8> {
183        Request::new(self.request.tag, record).write()
184    }
185
186    /// A value reply's bytes, the owner's (§5.1): the value form, its tag
187    /// the `response` type's, with the replying instance's as-of mark.
188    #[must_use]
189    pub fn value(&self, mark: Stamp, record: &[u8]) -> Vec<u8> {
190        Envelope::value(self.response.tag, mark, record).write()
191    }
192
193    /// A summary reply's bytes (O6): the value form under the `summary`
194    /// type's tag. `None` for an operation that declares no summary.
195    #[must_use]
196    pub fn summary(&self, mark: Stamp, record: &[u8]) -> Option<Vec<u8>> {
197        let s = self.summary.as_ref()?;
198        Some(Envelope::value(s.tag, mark, record).write())
199    }
200
201    /// An error reply's bytes, the owner's (§5.2): the error form, its tag
202    /// the `error` type's or 0, with the replying instance's as-of mark. A
203    /// message is cut at 255 bytes (§7.5); `detail` is the bytes of a value
204    /// of the `error` type, as that type encodes it.
205    ///
206    /// # Errors
207    ///
208    /// [`WriteRefusal::Undeclared`] for a detail on an operation that
209    /// declares no `error` type, else §7.5's writer's refusal: a cause on a
210    /// code other than `unavailable` or none on it (`cause`), a detail on a
211    /// code other than `app` (`detail`).
212    pub fn error(
213        &self,
214        mark: Stamp,
215        code: Code,
216        cause: Option<Cause>,
217        message: Option<&str>,
218        detail: Option<&[u8]>,
219    ) -> Result<Vec<u8>, WriteRefusal> {
220        if detail.is_some() && self.error.is_none() {
221            return Err(WriteRefusal::Undeclared);
222        }
223        ErrorForm {
224            message,
225            detail,
226            ..ErrorForm::new(self.error_tag(), mark, code, cause)
227        }
228        .write()
229        .map_err(WriteRefusal::Form)
230    }
231
232    /// A query's payload read as this operation's request, as its owner
233    /// reads it (§5.1, "The request"): §7.5's parse, then a packed record
234    /// under CH's tag. Any other kind's record is its type's decoder's.
235    ///
236    /// # Errors
237    ///
238    /// The first refusal: §7.5's ([`RequestRefusal::Form`]: `short`,
239    /// `form`, `sample_kind`, `request_run`), then §7.6's
240    /// ([`RequestRefusal::Record`]: `tag`, `length`, `code`, `extension`,
241    /// `pad`).
242    pub fn read_request<'a>(&self, payload: &'a [u8]) -> Result<Request<'a>, RequestRefusal> {
243        let req = wire::read_query(payload).map_err(RequestRefusal::Form)?;
244        self.request
245            .check(req.tag, req.record)
246            .map_err(RequestRefusal::Record)?;
247        Ok(req)
248    }
249}
250
251#[cfg(test)]
252mod tests {
253    use super::{Forms, WriteRefusal};
254    use crate::envelope::Code;
255    use crate::wire::{Run, Seq, Stamp};
256
257    fn seed() -> crate::contract::Contract {
258        let dir =
259            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../spec/conformance/contracts");
260        let l = crate::contract::load_path(&dir.join("ok-packed-operation.toml"));
261        l.contract.unwrap_or_else(|| panic!("{}", l.report))
262    }
263
264    fn forms(c: &crate::contract::Contract, name: &str) -> Forms {
265        let r = c
266            .resources
267            .iter()
268            .find(|r| r.template.as_str() == name)
269            .expect("the operation");
270        let crate::contract::Body::Operation(op) = &r.body else {
271            panic!("{name} is an operation")
272        };
273        Forms::of(c, op).expect("its forms")
274    }
275
276    /// Core §5.1, §5.2: each form's CH holds its type's tag, an error's the
277    /// `error` type's or 0, and a detail with no `error` type is refused.
278    #[test]
279    fn each_form_carries_its_types_tag() {
280        let c = seed();
281        let mark = Stamp {
282            run: Run::U16(1),
283            seq: Seq::new(7).unwrap(),
284        };
285        let cal = forms(&c, "calibrate");
286        assert_eq!(cal.request(&[])[0], 0x46);
287        assert_eq!(cal.value(mark, &[])[0], 0x4e);
288        assert_eq!(
289            cal.error(mark, Code::Busy, None, None, None).unwrap()[0],
290            0x62
291        );
292        assert_eq!(cal.summary(mark, &[]), None, "no summary declared");
293        let scan = forms(&c, "scan");
294        assert_eq!(scan.summary(mark, &[]).unwrap()[0], 0x4e);
295        let reset = forms(&c, "reset");
296        assert_eq!(
297            reset.error(mark, Code::App, None, None, Some(&[0])),
298            Err(WriteRefusal::Undeclared)
299        );
300        assert_eq!(
301            reset
302                .read_request(&[0x40, 0x1f, 0x59, 0x00])
303                .map_err(|r| r.token()),
304            Err("tag")
305        );
306        assert!(reset.read_request(&[0x4e, 0x1f, 0x59, 0x00]).is_ok());
307    }
308}