Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
2972 lines (2744 loc) · 111 KB
/
Copy pathlib.rs
File metadata and controls
2972 lines (2744 loc) · 111 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
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
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![cfg_attr(
test,
allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing,
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss,
)
)]
use minigraf::{QueryResult, Value};
use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard};
uniffi::setup_scaffolding!();
// ─── Error type ──────────────────────────────────────────────────────────────
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum MiniGrafError {
#[error("storage error: {msg}")]
Storage { msg: String },
#[error("query error: {msg}")]
Query { msg: String },
#[error("parse error: {msg}")]
Parse { msg: String },
#[error("unknown error: {msg}")]
Other { msg: String },
/// A call the API refuses: a bad argument, a closed object, a bind
/// mistake. The message starts with its `API-` code.
#[error("API error: {msg}")]
Api { msg: String },
}
// ─── minigraf::MinigrafError → MiniGrafError conversion ──────────────────────
impl From<minigraf::MinigrafError> for MiniGrafError {
fn from(e: minigraf::MinigrafError) -> Self {
let msg = e.to_string();
match e.category() {
minigraf::ErrorCategory::Parser => MiniGrafError::Parse { msg },
minigraf::ErrorCategory::Storage | minigraf::ErrorCategory::Wal => {
MiniGrafError::Storage { msg }
}
minigraf::ErrorCategory::Query => MiniGrafError::Query { msg },
minigraf::ErrorCategory::Api => MiniGrafError::Api { msg },
minigraf::ErrorCategory::Internal | _ => MiniGrafError::Other { msg },
}
}
}
impl MiniGrafError {
/// Append the position of the rejected record to the message.
fn at_batch_index(self, index: usize) -> Self {
let suffix = |msg: String| format!("{msg} (batch index {index})");
match self {
MiniGrafError::Storage { msg } => MiniGrafError::Storage { msg: suffix(msg) },
MiniGrafError::Query { msg } => MiniGrafError::Query { msg: suffix(msg) },
MiniGrafError::Parse { msg } => MiniGrafError::Parse { msg: suffix(msg) },
MiniGrafError::Other { msg } => MiniGrafError::Other { msg: suffix(msg) },
MiniGrafError::Api { msg } => MiniGrafError::Api { msg: suffix(msg) },
}
}
}
fn lock<T>(m: &Mutex<T>) -> Result<MutexGuard<'_, T>, MiniGrafError> {
m.lock().map_err(|_| MiniGrafError::Other {
msg: "mutex poisoned".into(),
})
}
// Counts cross the FFI as signed integers: Kotlin's unsigned types cannot be
// called from Java. A negative or oversized count is API-017.
fn to_u64(n: i64, what: &str) -> Result<u64, MiniGrafError> {
u64::try_from(n).map_err(|_| {
minigraf::MinigrafError::invalid_argument(format!("{what} {n} is negative")).into()
})
}
fn to_usize(n: i64, what: &str) -> Result<usize, MiniGrafError> {
usize::try_from(to_u64(n, what)?).map_err(|_| {
minigraf::MinigrafError::invalid_argument(format!("{what} {n} is too large")).into()
})
}
/// A limit: `i64::MAX` stands for core's `usize::MAX` (no limit), which is
/// out of reach of a signed count; any other negative count is API-017.
fn to_limit(n: i64, what: &str) -> Result<usize, MiniGrafError> {
if n == i64::MAX {
Ok(usize::MAX)
} else {
to_usize(n, what)
}
}
/// A transaction counter or timestamp for the FFI. Both stay far below
/// `i64::MAX` (a counter of one per transaction; Unix milliseconds).
fn from_u64(n: u64) -> i64 {
i64::try_from(n).unwrap_or(i64::MAX)
}
fn parse_uuid(s: &str, what: &str) -> Result<minigraf::EntityId, minigraf::MinigrafError> {
minigraf::EntityId::parse_str(s).map_err(|_| {
minigraf::MinigrafError::invalid_argument(format!("{what} {s:?} is not a UUID"))
})
}
// ─── Open options ────────────────────────────────────────────────────────────
/// WAL durability mode. See the Rust `SyncMode`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum SyncMode {
/// Flush the WAL after every write (the default).
Full,
/// Flush only at checkpoints.
Normal,
}
/// A query keyword that `OpenOptions.allow_overrides` may let query text
/// use. See the Rust `Overridable`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum Overridable {
/// `:max-derived-facts` (in the defaults).
MaxDerivedFacts,
/// `:max-results` (in the defaults).
MaxResults,
/// `:query-memory-limit` (not in the defaults).
QueryMemoryLimit,
/// `:max-iterations` (in the defaults).
MaxIterations,
}
impl Overridable {
fn to_core(self) -> minigraf::Overridable {
match self {
Overridable::MaxDerivedFacts => minigraf::Overridable::MaxDerivedFacts,
Overridable::MaxResults => minigraf::Overridable::MaxResults,
Overridable::QueryMemoryLimit => minigraf::Overridable::QueryMemoryLimit,
Overridable::MaxIterations => minigraf::Overridable::MaxIterations,
}
}
fn from_core(o: minigraf::Overridable) -> Option<Self> {
match o {
minigraf::Overridable::MaxDerivedFacts => Some(Overridable::MaxDerivedFacts),
minigraf::Overridable::MaxResults => Some(Overridable::MaxResults),
minigraf::Overridable::QueryMemoryLimit => Some(Overridable::QueryMemoryLimit),
minigraf::Overridable::MaxIterations => Some(Overridable::MaxIterations),
_ => None,
}
}
}
/// The override list that applies when `OpenOptions.allow_overrides` is
/// absent: the Rust `Overridable::DEFAULTS`.
#[uniffi::export]
pub fn overridable_defaults() -> Vec<Overridable> {
minigraf::Overridable::DEFAULTS
.iter()
.copied()
.filter_map(Overridable::from_core)
.collect()
}
/// Options for `MiniGrafDb.open_with_options` and `MiniGrafLogWriter.create`.
/// Every field is optional; an absent field keeps the Rust default.
#[derive(Debug, Clone, Default, uniffi::Record)]
pub struct OpenOptions {
/// Open read-only: shared lock, nothing written, writes fail with API-014.
#[uniffi(default)]
pub read_only: Option<bool>,
/// Pages (4 KB each) in the page cache. Default 256.
#[uniffi(default)]
pub page_cache_size: Option<i64>,
/// Open even when the filesystem cannot lock files. Default false.
#[uniffi(default)]
pub allow_unlocked: Option<bool>,
/// WAL entries before an automatic checkpoint. Default 1000. The maximum
/// (i64::MAX, 9223372036854775807) means never: no automatic checkpoint
/// and no checkpoint when the handle closes; call `checkpoint()` yourself.
#[uniffi(default)]
pub wal_checkpoint_threshold: Option<i64>,
/// Facts a recursive rule may derive per iteration. Default 1,000,000.
#[uniffi(default)]
pub max_derived_facts: Option<i64>,
/// Deprecated alias of `max_derived_facts`; the lower of the two applies.
#[uniffi(default)]
pub max_results: Option<i64>,
/// WAL durability. Default `Full`.
#[uniffi(default)]
pub synchronous: Option<SyncMode>,
/// The most bytes one query may hold; a query that would hold more fails
/// with QRY-012. The maximum (i64::MAX, 9223372036854775807) means no
/// limit, the default.
#[uniffi(default)]
pub query_memory_limit: Option<i64>,
/// The query keywords query text may use to override these settings.
/// Absent: `overridable_defaults()`. A list replaces the defaults; an
/// empty one refuses every override keyword (API-025).
#[uniffi(default)]
pub allow_overrides: Option<Vec<Overridable>>,
/// Facts one transaction stages before a file database writes them in
/// chunks. Default 65,536; clamped to 1..=1,000,000.
#[uniffi(default)]
pub transaction_chunk_facts: Option<i64>,
/// Rounds one stratum of a rule query may run; more fail with INT-020.
/// Default 1,000,000. The maximum (i64::MAX) means no limit.
#[uniffi(default)]
pub max_iterations: Option<i64>,
}
impl OpenOptions {
fn to_core(&self) -> Result<minigraf::OpenOptions, MiniGrafError> {
let mut o = minigraf::OpenOptions::new();
if let Some(v) = self.read_only {
o = o.read_only(v);
}
if let Some(v) = self.page_cache_size {
o = o.page_cache_size(to_usize(v, "page_cache_size")?);
}
if let Some(v) = self.allow_unlocked {
o = o.allow_unlocked(v);
}
if let Some(v) = self.wal_checkpoint_threshold {
// i64::MAX stands for core's usize::MAX sentinel, which is out of
// reach of a signed count.
let n = if v == i64::MAX {
usize::MAX
} else {
to_usize(v, "wal_checkpoint_threshold")?
};
o = o.wal_checkpoint_threshold(n);
}
if let Some(v) = self.max_derived_facts {
o = o.max_derived_facts(to_usize(v, "max_derived_facts")?);
}
if let Some(v) = self.max_results {
#[allow(deprecated)]
{
o = o.max_results(to_usize(v, "max_results")?);
}
}
if let Some(v) = self.synchronous {
o = o.synchronous(match v {
SyncMode::Full => minigraf::SyncMode::Full,
SyncMode::Normal => minigraf::SyncMode::Normal,
});
}
if let Some(v) = self.query_memory_limit {
// i64::MAX stands for core's usize::MAX (no limit), as for
// wal_checkpoint_threshold.
let n = if v == i64::MAX {
usize::MAX
} else {
to_usize(v, "query_memory_limit")?
};
o = o.query_memory_limit(n);
}
if let Some(list) = &self.allow_overrides {
o = o.allow_overrides(list.iter().map(|v| v.to_core()));
}
if let Some(v) = self.transaction_chunk_facts {
o = o.transaction_chunk_facts(to_usize(v, "transaction_chunk_facts")?);
}
if let Some(v) = self.max_iterations {
o = o.max_iterations(to_limit(v, "max_iterations")?);
}
Ok(o)
}
}
// ─── Values and fact records ─────────────────────────────────────────────────
/// A fact value with its type kept, so a record can be written back exactly.
/// `Ref` holds an entity UUID string. `Set` holds the elements of a set
/// value in canonical order; an element that is itself a `Set` is API-021.
#[derive(Debug, Clone, PartialEq, uniffi::Enum)]
pub enum MiniGrafValue {
Text { value: String },
Int64 { value: i64 },
Float64 { value: f64 },
Bool { value: bool },
Ref { value: String },
Keyword { value: String },
Null,
Set { value: Vec<MiniGrafValue> },
}
impl From<Value> for MiniGrafValue {
fn from(v: Value) -> Self {
match v {
Value::String(value) => MiniGrafValue::Text { value },
Value::Integer(value) => MiniGrafValue::Int64 { value },
Value::Float(value) => MiniGrafValue::Float64 { value },
Value::Boolean(value) => MiniGrafValue::Bool { value },
Value::Ref(id) => MiniGrafValue::Ref {
value: id.to_string(),
},
Value::Keyword(value) => MiniGrafValue::Keyword { value },
Value::Null => MiniGrafValue::Null,
Value::Set(set) => MiniGrafValue::Set {
value: set.iter().cloned().map(MiniGrafValue::from).collect(),
},
// A value kind newer than this binding: its debug form, until
// the binding learns it.
other => MiniGrafValue::Text {
value: format!("{other:?}"),
},
}
}
}
impl MiniGrafValue {
fn to_core(&self) -> Result<Value, minigraf::MinigrafError> {
Ok(match self {
MiniGrafValue::Text { value } => Value::String(value.clone()),
MiniGrafValue::Int64 { value } => Value::Integer(*value),
MiniGrafValue::Float64 { value } => Value::Float(*value),
MiniGrafValue::Bool { value } => Value::Boolean(*value),
MiniGrafValue::Ref { value } => Value::Ref(parse_uuid(value, "ref value")?),
MiniGrafValue::Keyword { value } => Value::Keyword(value.clone()),
MiniGrafValue::Null => Value::Null,
MiniGrafValue::Set { value } => Value::Set(minigraf::ValueSet::new(
value
.iter()
.map(MiniGrafValue::to_core)
.collect::<Result<Vec<_>, _>>()?,
)?),
})
}
}
/// One fact-log record: an assertion or a retraction, with its transaction
/// and valid-time bounds. `valid_to` = 9223372036854775807 (i64 max) is forever.
#[derive(Debug, Clone, PartialEq, uniffi::Record)]
pub struct FactRecord {
/// The entity UUID string.
pub entity: String,
pub attribute: String,
pub value: MiniGrafValue,
pub tx_count: i64,
pub tx_id: i64,
pub valid_from: i64,
pub valid_to: i64,
pub asserted: bool,
}
impl From<minigraf::FactRecord> for FactRecord {
fn from(r: minigraf::FactRecord) -> Self {
FactRecord {
entity: r.entity.to_string(),
attribute: r.attribute,
value: r.value.into(),
tx_count: from_u64(r.tx_count),
tx_id: from_u64(r.tx_id),
valid_from: r.valid_from,
valid_to: r.valid_to,
asserted: r.asserted,
}
}
}
impl FactRecord {
fn to_core(&self) -> Result<minigraf::FactRecord, minigraf::MinigrafError> {
let count = |n: i64, what: &str| {
u64::try_from(n).map_err(|_| {
minigraf::MinigrafError::invalid_argument(format!("{what} {n} is negative"))
})
};
Ok(minigraf::FactRecord {
entity: parse_uuid(&self.entity, "entity")?,
attribute: self.attribute.clone(),
value: self.value.to_core()?,
tx_count: count(self.tx_count, "tx_count")?,
tx_id: count(self.tx_id, "tx_id")?,
valid_from: self.valid_from,
valid_to: self.valid_to,
asserted: self.asserted,
})
}
}
/// The order of a fact log.
#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
pub enum FactOrder {
/// Ascending `tx_count`, each transaction's records together (the default).
Tx,
/// The cheapest order to read, in one scan.
Storage,
}
/// Which records a fact log returns. Every field is optional; the ones that
/// are set must all match.
#[derive(Debug, Clone, Default, uniffi::Record)]
pub struct FactFilter {
/// Keep these attributes (combined with `attribute_prefixes`, either matches).
#[uniffi(default)]
pub attributes: Option<Vec<String>>,
/// Keep attributes starting with one of these, such as `":ingestion/"`.
#[uniffi(default)]
pub attribute_prefixes: Option<Vec<String>>,
/// Keep these entity UUID strings.
#[uniffi(default)]
pub entities: Option<Vec<String>>,
/// Lowest `tx_count` kept (inclusive).
#[uniffi(default)]
pub tx_from: Option<i64>,
/// Highest `tx_count` kept (inclusive).
#[uniffi(default)]
pub tx_to: Option<i64>,
#[uniffi(default)]
pub order: Option<FactOrder>,
/// In `Tx` order, the most records held in memory at once.
#[uniffi(default)]
pub window: Option<i64>,
}
impl FactFilter {
fn to_core(&self) -> Result<minigraf::FactFilter, MiniGrafError> {
let mut f = minigraf::FactFilter::new();
if let Some(attrs) = &self.attributes {
f = f.attributes(attrs.iter().cloned());
}
for prefix in self.attribute_prefixes.iter().flatten() {
f = f.attribute_prefix(prefix);
}
if let Some(entities) = &self.entities {
let ids = entities
.iter()
.map(|e| parse_uuid(e, "entity"))
.collect::<Result<Vec<_>, _>>()?;
f = f.entities(ids);
}
if self.tx_from.is_some() || self.tx_to.is_some() {
let lo = self.tx_from.map_or(Ok(0), |n| to_u64(n, "tx_from"))?;
let hi = self.tx_to.map_or(Ok(u64::MAX), |n| to_u64(n, "tx_to"))?;
f = f.tx_range(lo..=hi);
}
if let Some(order) = self.order {
f = f.order(match order {
FactOrder::Tx => minigraf::FactOrder::Tx,
FactOrder::Storage => minigraf::FactOrder::Storage,
});
}
if let Some(w) = self.window {
f = f.window(to_usize(w, "window")?);
}
Ok(f)
}
}
// ─── Bind values ─────────────────────────────────────────────────────────────
/// The value of one `$slot` of a prepared query.
///
/// `Value` fills an entity position with a `Ref`, and a value, expression or
/// rule-argument position. `Entity` fills an entity position, and the others
/// as a `Ref`. `TxCount` and `Timestamp` fill `:as-of`; `Timestamp` and
/// `AnyValidTime` fill `:valid-at`. A bind value of the wrong kind for its
/// slot is API-024.
#[derive(Debug, Clone, PartialEq, uniffi::Enum)]
pub enum MiniGrafBindValue {
Value {
value: MiniGrafValue,
},
/// An entity UUID string.
Entity {
uuid: String,
},
/// The counter `:as-of N` compares against; negative is API-017.
TxCount {
value: i64,
},
/// Unix milliseconds.
Timestamp {
value: i64,
},
AnyValidTime,
}
impl MiniGrafBindValue {
fn to_core(&self) -> Result<minigraf::BindValue, MiniGrafError> {
Ok(match self {
MiniGrafBindValue::Value { value } => minigraf::BindValue::Val(value.to_core()?),
MiniGrafBindValue::Entity { uuid } => {
minigraf::BindValue::Entity(parse_uuid(uuid, "entity")?)
}
MiniGrafBindValue::TxCount { value } => {
minigraf::BindValue::TxCount(to_u64(*value, "tx count")?)
}
MiniGrafBindValue::Timestamp { value } => minigraf::BindValue::Timestamp(*value),
MiniGrafBindValue::AnyValidTime => minigraf::BindValue::AnyValidTime,
})
}
}
/// `bindings` as core bind values, named without their `$`.
fn core_bindings(
bindings: &HashMap<String, MiniGrafBindValue>,
) -> Result<Vec<(&str, minigraf::BindValue)>, MiniGrafError> {
bindings
.iter()
.map(|(name, value)| Ok((name.as_str(), value.to_core()?)))
.collect()
}
// ─── MiniGrafDb ──────────────────────────────────────────────────────────────
#[derive(uniffi::Object)]
pub struct MiniGrafDb {
inner: Arc<Mutex<minigraf::Minigraf>>,
}
#[uniffi::export]
impl MiniGrafDb {
#[uniffi::constructor]
pub fn open(path: String) -> Result<Arc<Self>, MiniGrafError> {
let db = minigraf::Minigraf::open(&path).map_err(MiniGrafError::from)?;
Ok(Arc::new(Self {
inner: Arc::new(Mutex::new(db)),
}))
}
#[uniffi::constructor]
pub fn open_in_memory() -> Result<Arc<Self>, MiniGrafError> {
let db = minigraf::Minigraf::in_memory().map_err(MiniGrafError::from)?;
Ok(Arc::new(Self {
inner: Arc::new(Mutex::new(db)),
}))
}
pub fn execute(&self, datalog: String) -> Result<String, MiniGrafError> {
let result = self.db()?.execute(&datalog)?;
Ok(query_result_to_json(result))
}
/// Open a file-backed database with `options`.
#[uniffi::constructor]
pub fn open_with_options(
path: String,
options: OpenOptions,
) -> Result<Arc<Self>, MiniGrafError> {
let db = minigraf::Minigraf::open_with_options(&path, options.to_core()?)
.map_err(MiniGrafError::from)?;
Ok(Arc::new(Self {
inner: Arc::new(Mutex::new(db)),
}))
}
/// Open a cursor over a `(query ...)`. Its answer is fixed when it opens.
pub fn query(&self, datalog: String) -> Result<Arc<MiniGrafCursor>, MiniGrafError> {
let cursor = self.db()?.query(&datalog)?;
Ok(Arc::new(MiniGrafCursor {
vars: cursor.vars().to_vec(),
inner: Mutex::new(Some(cursor)),
}))
}
/// Stream every fact record that `filter` keeps. Checkpoints wait until
/// the log is closed or read to the end.
pub fn fact_log(&self, filter: FactFilter) -> Result<Arc<MiniGrafFactLog>, MiniGrafError> {
let filter = filter.to_core()?;
let log = self.db()?.fact_log(&filter)?;
Ok(Arc::new(MiniGrafFactLog {
inner: Mutex::new(Some(log)),
}))
}
/// Parse and validate a `(query ...)` once, for running many times with
/// different bind values in its `$name` slots. A transact, retract or
/// rule is API-005/006/007; a slot in an attribute position is API-023.
pub fn prepare(&self, datalog: String) -> Result<Arc<MiniGrafPreparedQuery>, MiniGrafError> {
let inner = self.db()?.prepare(&datalog)?;
Ok(Arc::new(MiniGrafPreparedQuery {
_db: self.inner.clone(),
inner,
}))
}
/// The transaction counter that `:as-of N` compares against.
pub fn current_tx_count(&self) -> Result<i64, MiniGrafError> {
Ok(from_u64(self.db()?.current_tx_count()))
}
pub fn checkpoint(&self) -> Result<(), MiniGrafError> {
Ok(self.db()?.checkpoint()?)
}
/// Register `predicate` under `name`, called in Datalog as
/// `[(name ?v)]`. A predicate that throws stops the query with QRY-014.
/// Queries already open keep the functions they opened with.
pub fn register_predicate(
&self,
name: String,
predicate: Arc<dyn MiniGrafPredicate>,
) -> Result<(), MiniGrafError> {
Ok(self.db()?.try_register_predicate(&name, move |v| {
Ok(predicate.test(MiniGrafValue::from(v.clone()))?)
})?)
}
/// Register `aggregate` under `name`, used in `:find` as `(name ?v)` and
/// as a window function with `:over`. Each group or window partition
/// gets its own accumulator. A throw stops the query with QRY-014.
pub fn register_aggregate(
&self,
name: String,
aggregate: Arc<dyn MiniGrafAggregate>,
) -> Result<(), MiniGrafError> {
Ok(self.db()?.try_register_aggregate(
&name,
move || Ok(aggregate.accumulator()?),
|acc: &mut Arc<dyn MiniGrafAccumulator>, v| {
Ok(acc.step(MiniGrafValue::from(v.clone()))?)
},
|acc, count| {
// A count of values held in memory stays far below i64::MAX.
let count = i64::try_from(count).unwrap_or(i64::MAX);
acc.finish(count)?
.to_core()
.map_err(|e| minigraf::UdfError::new(e.to_string()))
},
)?)
}
}
impl MiniGrafDb {
/// The database, cloned out of the handle so that no binding lock is
/// held while the core runs: a user function may call back into this
/// handle.
fn db(&self) -> Result<minigraf::Minigraf, MiniGrafError> {
Ok(lock(&self.inner)?.clone())
}
}
// ─── User functions ──────────────────────────────────────────────────────────
/// Why a user function failed. A callback that throws anything else is
/// mapped to this. The query stops with QRY-014, which carries `msg`.
#[derive(Debug, thiserror::Error, uniffi::Error)]
pub enum MiniGrafUdfError {
#[error("{msg}")]
Failed { msg: String },
}
/// Any other exception. Kotlin sends its stack trace, so only the first
/// line is kept: the exception's class and message.
impl From<uniffi::UnexpectedUniFFICallbackError> for MiniGrafUdfError {
fn from(e: uniffi::UnexpectedUniFFICallbackError) -> Self {
let msg = e.reason.lines().next().unwrap_or_default().to_string();
MiniGrafUdfError::Failed { msg }
}
}
impl From<MiniGrafUdfError> for minigraf::UdfError {
fn from(e: MiniGrafUdfError) -> Self {
let MiniGrafUdfError::Failed { msg } = e;
minigraf::UdfError::new(msg)
}
}
/// A user predicate. It may be called from any thread that queries the
/// database, concurrently, so it must be thread-safe.
#[uniffi::export(with_foreign)]
pub trait MiniGrafPredicate: Send + Sync {
fn test(&self, value: MiniGrafValue) -> Result<bool, MiniGrafUdfError>;
}
/// A user aggregate: a factory of accumulators.
#[uniffi::export(with_foreign)]
pub trait MiniGrafAggregate: Send + Sync {
/// A new, empty accumulator: one per group, or per window partition.
fn accumulator(&self) -> Result<Arc<dyn MiniGrafAccumulator>, MiniGrafUdfError>;
}
/// The running state of one aggregate. One query uses it, on one thread at
/// a time.
#[uniffi::export(with_foreign)]
pub trait MiniGrafAccumulator: Send + Sync {
fn step(&self, value: MiniGrafValue) -> Result<(), MiniGrafUdfError>;
/// `count`: values stepped so far.
fn finish(&self, count: i64) -> Result<MiniGrafValue, MiniGrafUdfError>;
}
// ─── MiniGrafPreparedQuery ───────────────────────────────────────────────────
/// A query parsed once by `MiniGrafDb.prepare`, run with bind values. It
/// keeps its database open until both are freed, and each run reads the
/// database as it is then.
#[derive(uniffi::Object)]
pub struct MiniGrafPreparedQuery {
/// Keeps the database (and its close-time checkpoint) alive.
_db: Arc<Mutex<minigraf::Minigraf>>,
inner: minigraf::PreparedQuery,
}
#[uniffi::export]
impl MiniGrafPreparedQuery {
/// Run the query with `bindings` (slot name without its `$` to bind
/// value) and return its result as JSON, encoded like
/// `MiniGrafDb.execute`. Names the query does not use are ignored. A
/// missing slot is API-022.
pub fn execute(
&self,
bindings: HashMap<String, MiniGrafBindValue>,
) -> Result<String, MiniGrafError> {
let result = self.inner.execute(&core_bindings(&bindings)?)?;
Ok(query_result_to_json(result))
}
/// Run the query with `bindings` and return a cursor over its rows. The
/// answer is fixed when the cursor opens.
pub fn query(
&self,
bindings: HashMap<String, MiniGrafBindValue>,
) -> Result<Arc<MiniGrafCursor>, MiniGrafError> {
let cursor = self.inner.query(&core_bindings(&bindings)?)?;
Ok(Arc::new(MiniGrafCursor {
vars: cursor.vars().to_vec(),
inner: Mutex::new(Some(cursor)),
}))
}
/// A new prepared query that may derive at most `n` facts; this one is
/// unchanged. An allowed `:max-derived-facts` or `:max-results` in the
/// query still overrides it. `i64::MAX` means no limit; negative is
/// API-017. Not gated by `OpenOptions.allow_overrides`.
pub fn with_max_derived_facts(
&self,
n: i64,
) -> Result<Arc<MiniGrafPreparedQuery>, MiniGrafError> {
let n = to_limit(n, "max_derived_facts")?;
Ok(self.derive(|q| q.with_max_derived_facts(n)))
}
/// A new prepared query that may hold at most `bytes` bytes (QRY-012
/// beyond); this one is unchanged. `0` lets only queries that hold no
/// state run. Takes its argument as `with_max_derived_facts` does.
pub fn with_query_memory_limit(
&self,
bytes: i64,
) -> Result<Arc<MiniGrafPreparedQuery>, MiniGrafError> {
let bytes = to_limit(bytes, "query_memory_limit")?;
Ok(self.derive(|q| q.with_query_memory_limit(bytes)))
}
/// A new prepared query whose rule strata may run at most `n` rounds
/// (INT-020 beyond); this one is unchanged. An allowed `:max-iterations`
/// in the query still overrides it. Takes its argument as
/// `with_max_derived_facts` does.
pub fn with_max_iterations(&self, n: i64) -> Result<Arc<MiniGrafPreparedQuery>, MiniGrafError> {
let n = to_limit(n, "max_iterations")?;
Ok(self.derive(|q| q.with_max_iterations(n)))
}
}
impl MiniGrafPreparedQuery {
/// A copy with `set` applied, keeping the same database open.
fn derive(
&self,
set: impl FnOnce(minigraf::PreparedQuery) -> minigraf::PreparedQuery,
) -> Arc<MiniGrafPreparedQuery> {
Arc::new(MiniGrafPreparedQuery {
_db: self._db.clone(),
inner: set(self.inner.clone()),
})
}
}
// ─── MiniGrafCursor ──────────────────────────────────────────────────────────
/// The rows of one query answer, in batches.
#[derive(uniffi::Object)]
pub struct MiniGrafCursor {
vars: Vec<String>,
/// `None` after `close()` or the end.
inner: Mutex<Option<minigraf::Cursor>>,
}
#[uniffi::export]
impl MiniGrafCursor {
/// The `:find` variables, in column order.
pub fn vars(&self) -> Vec<String> {
self.vars.clone()
}
/// The next batch of at most `max_rows` rows (0 counts as 1), as a JSON
/// array of rows encoded like `execute()`'s `results`; `None` at the end
/// or after `close()`. A batch is never empty.
pub fn next_batch(&self, max_rows: i32) -> Result<Option<String>, MiniGrafError> {
let mut guard = lock(&self.inner)?;
let Some(cursor) = guard.as_mut() else {
return Ok(None);
};
match cursor.next_batch(to_usize(i64::from(max_rows), "max_rows")?)? {
Some(batch) => Ok(Some(rows_to_json(batch.rows()))),
None => {
*guard = None;
Ok(None)
}
}
}
/// Release the cursor. Later `next_batch` calls return `None`.
pub fn close(&self) {
if let Ok(mut guard) = self.inner.lock() {
*guard = None;
}
}
}
// ─── MiniGrafFactLog ─────────────────────────────────────────────────────────
/// A forward-only stream of fact records from `MiniGrafDb.fact_log`.
#[derive(uniffi::Object)]
pub struct MiniGrafFactLog {
/// `None` after `close()` or the end, which releases the database.
inner: Mutex<Option<minigraf::FactLog>>,
}
#[uniffi::export]
impl MiniGrafFactLog {
/// The next batch of at most `max_records` records (0 counts as 1);
/// `None` at the end or after `close()`. A batch is never empty.
pub fn next_batch(&self, max_records: i32) -> Result<Option<Vec<FactRecord>>, MiniGrafError> {
let mut guard = lock(&self.inner)?;
let Some(log) = guard.as_mut() else {
return Ok(None);
};
match log.next_batch(to_usize(i64::from(max_records), "max_records")?) {
Ok(Some(batch)) => Ok(Some(batch.into_iter().map(FactRecord::from).collect())),
Ok(None) => {
*guard = None;
Ok(None)
}
Err(e) => {
*guard = None;
Err(e.into())
}
}
}
/// Stop reading and release the database.
pub fn close(&self) {
if let Ok(mut guard) = self.inner.lock() {
*guard = None;
}
}
}
// ─── MiniGrafLogWriter ───────────────────────────────────────────────────────
/// Builds a new database file from fact records, keeping their transaction
/// and valid-time bounds. The file is built at `<path>.partial` and renamed
/// into place by `finish()`.
#[derive(uniffi::Object)]
pub struct MiniGrafLogWriter {
/// `None` after `finish()` or `close()`.
inner: Mutex<Option<minigraf::LogWriter>>,
}
fn writer_closed() -> MiniGrafError {
minigraf::MinigrafError::closed("log writer").into()
}
#[uniffi::export]
impl MiniGrafLogWriter {
/// Start building a new database at `path` (STG-043 if it exists).
#[uniffi::constructor]
pub fn create(path: String, options: OpenOptions) -> Result<Arc<Self>, MiniGrafError> {
let writer = minigraf::LogWriter::create(&path, options.to_core()?)?;
Ok(Arc::new(Self {
inner: Mutex::new(Some(writer)),
}))
}
/// Append one record. A rejected record changes nothing.
pub fn append(&self, record: FactRecord) -> Result<(), MiniGrafError> {
let record = record.to_core()?;
let mut guard = lock(&self.inner)?;
let writer = guard.as_mut().ok_or_else(writer_closed)?;
Ok(writer.append(&record)?)
}
/// Append `records` in order, stopping at the first rejected one. Its
/// error ends with `(batch index N)`; the records before it stay appended.
pub fn append_batch(&self, records: Vec<FactRecord>) -> Result<(), MiniGrafError> {
let mut guard = lock(&self.inner)?;
let writer = guard.as_mut().ok_or_else(writer_closed)?;
for (i, record) in records.iter().enumerate() {
record
.to_core()
.and_then(|r| writer.append(&r))
.map_err(|e| MiniGrafError::from(e).at_batch_index(i))?;
}
Ok(())
}
/// Close the open transaction and raise the counter to `tx_count`.
pub fn advance_tx_count(&self, tx_count: i64) -> Result<(), MiniGrafError> {
let tx_count = to_u64(tx_count, "tx_count")?;
let mut guard = lock(&self.inner)?;
let writer = guard.as_mut().ok_or_else(writer_closed)?;
Ok(writer.advance_tx_count(tx_count)?)
}
/// The highest `tx_count` appended or advanced to.
pub fn tx_count(&self) -> Result<i64, MiniGrafError> {
let guard = lock(&self.inner)?;
Ok(from_u64(
guard.as_ref().ok_or_else(writer_closed)?.tx_count(),
))
}
/// Commit every record and rename the file into place. Later calls are
/// API-018.
pub fn finish(&self) -> Result<(), MiniGrafError> {
let writer = lock(&self.inner)?.take().ok_or_else(writer_closed)?;
Ok(writer.finish()?)
}
/// Abandon an unfinished build, deleting `<path>.partial`. A no-op after
/// `finish()` or `close()`.
pub fn close(&self) {
if let Ok(mut guard) = self.inner.lock() {
guard.take();
}
}
/// `false` once `finish()` or `close()` has been called.
pub fn is_open(&self) -> bool {
self.inner.lock().is_ok_and(|g| g.is_some())
}
}
// ─── Write transactions ──────────────────────────────────────────────────────
/// Options for `MiniGrafDb.begin_write_with`. Every field is optional; an
/// absent field is the database's value. See the Rust `TxOptions`.
#[derive(Debug, Clone, Default, uniffi::Record)]
pub struct TxOptions {
/// This transaction's WAL durability. Absent: the database's
/// `OpenOptions.synchronous`. No effect in memory or on a transaction
/// that becomes large, which commits as a checkpoint.
#[uniffi(default)]
pub synchronous: Option<SyncMode>,
/// Facts this transaction stages before a file database writes them in
/// chunks. Absent: the database's `transaction_chunk_facts`. Clamped to
/// 1..=1,000,000; negative is API-017.
#[uniffi(default)]
pub chunk_facts: Option<i64>,
}
impl TxOptions {
fn to_core(&self) -> Result<minigraf::TxOptions, MiniGrafError> {
let mut o = minigraf::TxOptions::new();
if let Some(v) = self.synchronous {
o = o.synchronous(match v {
SyncMode::Full => minigraf::SyncMode::Full,
SyncMode::Normal => minigraf::SyncMode::Normal,
});
}
if let Some(v) = self.chunk_facts {
o = o.chunk_facts(to_usize(v, "chunk_facts")?);
}
Ok(o)
}
}
#[uniffi::export]
impl MiniGrafDb {
/// Begin a write transaction with the database's options. See
/// `MiniGrafWriteTransaction`.
pub fn begin_write(&self) -> Result<Arc<MiniGrafWriteTransaction>, MiniGrafError> {
self.begin_write_with(TxOptions::default())
}
/// Begin a write transaction with `options`. It holds the database's
/// write lock until it commits, rolls back or is freed: a write or a
/// begin from another thread waits until then (this one included, while
/// another transaction is open), and a query from another thread reads
/// the committed state. On this thread, `execute`, `query`, `fact_log`,
/// `prepare`, `checkpoint`, a begin and a prepared query's runs fail
/// with INT-001 until it finishes. API-014 on a read-only database.
pub fn begin_write_with(
&self,
options: TxOptions,
) -> Result<Arc<MiniGrafWriteTransaction>, MiniGrafError> {
let options = options.to_core()?;
// No binding lock is held while the begin waits for the write lock.
let tx = self.db()?.begin_write_owned_with(options)?;
Ok(Arc::new(MiniGrafWriteTransaction {
inner: Mutex::new(Some(tx)),
running: Mutex::new(None),
}))
}