hawdb 0.9.0

An embedded Rust graph database for local data-plane workloads
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// Copyright 2026 Nowledge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

pub(super) use hawdb_search::projection_consumer::ConsumerRegistry;
pub use hawdb_search::projection_consumer::{
    SearchProjectionConsumer, SearchProjectionConsumerCatchUpReport, SearchProjectionConsumerError,
    SearchProjectionConsumerId, SearchProjectionConsumerOptions, SearchProjectionConsumerReadiness,
    SearchProjectionConsumerRebuildReason, SearchProjectionConsumerResult,
    SearchProjectionConsumerState, SearchProjectionConsumerStatus,
};

use super::Database;
use crate::{
    DatabaseReadTransaction, HawDBError, Result, SearchIndex, SearchProjectionCatchUpReport,
    SearchProjectionChangeBatch, SearchProjectionRelationalDelta,
};
use hawdb_core::uuidv7::generate_uuidv7;
use hawdb_search::consumer::{CheckpointReceipt, ConsumerBinding, ConsumerProjection};
use hawdb_search::projection_consumer::{Record, MAX_CONSUMERS};
use hawdb_storage::file_io as fs;
use std::path::{Path, PathBuf};
use SearchProjectionConsumerError as Error;
use SearchProjectionConsumerRebuildReason as Reason;
use SearchProjectionConsumerState as State;

impl Database {
    /// Initializes a complete application projection from one pinned source
    /// snapshot. The initializer must propagate incomplete hydration and budget
    /// errors; it owns the mapping of graph and relational rows into documents.
    /// The initializer must retain the staging index and its default analyzer;
    /// custom analyzer rules are not persisted by the current snapshot format.
    pub fn create_search_projection_consumer<F>(
        &mut self,
        id: SearchProjectionConsumerId,
        projection_directory: impl AsRef<Path>,
        options: SearchProjectionConsumerOptions,
        initialize: F,
    ) -> SearchProjectionConsumerResult<SearchProjectionConsumer>
    where
        F: FnOnce(&mut DatabaseReadTransaction, &mut SearchIndex) -> Result<()>,
    {
        let root = self.consumer_writable_root()?;
        if self.runtime.get_mut()?.projection_consumers.unavailable {
            self.runtime.get_mut()?.projection_consumers = ConsumerRegistry::load(
                Some(&root),
                self.runtime
                    .get()?
                    .store
                    .search_projection_database_identity(),
            );
        }
        let destination = projection_directory.as_ref();
        if destination.try_exists().map_err(HawDBError::from)? {
            return Err(HawDBError::Storage(
                "consumer projection destination already exists".into(),
            )
            .into());
        }
        let parent = destination
            .parent()
            .filter(|path| !path.as_os_str().is_empty())
            .unwrap_or_else(|| Path::new("."));
        if !parent.is_dir() {
            return Err(HawDBError::Storage("consumer projection parent must exist".into()).into());
        }
        let identity = self
            .runtime
            .get()?
            .store
            .search_projection_database_identity();
        let reinitialize_registry = self.runtime.get_mut()?.projection_consumers.unavailable
            || self
                .runtime
                .get_mut()?
                .projection_consumers
                .database_uuid
                .is_some_and(|registered_identity| Some(registered_identity) != identity);
        if !reinitialize_registry {
            if self
                .runtime
                .get_mut()?
                .projection_consumers
                .records
                .contains_key(id.as_str())
            {
                return Err(Error::AlreadyRegistered);
            }
            if self.runtime.get_mut()?.projection_consumers.records.len() >= MAX_CONSUMERS {
                return Err(Error::RegistryFull);
            }
        }
        let expires_at_commit_epoch = self
            .runtime
            .get()?
            .store
            .commit_epoch()
            .checked_add(options.max_idle_commits().get())
            .ok_or_else(|| HawDBError::Semantic("consumer expiry epoch overflow".into()))?;
        let database_uuid = match self
            .runtime
            .get()?
            .store
            .search_projection_database_identity()
        {
            Some(identity) => identity,
            None => {
                let identity = generate_uuidv7()?;
                self.runtime
                    .get_mut()?
                    .store
                    .set_search_projection_database_identity(identity);
                identity
            }
        };
        // Also retry this checkpoint after an earlier identity publication error.
        self.checkpoint()?;
        let registration_uuid = generate_uuidv7()?;
        let binding = ConsumerBinding {
            database_uuid,
            projection_uuid: generate_uuidv7()?,
            consumer_id: id.as_str().into(),
            registration_uuid,
            checkpoint_uuid: generate_uuidv7()?,
        };
        let stage = parent.join(format!(".hawdb-consumer-{registration_uuid}.stage"));
        fs::create_dir(&stage).map_err(HawDBError::from)?;
        let stage_guard = StageDirectory(stage.clone());
        let mut snapshot = self.begin_read_transaction()?;
        let epoch = snapshot.commit_epoch();
        let initialized = (|| -> Result<ConsumerProjection> {
            let mut projection = ConsumerProjection::initialize(&stage, binding, epoch, |index| {
                initialize(&mut snapshot, index)
            })?;
            publication_failpoint(PublicationStage::AfterCheckpoint)?;
            projection.publish_directory(destination)?;
            Ok(projection)
        })();
        drop(snapshot);
        let projection = match initialized {
            Ok(projection) => {
                stage_guard.cleanup()?;
                projection
            }
            Err(error) => {
                if let Err(cleanup) = stage_guard.cleanup() {
                    // An exhausted cleanup must retain the stage and remain
                    // retryable even if initialization failed for another reason.
                    if let Some(resource) = hawdb_core::error::file_descriptor_error(&error)
                        .or_else(|| hawdb_core::error::file_descriptor_error(&cleanup))
                    {
                        return Err(HawDBError::FileDescriptors(resource).into());
                    }
                    return Err(HawDBError::Storage(format!("consumer initialization failed: {error}; staging cleanup failed: {cleanup}")).into());
                }
                return Err(error.into());
            }
        };
        let receipt = projection.receipt();
        // Invalid foreign/corrupt records have no authority in this database.
        // Replace them only after explicit initialization actually succeeds.
        if reinitialize_registry {
            self.runtime.get_mut()?.projection_consumers = ConsumerRegistry::default();
        }
        self.runtime.get_mut()?.projection_consumers.database_uuid = Some(database_uuid);

        self.runtime.get_mut()?.projection_consumers.records.insert(
            id.as_str().into(),
            Record {
                checkpoint_uuid: receipt.binding.checkpoint_uuid.to_string(),
                durable_complete_through_epoch: receipt.source_epoch,
                expires_at_commit_epoch,
                id: id.as_str().into(),
                max_idle_commits: options.max_idle_commits().get(),
                projection_uuid: receipt.binding.projection_uuid.to_string(),
                registration_uuid: registration_uuid.to_string(),
                snapshot_encoded_len: receipt.encoded_len,
                snapshot_sha256: receipt.sha256,
            },
        );
        self.publish_consumer_registry(&root)?;
        self.runtime
            .get_mut()?
            .projection_consumers
            .verified
            .insert(id.as_str().into(), State::Active);
        Ok(SearchProjectionConsumer::from_projection(id, projection))
    }

