Skip to main content

gqls/load/
record_cache.rs

1//! On-disk cache of parsed schema records.
2//!
3//! Parsing dominates the fuzzy path on a large schema (~28ms of a ~45ms query
4//! at 48k records for SDL; more for introspection JSON), and the records
5//! depend only on the source bytes — SDL text or an introspection response —
6//! so cache them keyed by a hash of those bytes. Same idea and same house
7//! format rules as the vector cache: a small length-prefixed binary layout,
8//! dependency-free. A miss (schema edited, format bumped) simply re-parses
9//! and overwrites.
10
11use std::collections::hash_map::DefaultHasher;
12use std::hash::{Hash, Hasher};
13use std::io::Read;
14use std::path::PathBuf;
15
16use crate::model::{Kind, SchemaRecord};
17
18/// Bump when the on-disk encoding changes — old files then fail this check and
19/// re-parse. Changes to what the loaders *put* in a record are covered by the
20/// crate version in the key (see `path`), so they need no bump here.
21const MAGIC: u32 = 0x47_51_52_31; // "GQR1"
22
23/// Keep at most this many cache files (LRU by mtime, pruned on write).
24const MAX_FILES: usize = 32;
25
26/// Cached records for this source (SDL text or introspection JSON bytes), or
27/// `None` on any miss (absent, stale magic, corrupt).
28pub fn load(source: &[u8]) -> Option<Vec<SchemaRecord>> {
29    let p = path(source)?;
30    let mut buf = Vec::new();
31    std::fs::File::open(&p).ok()?.read_to_end(&mut buf).ok()?;
32    let records = decode(&buf)?;
33    crate::detail!("schema cache hit: {}", crate::paths::display(&p));
34    touch(&p);
35    Some(records)
36}
37
38/// Write records for this source (best-effort — a cache write failure is
39/// never fatal), then prune the least-recently-used files.
40pub fn store(source: &[u8], records: &[SchemaRecord]) {
41    let Some(p) = path(source) else {
42        return;
43    };
44    let Some(parent) = p.parent() else {
45        return;
46    };
47    if std::fs::create_dir_all(parent).is_err() {
48        return;
49    }
50    let _ = std::fs::write(&p, encode(records));
51    prune(MAX_FILES);
52}
53
54/// Delete every record cache file; returns how many were removed.
55pub fn clear() -> usize {
56    let Some(dir) = crate::paths::cache_dir() else {
57        return 0;
58    };
59    let mut removed = 0;
60    if let Ok(rd) = std::fs::read_dir(&dir) {
61        for e in rd.flatten() {
62            if e.path().extension().is_some_and(|x| x == "rcds")
63                && std::fs::remove_file(e.path()).is_ok()
64            {
65                removed += 1;
66            }
67        }
68    }
69    removed
70}
71
72fn path(source: &[u8]) -> Option<PathBuf> {
73    let mut h = DefaultHasher::new();
74    MAGIC.hash(&mut h);
75    // Keyed by the crate version as well as the source, because the records
76    // depend on how the loaders render them — teaching the SDL parser to keep
77    // argument defaults changes what's cached without changing the schema a
78    // byte. Re-parsing after an upgrade costs milliseconds; serving records
79    // from a previous parser silently omits whatever it has since learned.
80    env!("CARGO_PKG_VERSION").hash(&mut h);
81    source.hash(&mut h);
82    Some(crate::paths::cache_dir()?.join(format!("{:016x}.rcds", h.finish())))
83}
84
85/// Refresh mtime on a hit so an actively-used schema survives LRU pruning.
86fn touch(p: &std::path::Path) {
87    if let Ok(f) = std::fs::File::open(p) {
88        let _ = f.set_modified(std::time::SystemTime::now());
89    }
90}
91
92/// Delete all but the `keep` most-recently-used record cache files.
93fn prune(keep: usize) {
94    let Some(dir) = crate::paths::cache_dir() else {
95        return;
96    };
97    let mut files: Vec<(std::time::SystemTime, PathBuf)> = match std::fs::read_dir(&dir) {
98        Ok(rd) => rd
99            .flatten()
100            .filter(|e| e.path().extension().is_some_and(|x| x == "rcds"))
101            .filter_map(|e| Some((e.metadata().ok()?.modified().ok()?, e.path())))
102            .collect(),
103        Err(_) => return,
104    };
105    if files.len() <= keep {
106        return;
107    }
108    files.sort_by_key(|f| std::cmp::Reverse(f.0)); // newest first
109    for (_, p) in files.into_iter().skip(keep) {
110        let _ = std::fs::remove_file(p);
111    }
112}
113
114// --- encoding: MAGIC u32 | count u64 | records, all little-endian ---
115// Strings are u32-length-prefixed UTF-8; Option is a 0/1 byte then the value;
116// Vec is a u32 count then values; Kind round-trips via its stable string form.
117
118fn encode(records: &[SchemaRecord]) -> Vec<u8> {
119    let mut buf = Vec::with_capacity(64 * records.len() + 16);
120    buf.extend_from_slice(&MAGIC.to_le_bytes());
121    buf.extend_from_slice(&(records.len() as u64).to_le_bytes());
122    for r in records {
123        put_str(&mut buf, &r.path);
124        put_str(&mut buf, &r.name);
125        put_str(&mut buf, r.kind.as_str());
126        put_opt(&mut buf, r.parent.as_deref());
127        put_opt(&mut buf, r.type_ref.as_deref());
128        put_vec(&mut buf, &r.args);
129        put_opt(&mut buf, r.description.as_deref());
130        put_opt(&mut buf, r.deprecated.as_deref());
131        put_vec(&mut buf, &r.directives);
132    }
133    buf
134}
135
136fn decode(buf: &[u8]) -> Option<Vec<SchemaRecord>> {
137    let mut rd = Reader { buf, off: 0 };
138    if rd.u32()? != MAGIC {
139        return None;
140    }
141    let n = rd.u64()? as usize;
142    // Guard the capacity against a corrupt count: every record costs ≥ 9 bytes.
143    if n > buf.len() / 9 {
144        return None;
145    }
146    let mut out = Vec::with_capacity(n);
147    for _ in 0..n {
148        out.push(SchemaRecord {
149            path: rd.str()?,
150            name: rd.str()?,
151            kind: rd.str()?.parse::<Kind>().ok()?,
152            parent: rd.opt()?,
153            type_ref: rd.opt()?,
154            args: rd.vec()?,
155            description: rd.opt()?,
156            deprecated: rd.opt()?,
157            directives: rd.vec()?,
158        });
159    }
160    (rd.off == buf.len()).then_some(out)
161}
162
163fn put_str(buf: &mut Vec<u8>, s: &str) {
164    buf.extend_from_slice(&(s.len() as u32).to_le_bytes());
165    buf.extend_from_slice(s.as_bytes());
166}
167
168fn put_opt(buf: &mut Vec<u8>, s: Option<&str>) {
169    match s {
170        Some(s) => {
171            buf.push(1);
172            put_str(buf, s);
173        }
174        None => buf.push(0),
175    }
176}
177
178fn put_vec(buf: &mut Vec<u8>, v: &[String]) {
179    buf.extend_from_slice(&(v.len() as u32).to_le_bytes());
180    for s in v {
181        put_str(buf, s);
182    }
183}
184
185struct Reader<'a> {
186    buf: &'a [u8],
187    off: usize,
188}
189
190impl Reader<'_> {
191    fn take(&mut self, n: usize) -> Option<&[u8]> {
192        let end = self.off.checked_add(n)?;
193        let s = self.buf.get(self.off..end)?;
194        self.off = end;
195        Some(s)
196    }
197
198    fn u32(&mut self) -> Option<u32> {
199        Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
200    }
201
202    fn u64(&mut self) -> Option<u64> {
203        Some(u64::from_le_bytes(self.take(8)?.try_into().ok()?))
204    }
205
206    fn str(&mut self) -> Option<String> {
207        let n = self.u32()? as usize;
208        Some(std::str::from_utf8(self.take(n)?).ok()?.to_string())
209    }
210
211    fn opt(&mut self) -> Option<Option<String>> {
212        match self.take(1)?[0] {
213            0 => Some(None),
214            1 => Some(Some(self.str()?)),
215            _ => None,
216        }
217    }
218
219    fn vec(&mut self) -> Option<Vec<String>> {
220        let n = self.u32()? as usize;
221        // ≥ 4 bytes per element; reject a corrupt count before allocating.
222        if n > self.buf.len() / 4 {
223            return None;
224        }
225        let mut out = Vec::with_capacity(n);
226        for _ in 0..n {
227            out.push(self.str()?);
228        }
229        Some(out)
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    fn rec(name: &str) -> SchemaRecord {
238        SchemaRecord {
239            path: format!("User.{name}"),
240            name: name.into(),
241            kind: Kind::Field,
242            parent: Some("User".into()),
243            type_ref: Some("String!".into()),
244            args: vec!["first: Int".into(), "after: String".into()],
245            description: None,
246            deprecated: Some("use other".into()),
247            directives: vec![],
248        }
249    }
250
251    #[test]
252    fn round_trips_records() {
253        let records = vec![rec("email"), rec("name")];
254        let decoded = decode(&encode(&records)).unwrap();
255        assert_eq!(decoded.len(), 2);
256        let (a, b) = (&records[0], &decoded[0]);
257        assert_eq!(a.path, b.path);
258        assert_eq!(a.kind, b.kind);
259        assert_eq!(a.parent, b.parent);
260        assert_eq!(a.type_ref, b.type_ref);
261        assert_eq!(a.args, b.args);
262        assert_eq!(a.description, b.description);
263        assert_eq!(a.deprecated, b.deprecated);
264        assert_eq!(a.directives, b.directives);
265    }
266
267    #[test]
268    fn rejects_corrupt_data() {
269        let mut buf = encode(&[rec("email")]);
270        assert!(decode(&buf[..buf.len() - 1]).is_none()); // truncated
271        buf[0] ^= 0xFF; // bad magic
272        assert!(decode(&buf).is_none());
273        assert!(decode(&[]).is_none());
274    }
275
276    #[test]
277    fn rejects_trailing_garbage() {
278        let mut buf = encode(&[rec("email")]);
279        buf.push(0);
280        assert!(decode(&buf).is_none());
281    }
282}