use std::sync::Arc;
use crate::contract::{Contract, Operation};
use crate::envelope::{Cause, Code, ErrorForm};
use crate::packed::{Layout, ReadRefusal};
use crate::schema::TypeId;
use crate::wire::{self, Envelope, Refusal, Request, Stamp, Tag};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FormType {
tag: Tag,
layout: Option<Arc<Layout>>,
}
impl FormType {
pub fn of(contract: &Contract, ty: &TypeId) -> Result<FormType, String> {
match contract.packed_layout(ty)? {
None => Ok(FormType {
tag: Tag::NONE,
layout: None,
}),
Some(l) => Ok(FormType {
tag: Tag::new(l.tag()).ok_or_else(|| format!("a tag past 15: {}", l.tag()))?,
layout: Some(Arc::new(l)),
}),
}
}
#[must_use]
pub const fn tag(&self) -> Tag {
self.tag
}
#[must_use]
pub fn layout(&self) -> Option<&Layout> {
self.layout.as_deref()
}
pub fn check(&self, tag: Tag, record: &[u8]) -> Result<(), ReadRefusal> {
match &self.layout {
Some(l) => l.check(tag.get(), record),
None => Ok(()),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Forms {
pub request: FormType,
pub response: FormType,
pub summary: Option<FormType>,
pub error: Option<FormType>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum WriteRefusal {
#[error("a detail on an operation that declares no error type")]
Undeclared,
#[error(transparent)]
Form(Refusal),
}
impl WriteRefusal {
#[must_use]
pub const fn token(&self) -> &'static str {
match self {
WriteRefusal::Undeclared => "detail",
WriteRefusal::Form(r) => r.token(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum RequestRefusal {
#[error("no request form: {}", .0.reason())]
Form(Refusal),
#[error("the request's packed record: {}", .0.reason())]
Record(ReadRefusal),
}
impl RequestRefusal {
#[must_use]
pub fn token(&self) -> &'static str {
match self {
RequestRefusal::Form(r) => r.token(),
RequestRefusal::Record(r) => r.token(),
}
}
}
impl Forms {
pub fn of(contract: &Contract, op: &Operation) -> Result<Forms, String> {
let of = |ty: &TypeId| FormType::of(contract, ty);
Ok(Forms {
request: of(&op.request)?,
response: of(&op.response)?,
summary: op.summary.as_ref().map(of).transpose()?,
error: op.error.as_ref().map(of).transpose()?,
})
}
#[must_use]
pub fn error_tag(&self) -> Tag {
self.error.as_ref().map_or(Tag::NONE, FormType::tag)
}
#[must_use]
pub fn request(&self, record: &[u8]) -> Vec<u8> {
Request::new(self.request.tag, record).write()
}
#[must_use]
pub fn value(&self, mark: Stamp, record: &[u8]) -> Vec<u8> {
Envelope::value(self.response.tag, mark, record).write()
}
#[must_use]
pub fn summary(&self, mark: Stamp, record: &[u8]) -> Option<Vec<u8>> {
let s = self.summary.as_ref()?;
Some(Envelope::value(s.tag, mark, record).write())
}
pub fn error(
&self,
mark: Stamp,
code: Code,
cause: Option<Cause>,
message: Option<&str>,
detail: Option<&[u8]>,
) -> Result<Vec<u8>, WriteRefusal> {
if detail.is_some() && self.error.is_none() {
return Err(WriteRefusal::Undeclared);
}
ErrorForm {
message,
detail,
..ErrorForm::new(self.error_tag(), mark, code, cause)
}
.write()
.map_err(WriteRefusal::Form)
}
pub fn read_request<'a>(&self, payload: &'a [u8]) -> Result<Request<'a>, RequestRefusal> {
let req = wire::read_query(payload).map_err(RequestRefusal::Form)?;
self.request
.check(req.tag, req.record)
.map_err(RequestRefusal::Record)?;
Ok(req)
}
}
#[cfg(test)]
mod tests {
use super::{Forms, WriteRefusal};
use crate::envelope::Code;
use crate::wire::{Run, Seq, Stamp};
fn seed() -> crate::contract::Contract {
let dir =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../spec/conformance/contracts");
let l = crate::contract::load_path(&dir.join("ok-packed-operation.toml"));
l.contract.unwrap_or_else(|| panic!("{}", l.report))
}
fn forms(c: &crate::contract::Contract, name: &str) -> Forms {
let r = c
.resources
.iter()
.find(|r| r.template.as_str() == name)
.expect("the operation");
let crate::contract::Body::Operation(op) = &r.body else {
panic!("{name} is an operation")
};
Forms::of(c, op).expect("its forms")
}
#[test]
fn each_form_carries_its_types_tag() {
let c = seed();
let mark = Stamp {
run: Run::U16(1),
seq: Seq::new(7).unwrap(),
};
let cal = forms(&c, "calibrate");
assert_eq!(cal.request(&[])[0], 0x46);
assert_eq!(cal.value(mark, &[])[0], 0x4e);
assert_eq!(
cal.error(mark, Code::Busy, None, None, None).unwrap()[0],
0x62
);
assert_eq!(cal.summary(mark, &[]), None, "no summary declared");
let scan = forms(&c, "scan");
assert_eq!(scan.summary(mark, &[]).unwrap()[0], 0x4e);
let reset = forms(&c, "reset");
assert_eq!(
reset.error(mark, Code::App, None, None, Some(&[0])),
Err(WriteRefusal::Undeclared)
);
assert_eq!(
reset
.read_request(&[0x40, 0x1f, 0x59, 0x00])
.map_err(|r| r.token()),
Err("tag")
);
assert!(reset.read_request(&[0x4e, 0x1f, 0x59, 0x00]).is_ok());
}
}