    pub fn open_search_projection_consumer(
        &mut self,
        id: &SearchProjectionConsumerId,
        projection_directory: impl AsRef<Path>,
    ) -> SearchProjectionConsumerResult<SearchProjectionConsumer> {
        self.ensure_writable()?;
        let status = self.search_projection_consumer_status(id)?;
        if let State::RebuildRequired(reason) = status.state {
            return Err(Error::RebuildRequired(reason));
        }
        let projection = match ConsumerProjection::open(projection_directory.as_ref()) {
            Ok(projection) => projection,
            Err(HawDBError::StorageIntegrity(_)) => {
                self.runtime
                    .get_mut()?
                    .projection_consumers
                    .verified
                    .insert(
                        id.as_str().into(),
                        State::RebuildRequired(Reason::CheckpointMismatch),
                    );
                return Err(Error::RebuildRequired(Reason::CheckpointMismatch));
            }
            Err(error) => return Err(error.into()),
        };
        let consumer = SearchProjectionConsumer::from_projection(id.clone(), projection);
        if let Err(error) = self.validate_consumer_receipt(&consumer) {
            if let Error::RebuildRequired(reason) = &error {
                self.runtime
                    .get_mut()?
                    .projection_consumers
                    .verified
                    .insert(id.as_str().into(), State::RebuildRequired(reason.clone()));
            }
            return Err(error);
        }
        self.runtime
            .get_mut()?
            .projection_consumers
            .verified
            .insert(id.as_str().into(), State::Active);
        Ok(consumer)
    }

