Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 6.6 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Reading and writing braid objects, with kinds checked and errors converted.
5
6use std::collections::HashMap;
7use std::sync::{Arc, Mutex, PoisonError};
8
9use braid_format::{Changeset, Entry, Kind, ObjectId, Objects, read_directory};
10
11use crate::error::Error;
12
13/// How many entries the directories a [`TreeCache`] keeps since its last
14/// drop may hold before the ones not used since are dropped.
15const TREE_CACHE_ENTRIES: usize = 1 << 17;
16
17/// Fetches an object that must be of `kind`.
18pub(crate) fn get<O: Objects>(objects: &O, id: &ObjectId, kind: Kind) -> Result<Vec<u8>, Error> {
19 match objects.get(id).map_err(Error::objects)? {
20 Some((found, payload)) if found == kind => Ok(payload),
21 Some((found, _)) => Err(Error::BadBraidObject {
22 id: *id,
23 detail: format!("is a {found}, expected a {kind}"),
24 }),
25 None => Err(Error::MissingBraidObject {
26 id: *id,
27 expected: kind,
28 }),
29 }
30}
31
32/// Stores an object and checks the id the store gives back.
33pub(crate) fn put<O: Objects>(objects: &O, kind: Kind, payload: &[u8]) -> Result<ObjectId, Error> {
34 put_hinted(objects, kind, payload, None)
35}
36
37/// Stores an object, with an object it is probably close to as a hint for
38/// the store, and checks the id the store gives back.
39pub(crate) fn put_hinted<O: Objects>(
40 objects: &O,
41 kind: Kind,
42 payload: &[u8],
43 similar: Option<&ObjectId>,
44) -> Result<ObjectId, Error> {
45 put_known(
46 objects,
47 kind,
48 payload,
49 similar,
50 ObjectId::hash(kind, payload),
51 )
52}
53
54/// [`put_hinted`] for a payload whose id the caller computed already, as
55/// `ObjectId::hash(kind, payload)`: the id the store gives back is checked
56/// against it.
57pub(crate) fn put_known<O: Objects>(
58 objects: &O,
59 kind: Kind,
60 payload: &[u8],
61 similar: Option<&ObjectId>,
62 expected: ObjectId,
63) -> Result<ObjectId, Error> {
64 let id = match similar {
65 Some(similar) => objects.put_similar(kind, payload, similar),
66 None => objects.put(kind, payload),
67 }
68 .map_err(Error::objects)?;
69 if id != expected {
70 return Err(Error::BadBraidObject {
71 id,
72 detail: format!("the store gave this id to the {kind} {expected}"),
73 });
74 }
75 Ok(id)
76}
77
78/// Directories, by id, so that reading one again costs a lookup.
79///
80/// What [`tree_entries`] gives for an id depends on nothing but the id: each
81/// node it reads is checked to hash to its id, every name is checked, and the
82/// nodes must be the canonical split of the entries. Keeping what it gave
83/// changes only the cost of reading a directory again.
84///
85/// A one-thread import keeps only what it read back from the store, so its
86/// checks, which read through this cache, still read what was stored, once.
87/// A parallel import also keeps the directories it converted and has not
88/// stored yet, as it built them ([`hold`](Self::hold)), since they cannot be
89/// read from the store until their batch is stored; its checks read the
90/// store directly, never through this cache.
91///
92/// Memory is bounded: once the directories used since the last drop hold
93/// [`TREE_CACHE_ENTRIES`] entries, the ones not used since are dropped.
94/// Directories held are never dropped until they are let go.
95#[derive(Default)]
96pub(crate) struct TreeCache {
97 inner: Mutex<Generations>,
98}
99
100#[derive(Default)]
101struct Generations {
102 /// Directories converted and not stored yet.
103 held: HashMap<ObjectId, Arc<[Entry]>>,
104 /// Directories read or used since the last drop.
105 recent: HashMap<ObjectId, Arc<[Entry]>>,
106 /// How many entries they hold, counting an empty one as one.
107 recent_entries: usize,
108 /// Directories read or used before the last drop: dropped at the next.
109 older: HashMap<ObjectId, Arc<[Entry]>>,
110}
111
112impl TreeCache {
113 /// Every entry of the directory `root`: the ones kept, or
114 /// [`tree_entries`].
115 pub(crate) fn entries<O: Objects>(
116 &self,
117 objects: &O,
118 root: ObjectId,
119 ) -> Result<Arc<[Entry]>, Error> {
120 if let Some(found) = self.lock().get(&root) {
121 return Ok(found);
122 }
123 let read: Arc<[Entry]> = tree_entries(objects, root)?.into();
124 self.lock().insert(root, Arc::clone(&read));
125 Ok(read)
126 }
127
128 /// Keeps the entries of a directory that is not stored yet, until
129 /// [`let_go`](Self::let_go).
130 pub(crate) fn hold(&self, id: ObjectId, entries: Arc<[Entry]>) {
131 self.lock().held.insert(id, entries);
132 }
133
134 /// The directories `ids` are stored now: they are kept like any other,
135 /// and may be dropped.
136 pub(crate) fn let_go(&self, ids: &[ObjectId]) {
137 let mut inner = self.lock();
138 for id in ids {
139 if let Some(entries) = inner.held.remove(id) {
140 inner.insert(*id, entries);
141 }
142 }
143 }
144
145 fn lock(&self) -> std::sync::MutexGuard<'_, Generations> {
146 // Every operation is a lookup or an insert: a panic cannot leave the
147 // maps half-written.
148 self.inner.lock().unwrap_or_else(PoisonError::into_inner)
149 }
150}
151
152impl Generations {
153 fn get(&mut self, id: &ObjectId) -> Option<Arc<[Entry]>> {
154 if let Some(found) = self.held.get(id).or_else(|| self.recent.get(id)) {
155 return Some(Arc::clone(found));
156 }
157 let found = self.older.remove(id)?;
158 self.insert(*id, Arc::clone(&found));
159 Some(found)
160 }
161
162 fn insert(&mut self, id: ObjectId, entries: Arc<[Entry]>) {
163 if self.recent_entries >= TREE_CACHE_ENTRIES {
164 self.older = std::mem::take(&mut self.recent);
165 self.recent_entries = 0;
166 }
167 self.recent_entries += entries.len().max(1);
168 self.recent.insert(id, entries);
169 }
170}
171
172/// Every entry of a directory, whether it is one flat node or split.
173pub(crate) fn tree_entries<O: Objects>(objects: &O, root: ObjectId) -> Result<Vec<Entry>, Error> {
174 let mut failure = None;
175 let entries = read_directory(root, |id| match get(objects, id, Kind::Tree) {
176 Ok(bytes) => Some(bytes),
177 Err(err) => {
178 failure.get_or_insert(err);
179 None
180 }
181 });
182 if let Some(err) = failure {
183 return Err(err);
184 }
185 entries.map_err(|err| Error::BadBraidObject {
186 id: root,
187 detail: err.to_string(),
188 })
189}
190
191/// A decoded changeset.
192pub(crate) fn changeset<O: Objects>(objects: &O, id: &ObjectId) -> Result<Changeset, Error> {
193 let bytes = get(objects, id, Kind::Changeset)?;
194 Changeset::decode(&bytes).map_err(|err| Error::BadBraidObject {
195 id: *id,
196 detail: err.to_string(),
197 })
198}