Skip to main content

oxabl_cache_format/
lookup_response.rs

1//! `OXLR` lookup response.
2
3use std::collections::HashSet;
4
5use crate::cursor::Cursor;
6use crate::error::{FormatError, Result};
7use crate::frame::{read_header, write_header};
8use crate::ids::{PackId, SegmentId};
9use crate::location::check_range;
10use crate::lookup_request::{LookupFlags, LookupShape};
11use crate::namespace::Namespace;
12use crate::writer::{Writer, len32};
13
14const MAGIC: [u8; 4] = *b"OXLR";
15
16/// A pack the response refers to.
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct ResponsePack<'a> {
19    pub pack_id: PackId,
20    /// Presigned GET URL; empty unless the request asked for URLs.
21    pub url: &'a str,
22    pub expires_at: u64,
23}
24
25/// A hit's record and where its segment lives.
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub struct HitRecord<'a> {
28    pub pack_idx: u32,
29    pub offset: u64,
30    pub length: u32,
31    /// Sealed record bytes, opaque at this layer.
32    pub record: &'a [u8],
33}
34
35/// One hit of one request id in one namespace.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct LookupHit<'a> {
38    /// Position of the id in the request.
39    pub index: u32,
40    pub ns: Namespace,
41    /// Present exactly when the request asked for records.
42    pub record: Option<HitRecord<'a>>,
43}
44
45/// A dictionary segment named by a returned entry.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct ResponseDictionary {
48    pub dict_id: SegmentId,
49    pub pack_idx: u32,
50    pub offset: u64,
51    pub length: u32,
52}
53
54/// A lookup response.
55#[derive(Debug, Clone, PartialEq, Eq)]
56pub struct LookupResponse<'a> {
57    pub flags: LookupFlags,
58    pub packs: Vec<ResponsePack<'a>>,
59    pub hits: Vec<LookupHit<'a>>,
60    pub dictionaries: Vec<ResponseDictionary>,
61}
62
63const PACK_MIN: usize = 16 + 2 + 8;
64const HIT_PRESENCE: usize = 5;
65const HIT_RECORD: usize = HIT_PRESENCE + 4 + 8 + 4 + 2;
66const DICT_LEN: usize = 32 + 4 + 8 + 4;
67
68fn max_hits(shape: &LookupShape) -> usize {
69    (shape.count as usize).saturating_mul(shape.namespaces.len())
70}
71
72impl<'a> LookupResponse<'a> {
73    pub fn encode(&self, shape: &LookupShape) -> Result<Vec<u8>> {
74        self.check(shape)?;
75        let mut w = Writer::default();
76        write_header(&mut w, MAGIC, self.flags.to_bits());
77        w.u16(0);
78        w.u32(len32(self.packs.len(), "response packs")?);
79        for p in &self.packs {
80            w.bytes(&p.pack_id.0);
81            w.str16(p.url)?;
82            w.u64(p.expires_at);
83        }
84        w.u32(len32(self.hits.len(), "response hits")?);
85        for h in &self.hits {
86            w.u32(h.index);
87            w.u8(h.ns.to_u8());
88            if let Some(r) = &h.record {
89                w.u32(r.pack_idx);
90                w.u64(r.offset);
91                w.u32(r.length);
92                w.record(r.record)?;
93            }
94        }
95        w.u32(len32(self.dictionaries.len(), "response dictionaries")?);
96        for d in &self.dictionaries {
97            w.bytes(&d.dict_id.0);
98            w.u32(d.pack_idx);
99            w.u64(d.offset);
100            w.u32(d.length);
101        }
102        Ok(w.into_vec())
103    }
104
105    /// Decodes a response to a request of the given shape.
106    pub fn decode(bytes: &'a [u8], shape: &LookupShape) -> Result<Self> {
107        let mut c = Cursor::new(bytes);
108        let flags = LookupFlags::from_bits(read_header(&mut c, MAGIC, 0b11)?);
109        if flags != shape.flags {
110            return Err(FormatError::Invalid("flags differ from the request"));
111        }
112        c.reserved_u16()?;
113        let hit_cap = max_hits(shape);
114        let pack_cap = hit_cap.saturating_mul(2);
115        let pack_count = c.count32(pack_cap, "response packs", PACK_MIN)?;
116        let mut packs = Vec::with_capacity(pack_count);
117        for _ in 0..pack_count {
118            packs.push(ResponsePack {
119                pack_id: PackId(c.array()?),
120                url: c.str16()?,
121                expires_at: c.u64()?,
122            });
123        }
124        let hit_min = if flags.records {
125            HIT_RECORD
126        } else {
127            HIT_PRESENCE
128        };
129        let hit_count = c.count32(hit_cap, "response hits", hit_min)?;
130        let mut hits = Vec::with_capacity(hit_count);
131        for _ in 0..hit_count {
132            let index = c.u32()?;
133            let ns = Namespace::from_u8(c.u8()?)?;
134            let record = if flags.records {
135                let pack_idx = c.u32()?;
136                let offset = c.u64()?;
137                let length = c.u32()?;
138                Some(HitRecord {
139                    pack_idx,
140                    offset,
141                    length,
142                    record: c.record()?,
143                })
144            } else {
145                None
146            };
147            hits.push(LookupHit { index, ns, record });
148        }
149        let dict_count = c.count32(hit_cap, "response dictionaries", DICT_LEN)?;
150        let mut dictionaries = Vec::with_capacity(dict_count);
151        for _ in 0..dict_count {
152            dictionaries.push(ResponseDictionary {
153                dict_id: SegmentId(c.array()?),
154                pack_idx: c.u32()?,
155                offset: c.u64()?,
156                length: c.u32()?,
157            });
158        }
159        c.finish()?;
160        let response = Self {
161            flags,
162            packs,
163            hits,
164            dictionaries,
165        };
166        response.check(shape)?;
167        Ok(response)
168    }
169
170    fn check(&self, shape: &LookupShape) -> Result<()> {
171        if self.flags != shape.flags {
172            return Err(FormatError::Invalid("flags differ from the request"));
173        }
174        let hit_cap = max_hits(shape);
175        if self.hits.len() > hit_cap || self.dictionaries.len() > hit_cap {
176            return Err(FormatError::LimitExceeded("response hits"));
177        }
178        if self.packs.len() > hit_cap.saturating_mul(2) {
179            return Err(FormatError::LimitExceeded("response packs"));
180        }
181        if !self.flags.urls && self.packs.iter().any(|p| !p.url.is_empty()) {
182            return Err(FormatError::Invalid("url without the urls flag"));
183        }
184        if self.flags.urls && self.packs.iter().any(|p| p.url.is_empty()) {
185            return Err(FormatError::Invalid("missing url"));
186        }
187        if !self.flags.records && !self.dictionaries.is_empty() {
188            return Err(FormatError::Invalid(
189                "dictionaries without the records flag",
190            ));
191        }
192        let pack_count = self.packs.len();
193        let in_range = |idx: u32| (idx as usize) < pack_count;
194        let mut seen = HashSet::with_capacity(self.hits.len());
195        for h in &self.hits {
196            if h.index >= shape.count || !shape.namespaces.contains(h.ns) {
197                return Err(FormatError::Invalid("hit outside the request"));
198            }
199            if !seen.insert((h.index, h.ns)) {
200                return Err(FormatError::Invalid("duplicate hit"));
201            }
202            match (&h.record, self.flags.records) {
203                (Some(r), true) => {
204                    if !in_range(r.pack_idx) {
205                        return Err(FormatError::Invalid("pack index"));
206                    }
207                    check_range(r.offset, r.length)?;
208                }
209                (None, false) => {}
210                _ => return Err(FormatError::Invalid("record presence")),
211            }
212        }
213        let mut dicts = HashSet::with_capacity(self.dictionaries.len());
214        for d in &self.dictionaries {
215            if !in_range(d.pack_idx) {
216                return Err(FormatError::Invalid("pack index"));
217            }
218            check_range(d.offset, d.length)?;
219            if !dicts.insert(d.dict_id) {
220                return Err(FormatError::Invalid("duplicate dictionary"));
221            }
222        }
223        Ok(())
224    }
225}