Skip to main content

iggy_binary_protocol/responses/users/
user_response.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::WireError;
19use crate::codec::{WireDecode, WireEncode, read_u8, read_u32_le, read_u64_le};
20use crate::primitives::identifier::WireName;
21use crate::primitives::options::{
22    WireOptions, decode_options_prefixed, encode_options_prefixed, options_prefixed_size,
23};
24use bytes::{BufMut, BytesMut};
25
26/// User header on the wire. Used in both single-user and multi-user responses.
27///
28/// Wire format (13 + `username_len` + options bytes):
29/// ```text
30/// [id:4][created_at:8][status:1][username_len:1][username:N]
31/// [options_len:4][options TLV]
32/// ```
33///
34/// Users have no server-derived options (no catalog keys resolve against
35/// config yet), so a single client-explicit block suffices.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct UserResponse {
38    pub id: u32,
39    pub created_at: u64,
40    pub status: u8,
41    pub username: WireName,
42    pub options: WireOptions,
43}
44
45impl UserResponse {
46    const FIXED_SIZE: usize = 4 + 8 + 1; // 13
47}
48
49impl WireEncode for UserResponse {
50    fn encoded_size(&self) -> usize {
51        Self::FIXED_SIZE + self.username.encoded_size() + options_prefixed_size(&self.options)
52    }
53
54    fn encode(&self, buf: &mut BytesMut) {
55        buf.put_u32_le(self.id);
56        buf.put_u64_le(self.created_at);
57        buf.put_u8(self.status);
58        self.username.encode(buf);
59        encode_options_prefixed(&self.options, buf);
60    }
61}
62
63impl WireDecode for UserResponse {
64    fn decode(buf: &[u8]) -> Result<(Self, usize), WireError> {
65        let id = read_u32_le(buf, 0)?;
66        let created_at = read_u64_le(buf, 4)?;
67        let status = read_u8(buf, 12)?;
68        let (username, name_consumed) = WireName::decode(&buf[13..])?;
69        let mut consumed = 13 + name_consumed;
70        let (options, options_consumed) = decode_options_prefixed(buf, consumed)?;
71        consumed += options_consumed;
72
73        Ok((
74            Self {
75                id,
76                created_at,
77                status,
78                username,
79                options,
80            },
81            consumed,
82        ))
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    fn sample() -> UserResponse {
91        UserResponse {
92            id: 1,
93            created_at: 1_710_000_000_000,
94            status: 1,
95            username: WireName::new("admin").unwrap(),
96            options: WireOptions::empty(),
97        }
98    }
99
100    #[test]
101    fn roundtrip() {
102        let resp = sample();
103        let bytes = resp.to_bytes();
104        assert_eq!(bytes.len(), UserResponse::FIXED_SIZE + 1 + 5 + 4);
105        let (decoded, consumed) = UserResponse::decode(&bytes).unwrap();
106        assert_eq!(consumed, bytes.len());
107        assert_eq!(decoded, resp);
108    }
109
110    #[test]
111    fn truncated_returns_error() {
112        let resp = sample();
113        let bytes = resp.to_bytes();
114        for i in 0..bytes.len() {
115            assert!(
116                UserResponse::decode(&bytes[..i]).is_err(),
117                "expected error for truncation at byte {i}"
118            );
119        }
120    }
121
122    #[test]
123    fn multiple_users_sequential() {
124        let u1 = UserResponse {
125            id: 1,
126            username: WireName::new("alice").unwrap(),
127            ..sample()
128        };
129        let u2 = UserResponse {
130            id: 2,
131            username: WireName::new("bob").unwrap(),
132            ..sample()
133        };
134        let mut buf = BytesMut::new();
135        u1.encode(&mut buf);
136        u2.encode(&mut buf);
137        let bytes = buf.freeze();
138
139        let (d1, pos1) = UserResponse::decode(&bytes).unwrap();
140        let (d2, pos2) = UserResponse::decode(&bytes[pos1..]).unwrap();
141        assert_eq!(d1, u1);
142        assert_eq!(d2, u2);
143        assert_eq!(pos1 + pos2, bytes.len());
144    }
145}