-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathlib.rs
More file actions
850 lines (813 loc) · 29.6 KB
/
lib.rs
File metadata and controls
850 lines (813 loc) · 29.6 KB
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
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
// Copyright (C) 2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE.md for licensing terms.
// HINT WHEN REFERENCING TYPES OUTSIDE THIS LIBRARY:
// - Anything that is outside the crate must be included as a `type` alias (not just
// a `use`) in order for cbindgen to generate an opaque forward declaration. The type
// alias can have a doc comment which will be included in the generated header file.
// - The value must be boxed, or otherwise used via a pointer. This is because only
// a forward declaration is generated and callers will be unable to instantiate the
// type without a complete definition.
#![doc = include_str!("../README.md")]
#![expect(
unsafe_code,
reason = "This is an FFI library, so unsafe code is expected."
)]
#![cfg_attr(
not(target_pointer_width = "64"),
forbid(
clippy::cast_possible_truncation,
reason = "non-64 bit target likely to cause issues during u64 to usize conversions"
)
)]
mod arc_cache;
mod handle;
mod iterator;
mod logging;
mod metrics_setup;
mod proofs;
mod proposal;
mod revision;
mod value;
use firewood::v2::api::DbView;
pub use crate::handle::*;
pub use crate::iterator::*;
pub use crate::logging::*;
pub use crate::proofs::*;
pub use crate::proposal::*;
pub use crate::revision::*;
pub use crate::value::*;
#[global_allocator]
#[doc(hidden)]
static GLOBAL: tikv_jemallocator::Jemalloc = tikv_jemallocator::Jemalloc;
/// Invokes a closure and returns the result as a [`CResult`].
///
/// If the closure panics, it will return [`CResult::from_panic`] with the panic
/// information.
#[inline]
fn invoke<T: CResult, V: Into<T>>(once: impl FnOnce() -> V) -> T {
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(once)) {
Ok(result) => result.into(),
Err(panic) => T::from_panic(panic),
}
}
/// Invokes a closure that requires a handle and returns the result as a [`NullHandleResult`].
///
/// If the provided handle is [`None`], the function will return early with the
/// [`NullHandleResult::null_handle_pointer_error`] result.
///
/// Otherwise, the closure is invoked with the handle. If the closure panics,
/// it will be caught and returned as a [`CResult::from_panic`].
#[inline]
fn invoke_with_handle<H, T: NullHandleResult, V: Into<T>>(
handle: Option<H>,
once: impl FnOnce(H) -> V,
) -> T {
match handle {
Some(handle) => invoke(move || once(handle)),
None => T::null_handle_pointer_error(),
}
}
/// Gets the value associated with the given key from the database for the
/// latest revision.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
/// * `key` - The key to look up as a [`BorrowedBytes`]
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ValueResult::RevisionNotFound`] if no revision was found for the root
/// (i.e., there is no current root).
/// - [`ValueResult::None`] if the key was not found.
/// - [`ValueResult::Some`] if the key was found with the associated value.
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`].
/// * ensure that `key` is valid for [`BorrowedBytes`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned error or value.
///
/// [`BorrowedBytes`]: crate::value::BorrowedBytes
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_get_latest(
db: Option<&DatabaseHandle>,
key: BorrowedBytes,
) -> ValueResult {
invoke_with_handle(db, move |db| db.get_latest(key))
}
/// Returns an iterator optionally starting from a key in the provided revision.
///
/// # Arguments
///
/// * `revision` - The revision handle returned by [`fwd_get_revision`].
/// * `key` - The key to look up as a [`BorrowedBytes`]
///
/// # Returns
///
/// - [`IteratorResult::NullHandlePointer`] if the provided revision handle is null.
/// - [`IteratorResult::Ok`] if the iterator was created, with the iterator handle.
/// - [`IteratorResult::Err`] if an error occurred while creating the iterator.
///
/// # Safety
///
/// The caller must:
/// * ensure that `revision` is a valid pointer to a [`RevisionHandle`]
/// * ensure that `key` is a valid [`BorrowedBytes`]
/// * call [`fwd_free_iterator`] to free the memory associated with the iterator.
///
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_iter_on_revision<'view>(
revision: Option<&'view RevisionHandle>,
key: BorrowedBytes,
) -> IteratorResult<'view> {
invoke_with_handle(revision, move |rev| rev.iter_from(Some(key.as_slice())))
}
/// Returns an iterator on the provided proposal optionally starting from a key
///
/// # Arguments
///
/// * `handle` - The proposal handle returned by [`fwd_propose_on_db`] or
/// [`fwd_propose_on_proposal`].
/// * `key` - The key to look up as a [`BorrowedBytes`]
///
/// # Returns
///
/// - [`IteratorResult::NullHandlePointer`] if the provided proposal handle is null.
/// - [`IteratorResult::Ok`] if the iterator was created, with the iterator handle.
/// - [`IteratorResult::Err`] if an error occurred while creating the iterator.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ProposalHandle`]
/// * ensure that `key` is a valid for [`BorrowedBytes`]
/// * call [`fwd_free_iterator`] to free the memory associated with the iterator.
///
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_iter_on_proposal<'p>(
handle: Option<&'p ProposalHandle<'_>>,
key: BorrowedBytes,
) -> IteratorResult<'p> {
invoke_with_handle(handle, move |p| p.iter_from(Some(key.as_slice())))
}
/// Retrieves the next item from the iterator.
///
/// # Arguments
///
/// * `handle` - The iterator handle returned by [`fwd_iter_on_revision`] or
/// [`fwd_iter_on_proposal`].
///
/// # Returns
///
/// - [`KeyValueResult::NullHandlePointer`] if the provided iterator handle is null.
/// - [`KeyValueResult::None`] if the iterator is exhausted (no remaining values). Once returned,
/// subsequent calls will continue returning [`KeyValueResult::None`]. You may still call this
/// safely, but freeing the iterator with [`fwd_free_iterator`] is recommended.
/// - [`KeyValueResult::Some`] if the next item on iterator was retrieved, with the associated
/// key value pair.
/// - [`KeyValueResult::Err`] if an I/O error occurred while retrieving the next item. Most
/// iterator errors are non-reentrant. Once returned, the iterator should be considered
/// invalid and must be freed with [`fwd_free_iterator`].
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`IteratorHandle`].
/// * call [`fwd_free_owned_kv_pair`] on returned [`OwnedKeyValuePair`]
/// to free the memory associated with the returned value.
///
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_iter_next(handle: Option<&mut IteratorHandle<'_>>) -> KeyValueResult {
invoke_with_handle(handle, Iterator::next)
}
/// Retrieves the next batch of items from the iterator.
///
/// # Arguments
///
/// * `handle` - The iterator handle returned by [`fwd_iter_on_revision`] or
/// [`fwd_iter_on_proposal`].
///
/// # Returns
///
/// - [`KeyValueBatchResult::NullHandlePointer`] if the provided iterator handle is null.
/// - [`KeyValueBatchResult::Some`] with up to `n` key/value pairs. If the iterator is
/// exhausted, this may be fewer than `n`, including zero items.
/// - [`KeyValueBatchResult::Err`] if an I/O error occurred while retrieving items. Most
/// iterator errors are non-reentrant. Once returned, the iterator should be considered
/// invalid and must be freed with [`fwd_free_iterator`].
///
/// Once an empty batch or items fewer than `n` is returned (iterator exhausted), subsequent calls
/// will continue returning empty batches. You may still call this safely, but freeing the
/// iterator with [`fwd_free_iterator`] is recommended.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`IteratorHandle`].
/// * call [`fwd_free_owned_key_value_batch`] on the returned batch to free any allocated memory.
///
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_iter_next_n(
handle: Option<&mut IteratorHandle<'_>>,
n: usize,
) -> KeyValueBatchResult {
invoke_with_handle(handle, |it| it.iter_next_n(n))
}
/// Consumes the [`IteratorHandle`], destroys the iterator, and frees the memory.
///
/// # Arguments
///
/// * `iterator` - A pointer to a [`IteratorHandle`] previously returned from a
/// function from this library.
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided iterator handle is null.
/// - [`VoidResult::Ok`] if the iterator was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `iterator` is not null and that it points to
/// a valid [`IteratorHandle`] previously returned by a function from this library.
///
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_free_iterator(
iterator: Option<Box<IteratorHandle<'_>>>,
) -> VoidResult {
invoke_with_handle(iterator, drop)
}
/// Gets a handle to the revision identified by the provided root hash.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`].
/// * `root` - The hash of the revision as a [`BorrowedBytes`].
///
/// # Returns
///
/// - [`RevisionResult::NullHandlePointer`] if the provided database handle is null.
/// - [`RevisionResult::Ok`] containing a [`RevisionHandle`] and root hash if the revision exists.
/// - [`RevisionResult::Err`] if the revision cannot be fetched or the root hash is invalid.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`].
/// * ensure that `root` is valid for [`BorrowedBytes`].
/// * call [`fwd_free_revision`] to free the returned handle when it is no longer needed.
///
/// [`BorrowedBytes`]: crate::value::BorrowedBytes
/// [`RevisionHandle`]: crate::revision::RevisionHandle
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_get_revision(
db: Option<&DatabaseHandle>,
root: HashKey,
) -> RevisionResult {
invoke_with_handle(db, move |db| db.get_revision(root.into()))
}
/// Gets the value associated with the given key from the provided revision handle.
///
/// # Arguments
///
/// * `revision` - The revision handle returned by [`fwd_get_revision`].
/// * `key` - The key to look up as a [`BorrowedBytes`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided revision handle is null.
/// - [`ValueResult::None`] if the key was not found in the revision.
/// - [`ValueResult::Some`] if the key was found with the associated value.
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * ensure that `revision` is a valid pointer to a [`RevisionHandle`].
/// * ensure that `key` is valid for [`BorrowedBytes`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the [`OwnedBytes`]
/// returned in the result.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_get_from_revision(
revision: Option<&RevisionHandle>,
key: BorrowedBytes,
) -> ValueResult {
invoke_with_handle(revision, move |rev| rev.val(key))
}
/// Consumes the [`RevisionHandle`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `revision` - A pointer to a [`RevisionHandle`] previously returned by
/// [`fwd_get_revision`].
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided revision handle is null.
/// - [`VoidResult::Ok`] if the revision handle was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the revision handle is valid and is not used again after
/// this function is called.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_free_revision(revision: Option<Box<RevisionHandle>>) -> VoidResult {
invoke_with_handle(revision, drop)
}
/// Gets the value associated with the given key from the proposal provided.
///
/// # Arguments
///
/// * `handle` - The proposal handle returned by [`fwd_propose_on_db`] or
/// [`fwd_propose_on_proposal`].
/// * `key` - The key to look up, as a [`BorrowedBytes`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ValueResult::None`] if the key was not found.
/// - [`ValueResult::Some`] if the key was found with the associated value.
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ProposalHandle`]
/// * ensure that `key` is valid for [`BorrowedBytes`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated [`OwnedBytes`]
/// returned in the result.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_get_from_proposal(
handle: Option<&ProposalHandle<'_>>,
key: BorrowedBytes,
) -> ValueResult {
invoke_with_handle(handle, move |handle| handle.val(key))
}
/// Gets a value assoicated with the given root hash and key.
///
/// The hash may refer to a historical revision or an existing proposal.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
/// * `root` - The root hash to look up as a [`BorrowedBytes`]
/// * `key` - The key to look up as a [`BorrowedBytes`]
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ValueResult::RevisionNotFound`] if no revision was found for the specified root.
/// - [`ValueResult::None`] if the key was not found.
/// - [`ValueResult::Some`] if the key was found with the associated value.
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`]
/// * ensure that `root` is a valid for [`BorrowedBytes`]
/// * ensure that `key` is a valid for [`BorrowedBytes`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated [`OwnedBytes`]
/// returned in the result.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_get_from_root(
db: Option<&DatabaseHandle>,
root: HashKey,
key: BorrowedBytes,
) -> ValueResult {
invoke_with_handle(db, move |db| db.get_from_root(root.into(), key))
}
/// Puts the given key-value pairs into the database.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
/// * `values` - A [`BorrowedKeyValuePairs`] containing the key-value pairs to put.
///
/// # Returns
///
/// - [`HashResult::NullHandlePointer`] if the provided database handle is null.
/// - [`HashResult::None`] if the commit resulted in an empty database.
/// - [`HashResult::Some`] if the commit was successful, containing the new root hash.
/// - [`HashResult::Err`] if an error occurred while committing the batch.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`]
/// * ensure that `values` is valid for [`BorrowedKeyValuePairs`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned error ([`HashKey`] does not need to be freed as it is returned by
/// value).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_batch(
db: Option<&DatabaseHandle>,
values: BorrowedKeyValuePairs<'_>,
) -> HashResult {
invoke_with_handle(db, move |db| db.create_batch(values))
}
/// Proposes a batch of operations to the database.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
/// * `values` - A [`BorrowedKeyValuePairs`] containing the key-value pairs to put.
///
/// # Returns
///
/// - [`ProposalResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ProposalResult::Ok`] if the proposal was created, with the proposal handle
/// and calculated root hash.
/// - [`ProposalResult::Err`] if an error occurred while creating the proposal.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`]
/// * ensure that `values` is valid for [`BorrowedKeyValuePairs`]
/// * call [`fwd_commit_proposal`] or [`fwd_free_proposal`] to free the memory
/// associated with the proposal. And, the caller must ensure this is done
/// before calling [`fwd_close_db`] to avoid memory leaks or undefined behavior.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_propose_on_db<'db>(
db: Option<&'db DatabaseHandle>,
values: BorrowedKeyValuePairs<'_>,
) -> ProposalResult<'db> {
invoke_with_handle(db, move |db| db.create_proposal_handle(values))
}
/// Proposes a batch of operations to the database on top of an existing proposal.
///
/// # Arguments
///
/// * `handle` - The proposal handle returned by [`fwd_propose_on_db`] or
/// [`fwd_propose_on_proposal`].
/// * `values` - A [`BorrowedKeyValuePairs`] containing the key-value pairs to put.
///
/// # Returns
///
/// - [`ProposalResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ProposalResult::Ok`] if the proposal was created, with the proposal handle
/// and calculated root hash.
/// - [`ProposalResult::Err`] if an error occurred while creating the proposal.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ProposalHandle`]
/// * ensure that `values` is valid for [`BorrowedKeyValuePairs`]
/// * call [`fwd_commit_proposal`] or [`fwd_free_proposal`] to free the memory
/// associated with the proposal. And, the caller must ensure this is done
/// before calling [`fwd_close_db`] to avoid memory leaks or undefined behavior.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_propose_on_proposal<'db>(
handle: Option<&ProposalHandle<'db>>,
values: BorrowedKeyValuePairs<'_>,
) -> ProposalResult<'db> {
invoke_with_handle(handle, move |p| p.create_proposal_handle(values))
}
/// Commits a proposal to the database.
///
/// This function will consume the proposal regardless of whether the commit
/// is successful.
///
/// # Arguments
///
/// * `handle` - The proposal handle returned by [`fwd_propose_on_db`] or
/// [`fwd_propose_on_proposal`].
///
/// # Returns
///
/// # Returns
///
/// - [`HashResult::NullHandlePointer`] if the provided database handle is null.
/// - [`HashResult::None`] if the commit resulted in an empty database.
/// - [`HashResult::Some`] if the commit was successful, containing the new root hash.
/// - [`HashResult::Err`] if an error occurred while committing the batch.
///
/// # Safety
///
/// The caller must:
/// * ensure that `handle` is a valid pointer to a [`ProposalHandle`]
/// * ensure that `handle` is not used again after this function is called.
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned error ([`HashKey`] does not need to be freed as it is returned
/// by value).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_commit_proposal(
proposal: Option<Box<ProposalHandle<'_>>>,
) -> HashResult {
invoke_with_handle(proposal, move |proposal| {
proposal.commit_proposal(|commit_time| {
metrics::counter!("firewood.ffi.commit_ms").increment(commit_time.as_millis());
metrics::counter!("firewood.ffi.commit").increment(1);
})
})
}
/// Consumes the [`ProposalHandle`], cancels the proposal, and frees the memory.
///
/// # Arguments
///
/// * `proposal` - A pointer to a [`ProposalHandle`] previously returned from a
/// function from this library.
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided proposal handle is null.
/// - [`VoidResult::Ok`] if the proposal was successfully cancelled and freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `proposal` is not null and that it points to
/// a valid [`ProposalHandle`] previously returned by a function from this library.
///
/// The caller must ensure that the proposal was not committed. [`fwd_commit_proposal`]
/// will consume the proposal automatically.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_free_proposal(
proposal: Option<Box<ProposalHandle<'_>>>,
) -> VoidResult {
invoke_with_handle(proposal, drop)
}
/// Get the root hash of the latest version of the database
///
/// # Argument
///
/// * `db` - The database handle returned by [`fwd_open_db`]
///
/// # Returns
///
/// - [`HashResult::NullHandlePointer`] if the provided database handle is null.
/// - [`HashResult::None`] if the database is empty.
/// - [`HashResult::Some`] with the root hash of the database.
/// - [`HashResult::Err`] if an error occurred while looking up the root hash.
///
/// # Safety
///
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`]
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned error ([`HashKey`] does not need to be freed as it is returned
/// by value).
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_root_hash(db: Option<&DatabaseHandle>) -> HashResult {
invoke_with_handle(db, DatabaseHandle::current_root_hash)
}
/// Start metrics recorder for this process.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the recorder was initialized.
/// - [`VoidResult::Err`] if an error occurs during initialization.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_start_metrics() -> VoidResult {
invoke(metrics_setup::setup_metrics)
}
/// Start metrics recorder and exporter for this process.
///
/// # Arguments
///
/// * `metrics_port` - the port where metrics will be exposed at
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the recorder was initialized.
/// - [`VoidResult::Err`] if an error occurs during initialization.
///
/// # Safety
///
/// The caller must:
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned error (if any).
#[unsafe(no_mangle)]
pub extern "C" fn fwd_start_metrics_with_exporter(metrics_port: u16) -> VoidResult {
invoke(move || metrics_setup::setup_metrics_with_exporter(metrics_port))
}
/// Gather latest metrics for this process.
///
/// # Returns
///
/// - [`ValueResult::None`] if the gathered metrics resulted in an empty string.
/// - [`ValueResult::Some`] the gathered metrics as an [`OwnedBytes`] (with
/// guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while retrieving the value.
///
/// # Safety
///
/// The caller must:
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned error or value.
#[unsafe(no_mangle)]
pub extern "C" fn fwd_gather() -> ValueResult {
invoke(metrics_setup::gather_metrics)
}
/// Open a database with the given arguments.
///
/// # Arguments
///
/// See [`DatabaseHandleArgs`].
///
/// # Returns
///
/// - [`HandleResult::Ok`] with the database handle if successful.
/// - [`HandleResult::Err`] if an error occurs while opening the database.
///
/// # Safety
///
/// The caller must:
/// - ensure that the database is freed with [`fwd_close_db`] when no longer needed.
/// - ensure that the database handle is freed only after freeing or committing
/// all proposals created on it.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_open_db(args: DatabaseHandleArgs) -> HandleResult {
invoke(move || DatabaseHandle::new(args))
}
/// Start logs for this process.
///
/// Logging is global per-process and can only be initialized once. Subsequent calls
/// will return an error.
///
/// # Arguments
///
/// See [`LogArgs`].
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the logger was initialized.
/// - [`VoidResult::Err`] if an error occurs during initialization (e.g., invalid path,
/// invalid filter, or logger already initialized).
///
/// # Safety
///
/// The caller must:
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned error (if any).
#[unsafe(no_mangle)]
pub extern "C" fn fwd_start_logs(args: LogArgs) -> VoidResult {
invoke(move || args.start_logging())
}
/// Close and free the memory for a database handle
///
/// # Arguments
///
/// * `db` - The database handle to close, previously returned from a call to [`fwd_open_db`].
///
/// # Returns
///
/// - [`VoidResult::NullHandlePointer`] if the provided database handle is null.
/// - [`VoidResult::Ok`] if the database handle was successfully closed and freed.
/// - [`VoidResult::Err`] if the process panics while closing the database handle.
///
/// # Safety
///
/// Callers must ensure that:
///
/// - `db` is a valid pointer to a [`DatabaseHandle`] returned by [`fwd_open_db`].
/// - There are no handles to any open proposals. If so, they must be freed first
/// using [`fwd_free_proposal`].
/// - Freeing the database handle does not free outstanding [`RevisionHandle`]s
/// returned by [`fwd_get_revision`]. To prevent leaks, free them separately
/// with [`fwd_free_revision`].
/// - The database handle is not used after this function is called.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_close_db(db: Option<Box<DatabaseHandle>>) -> VoidResult {
invoke_with_handle(db, drop)
}
/// Consumes the [`OwnedBytes`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `bytes` - The [`OwnedBytes`] struct to free, previously returned from any
/// function from this library.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the memory was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `bytes` struct is valid and that the memory
/// it points to is uniquely owned by this object. However, if `bytes.ptr` is null,
/// this function does nothing.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_free_owned_bytes(bytes: OwnedBytes) -> VoidResult {
invoke(move || drop(bytes))
}
/// Consumes the [`OwnedKeyValueBatch`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `batch` - The [`OwnedKeyValueBatch`] struct to free, previously returned from any
/// function from this library.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the memory was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `batch` struct is valid and that the memory
/// it points to is uniquely owned by this object. However, if `batch.ptr` is null,
/// this function does nothing.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_free_owned_key_value_batch(batch: OwnedKeyValueBatch) -> VoidResult {
invoke(move || drop(batch))
}
/// Consumes the [`OwnedKeyValuePair`] and frees the memory associated with it.
///
/// # Arguments
///
/// * `kv` - The [`OwnedKeyValuePair`] struct to free, previously returned from any
/// function from this library.
///
/// # Returns
///
/// - [`VoidResult::Ok`] if the memory was successfully freed.
/// - [`VoidResult::Err`] if the process panics while freeing the memory.
///
/// # Safety
///
/// The caller must ensure that the `kv` struct is valid.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_free_owned_kv_pair(kv: OwnedKeyValuePair) -> VoidResult {
invoke(move || drop(kv))
}
/// Dumps the Trie structure of the latest revision of the database to a DOT
/// (Graphviz) format string for debugging.
///
/// # Arguments
///
/// * `db` - The database handle returned by [`fwd_open_db`]
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided database handle is null.
/// - [`ValueResult::Some`] with the DOT format string if successful (the data is
/// guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while dumping the database.
///
/// # Safety
///
/// The caller must:
/// * ensure that `db` is a valid pointer to a [`DatabaseHandle`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned value.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_db_dump(db: Option<&DatabaseHandle>) -> ValueResult {
invoke_with_handle(db, handle::DatabaseHandle::dump_to_string)
}
/// Dumps the Trie structure of a revision to a DOT (Graphviz) format string for debugging.
///
/// # Arguments
///
/// * `revision` - A pointer to a [`RevisionHandle`] previously returned by
/// [`fwd_get_revision`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided revision handle is null.
/// - [`ValueResult::Some`] with the DOT format string if successful (the data is
/// guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while dumping the revision.
///
/// # Safety
///
/// The caller must:
/// * ensure that `revision` is a valid pointer to a [`RevisionHandle`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned value.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_revision_dump(revision: Option<&RevisionHandle>) -> ValueResult {
invoke_with_handle(revision, firewood::v2::api::DbView::dump_to_string)
}
/// Dumps the Trie structure of a proposal to a DOT (Graphviz) format string for debugging.
///
/// # Arguments
///
/// * `proposal` - The proposal handle returned by [`fwd_propose_on_db`] or
/// [`fwd_propose_on_proposal`].
///
/// # Returns
///
/// - [`ValueResult::NullHandlePointer`] if the provided proposal handle is null.
/// - [`ValueResult::Some`] with the DOT format string if successful (the data is
/// guaranteed to be utf-8 data, not null terminated).
/// - [`ValueResult::Err`] if an error occurred while dumping the proposal.
///
/// # Safety
///
/// The caller must:
/// * ensure that `proposal` is a valid pointer to a [`ProposalHandle`].
/// * call [`fwd_free_owned_bytes`] to free the memory associated with the
/// returned value.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn fwd_proposal_dump(proposal: Option<&ProposalHandle>) -> ValueResult {
invoke_with_handle(proposal, firewood::v2::api::DbView::dump_to_string)
}