hakocluster 0.2.3

In-process dispatcher over N hakodb instances: reads fan out, writes route, socket_sync keeps replicas identical
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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
//! C ABI over JSON for non-Rust consumers (go, pascal, ...).
//!
//! Strings cross as NUL-terminated UTF-8; every returned `*mut c_char`
//! is heap-owned — free with [`hk_cluster_string_free`] ( Hakodb's
//! `hk_string_free` is a different symbol; both libs static-link their
//! own, so the cluster ABI carries its own to avoid collisions).
//! [`hk_cluster_last_error`]; data calls return null on error (and on
//! plain key-miss for get). Header: `hakocluster.h` (hand-written, the
//! API is small and stable).
//!
//! Query JSON: `{"collection":"b","where":{"field":"g","op":"eq",
//! "value":"g1"},"limit":20}` (`where` optional; only `eq` for now).
//! Config JSON: `{"durability":"interval","interval_ms":5,
//! "sock_dir":"...","max_lag":5000000,"stagger":"a",
//! "stagger_offset_ms":1}` — all keys optional; `"stagger":"b"` takes
//! `"intervals":[5,7]`, `"c"` selects ManualRotation (which additionally
//! requires `"durability":"manual"`).

use std::cell::RefCell;
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::ptr;

use hakodb::document::hako_doc::HakoDoc;
use hakodb::document::value::Value;
use hakodb::query::query::Query;

use crate::{Cluster, ClusterConfig, StaggerPolicy};

#[allow(non_camel_case_types)]
pub struct HK_Cluster {
    inner: Cluster,
}

thread_local! {
    static LAST_ERROR: RefCell<Option<CString>> = RefCell::new(None);
}

macro_rules! shield {
    ($fallback:expr, $block:block) => {
        match catch_unwind(AssertUnwindSafe(|| $block)) {
            Ok(val) => val,
            Err(_) => {
                set_last_error("CRITICAL: cluster panic, aborted");
                $fallback
            }
        }
    };
}

fn set_last_error(msg: impl Into<String>) {
    let m = CString::new(msg.into())
        .unwrap_or_else(|_| CString::new("ffi error").expect("static"));
    LAST_ERROR.with(|slot| {
        *slot.borrow_mut() = Some(m);
    });
}

fn clear_last_error() {
    LAST_ERROR.with(|slot| {
        *slot.borrow_mut() = None;
    });
}

fn cstr_to_string(ptr: *const c_char) -> Result<String, String> {
    if ptr.is_null() {
        return Err("null pointer".into());
    }
    unsafe { CStr::from_ptr(ptr) }
        .to_str()
        .map(|s| s.to_string())
        .map_err(|_| "invalid utf8".into())
}

fn ok_string(s: String) -> *mut c_char {
    match CString::new(s) {
        Ok(c) => {
            clear_last_error();
            c.into_raw()
        }
        Err(e) => {
            set_last_error(e.to_string());
            ptr::null_mut()
        }
    }
}

/// Free a string returned by any hk_cluster_* call.
#[no_mangle]
pub extern "C" fn hk_cluster_string_free(value: *mut c_char) {
    if !value.is_null() {
        unsafe {
            drop(CString::from_raw(value));
        }
    }
}

/// Last error text (borrowed; do not free; valid until the next call on
/// this thread). Null when the last call succeeded.
#[no_mangle]
pub extern "C" fn hk_cluster_last_error() -> *const c_char {
    LAST_ERROR.with(|slot| match slot.borrow().as_ref() {
        Some(c) => c.as_ptr(),
        None => ptr::null(),
    })
}

fn parse_config(json: &str) -> Result<ClusterConfig, String> {
    let v: serde_json::Value =
        serde_json::from_str(json).map_err(|e| e.to_string())?;
    let mut cfg = ClusterConfig::default();
    let get = |k: &str| v.get(k);
    if let Some(s) = get("durability").and_then(|x| x.as_str()) {
        cfg.durability_mode = match s {
            "manual" => hakodb::config::DurabilityMode::Manual,
            "always" => hakodb::config::DurabilityMode::Always,
            "oncommit" => hakodb::config::DurabilityMode::OnCommit,
            _ => hakodb::config::DurabilityMode::Interval,
        };
    }
    if let Some(ms) = get("interval_ms").and_then(|x| x.as_u64()) {
        cfg.group_commit_interval_ms = ms;
    }
    if let Some(d) = get("sock_dir").and_then(|x| x.as_str()) {
        cfg.sock_dir = d.into();
    }
    if let Some(m) = get("max_lag") {
        cfg.max_replica_lag_versions = m.as_u64();
    }
    if let Some(s) = get("stagger") {
        cfg.stagger = if let Some(arr) = s.get("intervals").and_then(|x| x.as_array()) {
            let mut iv = Vec::with_capacity(arr.len());
            for x in arr {
                iv.push(x.as_u64().ok_or("intervals must be numbers")?);
            }
            StaggerPolicy::PerInstance(iv)
        } else {
            match s.as_str().unwrap_or("a") {
                "c" => StaggerPolicy::ManualRotation,
                _ => StaggerPolicy::StaggeredStart {
                    offset_ms: get("stagger_offset_ms")
                        .and_then(|x| x.as_u64())
                        .unwrap_or(1),
                },
            }
        };
    }
    Ok(cfg)
}