    pub fn catch_up_search_projection_consumer<F>(
        &mut self,
        consumer: &mut SearchProjectionConsumer,
        max_change_operations_per_batch: usize,
        max_projection_operations_per_batch: usize,
        max_batches: usize,
        mut batch_hydrator: F,
    ) -> SearchProjectionConsumerResult<SearchProjectionConsumerCatchUpReport>
    where
        F: FnMut(
            &mut DatabaseReadTransaction,
            &SearchProjectionChangeBatch,
        ) -> Result<SearchProjectionRelationalDelta>,
    {
        let root = self.consumer_writable_root()?;
        self.validate_consumer_receipt(consumer)?;
        self.runtime
            .get_mut()?
            .projection_consumers
            .verified
            .insert(consumer.id().as_str().into(), State::Active);
        if max_change_operations_per_batch == 0
            || max_projection_operations_per_batch == 0
            || max_batches == 0
        {
            return Err(HawDBError::Semantic(
                "consumer catch-up budgets must be greater than zero".into(),
            )
            .into());
        }
        let start = consumer.search_index().projection_freshness();
        let graph_commit_epoch = self.runtime.get()?.store.commit_epoch();
        let mut applied_batch_count = 0usize;
        let mut applied_operation_count = 0usize;
        while applied_batch_count < max_batches {
            let Some(mut batch) = self.build_search_projection_change_batch_from_freshness(
                consumer.search_index(),
                Some(max_change_operations_per_batch),
            )?
            else {
                break;
            };
            let operation_count = batch.operation_count();
            let mut snapshot = self.begin_read_transaction()?;
            let hydrated = batch_hydrator(&mut snapshot, &batch)?;
            drop(snapshot);
            batch.graph_delta_mut().max_operations = Some(max_projection_operations_per_batch);
            consumer
                .projection_mut()
                .apply(|index| self.apply_search_projection_change_batch(index, batch, hydrated))?;
            // Any error from this point leaves an applied or durable projection
            // that must not be silently paired with the previous cursor receipt.
            self.runtime
                .get_mut()?
                .projection_consumers
                .verified
                .insert(
                    consumer.id().as_str().into(),
                    State::RebuildRequired(Reason::CheckpointMismatch),
                );
            publication_failpoint(PublicationStage::BeforeCheckpoint)?;
            let receipt = consumer.projection_mut().checkpoint()?;
            publication_failpoint(PublicationStage::AfterCheckpoint)?;
            self.acknowledge_consumer_checkpoint(consumer.id(), &receipt)?;
            self.publish_consumer_registry(&root)?;
            self.runtime
                .get_mut()?
                .projection_consumers
                .verified
                .insert(consumer.id().as_str().into(), State::Active);
            applied_batch_count = applied_batch_count.saturating_add(1);
            applied_operation_count = applied_operation_count.saturating_add(operation_count);
        }
        let end = consumer.search_index().projection_freshness();
        Ok(SearchProjectionConsumerCatchUpReport {
            catch_up: SearchProjectionCatchUpReport {
                graph_commit_epoch,
                start_applied_epoch: start.source_graph_commit_epoch,
                start_durable_epoch: start.durable_source_graph_commit_epoch,
                end_applied_epoch: end.source_graph_commit_epoch,
                end_durable_epoch: end.durable_source_graph_commit_epoch,
                applied_batch_count,
                applied_operation_count,
                complete: end.durable_source_graph_commit_epoch == Some(graph_commit_epoch),
            },
            consumer: self.search_projection_consumer_status(consumer.id())?,
        })
    }

    pub fn renew_search_projection_consumer(
        &mut self,
        consumer: &SearchProjectionConsumer,
    ) -> SearchProjectionConsumerResult<SearchProjectionConsumerStatus> {
        let root = self.consumer_writable_root()?;
        self.validate_consumer_receipt(consumer)?;
        self.runtime
            .get_mut()?
            .projection_consumers
            .verified
            .insert(consumer.id().as_str().into(), State::Active);
        let epoch = self.runtime.get()?.store.commit_epoch();
        let record = self
            .runtime
            .get_mut()?
            .projection_consumers
            .records
            .get_mut(consumer.id().as_str())
            .ok_or(Error::InvalidHandle)?;
        record.expires_at_commit_epoch = epoch
            .checked_add(record.max_idle_commits)
            .ok_or_else(|| HawDBError::Semantic("consumer expiry epoch overflow".into()))?;
        self.publish_consumer_registry(&root)?;
        self.search_projection_consumer_status(consumer.id())
    }

