sochdb_kernel/kernel_api.rs
1// SPDX-License-Identifier: AGPL-3.0-or-later
2// SochDB - LLM-Optimized Embedded Database
3// Copyright (C) 2026 Sushanth Reddy Vanagala (https://github.com/sushanthpy)
4//
5// This program is free software: you can redistribute it and/or modify
6// it under the terms of the GNU Affero General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// This program is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU Affero General Public License for more details.
14//
15// You should have received a copy of the GNU Affero General Public License
16// along with this program. If not, see <https://www.gnu.org/licenses/>.
17
18//! Kernel API Traits
19//!
20//! These traits define the stable API surface of the kernel.
21//! Extensions and plugins implement or consume these traits.
22//!
23//! ## API Stability Guarantee
24//!
25//! Once the kernel reaches 1.0, these traits will follow semver:
26//! - 1.x.x: No breaking changes to trait signatures
27//! - 2.0.0: May introduce breaking changes with migration guide
28
29use crate::error::KernelResult;
30use crate::transaction::TransactionId;
31use crate::wal::LogSequenceNumber;
32
33/// Page identifier
34pub type PageId = u64;
35
36/// Row identifier
37pub type RowId = u64;
38
39/// Table identifier
40pub type TableId = u32;
41
42/// Column identifier
43pub type ColumnId = u16;
44
45/// Core storage operations
46///
47/// This trait provides the minimal storage interface that all
48/// storage backends must implement.
49pub trait KernelStorage: Send + Sync {
50 /// Read a page from storage
51 fn read_page(&self, page_id: PageId) -> KernelResult<Vec<u8>>;
52
53 /// Write a page to storage
54 ///
55 /// Returns the LSN of the write operation for WAL tracking
56 fn write_page(&self, page_id: PageId, data: &[u8]) -> KernelResult<LogSequenceNumber>;
57
58 /// Allocate a new page
59 fn allocate_page(&self) -> KernelResult<PageId>;
60
61 /// Free a page
62 fn free_page(&self, page_id: PageId) -> KernelResult<()>;
63
64 /// Sync all pending writes to durable storage
65 fn sync(&self) -> KernelResult<()>;
66
67 /// Get the current durable LSN (all writes up to this LSN are on disk)
68 fn durable_lsn(&self) -> LogSequenceNumber;
69}
70
71/// Transaction operations
72///
73/// Provides ACID transaction semantics.
74pub trait KernelTransaction: Send + Sync {
75 /// Begin a new transaction
76 fn begin(&self) -> KernelResult<TransactionId>;
77
78 /// Begin a transaction with specific isolation level
79 fn begin_with_isolation(
80 &self,
81 isolation: crate::transaction::IsolationLevel,
82 ) -> KernelResult<TransactionId>;
83
84 /// Commit a transaction
85 fn commit(&self, txn_id: TransactionId) -> KernelResult<()>;
86
87 /// Abort a transaction
88 fn abort(&self, txn_id: TransactionId) -> KernelResult<()>;
89
90 /// Check if a transaction is active
91 fn is_active(&self, txn_id: TransactionId) -> bool;
92
93 /// Get the snapshot timestamp for a transaction
94 fn snapshot_ts(&self, txn_id: TransactionId) -> KernelResult<u64>;
95}
96
97/// Catalog operations
98///
99/// Schema management and metadata.
100pub trait KernelCatalog: Send + Sync {
101 /// Create a new table
102 fn create_table(&self, name: &str, schema: &TableSchema) -> KernelResult<TableId>;
103
104 /// Drop a table
105 fn drop_table(&self, table_id: TableId) -> KernelResult<()>;
106
107 /// Get table schema
108 fn get_schema(&self, table_id: TableId) -> KernelResult<TableSchema>;
109
110 /// List all tables
111 fn list_tables(&self) -> KernelResult<Vec<TableInfo>>;
112
113 /// Rename a table
114 fn rename_table(&self, table_id: TableId, new_name: &str) -> KernelResult<()>;
115}
116
117/// Table schema definition
118#[derive(Debug, Clone)]
119pub struct TableSchema {
120 /// Table name
121 pub name: String,
122 /// Column definitions
123 pub columns: Vec<ColumnDef>,
124 /// Primary key column indices
125 pub primary_key: Vec<usize>,
126}
127
128/// Column definition
129#[derive(Debug, Clone)]
130pub struct ColumnDef {
131 /// Column name
132 pub name: String,
133 /// Column type
134 pub data_type: DataType,
135 /// Is nullable
136 pub nullable: bool,
137 /// Default value (serialized)
138 pub default_value: Option<Vec<u8>>,
139}
140
141/// Supported data types (minimal set for kernel)
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub enum DataType {
144 /// Boolean
145 Bool,
146 /// 64-bit signed integer
147 Int64,
148 /// 64-bit float
149 Float64,
150 /// Variable-length string
151 String,
152 /// Variable-length bytes
153 Bytes,
154 /// Timestamp (microseconds since epoch)
155 Timestamp,
156 /// Null type
157 Null,
158}
159
160/// Table information
161#[derive(Debug, Clone)]
162pub struct TableInfo {
163 /// Table ID
164 pub id: TableId,
165 /// Table name
166 pub name: String,
167 /// Row count (approximate)
168 pub row_count: u64,
169 /// Creation timestamp
170 pub created_at: u64,
171}
172
173/// Recovery operations
174///
175/// Crash recovery and checkpoint management.
176pub trait KernelRecovery: Send + Sync {
177 /// Perform crash recovery
178 ///
179 /// Returns the number of transactions recovered (committed + aborted)
180 fn recover(&self) -> KernelResult<RecoveryStats>;
181
182 /// Create a checkpoint
183 fn checkpoint(&self) -> KernelResult<LogSequenceNumber>;
184
185 /// Get the last checkpoint LSN
186 fn last_checkpoint_lsn(&self) -> Option<LogSequenceNumber>;
187}
188
189/// Recovery statistics
190#[derive(Debug, Clone, Default)]
191pub struct RecoveryStats {
192 /// Number of committed transactions redone
193 pub txns_redone: u64,
194 /// Number of uncommitted transactions undone
195 pub txns_undone: u64,
196 /// Number of pages recovered
197 pub pages_recovered: u64,
198 /// Recovery duration in milliseconds
199 pub duration_ms: u64,
200}
201
202/// Health check for monitoring
203///
204/// Minimal health interface - detailed metrics are in ObservabilityExtension
205pub trait KernelHealth: Send + Sync {
206 /// Check if the kernel is healthy
207 fn is_healthy(&self) -> bool;
208
209 /// Get basic health info (for plugins to consume)
210 fn health_info(&self) -> HealthInfo;
211}
212
213/// Basic health information
214///
215/// This is the minimal info the kernel exposes.
216/// Detailed metrics are handled by ObservabilityExtension plugins.
217#[derive(Debug, Clone)]
218pub struct HealthInfo {
219 /// Is the kernel operational
220 pub operational: bool,
221 /// Current WAL size in bytes
222 pub wal_size_bytes: u64,
223 /// Active transaction count
224 pub active_txns: u64,
225 /// Buffer pool usage (0.0 - 1.0)
226 pub buffer_pool_usage: f64,
227 /// Last checkpoint age in seconds
228 pub checkpoint_age_secs: u64,
229}
230
231impl Default for HealthInfo {
232 fn default() -> Self {
233 Self {
234 operational: true,
235 wal_size_bytes: 0,
236 active_txns: 0,
237 buffer_pool_usage: 0.0,
238 checkpoint_age_secs: 0,
239 }
240 }
241}