fn parse_paths(json: &str) -> Result<Vec<String>, String> {
    let v: serde_json::Value =
        serde_json::from_str(json).map_err(|e| e.to_string())?;
    v.as_array()
        .ok_or_else(|| "paths must be a JSON array".to_string())
        .and_then(|arr| {
            arr.iter()
                .map(|x| {
                    x.as_str()
                        .map(|s| s.to_string())
                        .ok_or_else(|| "paths must be strings".to_string())
                })
                .collect()
        })
}

fn open_impl(paths_json: &str, cfg_json: Option<&str>) -> Result<*mut HK_Cluster, String> {
    let paths = parse_paths(paths_json)?;
    let refs: Vec<&str> = paths.iter().map(|s| s.as_str()).collect();
    let cfg = match cfg_json {
        Some(j) => parse_config(j)?,
        None => ClusterConfig::default(),
    };
    // Default sock dir (next to paths[0]) only works when the caller
    // passes none; FFI callers always pass sock_dir explicitly — but keep
    // the Rust default path intact by requiring it here.
    if cfg.sock_dir.as_os_str().is_empty() {
        return Err("config needs sock_dir".into());
    }
    let cluster = Cluster::open_with_config(&refs, cfg).map_err(|e| e)?;
    Ok(Box::into_raw(Box::new(HK_Cluster { inner: cluster })))
}

/// Open a cluster: `paths_json` = `["/data/a","/data/b"]`;
/// `config_json` = object per module docs, or null for defaults with
/// `./socks` (prefer explicit `sock_dir`). Null on error (see last_error).
#[no_mangle]
pub extern "C" fn hk_cluster_open(
    paths_json: *const c_char,
    sock_dir: *const c_char,
) -> *mut HK_Cluster {
    shield!(ptr::null_mut(), {
        let pj = match cstr_to_string(paths_json) {
            Ok(v) => v,
            Err(e) => {
                set_last_error(e);
                return ptr::null_mut();
            }
        };
        // Convenience overload: default config + explicit sock dir (the
        // 90% consumer shape — one call, no config JSON to build).
        let cfg = if sock_dir.is_null() {
            ClusterConfig::default()
        } else {
            match cstr_to_string(sock_dir) {
                Ok(d) => ClusterConfig {
                    sock_dir: d.into(),
                    ..ClusterConfig::default()
                },
                Err(e) => {
                    set_last_error(e);
                    return ptr::null_mut();
                }
            }
        };
        let paths = match parse_paths(&pj) {
            Ok(v) => v,
            Err(e) => {
                set_last_error(e);
                return ptr::null_mut();
            }
        };
        let refs: Vec<&str> = paths.iter().map(|s| s.as_str()).collect();
        match Cluster::open_with_config(&refs, cfg) {
            Ok(cluster) => {
                clear_last_error();
                Box::into_raw(Box::new(HK_Cluster { inner: cluster }))
            }
            Err(e) => {
                set_last_error(e);
                ptr::null_mut()
            }
        }
    })
}

/// Full-config open: `config_json` per module docs (stagger/policies,
/// ManualRotation, lag guard). Null `config_json` = defaults.
#[no_mangle]
pub extern "C" fn hk_cluster_open_with_config(
    paths_json: *const c_char,
    config_json: *const c_char,
) -> *mut HK_Cluster {
    shield!(ptr::null_mut(), {
        let pj = match cstr_to_string(paths_json) {
            Ok(v) => v,
            Err(e) => {
                set_last_error(e);
                return ptr::null_mut();
            }
        };
        let cj = if config_json.is_null() {
            None
        } else {
            match cstr_to_string(config_json) {
                Ok(v) => Some(v),
                Err(e) => {
                    set_last_error(e);
                    return ptr::null_mut();
                }
            }
        };
        match open_impl(&pj, cj.as_deref()) {
            Ok(h) => {
                clear_last_error();
                h
            }
            Err(e) => {
                set_last_error(e);
                ptr::null_mut()
            }
        }
    })
}

