1use crate::cache::ManifestGeneration;
16
17pub trait GraphReadAllocation {
21 fn bytes(&self) -> usize;
22
23 fn grow(&mut self, bytes: usize) -> hawdb_core::Result<()>;
26
27 fn retain_state(&mut self) -> hawdb_core::Result<()> {
31 Ok(())
32 }
33}
34
35pub struct GraphReadAllocator<'a, T = Box<dyn GraphReadAllocation>> {
38 admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<T>,
39 work: GraphReadWork<'a>,
40 control: Option<&'a hawdb_core::RuntimeTaskContext>,
41}
42
43impl<'a, T> GraphReadAllocator<'a, T> {
44 pub fn new(
45 admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<T>,
46 task_context: Option<&'a hawdb_core::RuntimeTaskContext>,
47 ) -> Self {
48 Self {
49 admit,
50 work: GraphReadWork(task_context.filter(|task| task.has_work_limit())),
51 control: task_context,
52 }
53 }
54
55 pub fn reserve(&mut self, bytes: usize) -> hawdb_core::Result<T> {
56 (self.admit)(bytes)
57 }
58
59 pub(crate) fn work(&self) -> GraphReadWork<'a> {
60 self.work
61 }
62
63 pub(crate) fn checkpoint(&self) -> hawdb_core::Result<()> {
64 self.control.map_or(Ok(()), |task| {
65 task.checkpoint()
66 .map_err(hawdb_core::HawDBError::RuntimeTaskStopped)
67 })
68 }
69
70 pub(crate) fn reborrow(&mut self) -> GraphReadAllocator<'_, T> {
71 GraphReadAllocator {
72 admit: self.admit,
73 work: self.work,
74 control: self.control,
75 }
76 }
77}
78
79#[derive(Clone, Copy)]
80pub(crate) struct GraphReadWork<'a>(Option<&'a hawdb_core::RuntimeTaskContext>);
81
82impl GraphReadWork<'_> {
83 pub(crate) fn has_work_limit(self) -> bool {
84 self.0.is_some()
85 }
86
87 pub(crate) fn check_work_limit(self) -> hawdb_core::Result<()> {
88 self.0.map_or(Ok(()), |task| task.check_work_limit())
89 }
90
91 pub(crate) fn charge_work(self, units: usize) -> hawdb_core::Result<()> {
92 self.0.map_or(Ok(()), |task| task.charge_work(units))
93 }
94}
95
96pub type ControlledGraphReadAllocator<'a> =
98 GraphReadAllocator<'a, Option<Box<dyn GraphReadAllocation>>>;
99
100pub enum AdmittedNodeRead {
103 Missing,
104 Stopped,
105 Node(AdmittedNodeRecord),
106}
107
108pub enum AdmittedRelationshipRead {
110 Missing,
111 Stopped,
112 Relationship(AdmittedRelationshipRecord),
113}
114
115pub struct AdmittedRelationshipRecord {
116 relationship: crate::RelRecord,
117 allocation: Box<dyn GraphReadAllocation>,
118}
119
120impl AdmittedRelationshipRecord {
121 pub(crate) fn new(
122 relationship: crate::RelRecord,
123 allocation: Box<dyn GraphReadAllocation>,
124 ) -> Self {
125 Self {
126 relationship,
127 allocation,
128 }
129 }
130
131 pub fn clone_admitted(
132 relationship: &crate::RelRecord,
133 allocation: Box<dyn GraphReadAllocation>,
134 ) -> hawdb_core::Result<Self> {
135 if allocation.bytes() < hawdb_core::ids::relationship_allocation_bytes(relationship) {
136 return Err(hawdb_core::HawDBError::Execution(
137 "relationship admission returned an insufficient allocation permit".into(),
138 ));
139 }
140 Ok(Self {
141 relationship: relationship.clone(),
142 allocation,
143 })
144 }
145
146 pub fn relationship(&self) -> &crate::RelRecord {
148 &self.relationship
149 }
150
151 pub fn retain_properties(&mut self, mut keep: impl FnMut(&str) -> bool) {
154 self.relationship
155 .properties
156 .retain(|name, _| keep(name.as_str()));
157 }
158
159 pub fn into_parts(self) -> (crate::RelRecord, Box<dyn GraphReadAllocation>) {
160 (self.relationship, self.allocation)
161 }
162}
163
164pub struct AdmittedProjectedNode {
167 node: crate::ProjectedNodeRecord,
168 allocation: Box<dyn GraphReadAllocation>,
169}
170
171impl AdmittedProjectedNode {
172 pub(crate) fn new(
173 node: crate::ProjectedNodeRecord,
174 allocation: Box<dyn GraphReadAllocation>,
175 ) -> Self {
176 Self { node, allocation }
177 }
178
179 pub fn clone_admitted(
181 node: &crate::NodeRecord,
182 properties: &std::collections::BTreeSet<String>,
183 allocation: Box<dyn GraphReadAllocation>,
184 ) -> hawdb_core::Result<Self> {
185 if allocation.bytes() < hawdb_core::ids::projected_node_allocation_bytes(node, properties) {
186 return Err(hawdb_core::HawDBError::Execution(
187 "projected node admission returned an insufficient allocation permit".into(),
188 ));
189 }
190 Ok(Self {
191 node: hawdb_core::ids::project_node_record_ref(node, properties),
192 allocation,
193 })
194 }
195
196 pub fn into_parts(self) -> (crate::ProjectedNodeRecord, Box<dyn GraphReadAllocation>) {
197 (self.node, self.allocation)
198 }
199}
200
201pub struct AdmittedNodeRecord {
203 node: crate::NodeRecord,
204 allocation: Box<dyn GraphReadAllocation>,
205}
206
207impl AdmittedNodeRecord {
208 pub(crate) fn new(node: crate::NodeRecord, allocation: Box<dyn GraphReadAllocation>) -> Self {
209 Self { node, allocation }
210 }
211
212 pub fn clone_admitted(
215 node: &crate::NodeRecord,
216 allocation: Box<dyn GraphReadAllocation>,
217 ) -> hawdb_core::Result<Self> {
218 if allocation.bytes() < hawdb_core::ids::node_allocation_bytes(node) {
219 return Err(hawdb_core::HawDBError::Execution(
220 "full node admission returned an insufficient allocation permit".into(),
221 ));
222 }
223 Ok(Self {
224 node: node.clone(),
225 allocation,
226 })
227 }
228
229 pub(crate) fn from_full_projection(input: AdmittedProjectedNode) -> Self {
230 let (node, allocation) = input.into_parts();
231 Self {
232 node: crate::NodeRecord {
233 id: node.id,
234 labels: node.labels,
235 properties: node.properties,
236 },
237 allocation,
238 }
239 }
240
241 pub fn into_parts(self) -> (crate::NodeRecord, Box<dyn GraphReadAllocation>) {
242 (self.node, self.allocation)
243 }
244}
245
246pub struct GraphReadAdmission<'a> {
248 admit: std::cell::RefCell<
249 &'a mut dyn FnMut(usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>>,
250 >,
251}
252
253impl<'a> GraphReadAdmission<'a> {
254 pub fn new(
255 admit: &'a mut dyn FnMut(usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>>,
256 ) -> Self {
257 Self {
258 admit: std::cell::RefCell::new(admit),
259 }
260 }
261
262 pub fn reserve(&self, bytes: usize) -> hawdb_core::Result<Box<dyn GraphReadAllocation>> {
263 let allocation = (self.admit.borrow_mut())(bytes)?;
264 if allocation.bytes() < bytes {
265 return Err(hawdb_core::HawDBError::Execution(
266 "graph read admission returned an insufficient allocation permit".into(),
267 ));
268 }
269 Ok(allocation)
270 }
271}
272
273pub struct AdmittedKeySet<T: Ord> {
277 keys: std::collections::BTreeSet<T>,
278 allocation: Box<dyn GraphReadAllocation>,
279}
280
281impl<T: Ord> AdmittedKeySet<T> {
282 pub fn new(admission: &GraphReadAdmission<'_>) -> hawdb_core::Result<Self> {
283 Ok(Self::with_allocation(admission.reserve(0)?))
284 }
285
286 pub(crate) fn with_allocation(allocation: Box<dyn GraphReadAllocation>) -> Self {
287 Self {
288 keys: std::collections::BTreeSet::new(),
289 allocation,
290 }
291 }
292
293 pub fn try_insert(&mut self, key: T) -> hawdb_core::Result<bool> {
294 self.allocation.grow(0)?;
297 if self.keys.contains(&key) {
298 return Ok(false);
299 }
300 self.allocation.retain_state()?;
301 let key_bytes = std::mem::size_of::<T>();
305 let bytes = self
306 .keys
307 .len()
308 .saturating_add(1)
309 .saturating_mul(64usize.saturating_add(key_bytes.saturating_mul(2)))
310 .saturating_add(128usize.saturating_add(key_bytes.saturating_mul(11)));
311 let additional = bytes.saturating_sub(self.allocation.bytes());
312 self.allocation.grow(additional)?;
313 if self.allocation.bytes() < bytes {
314 return Err(hawdb_core::HawDBError::Execution(
315 "graph read admission did not grow its allocation permit".into(),
316 ));
317 }
318 Ok(self.keys.insert(key))
319 }
320
321 pub fn try_extend(&mut self, keys: impl IntoIterator<Item = T>) -> hawdb_core::Result<()> {
322 for key in keys {
323 self.try_insert(key)?;
324 }
325 Ok(())
326 }
327}
328
329impl<T: Ord> std::ops::Deref for AdmittedKeySet<T> {
330 type Target = std::collections::BTreeSet<T>;
331 fn deref(&self) -> &Self::Target {
332 &self.keys
333 }
334}
335
336pub struct AdmittedVec<T> {
339 values: Vec<T>,
340 allocation: Box<dyn GraphReadAllocation>,
341}
342
343impl<T> AdmittedVec<T> {
344 pub fn new(admission: &GraphReadAdmission<'_>) -> hawdb_core::Result<Self> {
345 Ok(Self {
346 values: Vec::new(),
347 allocation: admission.reserve(0)?,
348 })
349 }
350
351 pub fn try_push(&mut self, value: T) -> hawdb_core::Result<()> {
352 if self.values.len() == self.values.capacity() {
353 let capacity = self.values.capacity().saturating_mul(2).max(4);
354 let bytes = capacity.saturating_mul(std::mem::size_of::<T>());
355 self.allocation
356 .grow(bytes.saturating_sub(self.allocation.bytes()))?;
357 if self.allocation.bytes() < bytes {
358 return Err(hawdb_core::HawDBError::Execution(
359 "graph read admission did not grow its allocation permit".into(),
360 ));
361 }
362 self.values.reserve_exact(capacity - self.values.len());
363 }
364 self.values.push(value);
365 Ok(())
366 }
367
368 pub fn into_parts(self) -> (Vec<T>, Box<dyn GraphReadAllocation>) {
369 (self.values, self.allocation)
370 }
371
372 pub fn as_slice(&self) -> &[T] {
373 &self.values
374 }
375
376 pub fn as_mut_slice(&mut self) -> &mut [T] {
378 &mut self.values
379 }
380
381 pub fn clear(&mut self) {
382 self.values.clear();
384 }
385
386 pub fn swap_remove(&mut self, index: usize) -> T {
388 self.values.swap_remove(index)
389 }
390}
391
392#[derive(Debug, Clone, Copy, PartialEq, Eq)]
398pub struct PublishedReadView {
399 visible_commit_epoch: u64,
400 checkpoint_commit_epoch: Option<u64>,
401 physical_generation: Option<ManifestGeneration>,
402 graph_generation: Option<ManifestGeneration>,
403}
404
405#[derive(Debug, Clone, Default)]
408pub struct PhysicalGenerationPins {
409 checkpoints: std::collections::BTreeSet<u64>,
410 graphs: std::collections::BTreeSet<u64>,
411 branch_wals: std::collections::BTreeSet<u64>,
412}
413
414impl PhysicalGenerationPins {
415 pub(crate) fn checkpoint_generations(&self) -> &std::collections::BTreeSet<u64> {
416 &self.checkpoints
417 }
418 pub(crate) fn graph_generations(&self) -> &std::collections::BTreeSet<u64> {
419 &self.graphs
420 }
421
422 pub(crate) fn retains_branch_wal(&self, generation: u64) -> bool {
423 self.checkpoints.contains(&generation) || self.branch_wals.contains(&generation)
424 }
425
426 #[doc(hidden)]
430 pub fn with_branch_wal_generation(mut self, generation: u64) -> Self {
431 self.branch_wals.insert(generation);
432 self
433 }
434
435 pub fn from_views(views: impl IntoIterator<Item = PublishedReadView>) -> Self {
436 let mut pins = Self::default();
437 for view in views {
438 pins.checkpoints
439 .extend(view.physical_generation.map(|generation| generation.0));
440 pins.graphs
441 .extend(view.graph_generation.map(|generation| generation.0));
442 }
443 pins
444 }
445}
446
447impl PublishedReadView {
448 #[doc(hidden)]
449 pub fn new(
450 visible_commit_epoch: u64,
451 checkpoint_commit_epoch: Option<u64>,
452 physical_generation: Option<ManifestGeneration>,
453 ) -> Self {
454 debug_assert_eq!(
455 checkpoint_commit_epoch.is_some(),
456 physical_generation.is_some(),
457 "checkpoint epoch and physical generation must be published together"
458 );
459 debug_assert!(
460 checkpoint_commit_epoch.is_none_or(|epoch| epoch <= visible_commit_epoch),
461 "checkpoint commit epoch must not exceed the visible commit epoch"
462 );
463 Self {
464 visible_commit_epoch,
465 checkpoint_commit_epoch,
466 physical_generation,
467 graph_generation: physical_generation,
468 }
469 }
470
471 #[doc(hidden)]
472 pub fn with_graph_generation(mut self, generation: Option<ManifestGeneration>) -> Self {
473 debug_assert_eq!(self.physical_generation.is_some(), generation.is_some());
474 self.graph_generation = generation;
475 self
476 }
477
478 pub fn physical_generations(self) -> impl Iterator<Item = ManifestGeneration> {
480 [self.physical_generation, self.graph_generation]
481 .into_iter()
482 .flatten()
483 }
484
485 pub const fn visible_commit_epoch(self) -> u64 {
486 self.visible_commit_epoch
487 }
488
489 pub const fn checkpoint_commit_epoch(self) -> Option<u64> {
490 self.checkpoint_commit_epoch
491 }
492
493 pub const fn physical_generation(self) -> Option<ManifestGeneration> {
494 self.physical_generation
495 }
496
497 pub const fn graph_generation(self) -> Option<ManifestGeneration> {
500 self.graph_generation
501 }
502
503 pub const fn physical_base_is_current(self) -> bool {
504 matches!(
505 self.checkpoint_commit_epoch,
506 Some(checkpoint_commit_epoch) if checkpoint_commit_epoch == self.visible_commit_epoch
507 )
508 }
509
510 pub const fn has_delta_after_physical_generation(self) -> bool {
511 matches!(
512 self.checkpoint_commit_epoch,
513 Some(checkpoint_commit_epoch) if checkpoint_commit_epoch < self.visible_commit_epoch
514 )
515 }
516}