Skip to main content

antfly_embedded/
db.rs

1// Copyright 2026 Antfly, Inc.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The embedded Antfly database handle and its core operations.
17
18use std::path::Path;
19
20use antfly_embedded_sys::{self as sys, antfly_buffer, antfly_db, antfly_error_code, antfly_slice};
21
22use crate::error::{Error, Result};
23use crate::ffi::{
24    HandleGate, borrow_slice, check, check_outcome, path_has_suffix, path_to_bytes,
25    path_to_cstring, take_buffer,
26};
27use crate::options::{GraphDirection, OpenOptions, WriteIntent};
28
29/// The resolved outcome of a write that failed with
30/// [`Error::OutcomeUnknown`]; see [`Database::outcome_receipt_status`].
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum OutcomeReceiptStatus {
33    /// The uncertain write applied.
34    Applied,
35    /// The uncertain write did not apply.
36    NotApplied,
37}
38
39/// The Antfly C ABI version this binding expects.
40pub const SUPPORTED_ABI_VERSION: u32 = 3;
41
42/// The only threading mode libantfly provides: any thread may call any
43/// method on a [`Database`] concurrently. See [`threading_mode`].
44pub const THREADING_SERIALIZED: u32 = sys::ANTFLY_THREADING_SERIALIZED;
45
46/// Minimum stack, in bytes, for any thread that calls into a [`Database`].
47/// Rust's default for spawned threads is 2 MiB, which is not enough; spawn
48/// callers with `std::thread::Builder::new().stack_size(MIN_THREAD_STACK_SIZE)`
49/// (and size async runtimes' blocking pools the same way).
50pub const MIN_THREAD_STACK_SIZE: usize = sys::ANTFLY_MIN_THREAD_STACK_SIZE;
51
52/// Reports the loaded libantfly threading contract, like
53/// `sqlite3_threadsafe()`.
54pub fn threading_mode() -> u32 {
55    unsafe { sys::antfly_threading_mode() }
56}
57
58/// Returns the loaded Antfly C ABI version.
59pub fn abi_version() -> u32 {
60    unsafe { sys::antfly_abi_version() }
61}
62
63/// Returns the loaded C ABI size of `antfly_open_options`.
64pub fn open_options_size() -> u32 {
65    unsafe { sys::antfly_open_options_size() }
66}
67
68fn compiled_open_options_size() -> u32 {
69    std::mem::size_of::<sys::antfly_open_options>() as u32
70}
71
72/// Verifies that the loaded C library matches the header this binding was
73/// compiled against. Every open function calls this first, like the Go
74/// binding. A mismatch is reported as [`Error::Internal`]: it indicates a
75/// build/deployment inconsistency (a `libantfly` built for a different ABI
76/// generation), not a normal operational failure.
77pub fn validate_abi() -> Result<()> {
78    if abi_version() != SUPPORTED_ABI_VERSION {
79        return Err(Error::Internal);
80    }
81    if open_options_size() != compiled_open_options_size() {
82        return Err(Error::Internal);
83    }
84    Ok(())
85}
86
87/// An embedded Antfly database handle.
88///
89/// `Database` is safe for concurrent use from multiple threads, like
90/// `*sql.DB` in the Go binding: libantfly runs in serialized threading mode
91/// (see [`threading_mode`]). Lite calls queue on the connection and coordinate
92/// with other connections to the same file. Streaming SQL readers keep their
93/// pinned snapshots while other connections publish changes. Schema or index
94/// changes wait for in-flight calls. [`Database::close`] (and
95/// [`Drop`]) wait for in-flight calls to finish; calls made after close
96/// return [`Error::InvalidArgument`].
97pub struct Database {
98    // See `HandleGate`: a writer-preferring reader/writer gate, not
99    // `std::sync::RwLock`, so a steady stream of reads cannot starve
100    // `close`. The actual write-vs-write serialization for concurrent
101    // mutations happens inside libantfly itself, not in this gate.
102    gate: HandleGate<antfly_db>,
103}
104
105// SAFETY: libantfly's only threading mode is "serialized" (see
106// `antfly_threading_mode`, `ANTFLY_THREADING_SERIALIZED`, and
107// zig/CAPI.md "Thread Safety"): any thread may call any exported function on
108// any handle concurrently. Lite calls queue on their connection; managed
109// owners coordinate reads, writes, and admin calls inside the engine.
110// `HandleGate` above coordinates Rust close with in-flight calls; nothing
111// about `*mut antfly_db` here is thread-affine.
112unsafe impl Send for Database {}
113unsafe impl Sync for Database {}
114
115/// A document handle borrowing a table's owning database.
116pub struct Table<'db> {
117    database: Database,
118    _owner: &'db Database,
119}
120impl std::ops::Deref for Table<'_> {
121    type Target = Database;
122    fn deref(&self) -> &Database {
123        &self.database
124    }
125}
126
127impl Database {
128    fn from_handle(handle: *mut antfly_db) -> Database {
129        Database {
130            gate: HandleGate::new(handle),
131        }
132    }
133
134    /// Opens a table-scoped document, schema, index, and enrichment handle.
135    /// Close it before dropping the table. Closing the owner invalidates it.
136    pub fn open_table(&self, name: &str) -> Result<Table<'_>> {
137        self.with_handle(|handle| {
138            let mut table = std::ptr::null_mut();
139            check(unsafe {
140                sys::antfly_db_open_table(handle, borrow_slice(name.as_bytes()), &mut table)
141            })?;
142            Ok(Table {
143                database: Self::from_handle(table),
144                _owner: self,
145            })
146        })
147    }
148
149    /// Runs `f` with the live handle, or returns [`Error::InvalidArgument`]
150    /// if the database has already been closed. See [`HandleGate`].
151    pub(crate) fn with_handle<T>(&self, f: impl FnOnce(*mut antfly_db) -> Result<T>) -> Result<T> {
152        self.gate.with_handle(f)
153    }
154
155    pub(crate) fn read_buffer(
156        &self,
157        f: impl FnOnce(*mut antfly_db, *mut antfly_buffer) -> antfly_error_code,
158    ) -> Result<Vec<u8>> {
159        self.with_handle(|handle| {
160            let mut out = antfly_buffer::default();
161            check(f(handle, &mut out))?;
162            Ok(unsafe { take_buffer(out) })
163        })
164    }
165
166    pub(crate) fn with_input(
167        &self,
168        input: &[u8],
169        f: impl FnOnce(*mut antfly_db, antfly_slice) -> antfly_error_code,
170    ) -> Result<()> {
171        self.with_handle(|handle| check(f(handle, borrow_slice(input))))
172    }
173
174    pub(crate) fn with_input_output(
175        &self,
176        input: &[u8],
177        f: impl FnOnce(*mut antfly_db, antfly_slice, *mut antfly_buffer) -> antfly_error_code,
178    ) -> Result<Vec<u8>> {
179        self.with_handle(|handle| {
180            let mut out = antfly_buffer::default();
181            check(f(handle, borrow_slice(input), &mut out))?;
182            Ok(unsafe { take_buffer(out) })
183        })
184    }
185
186    fn graph_lookup(
187        &self,
188        index_name: &str,
189        key: &str,
190        edge_type: &str,
191        direction: u8,
192        f: impl FnOnce(
193            *mut antfly_db,
194            antfly_slice,
195            antfly_slice,
196            antfly_slice,
197            u8,
198            *mut antfly_buffer,
199        ) -> antfly_error_code,
200    ) -> Result<Vec<u8>> {
201        self.with_handle(|handle| {
202            let mut out = antfly_buffer::default();
203            check(f(
204                handle,
205                borrow_slice(index_name.as_bytes()),
206                borrow_slice(key.as_bytes()),
207                borrow_slice(edge_type.as_bytes()),
208                direction,
209                &mut out,
210            ))?;
211            Ok(unsafe { take_buffer(out) })
212        })
213    }
214
215    // -- Open / create ---------------------------------------------------
216
217    /// Opens an existing Antfly Lite database using explicit options.
218    pub fn open(path: impl AsRef<Path>, options: &OpenOptions) -> Result<Database> {
219        Self::open_with(path.as_ref(), options, false)
220    }
221
222    /// Creates a new Antfly Lite database using explicit options.
223    pub fn create(path: impl AsRef<Path>, options: &OpenOptions) -> Result<Database> {
224        Self::open_with(path.as_ref(), options, true)
225    }
226
227    /// Opens an existing native Antfly Lite database file for writing
228    /// (writer mode, native profile, no other options).
229    pub fn open_default(path: impl AsRef<Path>) -> Result<Database> {
230        Self::open(path, &OpenOptions::default())
231    }
232
233    /// Creates a new native Antfly Lite database file for writing (writer
234    /// mode, native profile, no other options).
235    pub fn create_default(path: impl AsRef<Path>) -> Result<Database> {
236        Self::create(path, &OpenOptions::default())
237    }
238
239    /// Opens an existing Antfly Lite database file read-only.
240    pub fn open_readonly(path: impl AsRef<Path>) -> Result<Database> {
241        Self::open(
242            path,
243            &OpenOptions {
244                mode: crate::options::OpenMode::Readonly,
245                ..Default::default()
246            },
247        )
248    }
249
250    /// Opens enough of an Antfly Lite database to read status.
251    pub fn open_status_only(path: impl AsRef<Path>) -> Result<Database> {
252        Self::open(
253            path,
254            &OpenOptions {
255                mode: crate::options::OpenMode::StatusOnly,
256                ..Default::default()
257            },
258        )
259    }
260
261    /// Opens an existing Antfly Lite database in hosted/manual maintenance
262    /// mode. In this profile callers drive pending work explicitly with
263    /// [`Database::run_until_idle`].
264    pub fn open_hosted(path: impl AsRef<Path>) -> Result<Database> {
265        validate_abi()?;
266        let c_path = path_to_cstring(path.as_ref())?;
267        let mut handle: *mut antfly_db = std::ptr::null_mut();
268        check(unsafe { sys::antfly_lite_open_hosted(c_path.as_ptr(), &mut handle) })?;
269        Ok(Database::from_handle(handle))
270    }
271
272    /// Creates a new Antfly Lite database in hosted/manual maintenance
273    /// mode. In this profile callers drive pending work explicitly with
274    /// [`Database::run_until_idle`].
275    pub fn create_hosted(path: impl AsRef<Path>) -> Result<Database> {
276        validate_abi()?;
277        let c_path = path_to_cstring(path.as_ref())?;
278        let mut handle: *mut antfly_db = std::ptr::null_mut();
279        check(unsafe { sys::antfly_lite_create_hosted(c_path.as_ptr(), &mut handle) })?;
280        Ok(Database::from_handle(handle))
281    }
282
283    fn open_with(path: &Path, options: &OpenOptions, create: bool) -> Result<Database> {
284        validate_abi()?;
285        let c_path = path_to_cstring(path)?;
286
287        let mut c_opts: sys::antfly_open_options = unsafe { std::mem::zeroed() };
288        check(unsafe { sys::antfly_open_options_init(&mut c_opts) })?;
289
290        c_opts.storage_kind = options.storage.as_u32();
291        c_opts.open_mode = options.mode.as_u32();
292        c_opts.profile = options.profile.as_u32();
293        c_opts.map_size = options.map_size;
294        if options.no_sync {
295            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_NO_SYNC;
296        }
297        if options.remote_provider_configured {
298            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_REMOTE_PROVIDER_CONFIGURED;
299        }
300        if options.local_runtime_configured {
301            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_LOCAL_RUNTIME_CONFIGURED;
302        }
303        if options.generated_enrichment_replay {
304            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_GENERATED_ENRICHMENT_REPLAY;
305        }
306        c_opts.inference_host_budget_mb = options.host_budget_mb;
307        c_opts.inference_backend_budget_mb = options.backend_budget_mb;
308        c_opts.inference_combined_budget_mb = options.combined_budget_mb;
309        c_opts.inference_kv_budget_mb = options.kv_budget_mb;
310        c_opts.inference_scratch_budget_mb = options.scratch_budget_mb;
311        c_opts.inference_process_memory_budget_mb = options.process_memory_budget_mb;
312        c_opts.busy_timeout_ms = options.busy_timeout_ms();
313        let models_dir_bytes = options.models_dir.as_deref().map(path_to_bytes);
314        if let Some(bytes) = &models_dir_bytes {
315            c_opts.models_dir = borrow_slice(bytes);
316        }
317
318        if let Some(ttl) = &options.ttl_cleanup {
319            c_opts.flags |= sys::ANTFLY_OPEN_FLAG_TTL_CLEANUP;
320            c_opts.ttl_cleanup_enabled = ttl.enabled;
321            c_opts.ttl_cleanup_lease_owned = ttl.lease_owned;
322            c_opts.ttl_cleanup_lease_ttl_ms = ttl.lease_ttl_ms;
323            c_opts.ttl_cleanup_interval_ms = ttl.interval_ms;
324            c_opts.ttl_cleanup_batch_size = ttl.batch_size;
325            c_opts.ttl_cleanup_grace_period_ns = ttl.grace_period_ns;
326            // `ttl.owner_id` outlives this call (borrowed from `options`,
327            // which the caller keeps alive for the duration of `open_with`).
328            c_opts.ttl_cleanup_owner_id = borrow_slice(ttl.owner_id.as_bytes());
329        }
330
331        let mut handle: *mut antfly_db = std::ptr::null_mut();
332        let code = if create {
333            unsafe { sys::antfly_db_create_with_options(c_path.as_ptr(), &c_opts, &mut handle) }
334        } else {
335            unsafe { sys::antfly_db_open_with_options(c_path.as_ptr(), &c_opts, &mut handle) }
336        };
337        check(code)?;
338        Ok(Database::from_handle(handle))
339    }
340
341    // -- Close ------------------------------------------------------------
342
343    /// Releases the embedded database handle, waiting for in-flight calls
344    /// on other threads to finish first. Idempotent and safe to call
345    /// concurrently with itself or from several threads at once (matching
346    /// `antfly_db_close`'s contract), including through a shared
347    /// `Arc<Database>` -- calls made after (or racing) `close` return
348    /// [`Error::InvalidArgument`] rather than touching a freed handle.
349    ///
350    /// Takes `&self`, not `self`, specifically so it can be called on a
351    /// `Database` shared across threads (e.g. `Arc<Database>`) without every
352    /// other clone having to be dropped first; [`Drop`] still closes
353    /// automatically once the last owner goes out of scope, for callers who
354    /// never need to close early.
355    pub fn close(&self) -> Result<()> {
356        self.close_inner();
357        Ok(())
358    }
359
360    fn close_inner(&self) {
361        self.gate
362            .close(|handle| unsafe { sys::antfly_db_close(handle) });
363    }
364
365    // -- Status / maintenance JSON -----------------------------------------
366
367    pub fn status_json(&self) -> Result<Vec<u8>> {
368        self.read_buffer(|h, out| unsafe { sys::antfly_db_status_json(h, out) })
369    }
370
371    pub fn capabilities_json(&self) -> Result<Vec<u8>> {
372        self.read_buffer(|h, out| unsafe { sys::antfly_db_capabilities_json(h, out) })
373    }
374
375    pub fn replay_generated_enrichments_json(&self) -> Result<Vec<u8>> {
376        self.read_buffer(|h, out| unsafe {
377            sys::antfly_db_replay_generated_enrichments_json(h, out)
378        })
379    }
380
381    /// Returns a portable Antfly backup archive (`.afb`) of this database,
382    /// which restores or imports into either storage kind.
383    pub fn backup(&self) -> Result<Vec<u8>> {
384        self.read_buffer(|h, out| unsafe { sys::antfly_db_backup(h, out) })
385    }
386
387    /// Export with optional {"tables":[...]} scope; default is always included.
388    /// Full backups fail closed if any table is unavailable.
389    pub fn backup_json(&self, options: impl AsRef<[u8]>) -> Result<Vec<u8>> {
390        self.with_input_output(options.as_ref(), |h, input, out| unsafe {
391            sys::antfly_db_backup_json(h, input, out)
392        })
393    }
394
395    /// Imports a portable Antfly backup archive into this empty database.
396    /// [`Error::OutcomeUnknown`] means the live handle adopted the imported
397    /// generation, but crash durability could not be confirmed; inspect the
398    /// handle and do not retry automatically.
399    pub fn import_backup(&self, backup: impl AsRef<[u8]>) -> Result<()> {
400        self.with_input(backup.as_ref(), |h, input| unsafe {
401            sys::antfly_db_import_backup(h, input)
402        })
403    }
404
405    /// Runs Lite integrity checks and returns the JSON result.
406    pub fn check_json(&self) -> Result<Vec<u8>> {
407        self.read_buffer(|h, out| unsafe { sys::antfly_lite_check_json(h, out) })
408    }
409
410    /// Compacts free space and returns the JSON result.
411    pub fn vacuum_json(&self) -> Result<Vec<u8>> {
412        self.read_buffer(|h, out| unsafe { sys::antfly_lite_vacuum_json(h, out) })
413    }
414
415    /// Drains maintenance, compacts indexes, vacuums free space, and
416    /// returns the JSON result.
417    pub fn compact_json(&self) -> Result<Vec<u8>> {
418        self.read_buffer(|h, out| unsafe { sys::antfly_lite_compact_json(h, out) })
419    }
420
421    /// Copies a stable Lite snapshot to `dest_path`, which must end in
422    /// `.aflite`.
423    pub fn copy_stable_snapshot_json(
424        &self,
425        dest_path: impl AsRef<Path>,
426        replace: bool,
427    ) -> Result<Vec<u8>> {
428        let dest_path = dest_path.as_ref();
429        if !path_has_suffix(dest_path, ".aflite") {
430            return Err(Error::InvalidArgument);
431        }
432        let c_dest = path_to_cstring(dest_path)?;
433        self.with_handle(|handle| {
434            let mut out = antfly_buffer::default();
435            check(unsafe {
436                sys::antfly_lite_copy_stable_snapshot_json(
437                    handle,
438                    c_dest.as_ptr(),
439                    replace,
440                    &mut out,
441                )
442            })?;
443            Ok(unsafe { take_buffer(out) })
444        })
445    }
446
447    // -- Batch / documents --------------------------------------------------
448
449    /// Applies write intents at `timestamp_ns`.
450    pub fn batch(&self, writes: &[WriteIntent], timestamp_ns: u64) -> Result<()> {
451        self.with_handle(|handle| {
452            // Keep every borrowed antfly_slice's backing bytes alive for the
453            // duration of the call by holding the WriteIntent Vecs (`writes`)
454            // borrowed for the whole closure, and building the antfly_slice
455            // array from them just before the call.
456            let c_writes: Vec<sys::antfly_write_intent> = writes
457                .iter()
458                .map(|w| sys::antfly_write_intent {
459                    key: borrow_slice(&w.key),
460                    value: borrow_slice(&w.value),
461                    is_delete: w.delete,
462                })
463                .collect();
464            let ptr = if c_writes.is_empty() {
465                std::ptr::null()
466            } else {
467                c_writes.as_ptr()
468            };
469            check_outcome(unsafe {
470                sys::antfly_db_batch(
471                    handle,
472                    ptr,
473                    c_writes.len(),
474                    std::ptr::null(),
475                    0,
476                    timestamp_ns,
477                    0,
478                )
479            })
480        })
481    }
482
483    /// Applies a public Antfly batch request and returns the JSON result.
484    /// An `OutcomeUnknown` failure carries its outcome receipt (see
485    /// [`Error::outcome_receipt`]).
486    pub fn batch_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
487        let request = request.as_ref();
488        self.with_handle(|handle| {
489            let mut out = antfly_buffer::default();
490            let code =
491                unsafe { sys::antfly_db_batch_json(handle, borrow_slice(request), &mut out) };
492            if let Err(error) = check_outcome(code) {
493                unsafe { take_buffer(out) };
494                return Err(error);
495            }
496            Ok(unsafe { take_buffer(out) })
497        })
498    }
499
500    /// Resolves an outcome receipt from an `OutcomeUnknown` batch or
501    /// autocommit SQL write, on any handle for the same database. Returns
502    /// [`Error::Stalled`] while the uncertain commit is not reconciled yet:
503    /// retry on a Lite database; for a directory database, close the issuing
504    /// handle and reopen first.
505    pub fn outcome_receipt_status(&self, receipt: &str) -> Result<OutcomeReceiptStatus> {
506        self.with_handle(|handle| {
507            let mut status: u8 = 0;
508            check(unsafe {
509                sys::antfly_db_outcome_receipt_status(
510                    handle,
511                    borrow_slice(receipt.as_bytes()),
512                    &mut status,
513                )
514            })?;
515            match status {
516                sys::ANTFLY_OUTCOME_RECEIPT_APPLIED => Ok(OutcomeReceiptStatus::Applied),
517                sys::ANTFLY_OUTCOME_RECEIPT_NOT_APPLIED => Ok(OutcomeReceiptStatus::NotApplied),
518                _ => Err(Error::Internal),
519            }
520        })
521    }
522
523    /// Removes a resolved receipt's durable marker; afterwards the receipt
524    /// can no longer be resolved.
525    pub fn forget_outcome_receipt(&self, receipt: &str) -> Result<()> {
526        self.with_input(receipt.as_bytes(), |h, input| unsafe {
527            sys::antfly_db_outcome_receipt_forget(h, input)
528        })
529    }
530
531    /// Returns the JSON lookup result for `key`.
532    pub fn lookup_json(&self, key: impl AsRef<[u8]>) -> Result<Vec<u8>> {
533        self.with_input_output(key.as_ref(), |h, input, out| unsafe {
534            sys::antfly_db_lookup_json(h, input, out)
535        })
536    }
537
538    /// Returns the raw stored bytes for `key`.
539    pub fn get_raw(&self, key: impl AsRef<[u8]>) -> Result<Vec<u8>> {
540        self.with_input_output(key.as_ref(), |h, input, out| unsafe {
541            sys::antfly_db_get_raw(h, input, out)
542        })
543    }
544
545    // -- Schema / indexes / enrichments -------------------------------------
546
547    pub fn schema_json(&self) -> Result<Vec<u8>> {
548        self.read_buffer(|h, out| unsafe { sys::antfly_db_get_schema_json(h, out) })
549    }
550
551    pub fn set_schema_json(&self, schema: impl AsRef<[u8]>) -> Result<()> {
552        self.with_input(schema.as_ref(), |h, input| unsafe {
553            sys::antfly_db_set_schema_json(h, input)
554        })
555    }
556
557    /// Drains pending enrichment and index work.
558    pub fn run_until_idle(&self) -> Result<()> {
559        self.with_handle(|handle| check(unsafe { sys::antfly_db_run_until_idle(handle) }))
560    }
561
562    /// Drains pending enrichment and index work and returns the post-drain
563    /// pending work stats JSON.
564    pub fn run_until_idle_json(&self) -> Result<Vec<u8>> {
565        self.read_buffer(|h, out| unsafe { sys::antfly_db_run_until_idle_json(h, out) })
566    }
567
568    pub fn pending_work_stats_json(&self) -> Result<Vec<u8>> {
569        self.read_buffer(|h, out| unsafe { sys::antfly_db_pending_work_stats_json(h, out) })
570    }
571
572    pub fn indexes_json(&self) -> Result<Vec<u8>> {
573        self.read_buffer(|h, out| unsafe { sys::antfly_db_list_indexes_json(h, out) })
574    }
575
576    /// Render the durable template and follow key aliases, without writes or ANN search.
577    pub fn render_resolver_key_json(
578        &self,
579        resolver: &str,
580        mention: impl AsRef<[u8]>,
581    ) -> Result<Vec<u8>> {
582        self.with_input_output(mention.as_ref(), |h, input, out| unsafe {
583            sys::antfly_db_render_resolver_key_json(
584                h,
585                borrow_slice(resolver.as_bytes()),
586                input,
587                out,
588            )
589        })
590    }
591
592    /// Resolve text or extraction mentions, including aliases and ANN, without writes.
593    /// Execute native memory policy without an HTTP server or extension.
594    pub fn memory_json(&self, space: &str, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
595        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
596            sys::antfly_db_memory_json(h, borrow_slice(space.as_bytes()), input, out)
597        })
598    }
599
600    pub fn resolve_query_json(&self, resolver: &str, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
601        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
602            sys::antfly_db_resolve_query_json(h, borrow_slice(resolver.as_bytes()), input, out)
603        })
604    }
605
606    /// Persist a {"key","target"} redirect. Drain to re-key existing resolution edges.
607    pub fn merge_resolver_keys_json(
608        &self,
609        resolver: &str,
610        request: impl AsRef<[u8]>,
611    ) -> Result<()> {
612        self.with_input(request.as_ref(), |h, input| unsafe {
613            sys::antfly_db_merge_resolver_keys_json(h, borrow_slice(resolver.as_bytes()), input)
614        })
615    }
616
617    /// Undo a redirect, optionally pinning its former target distinct.
618    pub fn unmerge_resolver_key_json(
619        &self,
620        resolver: &str,
621        request: impl AsRef<[u8]>,
622    ) -> Result<Vec<u8>> {
623        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
624            sys::antfly_db_unmerge_resolver_key_json(
625                h,
626                borrow_slice(resolver.as_bytes()),
627                input,
628                out,
629            )
630        })
631    }
632
633    /// Atomically add or remove runtime key and normalized-text suppressions.
634    pub fn suppress_resolver_keys_json(
635        &self,
636        resolver: &str,
637        request: impl AsRef<[u8]>,
638    ) -> Result<Vec<u8>> {
639        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
640            sys::antfly_db_suppress_resolver_keys_json(
641                h,
642                borrow_slice(resolver.as_bytes()),
643                input,
644                out,
645            )
646        })
647    }
648
649    /// Remove runtime suppression of a key; declarative rules remain effective.
650    pub fn unsuppress_resolver_key_json(
651        &self,
652        resolver: &str,
653        request: impl AsRef<[u8]>,
654    ) -> Result<Vec<u8>> {
655        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
656            sys::antfly_db_unsuppress_resolver_key_json(
657                h,
658                borrow_slice(resolver.as_bytes()),
659                input,
660                out,
661            )
662        })
663    }
664
665    /// Inspect one resolver's durable curation, or all identities for an empty name.
666    pub fn resolver_curation_json(&self, resolver: &str) -> Result<Vec<u8>> {
667        self.read_buffer(|h, out| unsafe {
668            sys::antfly_db_resolver_curation_json(h, borrow_slice(resolver.as_bytes()), out)
669        })
670    }
671
672    /// Page reviews or submit a decision bound to the displayed artifact.
673    pub fn resolver_reviews_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
674        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
675            sys::antfly_db_resolver_reviews_json(h, input, out)
676        })
677    }
678
679    /// Propose an entity correction; repeated action and keys retain the existing decision.
680    pub fn propose_curation_json(&self, table: &str, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
681        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
682            sys::antfly_db_propose_curation_json(h, borrow_slice(table.as_bytes()), input, out)
683        })
684    }
685
686    /// List the persistent entity review queue with bounded keyset pagination.
687    pub fn list_curation_proposals_json(
688        &self,
689        table: &str,
690        request: impl AsRef<[u8]>,
691    ) -> Result<Vec<u8>> {
692        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
693            sys::antfly_db_list_curation_proposals_json(
694                h,
695                borrow_slice(table.as_bytes()),
696                input,
697                out,
698            )
699        })
700    }
701
702    /// Inspect a persistent proposal by its stable identifier.
703    pub fn get_curation_proposal_json(&self, table: &str, id: &str) -> Result<Vec<u8>> {
704        self.read_buffer(|h, out| unsafe {
705            sys::antfly_db_get_curation_proposal_json(
706                h,
707                borrow_slice(table.as_bytes()),
708                borrow_slice(id.as_bytes()),
709                out,
710            )
711        })
712    }
713
714    /// Accept or reject a proposal; retry incomplete fanout to resume durable receipts.
715    pub fn decide_curation_proposal_json(
716        &self,
717        table: &str,
718        id: &str,
719        request: impl AsRef<[u8]>,
720    ) -> Result<Vec<u8>> {
721        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
722            sys::antfly_db_decide_curation_proposal_json(
723                h,
724                borrow_slice(table.as_bytes()),
725                borrow_slice(id.as_bytes()),
726                input,
727                out,
728            )
729        })
730    }
731
732    /// Fan out a correction across resolver namespaces targeting this entity.
733    pub fn curate_entity_json(
734        &self,
735        table: &str,
736        key: &str,
737        request: impl AsRef<[u8]>,
738    ) -> Result<Vec<u8>> {
739        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
740            sys::antfly_db_curate_entity_json(
741                h,
742                borrow_slice(table.as_bytes()),
743                borrow_slice(key.as_bytes()),
744                input,
745                out,
746            )
747        })
748    }
749
750    /// List active and retired identities, including durable merges.
751    pub fn resolver_identities_json(&self) -> Result<Vec<u8>> {
752        self.read_buffer(|h, out| unsafe { sys::antfly_db_list_resolver_identities_json(h, out) })
753    }
754
755    /// Discard retired identity metadata; artifacts and canonical rows remain.
756    /// Delete source documents for artifact cleanup, then explicitly delete
757    /// unused canonical rows. Busy is retryable.
758    pub fn drop_resolver_identity(&self, name: &str) -> Result<bool> {
759        self.with_handle(|handle| {
760            let mut deleted = false;
761            check(unsafe {
762                sys::antfly_db_drop_resolver_identity(
763                    handle,
764                    borrow_slice(name.as_bytes()),
765                    &mut deleted,
766                )
767            })?;
768            Ok(deleted)
769        })
770    }
771
772    /// Atomically reset or migrate resolver identities; drain afterward.
773    /// Retry the identical request on Busy.
774    pub fn set_resolver_namespace_json(
775        &self,
776        resolver: &str,
777        request: impl AsRef<[u8]>,
778    ) -> Result<()> {
779        self.with_input(request.as_ref(), |h, input| unsafe {
780            sys::antfly_db_set_resolver_namespace_json(h, borrow_slice(resolver.as_bytes()), input)
781        })
782    }
783
784    /// Add or replace an index; retry the identical request on Busy.
785    /// A graph replaces command registers a resumable background shadow. The
786    /// old index serves until activation; absent old indexes behave like add.
787    /// Optional wait:{timeout_ms:N} waits for activation. A deadline Busy leaves
788    /// the accepted shadow running; pending work stats expose its progress.
789    pub fn add_index_json(&self, config: impl AsRef<[u8]>) -> Result<()> {
790        self.with_input(config.as_ref(), |h, input| unsafe {
791            sys::antfly_db_add_index_json(h, input)
792        })
793    }
794
795    /// Deletes an index by name and reports whether it existed.
796    /// Retire an index, returning whether it existed. Busy is retryable.
797    pub fn delete_index(&self, name: &str) -> Result<bool> {
798        self.with_handle(|handle| {
799            let mut deleted = false;
800            check(unsafe {
801                sys::antfly_db_delete_index(handle, borrow_slice(name.as_bytes()), &mut deleted)
802            })?;
803            Ok(deleted)
804        })
805    }
806
807    /// Cancel a running or failed shadow by its new name; idempotent.
808    pub fn cancel_replacement(&self, name: &str) -> Result<bool> {
809        self.with_handle(|handle| {
810            let mut deleted = false;
811            check(unsafe {
812                sys::antfly_db_cancel_replacement(
813                    handle,
814                    borrow_slice(name.as_bytes()),
815                    &mut deleted,
816                )
817            })?;
818            Ok(deleted)
819        })
820    }
821
822    pub fn enrichments_json(&self) -> Result<Vec<u8>> {
823        self.read_buffer(|h, out| unsafe { sys::antfly_db_list_enrichments_json(h, out) })
824    }
825
826    pub fn add_enrichment_json(&self, config: impl AsRef<[u8]>) -> Result<()> {
827        self.with_input(config.as_ref(), |h, input| unsafe {
828            sys::antfly_db_add_enrichment_json(h, input)
829        })
830    }
831
832    /// Deletes an enrichment by kind and name and reports whether it
833    /// existed.
834    pub fn delete_enrichment(&self, kind: &str, name: &str) -> Result<bool> {
835        self.with_handle(|handle| {
836            let mut deleted = false;
837            check(unsafe {
838                sys::antfly_db_delete_enrichment(
839                    handle,
840                    borrow_slice(kind.as_bytes()),
841                    borrow_slice(name.as_bytes()),
842                    &mut deleted,
843                )
844            })?;
845            Ok(deleted)
846        })
847    }
848
849    // -- Scan / stats / search ----------------------------------------------
850
851    pub fn scan_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
852        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
853            sys::antfly_db_scan_json(h, input, out)
854        })
855    }
856
857    pub fn stats_json(&self) -> Result<Vec<u8>> {
858        self.read_buffer(|h, out| unsafe { sys::antfly_db_stats_json(h, out) })
859    }
860
861    pub fn search_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
862        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
863            sys::antfly_db_search_json(h, input, out)
864        })
865    }
866
867    /// Executes a packed dense-vector wire search request.
868    pub fn dense_search_wire(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
869        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
870            sys::antfly_db_search_dense_wire(h, input, out)
871        })
872    }
873
874    /// Executes a packed text-match wire search request.
875    pub fn text_match_wire(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
876        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
877            sys::antfly_db_search_text_match_wire(h, input, out)
878        })
879    }
880
881    /// Executes a packed text-term wire search request.
882    pub fn text_term_wire(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
883        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
884            sys::antfly_db_search_text_term_wire(h, input, out)
885        })
886    }
887
888    /// Executes a packed text-match-phrase wire search request.
889    pub fn text_match_phrase_wire(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
890        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
891            sys::antfly_db_search_text_match_phrase_wire(h, input, out)
892        })
893    }
894
895    /// Aggregates hits from a JSON request.
896    pub fn aggregate_hits_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
897        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
898            sys::antfly_db_aggregate_hits_json(h, input, out)
899        })
900    }
901
902    /// Looks up an artifact by base64 artifact ID.
903    pub fn lookup_artifact_json(&self, artifact_id_base64: &str) -> Result<Vec<u8>> {
904        self.with_input_output(artifact_id_base64.as_bytes(), |h, input, out| unsafe {
905            sys::antfly_db_lookup_artifact_json(h, input, out)
906        })
907    }
908
909    pub fn extract_enrichments_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
910        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
911            sys::antfly_db_extract_enrichments_json(h, input, out)
912        })
913    }
914
915    pub fn compute_enrichments_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
916        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
917            sys::antfly_db_compute_enrichments_json(h, input, out)
918        })
919    }
920
921    // -- Graph ---------------------------------------------------------------
922
923    /// Returns graph edges for `key` from a graph index. `edge_type` of
924    /// `""` matches every edge type.
925    pub fn edges_json(
926        &self,
927        index_name: &str,
928        key: &str,
929        edge_type: &str,
930        direction: GraphDirection,
931    ) -> Result<Vec<u8>> {
932        self.graph_lookup(
933            index_name,
934            key,
935            edge_type,
936            direction.as_u8(),
937            |h, i, k, e, d, out| unsafe { sys::antfly_db_get_edges_json(h, i, k, e, d, out) },
938        )
939    }
940
941    pub fn traverse_edges_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
942        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
943            sys::antfly_db_traverse_edges_json(h, input, out)
944        })
945    }
946
947    pub fn execute_graph_queries_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
948        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
949            sys::antfly_db_execute_graph_queries_json(h, input, out)
950        })
951    }
952
953    /// Returns graph neighbors for `key` from a graph index. `edge_type` of
954    /// `""` matches every edge type.
955    pub fn neighbors_json(
956        &self,
957        index_name: &str,
958        key: &str,
959        edge_type: &str,
960        direction: GraphDirection,
961    ) -> Result<Vec<u8>> {
962        self.graph_lookup(
963            index_name,
964            key,
965            edge_type,
966            direction.as_u8(),
967            |h, i, k, e, d, out| unsafe { sys::antfly_db_get_neighbors_json(h, i, k, e, d, out) },
968        )
969    }
970
971    pub fn find_shortest_path_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
972        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
973            sys::antfly_db_find_shortest_path_json(h, input, out)
974        })
975    }
976
977    pub fn find_k_shortest_paths_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
978        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
979            sys::antfly_db_find_k_shortest_paths_json(h, input, out)
980        })
981    }
982
983    pub fn match_pattern_json(&self, request: impl AsRef<[u8]>) -> Result<Vec<u8>> {
984        self.with_input_output(request.as_ref(), |h, input, out| unsafe {
985            sys::antfly_db_match_pattern_json(h, input, out)
986        })
987    }
988}
989
990impl Drop for Database {
991    fn drop(&mut self) {
992        self.close_inner();
993    }
994}
995
996impl std::fmt::Debug for Database {
997    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
998        f.debug_struct("Database")
999            .field("open", &self.gate.is_open())
1000            .finish()
1001    }
1002}
1003
1004/// Decodes a base64 artifact ID without opening a database.
1005pub fn decode_artifact_id_json(artifact_id_base64: &str) -> Result<Vec<u8>> {
1006    let mut out = antfly_buffer::default();
1007    check(unsafe {
1008        sys::antfly_decode_artifact_id_json(borrow_slice(artifact_id_base64.as_bytes()), &mut out)
1009    })?;
1010    Ok(unsafe { take_buffer(out) })
1011}