Skip to main content

antfly_embedded/
status.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//! Typed convenience wrappers around the raw `*_json` status/capabilities
17//! calls. Only compiled with the (default-on) `serde` feature. Mirrors
18//! `go/pkg/embedded/status.go`.
19
20use std::fmt;
21
22use serde::Deserialize;
23
24use crate::db::Database;
25use crate::error::Error;
26
27/// Either an FFI error or a JSON decode failure from a typed convenience
28/// method. The raw `*_json` methods on [`Database`] never produce this;
29/// they return [`crate::Result`].
30#[derive(Debug)]
31pub enum TypedError {
32    Ffi(Error),
33    Json(serde_json::Error),
34}
35
36impl From<Error> for TypedError {
37    fn from(err: Error) -> Self {
38        TypedError::Ffi(err)
39    }
40}
41
42impl From<serde_json::Error> for TypedError {
43    fn from(err: serde_json::Error) -> Self {
44        TypedError::Json(err)
45    }
46}
47
48impl fmt::Display for TypedError {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        match self {
51            TypedError::Ffi(err) => fmt::Display::fmt(err, f),
52            TypedError::Json(err) => write!(f, "invalid Lite JSON response: {err}"),
53        }
54    }
55}
56
57impl std::error::Error for TypedError {
58    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
59        match self {
60            TypedError::Ffi(err) => Some(err),
61            TypedError::Json(err) => Some(err),
62        }
63    }
64}
65
66/// A `Result` whose error is [`TypedError`], used by the typed convenience
67/// methods (as opposed to [`crate::Result`], used by the raw `*_json`
68/// methods).
69pub type TypedResult<T> = std::result::Result<T, TypedError>;
70
71/// Describes the physical Lite database file backing a handle.
72#[derive(Debug, Clone, Deserialize)]
73pub struct StorageStatus {
74    pub format: String,
75    pub engine: String,
76    pub primary_layout: String,
77    pub replay_layout: String,
78    pub index_layout: String,
79    #[serde(default)]
80    pub index_namespace: Option<String>,
81    #[serde(default)]
82    pub format_version: Option<u32>,
83    #[serde(default)]
84    pub page_size: Option<u32>,
85    #[serde(default)]
86    pub active_checkpoint: Option<u8>,
87    #[serde(default)]
88    pub checkpoint_sequence: Option<u64>,
89    #[serde(default)]
90    pub page_count: Option<u64>,
91}
92
93/// Historical snapshot of the local runtime's last denied memory admission.
94#[derive(Debug, Clone, Deserialize)]
95pub struct MemoryAdmissionStats {
96    pub pressure: String,
97    pub denied_count: u64,
98    pub last_denied_ns: u64,
99    pub request_count: u64,
100    pub requested_host_bytes: u64,
101    pub requested_backend_bytes: u64,
102    pub requested_kv_bytes: u64,
103    pub requested_scratch_bytes: u64,
104    pub admitted_host_bytes: u64,
105    pub admitted_backend_bytes: u64,
106    pub host_limit_bytes: u64,
107    pub backend_limit_bytes: u64,
108    pub combined_limit_bytes: u64,
109    pub available_memory_bytes: u64,
110}
111
112/// Reports the configured inference execution mode for a Lite handle. See
113/// `go/pkg/embedded/status.go`'s `InferenceStatus` doc comment for the budget
114/// field semantics (0 vs. "resolved" values).
115#[derive(Debug, Clone, Deserialize)]
116pub struct InferenceStatus {
117    pub mode: String,
118    pub available_modes: Vec<String>,
119    pub configured: bool,
120    pub remote_provider_configured: bool,
121    pub local_runtime_configured: bool,
122    pub local_runtime_available: bool,
123    pub caller_supplied_artifacts: bool,
124    pub no_inference_configured_ok: bool,
125    pub host_budget_mb: u32,
126    pub backend_budget_mb: u32,
127    pub combined_budget_mb: u32,
128    pub kv_budget_mb: u32,
129    pub scratch_budget_mb: u32,
130    pub process_memory_budget_mb: u32,
131    pub process_memory_limit_bytes: u64,
132    pub process_memory_limit_source: String,
133    #[serde(default)]
134    pub memory_admission: Option<MemoryAdmissionStats>,
135}
136
137/// Describes the Lite feature contract advertised by a handle.
138#[derive(Debug, Clone, Deserialize)]
139pub struct Capabilities {
140    pub freestanding_build: bool,
141    pub threading: String,
142    pub hosted_profile: bool,
143    pub manual_maintenance: bool,
144    pub background_enrichment_runtime: bool,
145    pub ttl_cleanup_runtime: bool,
146    pub transaction_recovery_runtime: bool,
147    pub local_template_rendering: bool,
148    pub remote_template_rendering: bool,
149    pub remote_template_host_callbacks: bool,
150    pub inference_mode: String,
151    pub supported_inference_modes: Vec<String>,
152    pub available_inference_modes: Vec<String>,
153    pub inference_required: bool,
154    pub no_inference_configured_ok: bool,
155    pub caller_supplied_artifacts: bool,
156    pub caller_supplied_embeddings: bool,
157    pub remote_inference_providers: bool,
158    pub local_inference_runtime: bool,
159    pub generated_enrichment_planning: bool,
160    pub text_search: bool,
161    pub dense_vector_search: bool,
162    pub sparse_vector_search: bool,
163    pub hybrid_search: bool,
164    pub graph_search: bool,
165    pub distributed_shard_ownership: bool,
166    pub raft_replication: bool,
167    pub cluster_placement: bool,
168    pub cross_node_joins: bool,
169    pub remote_shard_fanout: bool,
170    pub distributed_transaction_coordination: bool,
171    pub cluster_heartbeat_status_aggregation: bool,
172    pub server_side_autoscaling: bool,
173    pub kubernetes_operator: bool,
174    pub object_storage_primary: bool,
175}
176
177/// Describes the stable Lite readiness fields for derived work. Nested
178/// maintenance telemetry is kept as raw JSON (`serde_json::Value`) because
179/// its shape is operational detail rather than a stable control-plane
180/// contract.
181#[derive(Debug, Clone, Deserialize)]
182pub struct PendingWorkStatus {
183    #[serde(default)]
184    pub background_publications: serde_json::Value,
185    pub derived_target_sequence: u64,
186    pub has_async_indexes: bool,
187    pub portable_import_publication_in_progress: bool,
188    pub portable_import_recovery_required: bool,
189    pub portable_runtime_activation_pending: bool,
190    #[serde(default)]
191    pub enrichment: serde_json::Value,
192    #[serde(default)]
193    pub resolution: serde_json::Value,
194    #[serde(default)]
195    pub promotion: serde_json::Value,
196    #[serde(default)]
197    pub text_merge: serde_json::Value,
198    #[serde(default)]
199    pub replacements: Vec<serde_json::Value>,
200}
201
202/// The typed form of [`Database::status_json`]. `stats` is kept as raw JSON
203/// because its shape is broader than the stable Lite control fields
204/// bindings need for feature branching.
205#[derive(Debug, Clone, Deserialize)]
206pub struct Status {
207    pub storage: StorageStatus,
208    #[serde(default)]
209    pub stats: serde_json::Value,
210    pub pending_work: PendingWorkStatus,
211    pub inference: InferenceStatus,
212    pub capabilities: Capabilities,
213}
214
215/// Reports how many generated enrichment references were recreated from
216/// stored documents.
217#[derive(Debug, Clone, Deserialize)]
218pub struct ReplayGeneratedEnrichmentsResult {
219    pub replayed: u64,
220}
221
222impl Database {
223    /// Returns the typed Lite status document for the database.
224    pub fn status(&self) -> TypedResult<Status> {
225        let body = self.status_json()?;
226        Ok(serde_json::from_slice(&body)?)
227    }
228
229    /// Returns the typed Lite pending-work readiness document.
230    pub fn pending_work_stats(&self) -> TypedResult<PendingWorkStatus> {
231        let body = self.pending_work_stats_json()?;
232        Ok(serde_json::from_slice(&body)?)
233    }
234
235    /// Drains pending enrichment and index work and returns the typed
236    /// post-drain readiness document.
237    pub fn run_until_idle_status(&self) -> TypedResult<PendingWorkStatus> {
238        let body = self.run_until_idle_json()?;
239        Ok(serde_json::from_slice(&body)?)
240    }
241
242    /// Recreates generated enrichment work from stored documents and
243    /// returns the replay count.
244    pub fn replay_generated_enrichments(&self) -> TypedResult<ReplayGeneratedEnrichmentsResult> {
245        let body = self.replay_generated_enrichments_json()?;
246        Ok(serde_json::from_slice(&body)?)
247    }
248
249    /// Returns the typed Lite capability document for the database.
250    pub fn capabilities(&self) -> TypedResult<Capabilities> {
251        let body = self.capabilities_json()?;
252        Ok(serde_json::from_slice(&body)?)
253    }
254}