Skip to main content

labstream_proto/
negotiate.rs

1//! The feed negotiation. SPEC.md 5.
2//!
3//! The server decides three things: the data protocol version, the byte order,
4//! and subnormal suppression. This module holds that decision as a pure
5//! function, so a test can drive every branch with no socket.
6
7use crate::header::{Headers, StatusLine};
8use labstream_wire::{ByteOrder, Format};
9
10/// The version constant of this implementation. `src/common.h:46`.
11pub const LSL_PROTOCOL_VERSION: i32 = 110;
12
13/// The byte order values that liblsl accepts. `src/util/endian.hpp:10-17`.
14pub const LITTLE: i32 = 1234;
15/// The big endian value.
16pub const BIG: i32 = 4321;
17
18/// True when liblsl can convert to the requested order.
19///
20/// `src/util/endian.hpp:23-30`. A one-byte value always passes, because no
21/// conversion takes place. Any other size needs a known order on both sides.
22pub fn can_convert_endian(requested: i32, value_size: i32) -> bool {
23    if value_size == 1 {
24        return true;
25    }
26    requested == LITTLE || requested == BIG
27}
28
29/// What the client asked for.
30#[derive(Debug, Clone, PartialEq)]
31pub struct FeedRequest {
32    /// The version from the request line, such as 110.
33    pub request_version: i32,
34    /// The UID from the request line. An empty value skips the UID test.
35    pub request_uid: String,
36    /// `Native-Byte-Order`.
37    pub native_byte_order: i32,
38    /// `Endian-Performance`. A measured value that a test must never compare.
39    pub endian_performance: f64,
40    /// `Has-IEEE754-Floats`.
41    pub has_ieee754_floats: bool,
42    /// `Supports-Subnormals`.
43    pub supports_subnormals: bool,
44    /// `Value-Size`. Zero for a string stream.
45    pub value_size: i32,
46    /// `Max-Buffer-Length`.
47    pub max_buffer_length: i32,
48    /// `Max-Chunk-Length`.
49    pub max_chunk_length: i32,
50    /// The version from `Protocol-Version`.
51    ///
52    /// The server reads this name and not `Data-Protocol-Version`
53    /// (`src/tcp_server.cpp:628`). SPEC.md 4.4 records the difference. The
54    /// default is the version from the request line
55    /// (`src/tcp_server.cpp:596-597`).
56    pub protocol_version: i32,
57}
58
59impl FeedRequest {
60    /// Read a request from a request line version, a UID, and a header block.
61    ///
62    /// Every default matches `src/tcp_server.cpp:590-600`. A missing header
63    /// keeps its default, and a wrong header name is the same as a missing one.
64    pub fn from_headers(
65        request_version: i32,
66        request_uid: &str,
67        h: &Headers,
68        channel_bytes: i32,
69    ) -> Self {
70        FeedRequest {
71            request_version,
72            request_uid: request_uid.to_string(),
73            native_byte_order: h.get_int("native-byte-order").unwrap_or(LITTLE as i64) as i32,
74            endian_performance: h.get_f64("endian-performance").unwrap_or(0.0),
75            has_ieee754_floats: h.get_bool("has-ieee754-floats").unwrap_or(true),
76            supports_subnormals: h.get_bool("supports-subnormals").unwrap_or(true),
77            value_size: h.get_int("value-size").unwrap_or(channel_bytes as i64) as i32,
78            max_buffer_length: h.get_int("max-buffer-length").unwrap_or(0) as i32,
79            max_chunk_length: h.get_int("max-chunk-length").unwrap_or(0) as i32,
80            // This reads `protocol-version`. A client that sends only
81            // `Data-Protocol-Version` leaves the default in place.
82            protocol_version: h
83                .get_int("protocol-version")
84                .unwrap_or(request_version as i64) as i32,
85        }
86    }
87}
88
89/// What the server knows about its own stream.
90#[derive(Debug, Clone, PartialEq)]
91pub struct ServerStream {
92    /// The stream UID.
93    pub uid: String,
94    /// The channel format.
95    pub format: Format,
96    /// The size of one channel value in bytes. Zero for a string stream.
97    pub channel_bytes: i32,
98    /// The version that this server runs.
99    pub configured_version: i32,
100    /// The byte order of this machine.
101    pub native_byte_order: i32,
102    /// How fast this machine converts a byte order.
103    ///
104    /// A measured value. A test injects a fixed number.
105    pub endian_performance: f64,
106}
107
108impl ServerStream {
109    /// Build a server description with the usual values.
110    pub fn new(uid: &str, format: Format, native_byte_order: i32, endian_performance: f64) -> Self {
111        ServerStream {
112            uid: uid.to_string(),
113            format,
114            channel_bytes: format.width().unwrap_or(0) as i32,
115            configured_version: LSL_PROTOCOL_VERSION,
116            native_byte_order,
117            endian_performance,
118        }
119    }
120}
121
122/// What the server decided.
123#[derive(Debug, Clone, PartialEq)]
124pub enum Outcome {
125    /// The server refuses, and it sends this status line.
126    Refuse(StatusLine),
127    /// The server accepts.
128    Accept(Accepted),
129}
130
131/// The accepted parameters.
132#[derive(Debug, Clone, PartialEq)]
133pub struct Accepted {
134    /// The negotiated data protocol version.
135    pub data_protocol_version: i32,
136    /// The byte order that goes in the answer.
137    pub byte_order: i32,
138    /// True when the server writes swapped values.
139    pub reverse_byte_order: bool,
140    /// True when the reader clears subnormal values.
141    pub suppress_subnormals: bool,
142    /// The buffer length that the client asked for.
143    pub max_buffer_length: i32,
144    /// The chunk length that the client asked for.
145    pub max_chunk_length: i32,
146}
147
148impl Accepted {
149    /// The byte order as the codec sees it.
150    pub fn codec_order(&self) -> Option<ByteOrder> {
151        match self.byte_order {
152            LITTLE => Some(ByteOrder::Little),
153            BIG => Some(ByteOrder::Big),
154            _ => None,
155        }
156    }
157
158    /// Write the answer as liblsl writes it. `src/tcp_server.cpp:673-678`.
159    pub fn to_wire(&self, configured_version: i32, uid: &str) -> String {
160        let mut s = StatusLine {
161            version: configured_version,
162            code: 200,
163            message: "OK".into(),
164        }
165        .to_wire();
166        s.push_str(&format!("UID: {uid}\r\n"));
167        s.push_str(&format!("Byte-Order: {}\r\n", self.byte_order));
168        s.push_str(&format!(
169            "Suppress-Subnormals: {}\r\n",
170            if self.suppress_subnormals { 1 } else { 0 }
171        ));
172        s.push_str(&format!(
173            "Data-Protocol-Version: {}\r\n",
174            self.data_protocol_version
175        ));
176        s.push_str("\r\n");
177        s
178    }
179}
180
181/// True when the format carries a subnormal value.
182///
183/// liblsl calls this table `format_subnormal` (`src/sample.h:28`). Only the
184/// two floating point formats hold one.
185fn format_has_subnormals(f: Format) -> bool {
186    f.is_float()
187}
188
189/// Decide what the server does with a request. SPEC.md 5.
190///
191/// This function reads no socket and no clock. Every input is an argument, so
192/// a test can drive each branch.
193pub fn negotiate(req: &FeedRequest, srv: &ServerStream) -> Outcome {
194    // A newer major version stops the feed. `src/tcp_server.cpp:576-580`.
195    if req.request_version / 100 > srv.configured_version / 100 {
196        return Outcome::Refuse(StatusLine {
197            version: srv.configured_version,
198            code: 505,
199            message: "Version not supported".into(),
200        });
201    }
202
203    // A UID that names another stream stops the feed.
204    // `src/tcp_server.cpp:585-588`. An empty UID skips the test.
205    if !req.request_uid.is_empty() && req.request_uid != srv.uid {
206        return Outcome::Refuse(StatusLine {
207            version: srv.configured_version,
208            code: 404,
209            message: "Not found".into(),
210        });
211    }
212
213    // A request below 1.10 carries no headers. `src/tcp_server.cpp:679-680`.
214    if req.request_version < 110 {
215        return Outcome::Accept(Accepted {
216            data_protocol_version: 100,
217            byte_order: srv.native_byte_order,
218            reverse_byte_order: false,
219            suppress_subnormals: false,
220            max_buffer_length: req.max_buffer_length,
221            max_chunk_length: req.max_chunk_length,
222        });
223    }
224
225    // The lower of the two versions wins. `src/tcp_server.cpp:641`.
226    let mut version = srv.configured_version.min(req.protocol_version);
227
228    // Two conditions force protocol 1.00. `src/tcp_server.cpp:643-649`.
229    if srv.format != Format::String && srv.channel_bytes != req.value_size {
230        version = 100;
231    }
232    if !req.has_ieee754_floats {
233        version = 100;
234    }
235
236    let mut byte_order = srv.native_byte_order;
237    let mut reverse = false;
238    let mut suppress = false;
239
240    if version >= 110 {
241        // Four conditions, all required. `src/tcp_server.cpp:652-664`.
242        if srv.native_byte_order != req.native_byte_order
243            && can_convert_endian(req.native_byte_order, req.value_size)
244            && req.value_size > 1
245            && srv.endian_performance > req.endian_performance
246        {
247            byte_order = req.native_byte_order;
248            reverse = true;
249        }
250        // `src/tcp_server.cpp:667-668`.
251        suppress = format_has_subnormals(srv.format) && !req.supports_subnormals;
252    }
253
254    Outcome::Accept(Accepted {
255        data_protocol_version: version,
256        byte_order,
257        reverse_byte_order: reverse,
258        suppress_subnormals: suppress,
259        max_buffer_length: req.max_buffer_length,
260        max_chunk_length: req.max_chunk_length,
261    })
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    fn server() -> ServerStream {
269        ServerStream::new("uid-1", Format::Float32, LITTLE, 1000.0)
270    }
271
272    fn request() -> FeedRequest {
273        FeedRequest {
274            request_version: 110,
275            request_uid: "uid-1".into(),
276            native_byte_order: LITTLE,
277            endian_performance: 500.0,
278            has_ieee754_floats: true,
279            supports_subnormals: true,
280            value_size: 4,
281            max_buffer_length: 360,
282            max_chunk_length: 0,
283            protocol_version: 110,
284        }
285    }
286
287    fn accepted(o: Outcome) -> Accepted {
288        match o {
289            Outcome::Accept(a) => a,
290            Outcome::Refuse(s) => panic!("refused with {} {}", s.code, s.message),
291        }
292    }
293
294    #[test]
295    fn the_usual_request_is_accepted_with_no_swap() {
296        let a = accepted(negotiate(&request(), &server()));
297        assert_eq!(a.data_protocol_version, 110);
298        assert_eq!(a.byte_order, LITTLE);
299        assert!(!a.reverse_byte_order);
300        assert!(!a.suppress_subnormals);
301    }
302
303    #[test]
304    fn a_newer_major_version_gets_505() {
305        let mut r = request();
306        r.request_version = 200;
307        match negotiate(&r, &server()) {
308            Outcome::Refuse(s) => {
309                assert_eq!(s.code, 505);
310                assert_eq!(s.message, "Version not supported");
311            }
312            other => panic!("expected a refusal, got {other:?}"),
313        }
314    }
315
316    #[test]
317    fn a_newer_minor_version_is_accepted() {
318        // 111 has the same major version as 110, so it passes the first test.
319        let mut r = request();
320        r.request_version = 111;
321        r.protocol_version = 111;
322        let a = accepted(negotiate(&r, &server()));
323        assert_eq!(a.data_protocol_version, 110);
324    }
325
326    #[test]
327    fn a_wrong_uid_gets_404() {
328        let mut r = request();
329        r.request_uid = "another".into();
330        match negotiate(&r, &server()) {
331            Outcome::Refuse(s) => assert_eq!(s.code, 404),
332            other => panic!("expected a refusal, got {other:?}"),
333        }
334    }
335
336    #[test]
337    fn an_empty_uid_skips_the_test() {
338        let mut r = request();
339        r.request_uid = String::new();
340        assert_eq!(
341            accepted(negotiate(&r, &server())).data_protocol_version,
342            110
343        );
344    }
345
346    #[test]
347    fn a_value_size_mismatch_forces_protocol_100() {
348        let mut r = request();
349        r.value_size = 8;
350        assert_eq!(
351            accepted(negotiate(&r, &server())).data_protocol_version,
352            100
353        );
354    }
355
356    #[test]
357    fn a_string_stream_ignores_the_value_size() {
358        let mut s = server();
359        s.format = Format::String;
360        s.channel_bytes = 0;
361        let mut r = request();
362        r.value_size = 0;
363        assert_eq!(accepted(negotiate(&r, &s)).data_protocol_version, 110);
364    }
365
366    #[test]
367    fn a_client_with_no_ieee754_floats_forces_protocol_100() {
368        let mut r = request();
369        r.has_ieee754_floats = false;
370        assert_eq!(
371            accepted(negotiate(&r, &server())).data_protocol_version,
372            100
373        );
374    }
375
376    #[test]
377    fn the_server_swaps_when_it_is_faster() {
378        let mut r = request();
379        r.native_byte_order = BIG;
380        r.endian_performance = 0.0;
381        let a = accepted(negotiate(&r, &server()));
382        assert_eq!(a.byte_order, BIG);
383        assert!(a.reverse_byte_order);
384    }
385
386    #[test]
387    fn the_server_does_not_swap_when_the_client_is_faster() {
388        let mut r = request();
389        r.native_byte_order = BIG;
390        r.endian_performance = 999999.0;
391        let a = accepted(negotiate(&r, &server()));
392        assert_eq!(a.byte_order, LITTLE);
393        assert!(!a.reverse_byte_order);
394    }
395
396    #[test]
397    fn a_one_byte_format_never_swaps() {
398        // Condition 3 needs a size above 1. This is the rule that makes the
399        // swapped one-byte stream unreachable in M2.
400        let mut s = server();
401        s.format = Format::Int8;
402        s.channel_bytes = 1;
403        let mut r = request();
404        r.value_size = 1;
405        r.native_byte_order = BIG;
406        r.endian_performance = 0.0;
407        let a = accepted(negotiate(&r, &s));
408        assert_eq!(a.byte_order, LITTLE);
409        assert!(!a.reverse_byte_order);
410    }
411
412    #[test]
413    fn an_unknown_byte_order_blocks_the_swap() {
414        let mut r = request();
415        r.native_byte_order = 2134; // the deprecated PDP order
416        r.endian_performance = 0.0;
417        let a = accepted(negotiate(&r, &server()));
418        assert_eq!(a.byte_order, LITTLE);
419        assert!(!a.reverse_byte_order);
420    }
421
422    #[test]
423    fn subnormal_suppression_follows_the_client() {
424        let mut r = request();
425        r.supports_subnormals = false;
426        assert!(accepted(negotiate(&r, &server())).suppress_subnormals);
427
428        // An integer format holds no subnormal value.
429        let mut s = server();
430        s.format = Format::Int32;
431        assert!(!accepted(negotiate(&r, &s)).suppress_subnormals);
432    }
433
434    #[test]
435    fn the_server_reads_protocol_version_and_not_data_protocol_version() {
436        // SPEC.md 4.4. This is the header that liblsl reads.
437        use crate::header::parse_block;
438
439        let with_dead = b"Data-Protocol-Version: 100\r\nValue-Size: 4\r\n\r\n";
440        let (h, _) = parse_block(with_dead).unwrap();
441        let r = FeedRequest::from_headers(110, "uid-1", &h, 4);
442        assert_eq!(
443            r.protocol_version, 110,
444            "the dead header must not change the version"
445        );
446        assert_eq!(
447            accepted(negotiate(&r, &server())).data_protocol_version,
448            110
449        );
450
451        let with_live = b"Protocol-Version: 100\r\nValue-Size: 4\r\n\r\n";
452        let (h, _) = parse_block(with_live).unwrap();
453        let r = FeedRequest::from_headers(110, "uid-1", &h, 4);
454        assert_eq!(r.protocol_version, 100);
455        assert_eq!(
456            accepted(negotiate(&r, &server())).data_protocol_version,
457            100
458        );
459    }
460
461    #[test]
462    fn the_answer_matches_the_shape_that_liblsl_writes() {
463        let a = accepted(negotiate(&request(), &server()));
464        let wire = a.to_wire(110, "uid-1");
465        assert_eq!(
466            wire,
467            "LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 1234\r\n\
468             Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n"
469        );
470    }
471}