Skip to main content

cufflink_sql_parse/
wire.rs

1//! Between the platform and a parser process, over the process's stdin and
2//! stdout: frames of a 4-byte big-endian length and that many bytes.
3//!
4//! - The process starts by sending a [`Hello`], which the platform takes
5//!   only if it is [`Hello::of_this_build`] with the published fingerprint.
6//! - Each request is a [`Request`] frame, then a frame of the statement.
7//! - Each answer is an [`Answer`] frame, and after [`Answer::Tree`] a frame
8//!   of the tree's canonical text.
9
10use cufflink_types::sql_parse::ParseError;
11use serde::{Deserialize, Serialize};
12use std::io::{self, Read, Write};
13
14/// The most a [`Hello`], [`Request`] or [`Answer`] frame holds.
15pub const MAX_CONTROL_FRAME: usize = 64 * 1024;
16
17/// The version of this exchange: its frames and messages, the bounds both
18/// sides apply and the tree's canonical text. It changes whenever any of
19/// them does, so a platform never uses a process built to other terms.
20pub const PROTOCOL: u32 = 1;
21
22/// What a process greets with: the terms it was built to, and its parser's
23/// identity, which it computes by parsing the probe corpus.
24#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25pub struct Hello {
26    pub protocol: u32,
27    /// The `cufflink-sql-parse` release the process was built with, and
28    /// every bound it applies.
29    pub build: String,
30    pub parser: String,
31    pub fingerprint: String,
32}
33
34impl Hello {
35    /// The greeting of a process built with this crate whose parser reads
36    /// the probe corpus as `fingerprint`.
37    pub fn of_this_build(fingerprint: impl Into<String>) -> Self {
38        Self {
39            protocol: PROTOCOL,
40            build: build(),
41            parser: crate::PARSER.to_string(),
42            fingerprint: fingerprint.into(),
43        }
44    }
45}
46
47/// This crate's release and its bounds, so that two builds that differ in
48/// either never take each other's processes.
49fn build() -> String {
50    use crate::bounds::*;
51    format!(
52        "{} input={MAX_INPUT_BYTES} brackets={MAX_BRACKET_DEPTH} chain={MAX_CHAIN_DEPTH} \
53         warned={MAX_WARNED_FORMS} operators={MAX_OPERATOR_RUN} comments={MAX_COMMENT_DEPTH} \
54         tree={}",
55        env!("CARGO_PKG_VERSION"),
56        crate::MAX_TREE_NESTING
57    )
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61pub struct Request {
62    /// The longest tree text the platform takes; a longer one is
63    /// `TooLarge`.
64    pub max_output: u64,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "snake_case")]
69pub enum Answer {
70    Tree,
71    Error(ParseError),
72}
73
74pub fn write_frame(out: &mut impl Write, bytes: &[u8]) -> io::Result<()> {
75    let len = u32::try_from(bytes.len())
76        .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a frame is over 4 GiB"))?;
77    out.write_all(&len.to_be_bytes())?;
78    out.write_all(bytes)
79}
80
81pub fn write_message(out: &mut impl Write, message: &impl Serialize) -> io::Result<()> {
82    let bytes = serde_json::to_vec(message).map_err(io::Error::other)?;
83    write_frame(out, &bytes)
84}
85
86/// The next frame, `None` at a clean end of input, and an error for a
87/// frame past `max` bytes, which is never read.
88pub fn read_frame(input: &mut impl Read, max: usize) -> io::Result<Option<Vec<u8>>> {
89    let mut header = [0u8; 4];
90    match input.read_exact(&mut header) {
91        Ok(()) => {}
92        Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => return Ok(None),
93        Err(e) => return Err(e),
94    }
95    let len = frame_len(header, max)?;
96    let mut bytes = vec![0u8; len];
97    input.read_exact(&mut bytes)?;
98    Ok(Some(bytes))
99}
100
101/// The length a frame's header announces, refused past `max`.
102pub fn frame_len(header: [u8; 4], max: usize) -> io::Result<usize> {
103    usize::try_from(u32::from_be_bytes(header))
104        .ok()
105        .filter(|len| *len <= max)
106        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "a frame is over its limit"))
107}
108
109pub fn read_message<T: for<'de> Deserialize<'de>>(input: &mut impl Read) -> io::Result<Option<T>> {
110    read_frame(input, MAX_CONTROL_FRAME)?
111        .map(|bytes| {
112            serde_json::from_slice(&bytes)
113                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
114        })
115        .transpose()
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    #[test]
123    fn frames_round_trip_and_refuse_what_is_past_their_limit() {
124        let mut wire = Vec::new();
125        write_message(&mut wire, &Request { max_output: 9 }).expect("request");
126        write_frame(&mut wire, b"SELECT 1").expect("statement");
127        write_message(&mut wire, &Answer::Error(ParseError::syntax())).expect("answer");
128        let mut input = wire.as_slice();
129        assert_eq!(
130            read_message::<Request>(&mut input).expect("read"),
131            Some(Request { max_output: 9 })
132        );
133        assert_eq!(
134            read_frame(&mut input, 8).expect("read").as_deref(),
135            Some(&b"SELECT 1"[..])
136        );
137        assert_eq!(
138            read_message::<Answer>(&mut input).expect("read"),
139            Some(Answer::Error(ParseError::syntax()))
140        );
141        assert_eq!(read_frame(&mut input, 8).expect("end"), None);
142
143        let mut long = Vec::new();
144        write_frame(&mut long, b"SELECT 10").expect("statement");
145        let refused = read_frame(&mut long.as_slice(), 8).expect_err("past the limit");
146        assert_eq!(refused.kind(), io::ErrorKind::InvalidData);
147        let cut = read_frame(&mut &long[..6], 16).expect_err("cut short");
148        assert_eq!(cut.kind(), io::ErrorKind::UnexpectedEof);
149    }
150
151    #[test]
152    fn a_greeting_names_its_terms_and_one_without_them_is_not_read() {
153        let hello = Hello::of_this_build("f");
154        assert_eq!(
155            serde_json::to_value(&hello).expect("encode"),
156            serde_json::json!({
157                "protocol": PROTOCOL,
158                "build": format!(
159                    "{} input=98304 brackets=1000 chain=10000 warned=100 operators=256 \
160                     comments=1000 tree=120",
161                    env!("CARGO_PKG_VERSION")
162                ),
163                "parser": crate::PARSER,
164                "fingerprint": "f",
165            })
166        );
167        let earlier = br#"{"parser":"6.2.1","fingerprint":"f"}"#;
168        let mut wire = Vec::new();
169        write_frame(&mut wire, earlier).expect("hello");
170        assert!(read_message::<Hello>(&mut wire.as_slice()).is_err());
171    }
172
173    #[test]
174    fn answers_are_small_and_tagged() {
175        assert_eq!(
176            serde_json::to_string(&Answer::Tree).expect("encode"),
177            r#""tree""#
178        );
179        assert_eq!(
180            serde_json::to_value(Answer::Error(ParseError::TooLarge("x".into()))).expect("encode"),
181            serde_json::json!({"error": {"kind": "too_large", "message": "x"}})
182        );
183    }
184}