/// Close (also stops socket tasks on unix).
#[no_mangle]
pub extern "C" fn hk_cluster_close(handle: *mut HK_Cluster) {
    if !handle.is_null() {
        shield!((), {
            unsafe {
                drop(Box::from_raw(handle));
            }
        });
    }
}

/// Write a doc given as JSON object; returns the id. Engine stamps _time.
#[no_mangle]
pub extern "C" fn hk_cluster_put(
    handle: *mut HK_Cluster,
    collection: *const c_char,
    doc_id: *const c_char,
    doc_json: *const c_char,
) -> *mut c_char {
    shield!(ptr::null_mut(), {
        if handle.is_null() {
            set_last_error("null cluster");
            return ptr::null_mut();
        }
        let (col, id, js) = match (
            cstr_to_string(collection),
            cstr_to_string(doc_id),
            cstr_to_string(doc_json),
        ) {
            (Ok(a), Ok(b), Ok(c)) => (a, b, c),
            _ => {
                set_last_error("bad string arg");
                return ptr::null_mut();
            }
        };
        let doc = match json_to_doc(&js) {
            Ok(d) => d,
            Err(e) => {
                set_last_error(e);
                return ptr::null_mut();
            }
        };
        let c: &HK_Cluster = unsafe { &*handle };
        match c.inner.put_owned(&col, &id, doc) {
            Ok(assigned) => ok_string(assigned),
            Err(e) => {
                set_last_error(e);
                ptr::null_mut()
            }
        }
    })
}

fn json_to_doc(js: &str) -> Result<HakoDoc, String> {
    let v: serde_json::Value =
        serde_json::from_str(js).map_err(|e| e.to_string())?;
    let obj = v.as_object().ok_or("doc must be a JSON object")?;
    // serde_json Map is a BTreeMap: iteration is sorted, which is exactly
    // the HakoDoc field order invariant. _time is engine-stamped on write.
    let mut fields = Vec::with_capacity(obj.len());
    for (k, val) in obj {
        if k == "_time" {
            continue;
        }
        let hv = Value::from_json(val.clone()).map_err(|e| e)?;
        fields.push((std::sync::Arc::from(k.as_str()), hv));
    }
    Ok(HakoDoc { fields, _time: 0 })
}

fn doc_to_json_str(doc: &HakoDoc) -> Result<String, String> {
    let mut out = Vec::with_capacity(256);
    doc.write_json(&mut out);
    String::from_utf8(out).map_err(|e| e.to_string())
}

/// Point read as JSON (with `_time`). Null on miss or error.
#[no_mangle]
pub extern "C" fn hk_cluster_get(
    handle: *mut HK_Cluster,
    collection: *const c_char,
    doc_id: *const c_char,
) -> *mut c_char {
    shield!(ptr::null_mut(), {
        if handle.is_null() {
            set_last_error("null cluster");
            return ptr::null_mut();
        }
        let (col, id) = match (cstr_to_string(collection), cstr_to_string(doc_id)) {
            (Ok(a), Ok(b)) => (a, b),
            _ => {
                set_last_error("bad string arg");
                return ptr::null_mut();
            }
        };
        let c: &HK_Cluster = unsafe { &*handle };
        match c.inner.get(&col, &id) {
            Ok(Some(doc)) => match doc_to_json_str(&doc) {
                Ok(s) => ok_string(s),
                Err(e) => {
                    set_last_error(e);
                    ptr::null_mut()
                }
            },
            Ok(None) => {
                clear_last_error();
                ptr::null_mut()
            }
            Err(e) => {
                set_last_error(e);
                ptr::null_mut()
            }
        }
    })
}

/// Delete through the designated writer. Returns 0 ok, -1 error.
#[no_mangle]
pub extern "C" fn hk_cluster_delete(
    handle: *mut HK_Cluster,
    collection: *const c_char,
    doc_id: *const c_char,
) -> i32 {
    shield!(-1, {
        if handle.is_null() {
            set_last_error("null cluster");
            return -1;
        }
        let (col, id) = match (cstr_to_string(collection), cstr_to_string(doc_id)) {
            (Ok(a), Ok(b)) => (a, b),
            _ => {
                set_last_error("bad string arg");
                return -1;
            }
        };
        let c: &HK_Cluster = unsafe { &*handle };
        match c.inner.delete(&col, &id) {
            Ok(_) => {
                clear_last_error();
                0
            }
            Err(e) => {
                set_last_error(e);
                -1
            }
        }
    })
}

