-
-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathcollection.rs
More file actions
394 lines (351 loc) · 13.1 KB
/
Copy pathcollection.rs
File metadata and controls
394 lines (351 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//! Collection type enum shared between Origin and Lite.
//!
//! Determines routing, storage format, and query execution strategy.
use serde::{Deserialize, Serialize};
use crate::columnar::{ColumnarProfile, DocumentMode, StrictSchema};
use crate::kv::{KV_DEFAULT_INLINE_THRESHOLD, KvConfig, KvTtlPolicy};
/// The type of a collection, determining its storage engine and query behavior.
///
/// Three top-level modes:
/// - `Document`: B-tree storage in redb (schemaless MessagePack or strict Binary Tuples).
/// - `Columnar`: Compressed segment files with profile specialization (plain, timeseries, spatial).
/// - `KeyValue`: Hash-indexed O(1) point lookups with typed value fields (Binary Tuples).
#[derive(
Debug,
Clone,
PartialEq,
Eq,
Serialize,
Deserialize,
zerompk::ToMessagePack,
zerompk::FromMessagePack,
)]
#[serde(tag = "storage")]
pub enum CollectionType {
/// Document storage in redb B-tree.
/// Schemaless (MessagePack) or strict (Binary Tuples).
Document(DocumentMode),
/// Columnar storage in compressed segment files.
/// Profile determines constraints and specialized behavior.
Columnar(ColumnarProfile),
/// Key-Value storage with hash-indexed primary key.
/// O(1) point lookups, optional TTL, optional secondary indexes.
/// Value fields use Binary Tuple codec (same as strict mode) for O(1) field extraction.
KeyValue(KvConfig),
}
impl Default for CollectionType {
fn default() -> Self {
Self::Document(DocumentMode::default())
}
}
impl CollectionType {
/// Schemaless document (default, backward compatible).
pub fn document() -> Self {
Self::Document(DocumentMode::Schemaless)
}
/// Strict document with schema.
pub fn strict(schema: StrictSchema) -> Self {
Self::Document(DocumentMode::Strict(schema))
}
/// Plain columnar (general analytics).
pub fn columnar() -> Self {
Self::Columnar(ColumnarProfile::Plain)
}
/// Columnar with timeseries profile.
pub fn timeseries(time_key: impl Into<String>, interval: impl Into<String>) -> Self {
Self::Columnar(ColumnarProfile::Timeseries {
time_key: time_key.into(),
interval: interval.into(),
})
}
/// Columnar with spatial profile.
pub fn spatial(geometry_column: impl Into<String>) -> Self {
Self::Columnar(ColumnarProfile::Spatial {
geometry_column: geometry_column.into(),
auto_rtree: true,
auto_geohash: true,
})
}
/// Key-Value collection with typed schema and optional TTL.
///
/// The schema MUST contain exactly one PRIMARY KEY column (the hash key).
/// Remaining columns are value fields encoded as Binary Tuples.
pub fn kv(schema: StrictSchema) -> Self {
Self::KeyValue(KvConfig {
schema,
ttl: None,
capacity_hint: 0,
inline_threshold: KV_DEFAULT_INLINE_THRESHOLD,
})
}
/// Key-Value collection with TTL policy.
pub fn kv_with_ttl(schema: StrictSchema, ttl: KvTtlPolicy) -> Self {
Self::KeyValue(KvConfig {
schema,
ttl: Some(ttl),
capacity_hint: 0,
inline_threshold: KV_DEFAULT_INLINE_THRESHOLD,
})
}
pub fn is_document(&self) -> bool {
matches!(self, Self::Document(_))
}
/// Returns `true` for any columnar-family type (Plain, Timeseries, Spatial).
/// Use `is_plain_columnar()` to check for plain columnar only.
pub fn is_columnar_family(&self) -> bool {
matches!(self, Self::Columnar(_))
}
pub fn is_plain_columnar(&self) -> bool {
matches!(self, Self::Columnar(ColumnarProfile::Plain))
}
pub fn is_timeseries(&self) -> bool {
matches!(self, Self::Columnar(ColumnarProfile::Timeseries { .. }))
}
pub fn is_spatial(&self) -> bool {
matches!(self, Self::Columnar(ColumnarProfile::Spatial { .. }))
}
pub fn is_strict(&self) -> bool {
matches!(self, Self::Document(DocumentMode::Strict(_)))
}
pub fn is_schemaless(&self) -> bool {
matches!(self, Self::Document(DocumentMode::Schemaless))
}
pub fn is_kv(&self) -> bool {
matches!(self, Self::KeyValue(_))
}
pub fn as_str(&self) -> &'static str {
match self {
Self::Document(DocumentMode::Schemaless) => "document",
Self::Document(DocumentMode::Strict(_)) => "strict",
Self::Columnar(ColumnarProfile::Plain) => "columnar",
Self::Columnar(ColumnarProfile::Timeseries { .. }) => "timeseries",
Self::Columnar(ColumnarProfile::Spatial { .. }) => "columnar:spatial",
Self::KeyValue(_) => "kv",
}
}
/// Get the document mode, if this is a document collection.
pub fn document_mode(&self) -> Option<&DocumentMode> {
match self {
Self::Document(mode) => Some(mode),
_ => None,
}
}
/// Get the columnar profile, if this is a columnar collection.
pub fn columnar_profile(&self) -> Option<&ColumnarProfile> {
match self {
Self::Columnar(profile) => Some(profile),
_ => None,
}
}
/// Get the KV config, if this is a key-value collection.
pub fn kv_config(&self) -> Option<&KvConfig> {
match self {
Self::KeyValue(config) => Some(config),
_ => None,
}
}
}
impl std::fmt::Display for CollectionType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl std::str::FromStr for CollectionType {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"document" | "doc" => Ok(Self::document()),
"strict" => Ok(Self::Document(DocumentMode::Strict(
// Placeholder — real schema comes from DDL parsing, not FromStr.
// FromStr only resolves the storage mode; schema is attached separately.
StrictSchema {
columns: vec![],
version: 1,
dropped_columns: Vec::new(),
},
))),
"columnar" => Ok(Self::columnar()),
"timeseries" | "ts" => Ok(Self::timeseries("time", "1h")),
"kv" | "key_value" | "keyvalue" => Ok(Self::KeyValue(KvConfig {
// Placeholder — real schema comes from DDL parsing, not FromStr.
schema: StrictSchema {
columns: vec![],
version: 1,
dropped_columns: Vec::new(),
},
ttl: None,
capacity_hint: 0,
inline_threshold: KV_DEFAULT_INLINE_THRESHOLD,
})),
other => Err(format!("unknown collection type: '{other}'")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::columnar::{ColumnDef, ColumnType};
#[test]
fn default_is_schemaless_document() {
let ct = CollectionType::default();
assert!(ct.is_document());
assert!(ct.is_schemaless());
assert!(!ct.is_columnar_family());
assert!(!ct.is_timeseries());
assert!(!ct.is_kv());
}
#[test]
fn factory_methods() {
assert!(CollectionType::document().is_schemaless());
assert!(CollectionType::columnar().is_columnar_family());
assert!(CollectionType::timeseries("time", "1h").is_timeseries());
assert!(CollectionType::spatial("geom").is_columnar_family());
assert!(CollectionType::spatial("geom").is_spatial());
let schema = StrictSchema::new(vec![
ColumnDef::required("key", ColumnType::String).with_primary_key(),
ColumnDef::nullable("value", ColumnType::Bytes),
])
.unwrap();
let kv = CollectionType::kv(schema);
assert!(kv.is_kv());
assert!(!kv.is_document());
assert!(!kv.is_columnar_family());
}
#[test]
fn kv_with_ttl_factory() {
let schema = StrictSchema::new(vec![
ColumnDef::required("ip", ColumnType::String).with_primary_key(),
ColumnDef::required("hits", ColumnType::Int64),
])
.unwrap();
let ttl = KvTtlPolicy::FixedDuration {
duration_ms: 60_000,
};
let ct = CollectionType::kv_with_ttl(schema, ttl);
assert!(ct.is_kv());
let config = ct.kv_config().unwrap();
assert!(config.has_ttl());
match config.ttl.as_ref().unwrap() {
KvTtlPolicy::FixedDuration { duration_ms } => assert_eq!(*duration_ms, 60_000),
_ => panic!("expected FixedDuration"),
}
}
#[test]
fn serde_roundtrip_document() {
let ct = CollectionType::document();
let json = sonic_rs::to_string(&ct).unwrap();
let back: CollectionType = sonic_rs::from_str(&json).unwrap();
assert_eq!(back, ct);
}
#[test]
fn serde_roundtrip_columnar() {
let ct = CollectionType::columnar();
let json = sonic_rs::to_string(&ct).unwrap();
let back: CollectionType = sonic_rs::from_str(&json).unwrap();
assert_eq!(back, ct);
}
#[test]
fn serde_roundtrip_timeseries() {
let ct = CollectionType::timeseries("ts", "1h");
let json = sonic_rs::to_string(&ct).unwrap();
let back: CollectionType = sonic_rs::from_str(&json).unwrap();
assert_eq!(back, ct);
}
#[test]
fn serde_roundtrip_kv_no_ttl() {
let schema = StrictSchema::new(vec![
ColumnDef::required("k", ColumnType::String).with_primary_key(),
ColumnDef::nullable("v", ColumnType::Bytes),
])
.unwrap();
let ct = CollectionType::kv(schema);
let json = sonic_rs::to_string(&ct).unwrap();
let back: CollectionType = sonic_rs::from_str(&json).unwrap();
assert_eq!(back, ct);
}
#[test]
fn serde_roundtrip_kv_fixed_ttl() {
let schema = StrictSchema::new(vec![
ColumnDef::required("k", ColumnType::String).with_primary_key(),
ColumnDef::required("v", ColumnType::Bytes),
])
.unwrap();
let ttl = KvTtlPolicy::FixedDuration {
duration_ms: 900_000,
};
let ct = CollectionType::kv_with_ttl(schema, ttl);
let json = sonic_rs::to_string(&ct).unwrap();
let back: CollectionType = sonic_rs::from_str(&json).unwrap();
assert_eq!(back, ct);
}
#[test]
fn serde_roundtrip_kv_field_ttl() {
let schema = StrictSchema::new(vec![
ColumnDef::required("k", ColumnType::String).with_primary_key(),
ColumnDef::required("last_active", ColumnType::Timestamp),
])
.unwrap();
let ttl = KvTtlPolicy::FieldBased {
field: "last_active".into(),
offset_ms: 3_600_000,
};
let ct = CollectionType::kv_with_ttl(schema, ttl);
let json = sonic_rs::to_string(&ct).unwrap();
let back: CollectionType = sonic_rs::from_str(&json).unwrap();
assert_eq!(back, ct);
}
#[test]
fn display() {
assert_eq!(CollectionType::document().to_string(), "document");
assert_eq!(CollectionType::columnar().to_string(), "columnar");
assert_eq!(
CollectionType::timeseries("time", "1h").to_string(),
"timeseries"
);
let schema = StrictSchema::new(vec![
ColumnDef::required("k", ColumnType::String).with_primary_key(),
])
.unwrap();
assert_eq!(CollectionType::kv(schema).to_string(), "kv");
}
#[test]
fn from_str() {
assert!("document".parse::<CollectionType>().unwrap().is_document());
assert!(
"columnar"
.parse::<CollectionType>()
.unwrap()
.is_columnar_family()
);
assert!(
"timeseries"
.parse::<CollectionType>()
.unwrap()
.is_timeseries()
);
assert!("ts".parse::<CollectionType>().unwrap().is_timeseries());
assert!("kv".parse::<CollectionType>().unwrap().is_kv());
assert!("key_value".parse::<CollectionType>().unwrap().is_kv());
assert!("keyvalue".parse::<CollectionType>().unwrap().is_kv());
assert!("unknown".parse::<CollectionType>().is_err());
}
#[test]
fn accessors() {
let ct = CollectionType::timeseries("time", "1h");
assert!(ct.columnar_profile().is_some());
assert!(ct.document_mode().is_none());
assert!(ct.kv_config().is_none());
let doc = CollectionType::document();
assert!(doc.document_mode().is_some());
assert!(doc.columnar_profile().is_none());
assert!(doc.kv_config().is_none());
let schema = StrictSchema::new(vec![
ColumnDef::required("k", ColumnType::String).with_primary_key(),
])
.unwrap();
let kv = CollectionType::kv(schema);
assert!(kv.kv_config().is_some());
assert!(kv.document_mode().is_none());
assert!(kv.columnar_profile().is_none());
}
}