1use serde_json::{json, Map, Value};
4
5use crate::bson::id_key;
6use crate::computes::{collect_field_deps, merge_depends_into_ast, InjectInfo};
7use crate::permission::{can_read_schema, is_relation_readable, merge_owner_condition, Context};
8use crate::pipeline::{
9 build_pipeline, build_pipeline_projection, build_projection, flatten_object_fields, is_nullish,
10 param, parse_gql, Ast, RelAst, REL_PRED_PREFIX,
11};
12use crate::rbac::{ensure_read, merge_row_condition};
13use crate::schema::{Registry, Schema};
14use crate::types::{is_truthy, validate_pipeline_stages};
15
16use super::cmd::{cmd_aggregate, cmd_find, num_value, to_number};
17use super::{ensure_context, ERR_PERMISSION, MAX_PAGE_SIZE, PHASE1_IDS};
18
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct Page {
21 pub page: f64,
22 pub page_size: f64,
23}
24
25impl Page {
26 pub fn to_value(&self) -> Value {
27 json!({
28 "page": num_value(self.page),
29 "pageSize": num_value(self.page_size),
30 })
31 }
32
33 pub fn has_more(&self, total: f64) -> bool {
35 (self.page + 1.0) * self.page_size < total
36 }
37}
38
39pub fn resolve_page(ast: &Ast, params: &Map<String, Value>) -> Page {
41 let (page, page_size) = if params.contains_key("page") || params.contains_key("pageSize") {
42 let page = match params.get("page").filter(|v| !v.is_null()) {
43 Some(v) => to_number(Some(v)).max(0.0).floor(),
44 None => 0.0,
45 };
46 let page_size = match params.get("pageSize").filter(|v| !v.is_null()) {
47 Some(v) => to_number(Some(v)),
48 None => 50.0,
49 };
50 (page, page_size)
51 } else {
52 let skip_val = param(params, ast.params.get("skip"));
53 let limit_val = param(params, ast.params.get("limit"));
54 let page = if !is_nullish(skip_val) && is_truthy(limit_val.unwrap_or(&Value::Null)) {
55 (to_number(skip_val) / to_number(limit_val)).floor()
56 } else {
57 0.0
58 };
59 let page_size = if is_nullish(limit_val) {
60 50.0
61 } else {
62 to_number(limit_val)
63 };
64 (page, page_size)
65 };
66
67 Page {
68 page,
69 page_size: if page_size < MAX_PAGE_SIZE {
70 page_size
71 } else {
72 MAX_PAGE_SIZE
73 },
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq)]
79pub enum Mode {
80 Find,
82 TwoPhase,
84 Aggregate,
86}
87
88impl Mode {
89 pub fn as_str(self) -> &'static str {
90 match self {
91 Mode::Find => "find",
92 Mode::TwoPhase => "two_phase",
93 Mode::Aggregate => "aggregate",
94 }
95 }
96}
97
98#[derive(Debug, Clone)]
99pub struct QueryPlan {
100 pub collection: String,
101 pub mode: Mode,
102 pub commands: Vec<Value>,
103 pub postprocess: Option<Value>,
105 pub sort: Option<Value>,
107}
108
109impl QueryPlan {
110 pub fn to_value(&self) -> Value {
111 json!({
112 "collection": self.collection,
113 "mode": self.mode.as_str(),
114 "commands": self.commands,
115 "postprocess": self.postprocess.clone().unwrap_or(Value::Null),
116 "sort": self.sort.clone().unwrap_or(Value::Null),
117 })
118 }
119}
120
121fn postprocess_value(ast: &Ast, inject: &InjectInfo) -> Value {
122 json!({
123 "ast": ast.to_value(),
124 "inject": if inject.is_empty() { Value::Null } else { inject.to_value() },
125 })
126}
127
128pub fn has_pipeline(ast: &Ast, params: &Map<String, Value>) -> bool {
134 ast.params
135 .get("pipeline")
136 .map(|r| !is_nullish(param(params, Some(r))))
137 .unwrap_or(false)
138}
139
140pub fn plan_query(
142 gql: &str,
143 params: &Map<String, Value>,
144 registry: &Registry,
145 ctx: Option<&Context>,
146) -> Result<QueryPlan, String> {
147 let mut params = params.clone();
148 plan_query_mut(gql, &mut params, registry, ctx)
149}
150
151pub fn plan_query_mut(
153 gql: &str,
154 params: &mut Map<String, Value>,
155 registry: &Registry,
156 ctx: Option<&Context>,
157) -> Result<QueryPlan, String> {
158 let ast = parse_gql(gql)?;
159 plan_query_ast_mut(ast, params, registry, ctx)
160}
161
162pub fn plan_query_one(
169 gql: &str,
170 params: &Map<String, Value>,
171 registry: &Registry,
172 ctx: Option<&Context>,
173) -> Result<QueryPlan, String> {
174 let mut params = params.clone();
175 let mut ast = parse_gql(gql)?;
176 if !ast.params.contains_key("limit") && !has_pipeline(&ast, ¶ms) {
177 ast.params
178 .insert("limit".to_string(), "@__core_one_limit__".to_string());
179 params.insert("__core_one_limit__".to_string(), json!(1));
180 }
181 plan_query_ast_mut(ast, &mut params, registry, ctx)
182}
183
184pub fn plan_query_ast_mut(
190 mut ast: Ast,
191 params: &mut Map<String, Value>,
192 registry: &Registry,
193 ctx: Option<&Context>,
194) -> Result<QueryPlan, String> {
195 ensure_context(registry, ctx)?;
196 let schema = registry.get(&ast.model)?;
197
198 if ctx.is_some() && !can_read_schema(registry.role_rules(), schema, ctx) {
199 return Err(ERR_PERMISSION.to_string());
200 }
201 ensure_read(registry, schema, ctx)?;
203
204 if ctx.is_some() {
207 if let Some(r) = ast.params.get("condition").cloned() {
208 let key = r.get(1..).unwrap_or("").to_string();
209 let owner_merged =
210 merge_owner_condition(registry.role_rules(), schema, ctx, params.get(&key).cloned());
211 match merge_row_condition(registry, schema, ctx, "read", owner_merged) {
212 Some(v) => {
213 params.insert(key, v);
214 }
215 None => {
216 params.remove(&key);
217 }
218 }
219 } else {
220 let static_owner = merge_owner_condition(registry.role_rules(), schema, ctx, None);
224 if let Some(owner) =
225 merge_row_condition(registry, schema, ctx, "read", static_owner)
226 .filter(|v| v.as_object().map(|o| !o.is_empty()).unwrap_or(false))
227 {
228 ast.params
229 .insert("condition".to_string(), "@__core_owner__".to_string());
230 params.insert("__core_owner__".to_string(), owner);
231 }
232 }
233 }
234
235 let has_pipeline = has_pipeline(&ast, params);
236
237 let mut inject = if has_pipeline {
238 InjectInfo::default()
239 } else {
240 merge_depends_into_ast(&mut ast.relations, schema)?
241 };
242 if !has_pipeline {
245 inject.fields = collect_field_deps(&mut ast.fields, schema);
246 }
247
248 let mut post_ast = ast.clone();
251 if !has_pipeline {
252 flatten_object_fields(&mut post_ast, schema);
253 }
254
255 build_plan(ast, &post_ast, &inject, params, registry, ctx)
256}
257
258pub fn check_readable_relations(
265 relations: &[(String, RelAst)],
266 schema: &Schema,
267 registry: &Registry,
268 ctx: Option<&Context>,
269) -> Result<(), String> {
270 if ctx.is_none() {
271 return Ok(());
272 }
273 for (rel_name, rel_ast) in relations {
274 let Some(rel_def) = schema.relations.get(rel_name) else {
275 continue;
276 };
277 if rel_def.model.is_empty() {
279 continue;
280 }
281 if !is_relation_readable(registry.role_rules(), schema, ctx, rel_name) {
282 return Err(ERR_PERMISSION.to_string());
283 }
284 let rel_schema = registry.get(&rel_def.model)?;
285 if !can_read_schema(registry.role_rules(), rel_schema, ctx) {
286 return Err(ERR_PERMISSION.to_string());
287 }
288 ensure_read(registry, rel_schema, ctx)?;
290 check_readable_relations(&rel_ast.relations, rel_schema, registry, ctx)?;
291 }
292 Ok(())
293}
294
295pub fn build_plan(
301 mut fetch_ast: Ast,
302 post_ast: &Ast,
303 inject: &InjectInfo,
304 params: &Map<String, Value>,
305 registry: &Registry,
306 ctx: Option<&Context>,
307) -> Result<QueryPlan, String> {
308 ensure_context(registry, ctx)?;
309 let schema = registry.get(&fetch_ast.model)?;
310
311 check_readable_relations(&fetch_ast.relations, schema, registry, ctx)?;
314
315 let has_pipeline = has_pipeline(&fetch_ast, params);
319
320 let pipeline = build_pipeline(&mut fetch_ast, params, registry, ctx)?;
321 let stages: Vec<Value> = pipeline.as_array().cloned().unwrap_or_default();
322
323 let grouped = stages.iter().any(|s| s.get("$group").is_some());
327
328 let projection = if has_pipeline {
329 build_pipeline_projection(&fetch_ast, schema)
330 } else if grouped {
331 None
332 } else {
333 build_projection(&fetch_ast, schema, ctx, registry)
334 };
335
336 let collection = schema.collection.clone();
337 let post = || {
338 if has_pipeline || grouped {
339 None
340 } else {
341 Some(postprocess_value(post_ast, inject))
342 }
343 };
344
345 if !has_pipeline && stages.len() == 1 {
347 if let Some(filter) = stages[0].get("$match") {
348 return Ok(QueryPlan {
349 collection: collection.clone(),
350 mode: Mode::Find,
351 commands: vec![cmd_find(schema, filter, projection.as_ref())],
352 postprocess: post(),
353 sort: None,
354 });
355 }
356 }
357
358 let first_lookup = stages.iter().position(|s| {
362 s.get("$lookup")
363 .map(|lo| {
364 !lo.get("as")
365 .and_then(|v| v.as_str())
366 .map(|a| a.starts_with(REL_PRED_PREFIX))
367 .unwrap_or(false)
368 })
369 .unwrap_or(false)
370 });
371 let has_skip_limit = !has_pipeline
373 && stages
374 .iter()
375 .any(|s| s.get("$skip").is_some() || s.get("$limit").is_some());
376 let sort_stage = stages.iter().find(|s| s.get("$sort").is_some()).cloned();
377
378 if let Some(idx) = first_lookup {
379 if !grouped && has_skip_limit && !sorts_by_relation(sort_stage.as_ref()) {
380 let mut id_pipeline: Vec<Value> = stages[..idx].to_vec();
381 for key in ["$sort", "$skip", "$limit"] {
382 if let Some(st) = stages.iter().find(|s| s.get(key).is_some()) {
383 id_pipeline.push(st.clone());
384 }
385 }
386 id_pipeline.push(json!({ "$project": { "_id": 1 } }));
387
388 let mut full: Vec<Value> = stages[idx..]
389 .iter()
390 .filter(|s| {
391 !(s.get("$sort").is_some()
392 || s.get("$skip").is_some()
393 || s.get("$limit").is_some())
394 })
395 .cloned()
396 .collect();
397 full.insert(0, json!({ "$match": { "_id": { "$in": PHASE1_IDS } } }));
398 if let Some(p) = projection.as_ref() {
399 full.push(json!({ "$project": p }));
400 }
401
402 return Ok(QueryPlan {
403 collection: collection.clone(),
404 mode: Mode::TwoPhase,
405 commands: vec![
406 cmd_aggregate(schema, &id_pipeline),
407 cmd_aggregate(schema, &full),
408 ],
409 postprocess: post(),
410 sort: sort_stage,
411 });
412 }
413 }
414
415 let mut final_stages = stages;
417 if let Some(p) = projection.as_ref() {
418 final_stages.push(json!({ "$project": p }));
419 }
420 validate_pipeline_stages(&final_stages)?;
423
424 Ok(QueryPlan {
425 collection,
426 mode: Mode::Aggregate,
427 commands: vec![cmd_aggregate(schema, &final_stages)],
428 postprocess: post(),
429 sort: None,
430 })
431}
432
433pub fn sorts_by_relation(sort_stage: Option<&Value>) -> bool {
435 sort_stage
436 .and_then(|s| s.get("$sort"))
437 .and_then(|s| s.as_object())
438 .map(|o| o.keys().any(|k| k.contains('.')))
439 .unwrap_or(false)
440}
441
442pub fn restore_sort_order(items: &mut [Value], ids: &[Value], sort_stage: Option<&Value>) {
444 if sort_stage.is_none() || ids.len() <= 1 {
445 return;
446 }
447 let mut index: std::collections::HashMap<_, usize> =
450 std::collections::HashMap::with_capacity(ids.len());
451 for (i, id) in ids.iter().enumerate() {
452 index.entry(id_key(id)).or_insert(i);
453 }
454 let keyed: Vec<(usize, Value)> = items
455 .iter()
456 .map(|it| {
457 let k = id_key(it.get("_id").unwrap_or(&Value::Null));
458 let pos = index.get(&k).copied().unwrap_or(ids.len());
459 (pos, it.clone())
460 })
461 .collect();
462 let mut sorted = keyed;
463 sorted.sort_by_key(|(pos, _)| *pos);
464 for (slot, (_, v)) in items.iter_mut().zip(sorted) {
465 *slot = v;
466 }
467}