-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathinput.rs
More file actions
1342 lines (1222 loc) · 46.9 KB
/
Copy pathinput.rs
File metadata and controls
1342 lines (1222 loc) · 46.9 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
//! Input types for JSON query deserialization.
//!
//! Security validation (identifiers, SQL injection) is handled by JSON Schema in lib.rs.
use ontology::constants::{DEFAULT_PRIMARY_KEY, SOURCE_ID_COLUMN, TARGET_ID_COLUMN};
use serde::{Deserialize, Deserializer};
use serde_json::Value;
use std::collections::{HashMap, HashSet};
// ─────────────────────────────────────────────────────────────────────────────
// Top-level input
// ─────────────────────────────────────────────────────────────────────────────
/// Controls which columns are fetched for dynamically-discovered entities
/// during hydration (PathFinding, Neighbors).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, strum::IntoStaticStr)]
#[strum(serialize_all = "lowercase")]
pub enum DynamicColumnMode {
/// Fetch all columns from the ontology for each entity type.
#[serde(rename = "*")]
All,
/// Fetch only the entity's `default_columns` from the ontology.
#[default]
#[serde(rename = "default")]
Default,
}
/// Optional presentation hints that control response shape without affecting query
/// semantics. Only `dynamic_columns` and `include_debug_sql` are recognized.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct QueryOptions {
/// Columns fetched for dynamically-discovered entities during hydration.
/// `All` returns every column; `Default` returns the entity's `default_columns`.
#[serde(default)]
pub dynamic_columns: DynamicColumnMode,
/// When true, includes compiled ClickHouse SQL in the response metadata.
/// On SaaS: honored for GitLab team members. On self-managed/Dedicated:
/// honored for instance admins only.
#[serde(default)]
pub include_debug_sql: bool,
}
/// Authorization config for an entity type, derived from the ontology and carried
/// through the compilation pipeline so the server never re-consults the ontology at
/// request time.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EntityAuthConfig {
/// Rails resource type sent to the authorization service (e.g. "projects").
pub resource_type: String,
/// Ability to check (e.g. "read_code").
pub ability: String,
/// DB column whose value is used as the authorization ID.
/// "id" for most entities; e.g. "project_id" for Definition/File/Branch.
pub auth_id_column: String,
/// For indirect-auth entities (auth_id_column != "id"): the entity type that
/// owns this resource, used to resolve the auth ID from edge columns for
/// dynamic (path/neighbor) nodes.
pub owner_entity: Option<String>,
/// Minimum GitLab role required on a traversal path for rows of this entity
/// to survive the security pass. Stored as an access-level integer so the
/// compiler can compare against per-path roles carried by `SecurityContext`
/// without pulling the ontology crate into `types.rs`.
pub required_access_level: u32,
}
impl Default for EntityAuthConfig {
fn default() -> Self {
Self {
resource_type: String::new(),
ability: String::new(),
auth_id_column: ontology::constants::DEFAULT_PRIMARY_KEY.to_string(),
owner_entity: None,
// Reporter mirrors the pre-fix access gate and is the right
// default for tests that do not care about role scoping.
required_access_level: crate::types::DEFAULT_PATH_ACCESS_LEVEL,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct Input {
pub query_type: QueryType,
#[serde(flatten, deserialize_with = "deserialize_nodes_or_node")]
pub nodes: Vec<InputNode>,
#[serde(default)]
pub relationships: Vec<InputRelationship>,
#[serde(default)]
#[serde(flatten)]
pub aggregation: InputAggregation,
pub path: Option<InputPath>,
pub neighbors: Option<InputNeighbors>,
#[serde(default = "default_limit")]
pub limit: u32,
pub cursor: Option<InputCursor>,
pub order_by: Option<InputOrderBy>,
#[serde(default)]
pub options: QueryOptions,
/// Auth config for every entity type with redaction configured. Populated by
/// normalization; covers all ontology entities (not just those in this query)
/// so dynamic nodes (path/neighbors) can be resolved without re-consulting the ontology.
#[serde(skip)]
pub entity_auth: HashMap<String, EntityAuthConfig>,
/// Metadata accumulated across compiler passes (lowering, optimize, etc.).
#[serde(skip)]
pub compiler: CompilerMetadata,
/// True when this Input was constructed for the *dynamic* hydration codepath
/// (Neighbors and PathFinding origin). Hydration over Traversal/Aggregation
/// uses the static path and leaves this `false`.
///
/// Selects the SQL shape for the `traversal_path` filter in hydration:
/// - dynamic: `arrayExists(p -> startsWith(tp, p), [paths])` (constant AST depth,
/// safe against ClickHouse `max_parser_depth=1000` when the base query
/// surfaced hundreds of namespace paths)
/// - static: left-nested OR of `startsWith(tp, p_i)` (per-leaf PK pushdown,
/// only ever a small project-bounded set of paths)
#[serde(skip)]
pub hydration_dynamic: bool,
}
/// Text index metadata for a column, used by the optimizer to rewrite
/// LIKE patterns to ClickHouse text-index-aware functions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextIndexMeta {
/// The tokenizer strategy, e.g. `"splitByNonAlpha"`, `"splitByString(['/'])"`.
pub tokenizer: String,
}
/// Metadata accumulated across compiler passes.
///
/// Written by normalize/lowering, read by downstream passes (deduplicate,
/// optimize, enforce, SIP, fold, etc.).
#[derive(Debug, Clone)]
pub struct CompilerMetadata {
/// Maps node alias → (edge_alias, edge_column) for edge-only nodes.
/// Written by lower, read by enforce to emit `_gkg_*` redaction columns
/// from edge columns instead of node table columns. Also used by SIP
/// and fold passes to skip edge-only targets.
pub node_edge_col: HashMap<String, (String, String)>,
/// All edge table names from the ontology. Used by dedup and optimizer
/// passes to identify edge scans without needing the full ontology.
pub edge_tables: HashSet<String>,
/// Default edge table name for creating new edge scans.
pub default_edge_table: String,
/// Maps relationship kind → edge table name. Populated by normalize from
/// `EdgeEntity.destination_table`. Used by lower/optimize to route each
/// relationship's scan to the correct physical table.
pub edge_table_for_rel: HashMap<String, String>,
/// Maps (node_kind, property_name, direction_prefix) → (edge_column, tag_key).
/// Populated by normalize from ontology denormalized properties.
/// Example: ("Pipeline", "status", "source") → ("source_tags", "status")
pub denormalized_columns: HashMap<(String, String, String), (String, String)>,
/// (node_kind, property, direction) → relationship kinds whose edge writes
/// that denorm tag. A filter is only pushed onto a hop whose relationship
/// is in this set.
pub denorm_rel_kinds: HashMap<(String, String, String), Vec<String>>,
/// `_nf_*` CTEs created by the lowerer from user-supplied filters or
/// node_ids. Distinguished from `_nf_*` CTEs synthesized by
/// `narrow_joined_nodes_via_pinned_neighbors` (reverse cascades).
/// The hop frontier optimizer uses this to decide whether a CTE is safe
/// to forward-chain from.
pub lowerer_nf_ctes: HashSet<String>,
/// Maps (table_name, column_name) → text index metadata. Populated by
/// normalize from the ontology's `StorageIndex` entries. Used by the
/// optimizer to rewrite `LIKE` patterns to `hasToken`/`hasAllTokens`.
pub text_indexes: HashMap<(String, String), TextIndexMeta>,
/// Physical table columns from the ontology. Used by lowering to emit
/// internal predicates only when a table is known to carry that column.
pub table_columns: HashMap<String, HashSet<String>>,
/// ORDER BY (sort key) columns per table from the ontology. Used by
/// the lowerer to emit `LIMIT 1 BY` dedup with PK-prefixed ORDER BY
/// instead of FINAL for single-hop edge aggregations.
pub table_sort_keys: HashMap<String, Vec<String>>,
/// Maps relationship kind → valid source entity kinds. Used by
/// pathfinding to add intermediate kind filters on frontier hops.
pub edge_source_kinds: HashMap<String, Vec<String>>,
/// Maps relationship kind → valid target entity kinds.
pub edge_target_kinds: HashMap<String, Vec<String>>,
/// Namespace entity (Group/Project) → (tp-dict table, key column) for pinning a neighbors anchor arm to its centers' exact traversal_paths.
pub tp_id_lookup: HashMap<String, (String, String)>,
}
/// Defaults to `gl_edge` for test convenience. In production, `normalize()`
/// always overwrites `edge_tables` and `default_edge_table` from the ontology.
impl Default for CompilerMetadata {
fn default() -> Self {
Self {
node_edge_col: HashMap::new(),
edge_tables: HashSet::from([ontology::constants::EDGE_TABLE.to_string()]),
default_edge_table: ontology::constants::EDGE_TABLE.to_string(),
edge_table_for_rel: HashMap::new(),
denormalized_columns: HashMap::new(),
denorm_rel_kinds: HashMap::new(),
lowerer_nf_ctes: HashSet::new(),
text_indexes: HashMap::new(),
table_columns: HashMap::new(),
table_sort_keys: HashMap::new(),
edge_source_kinds: HashMap::new(),
edge_target_kinds: HashMap::new(),
tp_id_lookup: HashMap::new(),
}
}
}
impl CompilerMetadata {
pub fn table_has_column(&self, table: &str, column: &str) -> bool {
self.table_columns
.get(table)
.is_some_and(|columns| columns.contains(column))
}
/// Resolve the edge table(s) for a relationship's type list.
///
/// Returns a deduplicated list of physical tables that need to be scanned.
/// - Single table → caller emits a normal `edge_scan`
/// - Multiple tables → caller emits a UNION ALL across tables
///
/// Wildcards and empty type lists resolve to all declared edge tables.
pub fn resolve_edge_tables(&self, types: &[String]) -> Vec<String> {
if crate::passes::normalize::is_wildcard(types) {
let mut tables: Vec<String> = self.edge_tables.iter().cloned().collect();
tables.sort();
return tables;
}
let mut seen = std::collections::BTreeSet::new();
for t in types {
let table = self
.edge_table_for_rel
.get(t)
.map(|s| s.as_str())
.unwrap_or(&self.default_edge_table);
seen.insert(table.to_string());
}
seen.into_iter().collect()
}
}
impl Input {
/// Whether this query has the "search shape": a single-node table scan
/// with no relationships (traversal with 1 node + 0 relationships).
pub fn is_search(&self) -> bool {
self.query_type == QueryType::Traversal
&& self.nodes.len() == 1
&& self.relationships.is_empty()
}
}
impl Default for Input {
fn default() -> Self {
Self {
query_type: QueryType::Traversal,
nodes: vec![],
relationships: vec![],
aggregation: InputAggregation::default(),
path: None,
neighbors: None,
limit: default_limit(),
cursor: None,
order_by: None,
options: QueryOptions::default(),
entity_auth: HashMap::new(),
compiler: CompilerMetadata::default(),
hydration_dynamic: false,
}
}
}
fn deserialize_nodes_or_node<'de, D>(deserializer: D) -> Result<Vec<InputNode>, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct Helper {
#[serde(default)]
node: Option<InputNode>,
#[serde(default)]
nodes: Option<Vec<InputNode>>,
}
let helper = Helper::deserialize(deserializer)?;
match (helper.node, helper.nodes) {
(Some(node), None) => Ok(vec![node]),
(None, Some(nodes)) => Ok(nodes),
(Some(_), Some(_)) => Err(serde::de::Error::custom(
"cannot specify both 'node' and 'nodes'",
)),
(None, None) => Err(serde::de::Error::custom(
"must specify either 'node' or 'nodes'",
)),
}
}
fn default_limit() -> u32 {
30
}
/// Agent-driven pagination cursor. Slices the authorized (post-redaction)
/// result set by `offset` and `page_size`. The server re-runs the query,
/// authorizes all rows up to `limit`, and returns `[offset..offset+page_size]`.
///
/// This model avoids SQL-level keyset pagination, which only generalizes to
/// Search queries and breaks when redaction removes rows from the LIMIT window.
// TODO: Server-side query caching with TTL to avoid re-running the same query on page 2+
#[derive(Debug, Clone, Copy, Deserialize)]
pub struct InputCursor {
pub offset: u32,
pub page_size: u32,
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
Deserialize,
strum::Display,
strum::IntoStaticStr,
strum::VariantNames,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum QueryType {
Traversal,
Aggregation,
PathFinding,
Neighbors,
/// Internal-only: consolidated hydration for multiple entity types.
/// Generates a UNION ALL of search-like arms, one per node. Skips
/// security context injection (IDs are pre-authorized by the pipeline).
#[serde(skip)]
Hydration,
}
// ─────────────────────────────────────────────────────────────────────────────
// Nodes
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct InputNode {
pub id: String,
/// Entity type (e.g., "User", "Project"). Determines which table to query.
#[serde(default)]
pub entity: Option<String>,
/// Resolved table name (e.g., "gl_user"). Populated during normalization.
#[serde(skip)]
pub table: Option<String>,
/// Columns to return for this node. Use `ColumnSelection::All` for all columns,
/// or `ColumnSelection::List` for specific columns. If not specified, only
/// mandatory columns (id, type) are returned.
#[serde(default, deserialize_with = "deserialize_columns")]
pub columns: Option<ColumnSelection>,
#[serde(default, deserialize_with = "deserialize_filters")]
pub filters: HashMap<String, Vec<InputFilter>>,
#[serde(default, deserialize_with = "deserialize_id_vec")]
pub node_ids: Vec<i64>,
pub id_range: Option<InputIdRange>,
pub id_property: String,
/// Which DB column to select as the auth ID for this node. Populated unconditionally
/// during normalization ("id" for most entities, e.g. "project_id" for Definition).
/// Always set before enforce.rs runs; do not add fallbacks in downstream code.
#[serde(skip)]
pub redaction_id_column: String,
/// Virtual columns stripped by normalize, consumed by the hydration plan.
#[serde(skip)]
pub virtual_columns: Vec<crate::passes::hydrate::VirtualColumnRequest>,
/// Filters on virtual columns, separated by normalize so they don't flow
/// into SQL. Applied in-memory after hydration resolves the column values.
#[serde(skip)]
pub virtual_filters: Vec<(String, InputFilter)>,
/// Whether the node table has a traversal_path column. Set during normalization.
#[serde(skip)]
pub has_traversal_path: bool,
/// Narrowed traversal paths extracted from base query results. Used by the
/// hydration pipeline to inject `startsWith(traversal_path, tp)` into hydration
/// queries, pruning granules through the primary key.
#[serde(skip)]
pub traversal_paths: Vec<String>,
}
impl Default for InputNode {
fn default() -> Self {
Self {
id: String::new(),
entity: None,
table: None,
columns: None,
filters: HashMap::new(),
node_ids: Vec::new(),
id_range: None,
id_property: DEFAULT_PRIMARY_KEY.to_string(),
redaction_id_column: DEFAULT_PRIMARY_KEY.to_string(),
virtual_columns: Vec::new(),
virtual_filters: Vec::new(),
has_traversal_path: false,
traversal_paths: Vec::new(),
}
}
}
/// Column selection for a node's result set.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColumnSelection {
/// Select all columns for this entity ("*")
All,
/// Select specific columns by name
List(Vec<String>),
}
fn deserialize_columns<'de, D>(deserializer: D) -> Result<Option<ColumnSelection>, D::Error>
where
D: Deserializer<'de>,
{
let value: Option<Value> = Option::deserialize(deserializer)?;
match value {
None => Ok(None),
Some(Value::String(s)) if s == "*" => Ok(Some(ColumnSelection::All)),
Some(Value::Array(arr)) => {
let cols: Result<Vec<String>, _> = arr
.into_iter()
.map(|v| {
v.as_str()
.map(String::from)
.ok_or_else(|| serde::de::Error::custom("column names must be strings"))
})
.collect();
Ok(Some(ColumnSelection::List(cols?)))
}
Some(_) => Err(serde::de::Error::custom(
"columns must be '*' or an array of column names",
)),
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct InputIdRange {
#[serde(deserialize_with = "deserialize_id")]
pub start: i64,
#[serde(deserialize_with = "deserialize_id")]
pub end: i64,
}
/// Accepts either a JSON integer or a JSON string of digits. Supports the
/// server response convention (IDs serialized as strings to avoid JavaScript
/// precision loss) so consumers can round-trip IDs without casting.
fn deserialize_id<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
D: Deserializer<'de>,
{
match Value::deserialize(deserializer)? {
Value::Number(n) => n
.as_i64()
.ok_or_else(|| serde::de::Error::custom("id out of i64 range")),
Value::String(s) => s.parse::<i64>().map_err(serde::de::Error::custom),
_ => Err(serde::de::Error::custom("id must be an integer or string")),
}
}
fn deserialize_id_vec<'de, D>(deserializer: D) -> Result<Vec<i64>, D::Error>
where
D: Deserializer<'de>,
{
let raw: Vec<Value> = Vec::deserialize(deserializer)?;
raw.into_iter()
.map(|v| match v {
Value::Number(n) => n
.as_i64()
.ok_or_else(|| serde::de::Error::custom("id out of i64 range")),
Value::String(s) => s.parse::<i64>().map_err(serde::de::Error::custom),
_ => Err(serde::de::Error::custom("id must be an integer or string")),
})
.collect()
}
// ─────────────────────────────────────────────────────────────────────────────
// Filters
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Default, PartialEq)]
pub struct InputFilter {
pub op: Option<FilterOp>,
pub value: Option<Value>,
/// Populated by the validate pass; lets the lowerer bind temporal columns
/// with their typed CH param.
pub data_type: Option<ontology::DataType>,
/// Populated by the validate pass from the ontology field definition.
/// Used by the planner to decide whether a filter justifies a narrowing CTE.
pub selectivity: ontology::FieldSelectivity,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, strum::AsRefStr)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum FilterOp {
Eq,
Gt,
Lt,
Gte,
Lte,
In,
Contains,
StartsWith,
EndsWith,
IsNull,
IsNotNull,
/// Token-boundary match via `hasToken()`. Requires a text index on the column.
TokenMatch,
/// All tokens present via `hasAllTokens()`. Requires a text index on the column.
AllTokens,
/// Any token present via `hasAnyTokens()`. Requires a text index on the column.
AnyTokens,
/// Fuzzy string matching via ClickHouse `ngramDistanceCaseInsensitive`.
FuzzyMatch,
}
fn deserialize_filters<'de, D>(
deserializer: D,
) -> Result<HashMap<String, Vec<InputFilter>>, D::Error>
where
D: Deserializer<'de>,
{
let raw: HashMap<String, Value> = HashMap::deserialize(deserializer)?;
Ok(raw
.into_iter()
.map(|(k, v)| (k, parse_filter_entry(v)))
.collect())
}
/// Parse a filter entry that may be a single filter or an array of
/// PropertyFilter objects (AND-combined, for expressing ranges).
fn parse_filter_entry(value: Value) -> Vec<InputFilter> {
if let Value::Array(ref arr) = value
&& !arr.is_empty()
&& arr.iter().all(|v| v.is_object() && v.get("op").is_some())
{
return arr.iter().cloned().map(parse_single_filter).collect();
}
vec![parse_single_filter(value)]
}
fn parse_single_filter(value: Value) -> InputFilter {
if let Value::Object(ref obj) = value
&& let Some(op_val) = obj.get("op")
&& let Ok(op) = serde_json::from_value::<FilterOp>(op_val.clone())
{
return InputFilter {
op: Some(op),
value: obj.get("value").cloned(),
..Default::default()
};
}
InputFilter {
op: None,
value: Some(value),
..Default::default()
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Relationships
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Deserialize)]
pub struct InputRelationship {
#[serde(rename = "type", deserialize_with = "deserialize_rel_types")]
pub types: Vec<String>,
pub from: String,
pub to: String,
#[serde(default = "default_hops")]
pub min_hops: u32,
#[serde(default = "default_hops")]
pub max_hops: u32,
#[serde(default)]
pub direction: Direction,
#[serde(default, deserialize_with = "deserialize_filters")]
pub filters: HashMap<String, Vec<InputFilter>>,
/// FK column on a node table that encodes this relationship. Set during normalization.
/// The compiler resolves which node has the column from the edge variant's entity types.
#[serde(skip)]
pub fk_column: Option<String>,
/// Tight `traversal_path` prefix this edge's scan may be confined to. Set by
/// `restrict` when both endpoints resolve to the same project/group scope, so
/// the edge scan inherits the PK prefix instead of the broad org-wide one.
/// Lossless because an edge row's `traversal_path` is its source entity's.
#[serde(skip)]
pub scope_prefix: Option<String>,
/// Whether every resolved variant of this relationship keeps both endpoints
/// in the same namespace. Set by `restrict`. Only scope-preserving FK edges
/// link a node to an intrinsic child whose lifecycle is coupled to the
/// parent; the FK-chain lowering relies on this to be result-equivalent to
/// the edge scan (an independent entity like a runner can outlive its edge).
#[serde(skip)]
pub scope_preserving: bool,
}
fn default_hops() -> u32 {
1
}
fn deserialize_rel_types<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
match Value::deserialize(deserializer)? {
Value::String(s) => Ok(vec![s]),
Value::Array(arr) => arr
.into_iter()
.map(|v| {
v.as_str()
.map(String::from)
.ok_or_else(|| serde::de::Error::custom("expected string"))
})
.collect(),
_ => Err(serde::de::Error::custom("type must be string or array")),
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Direction {
#[default]
Outgoing,
Incoming,
Both,
}
impl Direction {
/// Returns (start_col, end_col) for edge traversal.
pub fn edge_columns(self) -> (&'static str, &'static str) {
match self {
Direction::Outgoing | Direction::Both => (SOURCE_ID_COLUMN, TARGET_ID_COLUMN),
Direction::Incoming => (TARGET_ID_COLUMN, SOURCE_ID_COLUMN),
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Aggregations
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct InputAggregation {
#[serde(rename = "aggregations")]
pub metrics: Vec<InputAggregationMetric>,
#[serde(rename = "group_by")]
pub group_by: Vec<InputGroupByKey>,
#[serde(rename = "aggregation_sort")]
pub sort: Option<InputAggSort>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct InputAggregationMetric {
pub function: AggFunction,
#[serde(default)]
pub target: Option<String>,
#[serde(default)]
pub property: Option<String>,
#[serde(default)]
pub alias: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum InputGroupByKey {
Node {
node: String,
#[serde(default)]
alias: Option<String>,
},
Property {
node: String,
property: String,
#[serde(default)]
alias: Option<String>,
#[serde(default)]
transform: Option<PropertyTransform>,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum PropertyTransform {
/// Truncate a Date or DateTime property to the start of `unit`.
Truncate { unit: TruncateUnit },
}
impl PropertyTransform {
pub fn output_suffix(&self) -> String {
match self {
Self::Truncate { unit } => unit.name().to_string(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TruncateUnit {
Minute,
Hour,
Day,
Week,
Month,
Quarter,
Year,
}
impl TruncateUnit {
pub fn ch_function(self) -> &'static str {
match self {
Self::Minute => "toStartOfMinute",
Self::Hour => "toStartOfHour",
Self::Day => "toStartOfDay",
Self::Week => "toStartOfWeek",
Self::Month => "toStartOfMonth",
Self::Quarter => "toStartOfQuarter",
Self::Year => "toStartOfYear",
}
}
pub fn name(self) -> &'static str {
match self {
Self::Minute => "minute",
Self::Hour => "hour",
Self::Day => "day",
Self::Week => "week",
Self::Month => "month",
Self::Quarter => "quarter",
Self::Year => "year",
}
}
/// Granularities whose bucket cardinality is too high to allow without
/// the caller scoping the query to a bounded set.
pub fn requires_selectivity_guard(self) -> bool {
matches!(self, Self::Minute | Self::Hour)
}
}
impl InputGroupByKey {
pub fn node(&self) -> &str {
match self {
Self::Node { node, .. } | Self::Property { node, .. } => node,
}
}
pub fn property(&self) -> Option<&str> {
match self {
Self::Node { .. } => None,
Self::Property { property, .. } => Some(property),
}
}
pub fn transform(&self) -> Option<&PropertyTransform> {
match self {
Self::Property { transform, .. } => transform.as_ref(),
Self::Node { .. } => None,
}
}
pub fn truncate(&self) -> Option<TruncateUnit> {
self.transform()
.map(|PropertyTransform::Truncate { unit }| *unit)
}
pub fn output_name(&self, is_unique_property: bool) -> String {
match self {
Self::Node { node, alias } => alias.clone().unwrap_or_else(|| node.clone()),
Self::Property {
node,
property,
alias,
transform,
} => alias.clone().unwrap_or_else(|| {
let base = if is_unique_property {
property.clone()
} else {
format!("{}_{}", node, property)
};
match transform {
Some(t) => format!("{}_{}", base, t.output_suffix()),
None => base,
}
}),
}
}
}
pub fn group_by_output_names(groups: &[InputGroupByKey]) -> Vec<String> {
let mut property_counts: HashMap<&str, usize> = HashMap::new();
for group in groups {
if let Some(property) = group.property() {
*property_counts.entry(property).or_default() += 1;
}
}
groups
.iter()
.map(|group| {
let is_unique_property = group
.property()
.map(|property| property_counts[property] == 1)
.unwrap_or(false);
group.output_name(is_unique_property)
})
.collect()
}
pub fn node_group_ids(groups: &[InputGroupByKey]) -> impl Iterator<Item = &str> {
groups.iter().filter_map(|group| match group {
InputGroupByKey::Node { node, .. } => Some(node.as_str()),
InputGroupByKey::Property { .. } => None,
})
}
pub fn property_groups(
groups: &[InputGroupByKey],
) -> impl Iterator<Item = (&str, &str, Option<&str>)> {
groups.iter().filter_map(|group| match group {
InputGroupByKey::Property {
node,
property,
alias,
..
} => Some((node.as_str(), property.as_str(), alias.as_deref())),
InputGroupByKey::Node { .. } => None,
})
}
pub fn group_by_kind(group: &InputGroupByKey) -> &'static str {
match group {
InputGroupByKey::Node { .. } => "node",
InputGroupByKey::Property { .. } => "property",
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, strum::Display)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum AggFunction {
Count,
Sum,
Avg,
Min,
Max,
Collect,
}
impl AggFunction {
pub fn as_sql(&self) -> &'static str {
match self {
Self::Count => "COUNT",
Self::Sum => "SUM",
Self::Avg => "AVG",
Self::Min => "MIN",
Self::Max => "MAX",
Self::Collect => "groupArray",
}
}
/// ClickHouse `-If` combinator name (e.g. `countIf`, `sumIf`).
pub fn as_sql_if(&self) -> &'static str {
match self {
Self::Count => "countIf",
Self::Sum => "sumIf",
Self::Avg => "avgIf",
Self::Min => "minIf",
Self::Max => "maxIf",
Self::Collect => "groupArrayIf",
}
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Path finding
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Deserialize)]
pub struct InputPath {
#[serde(rename = "type")]
pub path_type: PathType,
pub from: String,
pub to: String,
pub max_depth: u32,
#[serde(default)]
pub rel_types: Vec<String>,
#[serde(skip)]
pub forward_first_hop_rel_types: Vec<String>,
#[serde(skip)]
pub backward_first_hop_rel_types: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PathType {
Shortest,
}
// ─────────────────────────────────────────────────────────────────────────────
// Neighbors
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Deserialize)]
pub struct InputNeighbors {
pub node: String,
#[serde(default)]
pub direction: Direction,
#[serde(default)]
pub rel_types: Vec<String>,
}
// ─────────────────────────────────────────────────────────────────────────────
// Ordering
// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Deserialize)]
pub struct InputOrderBy {
pub node: String,
pub property: String,
#[serde(default)]
pub direction: OrderDirection,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum OrderDirection {
#[default]
Asc,
Desc,
}
#[derive(Debug, Clone, Deserialize)]
pub struct InputAggSort {
pub column: String,
#[serde(default)]
pub direction: OrderDirection,
}
// ─────────────────────────────────────────────────────────────────────────────
// Public API
// ─────────────────────────────────────────────────────────────────────────────
/// Parse JSON into Input structure.
#[must_use = "the parsed input should be used"]
pub fn parse_input(json: &str) -> Result<Input, serde_json::Error> {
serde_json::from_str(json)
}
// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn simple_traversal() {
let input = parse_input(
r#"{
"query_type": "traversal",
"nodes": [
{"id": "n", "entity": "Note", "filters": {"system": false}},
{"id": "u", "entity": "User"}
],
"relationships": [{"type": "AUTHORED", "from": "u", "to": "n"}],
"limit": 25
}"#,
)
.unwrap();
assert_eq!(input.query_type, QueryType::Traversal);
assert_eq!(input.nodes.len(), 2);
assert_eq!(input.nodes[0].entity, Some("Note".into()));
assert_eq!(input.relationships.len(), 1);
assert_eq!(input.limit, 25);
}
#[test]
fn operator_filter() {
let input = parse_input(
r#"{
"query_type": "traversal",
"nodes": [{
"id": "u", "entity": "User",
"filters": {
"created_at": {"op": "gte", "value": "2024-01-01"},
"state": {"op": "in", "value": ["active", "blocked"]}
}
}]
}"#,
)
.unwrap();
let filters = &input.nodes[0].filters;
assert_eq!(
filters.get("created_at").unwrap()[0].op,
Some(FilterOp::Gte)