/// Fan-out query. Returns `[{"id":"..","doc":{..}},...]` (ids deduped by
/// construction — one row per id from a single replica).
#[no_mangle]
pub extern "C" fn hk_cluster_query(
    handle: *mut HK_Cluster,
    query_json: *const c_char,
) -> *mut c_char {
    shield!(ptr::null_mut(), {
        if handle.is_null() {
            set_last_error("null cluster");
            return ptr::null_mut();
        }
        let js = match cstr_to_string(query_json) {
            Ok(v) => v,
            Err(e) => {
                set_last_error(e);
                return ptr::null_mut();
            }
        };
        let q = match parse_query(&js) {
            Ok(q) => q,
            Err(e) => {
                set_last_error(e);
                return ptr::null_mut();
            }
        };
        let c: &HK_Cluster = unsafe { &*handle };
        match c.inner.query(q) {
            Ok(rows) => {
                let mut arr = Vec::with_capacity(rows.len());
                for (id, doc) in &rows {
                    let ds = match doc_to_json_str(doc) {
                        Ok(s) => s,
                        Err(e) => {
                            set_last_error(e);
                            return ptr::null_mut();
                        }
                    };
                    let dv: serde_json::Value =
                        serde_json::from_str(&ds).unwrap_or(serde_json::Value::Null);
                    arr.push(serde_json::json!({"id": id, "doc": dv}));
                }
                ok_string(serde_json::Value::Array(arr).to_string())
            }
            Err(e) => {
                set_last_error(e);
                ptr::null_mut()
            }
        }
    })
}

fn parse_query(js: &str) -> Result<Query, String> {
    let v: serde_json::Value =
        serde_json::from_str(js).map_err(|e| e.to_string())?;
    let col = v
        .get("collection")
        .and_then(|x| x.as_str())
        .ok_or("query needs collection")?;
    let mut q = Query::new(col);
    if let Some(w) = v.get("where") {
        let field = w
            .get("field")
            .and_then(|x| x.as_str())
            .ok_or("where needs field")?;
        let op = w.get("op").and_then(|x| x.as_str()).unwrap_or("eq");
        let val = w.get("value").cloned().unwrap_or(serde_json::Value::Null);
        let hv = Value::from_json(val).map_err(|e| e)?;
        match op {
            "eq" => q = q.where_eq(field, hv),
            _ => return Err(format!("unsupported op '{op}' (eq only for now)")),
        }
    }
    if let Some(n) = v.get("limit").and_then(|x| x.as_u64()) {
        q = q.limit(n as usize);
    }
    Ok(q)
}

/// Manual failover. Returns the promotion epoch, -1 on error.
#[no_mangle]
pub extern "C" fn hk_cluster_promote(handle: *mut HK_Cluster, index: usize) -> i64 {
    shield!(-1, {
        if handle.is_null() {
            set_last_error("null cluster");
            return -1;
        }
        let c: &HK_Cluster = unsafe { &*handle };
        match c.inner.promote(index) {
            Ok(e) => {
                clear_last_error();
                e as i64
            }
            Err(e) => {
                set_last_error(e);
                -1
            }
        }
    })
}

/// Current promotion epoch.
#[no_mangle]
pub extern "C" fn hk_cluster_epoch(handle: *mut HK_Cluster) -> u64 {
    shield!(0, {
        if handle.is_null() {
            return 0;
        }
        let c: &HK_Cluster = unsafe { &*handle };
        c.inner.epoch()
    })
}

/// Apply the lag guard + report health as JSON:
/// `[{"index":0,"lag":0,"healthy":true},...]`.
#[no_mangle]
pub extern "C" fn hk_cluster_refresh_health(handle: *mut HK_Cluster) -> *mut c_char {
    shield!(ptr::null_mut(), {
        if handle.is_null() {
            set_last_error("null cluster");
            return ptr::null_mut();
        }
        let c: &HK_Cluster = unsafe { &*handle };
        let rep = c.inner.refresh_health();
        let arr: Vec<serde_json::Value> = rep
            .iter()
            .map(|r| {
                serde_json::json!({"index": r.index, "lag": r.lag_versions, "healthy": r.healthy})
            })
            .collect();
        ok_string(serde_json::Value::Array(arr).to_string())
    })
}

/// Option C rotation tick. Returns 0 ok, -1 error.
#[no_mangle]
pub extern "C" fn hk_cluster_tick_flush(handle: *mut HK_Cluster) -> i32 {
    shield!(-1, {
        if handle.is_null() {
            set_last_error("null cluster");
            return -1;
        }
        let c: &HK_Cluster = unsafe { &*handle };
        match c.inner.tick_flush() {
            Ok(_) => {
                clear_last_error();
                0
            }
            Err(e) => {
                set_last_error(e);
                -1
            }
        }
    })
}