blazen-cabi 0.5.2

Hand-rolled C ABI over blazen-uniffi for the Ruby gem (via cbindgen + FFI gem) and any other FFI host
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
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! Persistence opaque object: [`BlazenCheckpointStore`].
//!
//! Wraps an `Arc<blazen_uniffi::persist::CheckpointStore>` (which itself
//! abstracts any `blazen_persist::CheckpointStore` backend) and exposes
//! its five async methods through both `*_blocking` and future-returning
//! C entry points:
//!
//! - `save(checkpoint)` — persist a checkpoint, overwriting any prior
//!   entry with the same `run_id`. The input `BlazenWorkflowCheckpoint`
//!   handle is **consumed** by the call (whether sync or async) — callers
//!   must NOT separately free it.
//! - `load(run_id)` — fetch a checkpoint by run id; returns a found / not
//!   found discriminator alongside the optional handle.
//! - `delete(run_id)` — drop the checkpoint for a given run id.
//! - `list()` — return every stored checkpoint as a heap-allocated array
//!   of `*mut BlazenWorkflowCheckpoint`.
//! - `list_run_ids()` — return every stored run id (UUID string) as a
//!   heap-allocated array of `*mut c_char`.
//!
//! ## Ownership conventions
//!
//! - Store handles are heap-allocated `Box<BlazenCheckpointStore>` and
//!   freed via [`blazen_checkpoint_store_free`].
//! - The list-returning methods produce a heap-allocated, contiguous,
//!   caller-owned slice of element pointers. The accompanying free
//!   helpers ([`blazen_workflow_checkpoint_array_free`] and
//!   [`blazen_string_array_free`]) drop each element AND the backing
//!   slice in one call.
//! - Error handles produced on the failure path are caller-owned and
//!   freed via [`crate::error::blazen_error_free`].

#![allow(dead_code)]

use std::ffi::c_char;
use std::sync::Arc;

use blazen_uniffi::persist::{
    CheckpointStore as InnerCheckpointStore, WorkflowCheckpoint as InnerWorkflowCheckpoint,
};

use crate::error::BlazenError;
use crate::future::BlazenFuture;
use crate::persist_records::BlazenWorkflowCheckpoint;
use crate::runtime::runtime;
use crate::string::{alloc_cstring, cstr_to_str};

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Convert a `Vec<InnerWorkflowCheckpoint>` into a heap-allocated array of
/// `*mut BlazenWorkflowCheckpoint`. Returns `(base_ptr, count)`.
///
/// Each element is wrapped via [`BlazenWorkflowCheckpoint::into_ptr`] so it
/// can be freed individually. The backing slice is leaked via
/// `Box::into_raw` so the FFI host can index into it; the matching
/// [`blazen_workflow_checkpoint_array_free`] reconstructs the slice via
/// `slice::from_raw_parts_mut` + `Box::from_raw` to release everything.
fn checkpoints_to_c_array(
    items: Vec<InnerWorkflowCheckpoint>,
) -> (*mut *mut BlazenWorkflowCheckpoint, usize) {
    let boxed: Box<[*mut BlazenWorkflowCheckpoint]> = items
        .into_iter()
        .map(|v| BlazenWorkflowCheckpoint::from(v).into_ptr())
        .collect::<Vec<_>>()
        .into_boxed_slice();
    let len = boxed.len();
    let raw = Box::into_raw(boxed);
    // `*mut [T]` -> `*mut T` via `.cast()` keeps provenance correct as long
    // as the matching free reconstructs the same `[T]` shape via
    // `slice::from_raw_parts_mut(base, len)` + `Box::from_raw`.
    (raw.cast::<*mut BlazenWorkflowCheckpoint>(), len)
}

/// Convert a `Vec<String>` into a heap-allocated array of `*mut c_char`.
/// Returns `(base_ptr, count)`.
///
/// Each element goes through [`alloc_cstring`] so it can be freed via
/// `blazen_string_free`. The slice itself is freed via
/// [`blazen_string_array_free`]. An interior-NUL string collapses to a
/// null element pointer (matching `alloc_cstring`'s behavior) — the array
/// free still tolerates null entries.
fn strings_to_c_array(items: Vec<String>) -> (*mut *mut c_char, usize) {
    let boxed: Box<[*mut c_char]> = items
        .into_iter()
        .map(|s| alloc_cstring(&s))
        .collect::<Vec<_>>()
        .into_boxed_slice();
    let len = boxed.len();
    let raw = Box::into_raw(boxed);
    (raw.cast::<*mut c_char>(), len)
}

