Skip to main content

antfly_embedded/
options.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//! Options for opening/creating an Antfly Lite database. Mirrors
17//! `go/pkg/embedded`'s `OpenOptions`/`TTLCleanupOptions`.
18
19use std::time::Duration;
20
21use antfly_embedded_sys as sys;
22
23/// Selects how a database is stored. The default is a single-file `.aflite`
24/// database.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
26pub enum Storage {
27    /// A single-file `.aflite` database.
28    #[default]
29    Lite,
30    /// A normal single-node Antfly directory.
31    Directory,
32}
33
34impl Storage {
35    pub(crate) fn as_u32(self) -> u32 {
36        match self {
37            Storage::Lite => sys::ANTFLY_STORAGE_KIND_LITE,
38            Storage::Directory => sys::ANTFLY_STORAGE_KIND_DIRECTORY,
39        }
40    }
41}
42
43/// Controls how an Antfly Lite file is opened.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
45pub enum OpenMode {
46    #[default]
47    Writer,
48    Readonly,
49    StatusOnly,
50}
51
52impl OpenMode {
53    pub(crate) fn as_u32(self) -> u32 {
54        match self {
55            OpenMode::Writer => sys::ANTFLY_OPEN_MODE_WRITER,
56            OpenMode::Readonly => sys::ANTFLY_OPEN_MODE_READONLY,
57            OpenMode::StatusOnly => sys::ANTFLY_OPEN_MODE_STATUS_ONLY,
58        }
59    }
60}
61
62/// Selects the Lite runtime profile.
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64pub enum Profile {
65    #[default]
66    Native,
67    Hosted,
68}
69
70impl Profile {
71    pub(crate) fn as_u32(self) -> u32 {
72        match self {
73            Profile::Native => sys::ANTFLY_PROFILE_NATIVE,
74            Profile::Hosted => sys::ANTFLY_PROFILE_HOSTED,
75        }
76    }
77}
78
79/// Inference execution mode strings returned by Lite status and
80/// capabilities documents. Kept as `&'static str` constants (not an enum)
81/// because the C ABI defines them as stable strings, not a closed set of
82/// integers.
83pub mod inference_mode {
84    use antfly_embedded_sys as sys;
85
86    pub const CALLER_SUPPLIED_OR_DISABLED: &str =
87        sys::ANTFLY_INFERENCE_MODE_CALLER_SUPPLIED_OR_DISABLED;
88    pub const CALLER_SUPPLIED_ARTIFACTS: &str =
89        sys::ANTFLY_INFERENCE_MODE_CALLER_SUPPLIED_ARTIFACTS;
90    pub const REMOTE_PROVIDER: &str = sys::ANTFLY_INFERENCE_MODE_REMOTE_PROVIDER;
91    pub const LOCAL_EMBEDDED: &str = sys::ANTFLY_INFERENCE_MODE_LOCAL_EMBEDDED;
92    pub const MANUAL_MAINTENANCE: &str = sys::ANTFLY_INFERENCE_MODE_MANUAL_MAINTENANCE;
93    pub const DISABLED_DEFERRED: &str = sys::ANTFLY_INFERENCE_MODE_DISABLED_DEFERRED;
94}
95
96/// Configures the optional Lite TTL cleanup runtime.
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct TtlCleanupOptions {
99    pub enabled: bool,
100    pub lease_owned: bool,
101    pub owner_id: String,
102    pub lease_ttl_ms: u64,
103    pub interval_ms: u64,
104    pub batch_size: u32,
105    pub grace_period_ns: u64,
106}
107
108/// Configures [`crate::Database::open`] and [`crate::Database::create`].
109///
110/// `busy_timeout`, like `sqlite3_busy_timeout`, retries Lite admission while
111/// another process holds the writer lease or advances the allocator checkpoint.
112/// Mutation bodies are never replayed by this admission retry.
113/// `None` (or `Some(Duration::ZERO)`) fails immediately with
114/// [`crate::Error::Busy`]. The C ABI takes whole milliseconds, so a
115/// sub-millisecond duration is rounded up.
116///
117/// `host_budget_mb`, `backend_budget_mb`, `combined_budget_mb`,
118/// `kv_budget_mb`, `scratch_budget_mb`, and `process_memory_budget_mb` are
119/// explicit resource-budget overrides for the local embedded inference
120/// runtime (0 means the embedded node's own host-clamped default). They are
121/// only consulted when `local_runtime_configured` is set.
122#[derive(Debug, Clone, Default, PartialEq, Eq)]
123pub struct OpenOptions {
124    /// Selects a `.aflite` file (the default) or a directory. Directory
125    /// storage is created by opening a missing path; [`crate::Database::create`]
126    /// only creates `.aflite` files.
127    pub storage: Storage,
128    pub mode: OpenMode,
129    pub profile: Profile,
130    pub no_sync: bool,
131    pub remote_provider_configured: bool,
132    pub local_runtime_configured: bool,
133    pub generated_enrichment_replay: bool,
134    pub map_size: u64,
135    pub ttl_cleanup: Option<TtlCleanupOptions>,
136    pub host_budget_mb: u32,
137    pub backend_budget_mb: u32,
138    pub combined_budget_mb: u32,
139    pub kv_budget_mb: u32,
140    pub scratch_budget_mb: u32,
141    pub process_memory_budget_mb: u32,
142    pub busy_timeout: Option<Duration>,
143    /// Model directory for database enrichments; None uses the default.
144    pub models_dir: Option<std::path::PathBuf>,
145}
146
147impl OpenOptions {
148    /// Starts a builder with all defaults (writer/native, no timeout, no TTL
149    /// cleanup, automatic inference budgets).
150    pub fn new() -> Self {
151        Self::default()
152    }
153
154    pub fn models_dir(mut self, directory: impl AsRef<std::path::Path>) -> Self {
155        self.models_dir = Some(directory.as_ref().to_path_buf());
156        self
157    }
158
159    pub fn storage(mut self, storage: Storage) -> Self {
160        self.storage = storage;
161        self
162    }
163
164    pub fn mode(mut self, mode: OpenMode) -> Self {
165        self.mode = mode;
166        self
167    }
168
169    pub fn profile(mut self, profile: Profile) -> Self {
170        self.profile = profile;
171        self
172    }
173
174    pub fn no_sync(mut self, no_sync: bool) -> Self {
175        self.no_sync = no_sync;
176        self
177    }
178
179    pub fn remote_provider_configured(mut self, configured: bool) -> Self {
180        self.remote_provider_configured = configured;
181        self
182    }
183
184    pub fn local_runtime_configured(mut self, configured: bool) -> Self {
185        self.local_runtime_configured = configured;
186        self
187    }
188
189    pub fn generated_enrichment_replay(mut self, replay: bool) -> Self {
190        self.generated_enrichment_replay = replay;
191        self
192    }
193
194    pub fn map_size(mut self, map_size: u64) -> Self {
195        self.map_size = map_size;
196        self
197    }
198
199    pub fn ttl_cleanup(mut self, ttl_cleanup: TtlCleanupOptions) -> Self {
200        self.ttl_cleanup = Some(ttl_cleanup);
201        self
202    }
203
204    pub fn busy_timeout(mut self, timeout: Duration) -> Self {
205        self.busy_timeout = Some(timeout);
206        self
207    }
208
209    pub fn host_budget_mb(mut self, mb: u32) -> Self {
210        self.host_budget_mb = mb;
211        self
212    }
213
214    pub fn backend_budget_mb(mut self, mb: u32) -> Self {
215        self.backend_budget_mb = mb;
216        self
217    }
218
219    pub fn combined_budget_mb(mut self, mb: u32) -> Self {
220        self.combined_budget_mb = mb;
221        self
222    }
223
224    pub fn kv_budget_mb(mut self, mb: u32) -> Self {
225        self.kv_budget_mb = mb;
226        self
227    }
228
229    pub fn scratch_budget_mb(mut self, mb: u32) -> Self {
230        self.scratch_budget_mb = mb;
231        self
232    }
233
234    pub fn process_memory_budget_mb(mut self, mb: u32) -> Self {
235        self.process_memory_budget_mb = mb;
236        self
237    }
238
239    /// Rounds `busy_timeout` up to whole milliseconds, like the Go binding.
240    /// Returns 0 (fail immediately) when unset or zero. Exposed so callers
241    /// can see exactly what will be sent to the C ABI.
242    pub fn busy_timeout_ms(&self) -> u64 {
243        match self.busy_timeout {
244            Some(d) if !d.is_zero() => {
245                let nanos = d.as_nanos();
246                let ms = nanos.div_ceil(1_000_000);
247                u64::try_from(ms).unwrap_or(u64::MAX)
248            }
249            _ => 0,
250        }
251    }
252}
253
254/// Configures [`crate::restore`] and [`crate::restore_file`].
255#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
256pub struct RestoreOptions {
257    /// Selects the kind of database created at the destination: a `.aflite`
258    /// file (the default) or a directory.
259    pub storage: Storage,
260    /// Atomically replaces an existing destination.
261    pub replace: bool,
262}
263
264/// Direction for [`crate::Database::edges_json`] and
265/// [`crate::Database::neighbors_json`].
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
267pub enum GraphDirection {
268    #[default]
269    Out,
270    In,
271    Both,
272}
273
274impl GraphDirection {
275    pub(crate) fn as_u8(self) -> u8 {
276        match self {
277            GraphDirection::Out => sys::ANTFLY_GRAPH_DIRECTION_OUT,
278            GraphDirection::In => sys::ANTFLY_GRAPH_DIRECTION_IN,
279            GraphDirection::Both => sys::ANTFLY_GRAPH_DIRECTION_BOTH,
280        }
281    }
282}
283
284/// A single key/value write or delete in a Lite batch.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct WriteIntent {
287    pub key: Vec<u8>,
288    pub value: Vec<u8>,
289    pub delete: bool,
290}
291
292impl WriteIntent {
293    /// A write that stores `value` at `key`.
294    pub fn put(key: impl Into<Vec<u8>>, value: impl Into<Vec<u8>>) -> Self {
295        WriteIntent {
296            key: key.into(),
297            value: value.into(),
298            delete: false,
299        }
300    }
301
302    /// A write that deletes `key`.
303    pub fn delete(key: impl Into<Vec<u8>>) -> Self {
304        WriteIntent {
305            key: key.into(),
306            value: Vec::new(),
307            delete: true,
308        }
309    }
310}