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    /// Write the answer with a `Labstream-Features` line.
181    ///
182    /// `features` is `None` when the request had no such header. The answer
183    /// is then the same as [`Accepted::to_wire`]. A request with the header
184    /// gets the line, also when no feature is on. `docs/extensions.md`.
185    pub fn to_wire_with(
186        &self,
187        configured_version: i32,
188        uid: &str,
189        features: Option<&[crate::features::Token]>,
190    ) -> String {
191        let mut s = self.to_wire(configured_version, uid);
192        if let Some(tokens) = features {
193            s.truncate(s.len() - 2);
194            s.push_str(&crate::features::header_line(tokens));
195            s.push_str("\r\n");
196        }
197        s
198    }
199}
200
201/// True when the format carries a subnormal value.
202///
203/// liblsl calls this table `format_subnormal` (`src/sample.h:28`). Only the
204/// two floating point formats hold one.
205fn format_has_subnormals(f: Format) -> bool {
206    f.is_float()
207}
208
209/// Decide what the server does with a request. SPEC.md 5.
210///
211/// This function reads no socket and no clock. Every input is an argument, so
212/// a test can drive each branch.
213pub fn negotiate(req: &FeedRequest, srv: &ServerStream) -> Outcome {
214    // A newer major version stops the feed. `src/tcp_server.cpp:576-580`.
215    if req.request_version / 100 > srv.configured_version / 100 {
216        return Outcome::Refuse(StatusLine {
217            version: srv.configured_version,
218            code: 505,
219            message: "Version not supported".into(),
220        });
221    }
222
223    // A UID that names another stream stops the feed.
224    // `src/tcp_server.cpp:585-588`. An empty UID skips the test.
225    if !req.request_uid.is_empty() && req.request_uid != srv.uid {
226        return Outcome::Refuse(StatusLine {
227            version: srv.configured_version,
228            code: 404,
229            message: "Not found".into(),
230        });
231    }
232
233    // A request below 1.10 carries no headers. `src/tcp_server.cpp:679-680`.
234    if req.request_version < 110 {
235        return Outcome::Accept(Accepted {
236            data_protocol_version: 100,
237            byte_order: srv.native_byte_order,
238            reverse_byte_order: false,
239            suppress_subnormals: false,
240            max_buffer_length: req.max_buffer_length,
241            max_chunk_length: req.max_chunk_length,
242        });
243    }
244
245    // The lower of the two versions wins. `src/tcp_server.cpp:641`.
246    let mut version = srv.configured_version.min(req.protocol_version);
247
248    // Two conditions force protocol 1.00. `src/tcp_server.cpp:643-649`.
249    if srv.format != Format::String && srv.channel_bytes != req.value_size {
250        version = 100;
251    }
252    if !req.has_ieee754_floats {
253        version = 100;
254    }
255
256    let mut byte_order = srv.native_byte_order;
257    let mut reverse = false;
258    let mut suppress = false;
259
260    if version >= 110 {
261        // Four conditions, all required. `src/tcp_server.cpp:652-664`.
262        if srv.native_byte_order != req.native_byte_order
263            && can_convert_endian(req.native_byte_order, req.value_size)
264            && req.value_size > 1
265            && srv.endian_performance > req.endian_performance
266        {
267            byte_order = req.native_byte_order;
268            reverse = true;
269        }
270        // `src/tcp_server.cpp:667-668`.
271        suppress = format_has_subnormals(srv.format) && !req.supports_subnormals;
272    }
273
274    Outcome::Accept(Accepted {
275        data_protocol_version: version,
276        byte_order,
277        reverse_byte_order: reverse,
278        suppress_subnormals: suppress,
279        max_buffer_length: req.max_buffer_length,
280        max_chunk_length: req.max_chunk_length,
281    })
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    fn server() -> ServerStream {
289        ServerStream::new("uid-1", Format::Float32, LITTLE, 1000.0)
290    }
291
292    fn request() -> FeedRequest {
293        FeedRequest {
294            request_version: 110,
295            request_uid: "uid-1".into(),
296            native_byte_order: LITTLE,
297            endian_performance: 500.0,
298            has_ieee754_floats: true,
299            supports_subnormals: true,
300            value_size: 4,
301            max_buffer_length: 360,
302            max_chunk_length: 0,
303            protocol_version: 110,
304        }
305    }
306
307    fn accepted(o: Outcome) -> Accepted {
308        match o {
309            Outcome::Accept(a) => a,
310            Outcome::Refuse(s) => panic!("refused with {} {}", s.code, s.message),
311        }
312    }
313
314    #[test]
315    fn the_usual_request_is_accepted_with_no_swap() {
316        let a = accepted(negotiate(&request(), &server()));
317        assert_eq!(a.data_protocol_version, 110);
318        assert_eq!(a.byte_order, LITTLE);
319        assert!(!a.reverse_byte_order);
320        assert!(!a.suppress_subnormals);
321    }
322
323    #[test]
324    fn a_newer_major_version_gets_505() {
325        let mut r = request();
326        r.request_version = 200;
327        match negotiate(&r, &server()) {
328            Outcome::Refuse(s) => {
329                assert_eq!(s.code, 505);
330                assert_eq!(s.message, "Version not supported");
331            }
332            other => panic!("expected a refusal, got {other:?}"),
333        }
334    }
335
336    #[test]
337    fn a_newer_minor_version_is_accepted() {
338        // 111 has the same major version as 110, so it passes the first test.
339        let mut r = request();
340        r.request_version = 111;
341        r.protocol_version = 111;
342        let a = accepted(negotiate(&r, &server()));
343        assert_eq!(a.data_protocol_version, 110);
344    }
345
346    #[test]
347    fn a_wrong_uid_gets_404() {
348        let mut r = request();
349        r.request_uid = "another".into();
350        match negotiate(&r, &server()) {
351            Outcome::Refuse(s) => assert_eq!(s.code, 404),
352            other => panic!("expected a refusal, got {other:?}"),
353        }
354    }
355
356    #[test]
357    fn an_empty_uid_skips_the_test() {
358        let mut r = request();
359        r.request_uid = String::new();
360        assert_eq!(
361            accepted(negotiate(&r, &server())).data_protocol_version,
362            110
363        );
364    }
365
366    #[test]
367    fn a_value_size_mismatch_forces_protocol_100() {
368        let mut r = request();
369        r.value_size = 8;
370        assert_eq!(
371            accepted(negotiate(&r, &server())).data_protocol_version,
372            100
373        );
374    }
375
376    #[test]
377    fn a_string_stream_ignores_the_value_size() {
378        let mut s = server();
379        s.format = Format::String;
380        s.channel_bytes = 0;
381        let mut r = request();
382        r.value_size = 0;
383        assert_eq!(accepted(negotiate(&r, &s)).data_protocol_version, 110);
384    }
385
386    #[test]
387    fn a_client_with_no_ieee754_floats_forces_protocol_100() {
388        let mut r = request();
389        r.has_ieee754_floats = false;
390        assert_eq!(
391            accepted(negotiate(&r, &server())).data_protocol_version,
392            100
393        );
394    }
395
396    #[test]
397    fn the_server_swaps_when_it_is_faster() {
398        let mut r = request();
399        r.native_byte_order = BIG;
400        r.endian_performance = 0.0;
401        let a = accepted(negotiate(&r, &server()));
402        assert_eq!(a.byte_order, BIG);
403        assert!(a.reverse_byte_order);
404    }
405
406    #[test]
407    fn the_server_does_not_swap_when_the_client_is_faster() {
408        let mut r = request();
409        r.native_byte_order = BIG;
410        r.endian_performance = 999999.0;
411        let a = accepted(negotiate(&r, &server()));
412        assert_eq!(a.byte_order, LITTLE);
413        assert!(!a.reverse_byte_order);
414    }
415
416    #[test]
417    fn a_one_byte_format_never_swaps() {
418        // Condition 3 needs a size above 1. This is the rule that makes the
419        // swapped one-byte stream unreachable in M2.
420        let mut s = server();
421        s.format = Format::Int8;
422        s.channel_bytes = 1;
423        let mut r = request();
424        r.value_size = 1;
425        r.native_byte_order = BIG;
426        r.endian_performance = 0.0;
427        let a = accepted(negotiate(&r, &s));
428        assert_eq!(a.byte_order, LITTLE);
429        assert!(!a.reverse_byte_order);
430    }
431
432    #[test]
433    fn an_unknown_byte_order_blocks_the_swap() {
434        let mut r = request();
435        r.native_byte_order = 2134; // the deprecated PDP order
436        r.endian_performance = 0.0;
437        let a = accepted(negotiate(&r, &server()));
438        assert_eq!(a.byte_order, LITTLE);
439        assert!(!a.reverse_byte_order);
440    }
441
442    #[test]
443    fn subnormal_suppression_follows_the_client() {
444        let mut r = request();
445        r.supports_subnormals = false;
446        assert!(accepted(negotiate(&r, &server())).suppress_subnormals);
447
448        // An integer format holds no subnormal value.
449        let mut s = server();
450        s.format = Format::Int32;
451        assert!(!accepted(negotiate(&r, &s)).suppress_subnormals);
452    }
453
454    #[test]
455    fn the_server_reads_protocol_version_and_not_data_protocol_version() {
456        // SPEC.md 4.4. This is the header that liblsl reads.
457        use crate::header::parse_block;
458
459        let with_dead = b"Data-Protocol-Version: 100\r\nValue-Size: 4\r\n\r\n";
460        let (h, _) = parse_block(with_dead).unwrap();
461        let r = FeedRequest::from_headers(110, "uid-1", &h, 4);
462        assert_eq!(
463            r.protocol_version, 110,
464            "the dead header must not change the version"
465        );
466        assert_eq!(
467            accepted(negotiate(&r, &server())).data_protocol_version,
468            110
469        );
470
471        let with_live = b"Protocol-Version: 100\r\nValue-Size: 4\r\n\r\n";
472        let (h, _) = parse_block(with_live).unwrap();
473        let r = FeedRequest::from_headers(110, "uid-1", &h, 4);
474        assert_eq!(r.protocol_version, 100);
475        assert_eq!(
476            accepted(negotiate(&r, &server())).data_protocol_version,
477            100
478        );
479    }
480
481    #[test]
482    fn the_answer_matches_the_shape_that_liblsl_writes() {
483        let a = accepted(negotiate(&request(), &server()));
484        let wire = a.to_wire(110, "uid-1");
485        assert_eq!(
486            wire,
487            "LSL/110 200 OK\r\nUID: uid-1\r\nByte-Order: 1234\r\n\
488             Suppress-Subnormals: 0\r\nData-Protocol-Version: 110\r\n\r\n"
489        );
490    }
491}