// ---------------------------------------------------------------------------
// BlazenCheckpointStore
// ---------------------------------------------------------------------------

/// Opaque handle wrapping an `Arc<blazen_uniffi::persist::CheckpointStore>`.
///
/// Produced by the per-backend store factories (`new_redb_checkpoint_store`,
/// `new_valkey_checkpoint_store`) wired in Phase R4. Free with
/// [`blazen_checkpoint_store_free`].
pub struct BlazenCheckpointStore(pub(crate) Arc<InnerCheckpointStore>);

impl BlazenCheckpointStore {
    /// Heap-allocate the handle and return the raw pointer the caller owns.
    pub(crate) fn into_ptr(self) -> *mut BlazenCheckpointStore {
        Box::into_raw(Box::new(self))
    }
}

impl From<Arc<InnerCheckpointStore>> for BlazenCheckpointStore {
    fn from(inner: Arc<InnerCheckpointStore>) -> Self {
        Self(inner)
    }
}

// ---------------------------------------------------------------------------
// save
// ---------------------------------------------------------------------------

/// Synchronously persist `checkpoint`. The `checkpoint` pointer is
/// **consumed** by this call — callers must NOT separately free it.
///
/// Returns `0` on success, `-1` on failure (writes into `out_err`), `-2`
/// on invalid input (null `store` or null `checkpoint`).
///
/// # Safety
///
/// - `store` must be a valid pointer to a `BlazenCheckpointStore` produced
///   by the cabi surface.
/// - `checkpoint` must be a pointer previously produced by
///   [`crate::persist_records::blazen_workflow_checkpoint_new`] (or any
///   cabi function producing a `BlazenWorkflowCheckpoint`) and not yet
///   freed.
/// - `out_err` must be null OR a writable pointer to a `*mut BlazenError`
///   slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_save_blocking(
    store: *const BlazenCheckpointStore,
    checkpoint: *mut BlazenWorkflowCheckpoint,
    out_err: *mut *mut BlazenError,
) -> i32 {
    if store.is_null() || checkpoint.is_null() {
        if !checkpoint.is_null() {
            // SAFETY: caller upholds the `Box::into_raw` contract on `checkpoint`.
            drop(unsafe { Box::from_raw(checkpoint) });
        }
        return -2;
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };
    // SAFETY: caller upholds the `Box::into_raw` contract on `checkpoint`.
    let checkpoint = unsafe { Box::from_raw(checkpoint) };
    let inner_checkpoint = checkpoint.0;

    let store_inner = Arc::clone(&store.0);
    let result = runtime().block_on(async move { store_inner.save(inner_checkpoint).await });
    match result {
        Ok(()) => 0,
        Err(e) => {
            if !out_err.is_null() {
                // SAFETY: caller has guaranteed `out_err` is writable.
                unsafe {
                    *out_err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}

/// Asynchronously persist `checkpoint`. The `checkpoint` pointer is
/// **consumed** by this call — callers must NOT separately free it.
///
/// Returns a future handle whose result is popped with
/// [`blazen_future_take_unit`]. Returns null if either input is null
/// (in which case the consumed `checkpoint` is dropped to avoid a leak).
///
/// # Safety
///
/// Same contracts as [`blazen_checkpoint_store_save_blocking`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_save(
    store: *const BlazenCheckpointStore,
    checkpoint: *mut BlazenWorkflowCheckpoint,
) -> *mut BlazenFuture {
    if store.is_null() || checkpoint.is_null() {
        if !checkpoint.is_null() {
            // SAFETY: caller upholds the `Box::into_raw` contract on `checkpoint`.
            drop(unsafe { Box::from_raw(checkpoint) });
        }
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };
    // SAFETY: caller upholds the `Box::into_raw` contract on `checkpoint`.
    let checkpoint = unsafe { Box::from_raw(checkpoint) };
    let inner_checkpoint = checkpoint.0;

    let store_inner = Arc::clone(&store.0);
    BlazenFuture::spawn::<(), _>(async move { store_inner.save(inner_checkpoint).await })
}

// ---------------------------------------------------------------------------
// load
// ---------------------------------------------------------------------------

/// Synchronously load a checkpoint by `run_id`.
///
/// On success, writes `1` into `out_found` and a freshly-allocated
/// `*mut BlazenWorkflowCheckpoint` into `out_checkpoint` (when `Some`), or
/// `0` into `out_found` (when `None`). Returns `0` on success, `-1` on
/// failure, `-2` on invalid input (null `store` / null `run_id` /
/// non-UTF-8 `run_id`).
///
/// # Safety
///
/// - `store` must be a valid pointer to a `BlazenCheckpointStore`.
/// - `run_id` must be a valid NUL-terminated UTF-8 buffer.
/// - `out_checkpoint` / `out_found` / `out_err` must be null OR writable
///   pointers to the appropriate slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_load_blocking(
    store: *const BlazenCheckpointStore,
    run_id: *const c_char,
    out_checkpoint: *mut *mut BlazenWorkflowCheckpoint,
    out_found: *mut i32,
    out_err: *mut *mut BlazenError,
) -> i32 {
    if store.is_null() {
        return -2;
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };
    // SAFETY: caller upholds the NUL-termination + UTF-8 contract on `run_id`.
    let Some(run_id) = (unsafe { cstr_to_str(run_id) }) else {
        return -2;
    };
    let run_id = run_id.to_owned();

    let store_inner = Arc::clone(&store.0);
    let result = runtime().block_on(async move { store_inner.load(run_id).await });
    match result {
        Ok(Some(v)) => {
            if !out_checkpoint.is_null() {
                // SAFETY: caller has guaranteed `out_checkpoint` is writable.
                unsafe {
                    *out_checkpoint = BlazenWorkflowCheckpoint::from(v).into_ptr();
                }
            }
            if !out_found.is_null() {
                // SAFETY: caller has guaranteed `out_found` is writable.
                unsafe {
                    *out_found = 1;
                }
            }
            0
        }
        Ok(None) => {
            if !out_found.is_null() {
                // SAFETY: caller has guaranteed `out_found` is writable.
                unsafe {
                    *out_found = 0;
                }
            }
            0
        }
        Err(e) => {
            if !out_err.is_null() {
                // SAFETY: caller has guaranteed `out_err` is writable.
                unsafe {
                    *out_err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}

/// Asynchronously load a checkpoint by `run_id`. Returns a future handle
/// whose result is popped with
/// [`blazen_future_take_workflow_checkpoint_option`].
///
/// Returns null on invalid input.
///
/// # Safety
///
/// Same string contracts as [`blazen_checkpoint_store_load_blocking`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_load(
    store: *const BlazenCheckpointStore,
    run_id: *const c_char,
) -> *mut BlazenFuture {
    if store.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };
    // SAFETY: caller upholds the NUL-termination + UTF-8 contract on `run_id`.
    let Some(run_id) = (unsafe { cstr_to_str(run_id) }) else {
        return std::ptr::null_mut();
    };
    let run_id = run_id.to_owned();

    let store_inner = Arc::clone(&store.0);
    BlazenFuture::spawn::<Option<InnerWorkflowCheckpoint>, _>(async move {
        store_inner.load(run_id).await
    })
}

// ---------------------------------------------------------------------------
// delete
// ---------------------------------------------------------------------------

/// Synchronously delete the checkpoint for `run_id`. The underlying
/// backends treat delete-of-missing as a no-op, so the call succeeds even
/// when no checkpoint exists for the id.
///
/// Returns `0` on success, `-1` on failure, `-2` on invalid input.
///
/// # Safety
///
/// Same contracts as [`blazen_checkpoint_store_load_blocking`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_delete_blocking(
    store: *const BlazenCheckpointStore,
    run_id: *const c_char,
    out_err: *mut *mut BlazenError,
) -> i32 {
    if store.is_null() {
        return -2;
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };
    // SAFETY: caller upholds the NUL-termination + UTF-8 contract on `run_id`.
    let Some(run_id) = (unsafe { cstr_to_str(run_id) }) else {
        return -2;
    };
    let run_id = run_id.to_owned();

    let store_inner = Arc::clone(&store.0);
    let result = runtime().block_on(async move { store_inner.delete(run_id).await });
    match result {
        Ok(()) => 0,
        Err(e) => {
            if !out_err.is_null() {
                // SAFETY: caller has guaranteed `out_err` is writable.
                unsafe {
                    *out_err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}

/// Asynchronously delete the checkpoint for `run_id`. Returns a future
/// handle whose result is popped with [`blazen_future_take_unit`].
///
/// # Safety
///
/// Same contracts as [`blazen_checkpoint_store_delete_blocking`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_delete(
    store: *const BlazenCheckpointStore,
    run_id: *const c_char,
) -> *mut BlazenFuture {
    if store.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };
    // SAFETY: caller upholds the NUL-termination + UTF-8 contract on `run_id`.
    let Some(run_id) = (unsafe { cstr_to_str(run_id) }) else {
        return std::ptr::null_mut();
    };
    let run_id = run_id.to_owned();

    let store_inner = Arc::clone(&store.0);
    BlazenFuture::spawn::<(), _>(async move { store_inner.delete(run_id).await })
}

// ---------------------------------------------------------------------------
// list
// ---------------------------------------------------------------------------

/// Synchronously list every stored checkpoint, ordered by timestamp
/// descending.
///
/// On success writes a heap-allocated array of
/// `*mut BlazenWorkflowCheckpoint` into `*out_array` plus its length into
/// `*out_count`. Free the array with
/// [`blazen_workflow_checkpoint_array_free`].
///
/// Returns `0` on success, `-1` on failure, `-2` on invalid input.
///
/// # Safety
///
/// `store` must be a valid pointer to a `BlazenCheckpointStore`.
/// `out_array` / `out_count` / `out_err` must be null OR writable pointers
/// to the appropriate slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_list_blocking(
    store: *const BlazenCheckpointStore,
    out_array: *mut *mut *mut BlazenWorkflowCheckpoint,
    out_count: *mut usize,
    out_err: *mut *mut BlazenError,
) -> i32 {
    if store.is_null() {
        return -2;
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };

    let store_inner = Arc::clone(&store.0);
    let result = runtime().block_on(async move { store_inner.list().await });
    match result {
        Ok(items) => {
            let (base, count) = checkpoints_to_c_array(items);
            if out_array.is_null() {
                // Caller doesn't want the array — release it immediately.
                // SAFETY: `base` + `count` were just produced by
                // `checkpoints_to_c_array`; reconstructing the boxed slice is
                // sound. The `Box<[_]>` drop releases the slice; each element
                // pointer is released via `Box::from_raw` below.
                unsafe {
                    let slice = std::slice::from_raw_parts_mut(base, count);
                    let owned = Box::from_raw(slice);
                    for &ptr in &owned {
                        if !ptr.is_null() {
                            drop(Box::from_raw(ptr));
                        }
                    }
                    drop(owned);
                }
            } else {
                // SAFETY: caller has guaranteed `out_array` is writable.
                unsafe {
                    *out_array = base;
                }
            }
            if !out_count.is_null() {
                // SAFETY: caller has guaranteed `out_count` is writable.
                unsafe {
                    *out_count = count;
                }
            }
            0
        }
        Err(e) => {
            if !out_err.is_null() {
                // SAFETY: caller has guaranteed `out_err` is writable.
                unsafe {
                    *out_err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}

/// Asynchronously list every stored checkpoint. Returns a future whose
/// result is popped with [`blazen_future_take_workflow_checkpoint_list`].
///
/// # Safety
///
/// `store` must be a valid pointer to a `BlazenCheckpointStore`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_list(
    store: *const BlazenCheckpointStore,
) -> *mut BlazenFuture {
    if store.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };

    let store_inner = Arc::clone(&store.0);
    BlazenFuture::spawn::<Vec<InnerWorkflowCheckpoint>, _>(async move { store_inner.list().await })
}

// ---------------------------------------------------------------------------
// list_run_ids
// ---------------------------------------------------------------------------

/// Synchronously list every stored run id, ordered by timestamp
/// descending.
///
/// On success writes a heap-allocated array of `*mut c_char` into
/// `*out_array` plus its length into `*out_count`. Free the array with
/// [`blazen_string_array_free`].
///
/// Returns `0` on success, `-1` on failure, `-2` on invalid input.
///
/// # Safety
///
/// Same contracts as [`blazen_checkpoint_store_list_blocking`].
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_list_run_ids_blocking(
    store: *const BlazenCheckpointStore,
    out_array: *mut *mut *mut c_char,
    out_count: *mut usize,
    out_err: *mut *mut BlazenError,
) -> i32 {
    if store.is_null() {
        return -2;
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };

    let store_inner = Arc::clone(&store.0);
    let result = runtime().block_on(async move { store_inner.list_run_ids().await });
    match result {
        Ok(items) => {
            let (base, count) = strings_to_c_array(items);
            if out_array.is_null() {
                // Caller doesn't want the array — release it immediately.
                // SAFETY: `base` + `count` were just produced by
                // `strings_to_c_array`; reconstructing the boxed slice is
                // sound and `Box::from_raw` on each non-null element pointer
                // returns the original `CString` allocation.
                unsafe {
                    let slice = std::slice::from_raw_parts_mut(base, count);
                    let owned = Box::from_raw(slice);
                    for &ptr in &owned {
                        if !ptr.is_null() {
                            drop(std::ffi::CString::from_raw(ptr));
                        }
                    }
                    drop(owned);
                }
            } else {
                // SAFETY: caller has guaranteed `out_array` is writable.
                unsafe {
                    *out_array = base;
                }
            }
            if !out_count.is_null() {
                // SAFETY: caller has guaranteed `out_count` is writable.
                unsafe {
                    *out_count = count;
                }
            }
            0
        }
        Err(e) => {
            if !out_err.is_null() {
                // SAFETY: caller has guaranteed `out_err` is writable.
                unsafe {
                    *out_err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}

/// Asynchronously list every stored run id. Returns a future whose result
/// is popped with [`blazen_future_take_string_list`].
///
/// # Safety
///
/// `store` must be a valid pointer to a `BlazenCheckpointStore`.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_list_run_ids(
    store: *const BlazenCheckpointStore,
) -> *mut BlazenFuture {
    if store.is_null() {
        return std::ptr::null_mut();
    }
    // SAFETY: caller has guaranteed `store` is a live `BlazenCheckpointStore`.
    let store = unsafe { &*store };

    let store_inner = Arc::clone(&store.0);
    BlazenFuture::spawn::<Vec<String>, _>(async move { store_inner.list_run_ids().await })
}

// ---------------------------------------------------------------------------
// free
// ---------------------------------------------------------------------------

/// Frees a `BlazenCheckpointStore` handle. No-op on a null pointer.
///
/// # Safety
///
/// `store` must be null OR a pointer previously produced by the cabi
/// surface's checkpoint-store factory functions. Double-free is undefined
/// behavior.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_checkpoint_store_free(store: *mut BlazenCheckpointStore) {
    if store.is_null() {
        return;
    }
    // SAFETY: caller upholds the `Box::into_raw` provenance contract.
    drop(unsafe { Box::from_raw(store) });
}

// ---------------------------------------------------------------------------
// Array free helpers
// ---------------------------------------------------------------------------

/// Frees an array of `*mut BlazenWorkflowCheckpoint` previously produced
/// by [`blazen_checkpoint_store_list_blocking`] or
/// [`blazen_future_take_workflow_checkpoint_list`].
///
/// Releases each element handle AND the backing slice in one call. No-op
/// on a null `arr` (regardless of `count`).
///
/// # Safety
///
/// `arr` must be null OR a pointer previously produced by the cabi
/// surface's checkpoint-list entry points, with `count` matching its
/// length. Double-free is undefined behavior; modifying or freeing
/// individual element pointers before this call is also undefined.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_workflow_checkpoint_array_free(
    arr: *mut *mut BlazenWorkflowCheckpoint,
    count: usize,
) {
    if arr.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `arr` + `count` describe a live
    // `Box<[*mut BlazenWorkflowCheckpoint]>` allocation. Reconstructing the
    // slice and reboxing releases the backing storage; each non-null
    // element pointer is then `Box::from_raw`'d back to release its
    // checkpoint allocation.
    unsafe {
        let slice = std::slice::from_raw_parts_mut(arr, count);
        let owned = Box::from_raw(slice);
        for &ptr in &owned {
            if !ptr.is_null() {
                drop(Box::from_raw(ptr));
            }
        }
        drop(owned);
    }
}

/// Frees an array of `*mut c_char` previously produced by
/// [`blazen_checkpoint_store_list_run_ids_blocking`] or
/// [`blazen_future_take_string_list`].
///
/// Releases each element string AND the backing slice in one call. No-op
/// on a null `arr` (regardless of `count`).
///
/// # Safety
///
/// `arr` must be null OR a pointer previously produced by the cabi
/// surface's string-list entry points, with `count` matching its length.
/// Double-free is undefined behavior; modifying or freeing individual
/// element pointers before this call is also undefined.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_string_array_free(arr: *mut *mut c_char, count: usize) {
    if arr.is_null() {
        return;
    }
    // SAFETY: caller has guaranteed `arr` + `count` describe a live
    // `Box<[*mut c_char]>` allocation. Reconstructing the slice and reboxing
    // releases the backing storage; each non-null element pointer is then
    // `CString::from_raw`'d back to release its string allocation.
    unsafe {
        let slice = std::slice::from_raw_parts_mut(arr, count);
        let owned = Box::from_raw(slice);
        for &ptr in &owned {
            if !ptr.is_null() {
                drop(std::ffi::CString::from_raw(ptr));
            }
        }
        drop(owned);
    }
}

// ---------------------------------------------------------------------------
// Typed future-take entry points
// ---------------------------------------------------------------------------

/// Pops a `()` result out of `fut` — used for `save` and `delete`. On
/// success returns `0`; on failure returns `-1` and writes a caller-owned
/// `*mut BlazenError` into `err`.
///
/// `err` may be null when the caller wants to discard the error.
///
/// # Safety
///
/// `fut` must be a non-null pointer produced by a cabi async wrapper
/// whose underlying future returns `Result<(), BlazenError>`, not yet
/// freed. `err` must be null OR a writable pointer to a `*mut BlazenError`
/// slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_future_take_unit(
    fut: *mut BlazenFuture,
    err: *mut *mut BlazenError,
) -> i32 {
    // SAFETY: caller upholds the live-future-pointer contract.
    match unsafe { BlazenFuture::take_typed::<()>(fut) } {
        Ok(()) => 0,
        Err(e) => {
            if !err.is_null() {
                // SAFETY: caller has guaranteed `err` is writable.
                unsafe {
                    *err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}

/// Pops an `Option<WorkflowCheckpoint>` result out of `fut`. Mirrors the
/// blocking `load` semantics:
///
/// - On success Some: returns `0`, writes a fresh handle into `out`, and
///   writes `1` into `out_found`.
/// - On success None: returns `0` and writes `0` into `out_found`.
/// - On failure: returns `-1` and writes a `*mut BlazenError` into `err`.
///
/// `out` / `out_found` / `err` may individually be null to discard.
///
/// # Safety
///
/// `fut` must be a non-null pointer produced by
/// [`blazen_checkpoint_store_load`], not yet freed. `out` / `out_found` /
/// `err` must be null OR writable pointers to the appropriate slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_future_take_workflow_checkpoint_option(
    fut: *mut BlazenFuture,
    out: *mut *mut BlazenWorkflowCheckpoint,
    out_found: *mut i32,
    err: *mut *mut BlazenError,
) -> i32 {
    // SAFETY: caller upholds the live-future-pointer contract.
    match unsafe { BlazenFuture::take_typed::<Option<InnerWorkflowCheckpoint>>(fut) } {
        Ok(Some(v)) => {
            if !out.is_null() {
                // SAFETY: caller has guaranteed `out` is writable.
                unsafe {
                    *out = BlazenWorkflowCheckpoint::from(v).into_ptr();
                }
            }
            if !out_found.is_null() {
                // SAFETY: caller has guaranteed `out_found` is writable.
                unsafe {
                    *out_found = 1;
                }
            }
            0
        }
        Ok(None) => {
            if !out_found.is_null() {
                // SAFETY: caller has guaranteed `out_found` is writable.
                unsafe {
                    *out_found = 0;
                }
            }
            0
        }
        Err(e) => {
            if !err.is_null() {
                // SAFETY: caller has guaranteed `err` is writable.
                unsafe {
                    *err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}

/// Pops a `Vec<WorkflowCheckpoint>` result out of `fut`. Mirrors the
/// blocking `list` semantics — on success returns `0` and writes a
/// heap-allocated array of `*mut BlazenWorkflowCheckpoint` into
/// `*out_array` with its length in `*out_count`. Free with
/// [`blazen_workflow_checkpoint_array_free`].
///
/// `out_array` / `out_count` / `err` may individually be null to discard.
/// When `out_array` is null the array is freed immediately to avoid a
/// leak.
///
/// # Safety
///
/// `fut` must be a non-null pointer produced by
/// [`blazen_checkpoint_store_list`], not yet freed. `out_array` /
/// `out_count` / `err` must be null OR writable pointers to the
/// appropriate slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_future_take_workflow_checkpoint_list(
    fut: *mut BlazenFuture,
    out_array: *mut *mut *mut BlazenWorkflowCheckpoint,
    out_count: *mut usize,
    err: *mut *mut BlazenError,
) -> i32 {
    // SAFETY: caller upholds the live-future-pointer contract.
    match unsafe { BlazenFuture::take_typed::<Vec<InnerWorkflowCheckpoint>>(fut) } {
        Ok(items) => {
            let (base, count) = checkpoints_to_c_array(items);
            if out_array.is_null() {
                // SAFETY: `base` + `count` describe the array just produced;
                // reconstructing the boxed slice is sound.
                unsafe {
                    let slice = std::slice::from_raw_parts_mut(base, count);
                    let owned = Box::from_raw(slice);
                    for &ptr in &owned {
                        if !ptr.is_null() {
                            drop(Box::from_raw(ptr));
                        }
                    }
                    drop(owned);
                }
            } else {
                // SAFETY: caller has guaranteed `out_array` is writable.
                unsafe {
                    *out_array = base;
                }
            }
            if !out_count.is_null() {
                // SAFETY: caller has guaranteed `out_count` is writable.
                unsafe {
                    *out_count = count;
                }
            }
            0
        }
        Err(e) => {
            if !err.is_null() {
                // SAFETY: caller has guaranteed `err` is writable.
                unsafe {
                    *err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}

/// Pops a `Vec<String>` result out of `fut`. Mirrors the blocking
/// `list_run_ids` semantics — on success returns `0` and writes a
/// heap-allocated array of `*mut c_char` into `*out_array` with its
/// length in `*out_count`. Free with [`blazen_string_array_free`].
///
/// `out_array` / `out_count` / `err` may individually be null to discard.
/// When `out_array` is null the array is freed immediately to avoid a
/// leak.
///
/// # Safety
///
/// `fut` must be a non-null pointer produced by
/// [`blazen_checkpoint_store_list_run_ids`], not yet freed. `out_array` /
/// `out_count` / `err` must be null OR writable pointers to the
/// appropriate slot.
#[unsafe(no_mangle)]
pub unsafe extern "C" fn blazen_future_take_string_list(
    fut: *mut BlazenFuture,
    out_array: *mut *mut *mut c_char,
    out_count: *mut usize,
    err: *mut *mut BlazenError,
) -> i32 {
    // SAFETY: caller upholds the live-future-pointer contract.
    match unsafe { BlazenFuture::take_typed::<Vec<String>>(fut) } {
        Ok(items) => {
            let (base, count) = strings_to_c_array(items);
            if out_array.is_null() {
                // SAFETY: `base` + `count` describe the array just produced;
                // reconstructing the boxed slice is sound.
                unsafe {
                    let slice = std::slice::from_raw_parts_mut(base, count);
                    let owned = Box::from_raw(slice);
                    for &ptr in &owned {
                        if !ptr.is_null() {
                            drop(std::ffi::CString::from_raw(ptr));
                        }
                    }
                    drop(owned);
                }
            } else {
                // SAFETY: caller has guaranteed `out_array` is writable.
                unsafe {
                    *out_array = base;
                }
            }
            if !out_count.is_null() {
                // SAFETY: caller has guaranteed `out_count` is writable.
                unsafe {
                    *out_count = count;
                }
            }
            0
        }
        Err(e) => {
            if !err.is_null() {
                // SAFETY: caller has guaranteed `err` is writable.
                unsafe {
                    *err = BlazenError::from(e).into_ptr();
                }
            }
            -1
        }
    }
}