    pub fn unregister_search_projection_consumer(
        &mut self,
        id: &SearchProjectionConsumerId,
    ) -> SearchProjectionConsumerResult<()> {
        self.ensure_writable()?;
        let root = self
            .runtime
            .get()?
            .store
            .search_projection_registry_root()
            .ok_or(Error::SourceNotDurable)?
            .to_path_buf();
        if self.runtime.get_mut()?.projection_consumers.unavailable {
            return Err(Error::RebuildRequired(Reason::RegistryUnavailable));
        }
        if self
            .runtime
            .get_mut()?
            .projection_consumers
            .records
            .remove(id.as_str())
            .is_none()
        {
            return Ok(());
        }
        self.runtime
            .get_mut()?
            .projection_consumers
            .verified
            .remove(id.as_str());
        self.publish_consumer_registry(&root)
    }

    pub fn search_projection_consumer_status(
        &self,
        id: &SearchProjectionConsumerId,
    ) -> SearchProjectionConsumerResult<SearchProjectionConsumerStatus> {
        if self.runtime.get()?.projection_consumers.unavailable {
            return Err(Error::RebuildRequired(Reason::RegistryUnavailable));
        }
        let record = self
            .runtime
            .get()?
            .projection_consumers
            .records
            .get(id.as_str())
            .ok_or(Error::InvalidHandle)?;
        let changefeed = self
            .runtime
            .get()?
            .store
            .search_projection_changefeed_status();
        let identity = self
            .runtime
            .get()?
            .store
            .search_projection_database_identity();
        let state = self.runtime.get()?.projection_consumers.state(
            record,
            identity,
            changefeed.graph_commit_epoch,
            changefeed.resume_floor_commit_epoch,
        );
        let registry = &self.runtime.get()?.projection_consumers;
        let minimum = self
            .runtime
            .get()?
            .projection_consumers
            .records
            .values()
            .filter(|record| {
                registry.state(
                    record,
                    identity,
                    changefeed.graph_commit_epoch,
                    changefeed.resume_floor_commit_epoch,
                ) == State::Active
            })
            .map(|record| record.durable_complete_through_epoch)
            .min();
        Ok(SearchProjectionConsumerStatus {
            consumer_id: id.clone(),
            state,
            durable_complete_through_commit_epoch: Some(record.durable_complete_through_epoch),
            expires_at_commit_epoch: record.expires_at_commit_epoch,
            minimum_valid_consumer_commit_epoch: minimum,
            changefeed,
        })
    }

    pub fn search_projection_consumer_readiness(
        &self,
        consumer: &SearchProjectionConsumer,
        max_operations: Option<usize>,
    ) -> SearchProjectionConsumerResult<SearchProjectionConsumerReadiness> {
        let mut status = self.search_projection_consumer_status(consumer.id())?;
        match self.validate_consumer_receipt(consumer) {
            Ok(()) => {}
            Err(Error::RebuildRequired(reason)) => status.state = State::RebuildRequired(reason),
            Err(error) => return Err(error),
        }
        let freshness = consumer.search_index().projection_freshness();
        let changefeed = status.changefeed.readiness_after(
            freshness.source_graph_commit_epoch,
            freshness.durable_source_graph_commit_epoch,
            true,
            max_operations,
        );
        Ok(SearchProjectionConsumerReadiness {
            consumer: status,
            changefeed,
        })
    }

    fn consumer_writable_root(&self) -> SearchProjectionConsumerResult<PathBuf> {
        self.ensure_writable()?;
        if self.runtime.get()?.store.wal_sync_group_active() {
            return Err(Error::SourceNotDurable);
        }
        self.runtime
            .get()?
            .store
            .search_projection_registry_root()
            .map(Path::to_path_buf)
            .ok_or(Error::SourceNotDurable)
    }

