1use std::collections::BTreeMap;
4use std::fs;
5use std::io;
6use std::path::{Path, PathBuf};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9use crate::api::{CatalogSnapshot, CollectionStats, RedDBOptions, SchemaManifest, StorageMode};
10use crate::index::IndexKind;
11use crate::serde_json::{Map, Value as JsonValue};
12
13pub const DEFAULT_GRID_BLOCK_SIZE: usize = 512 * 1024;
14pub const DEFAULT_PAGE_SIZE: usize = 4096;
15pub use reddb_file::layout::PHYSICAL_METADATA_BINARY_EXTENSION;
16pub use reddb_file::{
17 fold_dwb_into_wal_enabled, meta_json_sidecar_enabled, seqn_journal_enabled,
18 seqn_journal_retention, set_fold_dwb_into_wal_enabled, set_meta_json_sidecar_enabled,
19 set_seqn_journal_enabled, set_seqn_journal_retention, BlockReference, ExportDescriptor,
20 ManifestEvent, ManifestEventKind, ManifestPointers, PhysicalAnalyticsJob,
21 PhysicalGraphProjection, PhysicalTreeDefinition, SnapshotDescriptor, SuperblockHeader,
22 DEFAULT_METADATA_JOURNAL_RETENTION, DEFAULT_SUPERBLOCK_COPIES,
23 OPT_IN_METADATA_JOURNAL_RETENTION, PHYSICAL_METADATA_PROTOCOL_VERSION,
24};
25pub const DEFAULT_MANIFEST_EVENT_HISTORY: usize = 256;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum PhysicalMetadataSource {
29 Binary,
30 BinaryJournal,
31 Json,
32}
33
34impl PhysicalMetadataSource {
35 pub fn as_str(self) -> &'static str {
36 match self {
37 Self::Binary => "binary",
38 Self::BinaryJournal => "binary_journal",
39 Self::Json => "json",
40 }
41 }
42}
43#[derive(Debug, Clone, Copy, PartialEq, Eq)]
44pub enum CompactionPolicy {
45 Incremental,
46 Manual,
47}
48
49#[derive(Debug, Clone)]
50pub struct WalPolicy {
51 pub auto_checkpoint_pages: u32,
52 pub fsync_on_commit: bool,
53 pub ring_buffer_bytes: u64,
54}
55
56impl Default for WalPolicy {
57 fn default() -> Self {
58 Self {
59 auto_checkpoint_pages: 1000,
60 fsync_on_commit: true,
61 ring_buffer_bytes: 64 * 1024 * 1024,
62 }
63 }
64}
65
66#[derive(Debug, Clone)]
67pub struct GridLayout {
68 pub block_size: usize,
69 pub page_size: usize,
70 pub superblock_copies: u8,
71}
72
73impl Default for GridLayout {
74 fn default() -> Self {
75 Self {
76 block_size: DEFAULT_GRID_BLOCK_SIZE,
77 page_size: DEFAULT_PAGE_SIZE,
78 superblock_copies: DEFAULT_SUPERBLOCK_COPIES,
79 }
80 }
81}
82
83#[derive(Debug, Clone)]
84pub struct PhysicalLayout {
85 pub mode: StorageMode,
86 pub grid: GridLayout,
87 pub wal: WalPolicy,
88 pub compaction: CompactionPolicy,
89}
90
91impl PhysicalLayout {
92 pub fn from_options(options: &RedDBOptions) -> Self {
93 Self {
94 mode: options.mode,
95 grid: GridLayout::default(),
96 wal: WalPolicy {
97 auto_checkpoint_pages: options.auto_checkpoint_pages,
98 ..WalPolicy::default()
99 },
100 compaction: CompactionPolicy::Incremental,
101 }
102 }
103
104 pub fn is_persistent(&self) -> bool {
105 self.mode == StorageMode::Persistent
106 }
107}
108
109pub(crate) use reddb_engine::catalog::{
110 is_collection_contract_decode_error, CollectionContractDecodeError,
111};
112pub use reddb_engine::catalog::{CollectionContract, ContractOrigin, DeclaredColumnContract};
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
127pub enum ArtifactState {
128 Declared,
130 Building,
132 Ready,
134 Disabled,
136 Stale,
138 Failed,
140 RequiresRebuild,
142}
143
144impl ArtifactState {
145 pub fn from_build_state(s: &str, enabled: bool) -> Self {
147 if !enabled {
148 return Self::Disabled;
149 }
150 match s {
151 "ready" => Self::Ready,
152 "building" | "catalog-derived" | "metadata-only" | "artifact-published"
153 | "registry-loaded" => Self::Building,
154 "stale" => Self::Stale,
155 "failed" => Self::Failed,
156 "requires_rebuild" | "requires-rebuild" => Self::RequiresRebuild,
157 _ => Self::Declared,
158 }
159 }
160
161 pub fn as_str(&self) -> &'static str {
163 match self {
164 Self::Declared => "declared",
165 Self::Building => "building",
166 Self::Ready => "ready",
167 Self::Disabled => "disabled",
168 Self::Stale => "stale",
169 Self::Failed => "failed",
170 Self::RequiresRebuild => "requires_rebuild",
171 }
172 }
173
174 pub fn is_queryable(&self) -> bool {
176 matches!(self, Self::Ready)
177 }
178
179 pub fn can_rebuild(&self) -> bool {
181 matches!(
182 self,
183 Self::Declared | Self::Stale | Self::Failed | Self::RequiresRebuild
184 )
185 }
186
187 pub fn needs_attention(&self) -> bool {
189 matches!(self, Self::Failed | Self::RequiresRebuild | Self::Stale)
190 }
191}
192
193impl std::fmt::Display for ArtifactState {
194 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
195 f.write_str(self.as_str())
196 }
197}
198
199#[derive(Debug, Clone)]
200pub struct PhysicalIndexState {
201 pub name: String,
202 pub kind: IndexKind,
203 pub collection: Option<String>,
204 pub enabled: bool,
205 pub entries: usize,
206 pub estimated_memory_bytes: u64,
207 pub last_refresh_ms: Option<u128>,
208 pub backend: String,
209 pub artifact_kind: Option<String>,
210 pub artifact_root_page: Option<u32>,
211 pub artifact_checksum: Option<u64>,
212 pub build_state: String,
213}
214
215impl PhysicalIndexState {
216 pub fn artifact_state(&self) -> ArtifactState {
218 ArtifactState::from_build_state(&self.build_state, self.enabled)
219 }
220}
221
222#[derive(Debug, Clone)]
228pub struct PhysicalHypertableChunk {
229 pub start_ns: u64,
230 pub end_ns_exclusive: u64,
231 pub row_count: u64,
232 pub min_ts_ns: u64,
233 pub max_ts_ns: u64,
234 pub sealed: bool,
235 pub ttl_override_ns: Option<u64>,
236 pub columnar_page: Option<crate::storage::engine::PageLocation>,
241 pub columnar_derived: bool,
244}
245
246#[derive(Debug, Clone)]
252pub struct PhysicalHypertable {
253 pub name: String,
254 pub time_column: String,
255 pub chunk_interval_ns: u64,
256 pub default_ttl_ns: Option<u64>,
257 pub chunks: Vec<PhysicalHypertableChunk>,
258}
259
260#[derive(Debug, Clone)]
261pub struct PhysicalMetadataFile {
262 pub protocol_version: String,
263 pub generated_at_unix_ms: u128,
264 pub last_loaded_from: Option<String>,
265 pub last_healed_at_unix_ms: Option<u128>,
266 pub manifest: SchemaManifest,
267 pub catalog: CatalogSnapshot,
268 pub manifest_events: Vec<ManifestEvent>,
269 pub indexes: Vec<PhysicalIndexState>,
270 pub graph_projections: Vec<PhysicalGraphProjection>,
271 pub analytics_jobs: Vec<PhysicalAnalyticsJob>,
272 pub tree_definitions: Vec<PhysicalTreeDefinition>,
273 pub collection_ttl_defaults_ms: BTreeMap<String, u64>,
274 pub collection_contracts: Vec<CollectionContract>,
275 pub hypertables: Vec<PhysicalHypertable>,
279 pub exports: Vec<ExportDescriptor>,
280 pub superblock: SuperblockHeader,
281 pub snapshots: Vec<SnapshotDescriptor>,
282}
283
284mod helpers;
285mod json_codec;
286mod metadata_file;
287pub mod shm;
288
289pub(crate) use reddb_engine::catalog::codec::{
290 deserialize_collection_contracts, serialize_collection_contracts,
291};
292
293pub use self::shm::{
294 provision_shm, read_shm_header, set_shm_provisioning_enabled, shm_path_for,
295 shm_provisioning_enabled, ShmHandle, ShmHeader, ShmProvisionState, SHM_FILE_SIZE,
296 SHM_HEADER_SIZE, SHM_MAGIC, SHM_VERSION,
297};
298
299use self::helpers::*;
300use self::json_codec::*;