Skip to main content

qualia_core_db/did_qi/
git_object.rs

1//! In-process git-like object store for Qualia Identifier documents.
2//!
3//! Blob encoding is `blob <len>\0` + bytes. Object id is SHA-256 of that
4//! encoding (not git SHA-1, not GitHub). Generation is an annotated-tag
5//! analogue (`qi/<generation>` as u64). Fixed slot cap; no unbounded map.
6
7use sha2::{Digest, Sha256};
8
9use super::id::DidQi;
10use super::{QiError, QiStore};
11
12pub const GIT_STORE_CAP: usize = 32;
13pub const MAX_BLOB: usize = super::document::MAX_SIGNED;
14pub const MAX_RECORD: usize = MAX_BLOB;
15
16#[derive(Clone, Copy)]
17struct GitSlot {
18    did: [u8; 32],
19    object_id: [u8; 32],
20    generation: u64,
21    len: u16,
22    bytes: [u8; MAX_BLOB],
23}
24
25pub struct GitObjectStore {
26    slots: Box<[Option<GitSlot>]>,
27}
28
29impl GitObjectStore {
30    /// Creates an empty object store.
31    pub fn new() -> Self {
32        Self {
33            slots: vec![None; GIT_STORE_CAP].into_boxed_slice(),
34        }
35    }
36
37    /// Current generation for `id`; `QiError` when unknown.
38    pub fn current_generation(&self, id: &DidQi) -> Result<u64, QiError> {
39        match self.find_latest(id) {
40            Some((_, slot)) => Ok(slot.generation),
41            None => Err(QiError::NotFound),
42        }
43    }
44
45    /// `true` when `generation` trails the current one.
46    pub fn is_stale(&self, id: &DidQi, generation: u64) -> Result<bool, QiError> {
47        Ok(generation < self.current_generation(id)?)
48    }
49
50    /// Content object id for `id`; `QiError` when unknown.
51    pub fn object_id_of(&self, id: &DidQi) -> Result<[u8; 32], QiError> {
52        match self.find_latest(id) {
53            Some((_, slot)) => Ok(slot.object_id),
54            None => Err(QiError::NotFound),
55        }
56    }
57
58    fn find_latest(&self, id: &DidQi) -> Option<(usize, GitSlot)> {
59        let mut best: Option<(usize, GitSlot)> = None;
60        let mut i = 0;
61        while i < GIT_STORE_CAP {
62            if let Some(slot) = self.slots[i] {
63                if slot.did == id.0 {
64                    match best {
65                        None => best = Some((i, slot)),
66                        Some((_, b)) if slot.generation >= b.generation => best = Some((i, slot)),
67                        _ => {}
68                    }
69                }
70            }
71            i += 1;
72        }
73        best
74    }
75
76    fn find_slot(&self, id: &DidQi, generation: u64) -> Option<usize> {
77        let mut i = 0;
78        while i < GIT_STORE_CAP {
79            if let Some(slot) = self.slots[i] {
80                if slot.did == id.0 && slot.generation == generation {
81                    return Some(i);
82                }
83            }
84            i += 1;
85        }
86        None
87    }
88
89    fn free_slot(&self) -> Option<usize> {
90        let mut i = 0;
91        while i < GIT_STORE_CAP {
92            if self.slots[i].is_none() {
93                return Some(i);
94            }
95            i += 1;
96        }
97        None
98    }
99}
100
101impl Default for GitObjectStore {
102    fn default() -> Self {
103        Self::new()
104    }
105}
106
107impl QiStore for GitObjectStore {
108    fn put(&mut self, id: &DidQi, generation: u64, payload: &[u8]) -> Result<(), QiError> {
109        if payload.len() > MAX_BLOB {
110            return Err(QiError::CanonicalTooLarge);
111        }
112        let mut bytes = [0u8; MAX_BLOB];
113        bytes[..payload.len()].copy_from_slice(payload);
114        let slot = GitSlot {
115            did: id.0,
116            object_id: blob_object_id(payload),
117            generation,
118            len: payload.len() as u16,
119            bytes,
120        };
121        if let Some(i) = self.find_slot(id, generation) {
122            self.slots[i] = Some(slot);
123            return Ok(());
124        }
125        let i = self.free_slot().ok_or(QiError::StoreFull)?;
126        self.slots[i] = Some(slot);
127        Ok(())
128    }
129
130    fn get(&self, id: &DidQi, out: &mut [u8]) -> Result<(u64, usize), QiError> {
131        let (_, slot) = self.find_latest(id).ok_or(QiError::NotFound)?;
132        let n = slot.len as usize;
133        if out.len() < n {
134            return Err(QiError::BufferTooSmall);
135        }
136        out[..n].copy_from_slice(&slot.bytes[..n]);
137        Ok((slot.generation, n))
138    }
139}
140
141/// Writes `n` as ASCII decimal into `out`; returns bytes written.
142pub fn write_decimal(n: usize, out: &mut [u8]) -> Result<usize, QiError> {
143    if n == 0 {
144        if out.is_empty() {
145            return Err(QiError::BufferTooSmall);
146        }
147        out[0] = b'0';
148        return Ok(1);
149    }
150    let mut tmp = [0u8; 20];
151    let mut x = n;
152    let mut i = 20;
153    while x > 0 {
154        i -= 1;
155        tmp[i] = b'0' + (x % 10) as u8;
156        x /= 10;
157    }
158    let len = 20 - i;
159    if out.len() < len {
160        return Err(QiError::BufferTooSmall);
161    }
162    out[..len].copy_from_slice(&tmp[i..]);
163    Ok(len)
164}
165
166/// Encodes `content` as a git blob (`blob <len><content>`); returns bytes written.
167pub fn encode_blob(content: &[u8], out: &mut [u8]) -> Result<usize, QiError> {
168    let mut dec = [0u8; 20];
169    let dlen = write_decimal(content.len(), &mut dec)?;
170    let need = 5 + dlen + 1 + content.len();
171    if out.len() < need {
172        return Err(QiError::BufferTooSmall);
173    }
174    out[..5].copy_from_slice(b"blob ");
175    out[5..5 + dlen].copy_from_slice(&dec[..dlen]);
176    out[5 + dlen] = 0;
177    out[6 + dlen..need].copy_from_slice(content);
178    Ok(need)
179}
180
181/// SHA-256 object id of a blob encoding of `content`.
182pub fn blob_object_id(content: &[u8]) -> [u8; 32] {
183    let mut hasher = Sha256::new();
184    hasher.update(b"blob ");
185    let mut dec = [0u8; 20];
186    let dlen = write_decimal(content.len(), &mut dec).unwrap_or(1);
187    hasher.update(&dec[..dlen]);
188    hasher.update([0u8]);
189    hasher.update(content);
190    hasher.finalize().into()
191}
192
193/// Annotated-tag analogue: writes `qi/<generation>` into `out`.
194pub fn tag_name(generation: u64, out: &mut [u8]) -> Result<usize, QiError> {
195    if out.len() < 3 {
196        return Err(QiError::BufferTooSmall);
197    }
198    out[0] = b'q';
199    out[1] = b'i';
200    out[2] = b'/';
201    let mut dec = [0u8; 20];
202    let dlen = write_decimal(generation as usize, &mut dec)?;
203    if out.len() < 3 + dlen {
204        return Err(QiError::BufferTooSmall);
205    }
206    out[3..3 + dlen].copy_from_slice(&dec[..dlen]);
207    Ok(3 + dlen)
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213
214    #[test]
215    fn git_object_id_deterministic_for_same_bytes() {
216        let a = blob_object_id(b"qualia-identifier");
217        let b = blob_object_id(b"qualia-identifier");
218        let c = blob_object_id(b"qualia-identifier!");
219        assert_eq!(a, b);
220        assert_ne!(a, c);
221        let mut blob = [0u8; 64];
222        let n = encode_blob(b"qualia-identifier", &mut blob).unwrap();
223        assert_eq!(&blob[..5], b"blob ");
224        assert_eq!(&blob[5..8], b"17\0");
225        let hashed = {
226            let mut h = Sha256::new();
227            h.update(&blob[..n]);
228            let d: [u8; 32] = h.finalize().into();
229            d
230        };
231        assert_eq!(a, hashed);
232    }
233
234    #[test]
235    fn store_put_get_and_stale_generation() {
236        let mut store = GitObjectStore::new();
237        let id = DidQi([11u8; 32]);
238        store.put(&id, 1, b"gen-one").unwrap();
239        store.put(&id, 2, b"gen-two").unwrap();
240        let mut out = [0u8; 32];
241        let (gen, n) = store.get(&id, &mut out).unwrap();
242        assert_eq!(gen, 2);
243        assert_eq!(&out[..n], b"gen-two");
244        assert!(store.is_stale(&id, 1).unwrap());
245        assert!(!store.is_stale(&id, 2).unwrap());
246        let mut tag = [0u8; 16];
247        let tn = tag_name(2, &mut tag).unwrap();
248        assert_eq!(&tag[..tn], b"qi/2");
249    }
250
251    #[test]
252    fn empty_store_get_fails_closed() {
253        let store = GitObjectStore::new();
254        let mut out = [0u8; 8];
255        assert_eq!(
256            store.get(&DidQi([1u8; 32]), &mut out),
257            Err(QiError::NotFound)
258        );
259    }
260
261    #[test]
262    fn store_full_fails_closed() {
263        let mut store = GitObjectStore::new();
264        let mut i = 0u8;
265        while i < GIT_STORE_CAP as u8 {
266            let mut did = [0u8; 32];
267            did[0] = i;
268            store.put(&DidQi(did), 1, b"x").unwrap();
269            i += 1;
270        }
271        assert_eq!(
272            store.put(&DidQi([0xff; 32]), 1, b"y"),
273            Err(QiError::StoreFull)
274        );
275    }
276
277    #[test]
278    fn tag_name_formats_correctly() {
279        let mut buf = [0u8; 16];
280        let len = tag_name(42, &mut buf).unwrap();
281        assert_eq!(&buf[..len], b"qi/42");
282    }
283}