    fn validate_consumer_receipt(
        &self,
        consumer: &SearchProjectionConsumer,
    ) -> SearchProjectionConsumerResult<()> {
        let status = self.search_projection_consumer_status(consumer.id())?;
        let record = self
            .runtime
            .get()?
            .projection_consumers
            .records
            .get(consumer.id().as_str())
            .ok_or(Error::InvalidHandle)?;
        let binding = consumer.projection().binding();
        if Some(binding.database_uuid)
            != self
                .runtime
                .get()?
                .store
                .search_projection_database_identity()
        {
            return Err(Error::RebuildRequired(Reason::DatabaseIdentityMismatch));
        }
        if binding.consumer_id != consumer.id().as_str()
            || binding.registration_uuid.to_string() != record.registration_uuid
        {
            return Err(Error::InvalidHandle);
        }
        if binding.projection_uuid.to_string() != record.projection_uuid {
            return Err(Error::RebuildRequired(Reason::ProjectionIdentityMismatch));
        }
        if let State::RebuildRequired(reason) = status.state {
            return Err(Error::RebuildRequired(reason));
        }
        let receipt = consumer.projection().receipt();
        if receipt.binding.checkpoint_uuid.to_string() != record.checkpoint_uuid
            || receipt.encoded_len != record.snapshot_encoded_len
            || receipt.sha256 != record.snapshot_sha256
            || receipt.source_epoch != record.durable_complete_through_epoch
        {
            return Err(Error::RebuildRequired(Reason::CheckpointMismatch));
        }
        if !consumer.projection().binding_is_valid() {
            return Err(Error::RebuildRequired(Reason::UntrackedProjectionMutation));
        }
        let freshness = consumer.search_index().projection_freshness();
        if freshness.source_graph_commit_epoch != Some(receipt.source_epoch)
            || freshness.has_uncheckpointed_changes
        {
            return Err(Error::RebuildRequired(Reason::UntrackedProjectionMutation));
        }
        Ok(())
    }

    fn acknowledge_consumer_checkpoint(
        &mut self,
        id: &SearchProjectionConsumerId,
        receipt: &CheckpointReceipt,
    ) -> SearchProjectionConsumerResult<()> {
        let identity = self
            .runtime
            .get()?
            .store
            .search_projection_database_identity();
        let epoch = self.runtime.get()?.store.commit_epoch();
        let record = self
            .runtime
            .get_mut()?
            .projection_consumers
            .records
            .get_mut(id.as_str())
            .ok_or(Error::InvalidHandle)?;
        if Some(receipt.binding.database_uuid) != identity
            || receipt.binding.consumer_id != id.as_str()
            || receipt.binding.registration_uuid.to_string() != record.registration_uuid
            || receipt.binding.projection_uuid.to_string() != record.projection_uuid
            || receipt.source_epoch > epoch
            || receipt.source_epoch < record.durable_complete_through_epoch
            || (receipt.source_epoch == record.durable_complete_through_epoch
                && (receipt.binding.checkpoint_uuid.to_string() != record.checkpoint_uuid
                    || receipt.encoded_len != record.snapshot_encoded_len
                    || receipt.sha256 != record.snapshot_sha256))
        {
            return Err(Error::RebuildRequired(Reason::CheckpointMismatch));
        }
        record.checkpoint_uuid = receipt.binding.checkpoint_uuid.to_string();
        record.durable_complete_through_epoch = receipt.source_epoch;
        record.snapshot_encoded_len = receipt.encoded_len;
        record.snapshot_sha256 = receipt.sha256.clone();
        Ok(())
    }

    fn publish_consumer_registry(&mut self, root: &Path) -> SearchProjectionConsumerResult<()> {
        if let Err(error) = self.runtime.get_mut()?.projection_consumers.publish(
            root,
            || publication_failpoint(PublicationStage::BeforeRegistry),
            || publication_failpoint(PublicationStage::AfterRegistry),
        ) {
            self.runtime.get_mut()?.projection_consumers.unavailable = true;
            return Err(error.into());
        }
        Ok(())
    }
}

struct StageDirectory(PathBuf);
impl StageDirectory {
    fn cleanup(self) -> Result<()> {
        match fs::remove_dir_all(&self.0) {
            Ok(()) => Ok(()),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            Err(error) => Err(error.into()),
        }
    }
}
impl Drop for StageDirectory {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PublicationStage {
    BeforeCheckpoint,
    AfterCheckpoint,
    BeforeRegistry,
    AfterRegistry,
}

#[cfg(test)]
thread_local! {
    static PUBLICATION_FAILURE: std::cell::Cell<Option<(PublicationStage, bool)>> = const { std::cell::Cell::new(None) };
}

fn publication_failpoint(_stage: PublicationStage) -> Result<()> {
    #[cfg(test)]
    if let Some((stage, crash)) = PUBLICATION_FAILURE.get()
        && stage == _stage
    {
        PUBLICATION_FAILURE.set(None);
        if crash {
            std::process::exit(86);
        }
        return Err(HawDBError::Storage(format!(
            "injected consumer publication failure at {stage:?}"
        )));
    }
    Ok(())
}

#[cfg(test)]
mod tests;