1use std::collections::HashMap;
10use std::sync::Arc;
11
12use crate::adapter::WrappingDispenser;
13use crate::adapter::{ExecutionError, OpDispenser, OpResult};
14use crate::wrapper_registry::{WrapperName, WrapperRegistration, WrapperSubject};
15use nmbrs_workload::bindpoints;
16
17pub const NAME: WrapperName = WrapperName::new("traverse");
19
20fn triggers(s: WrapperSubject) -> bool {
24 s.op().is_some()
25}
26
27fn describe_assignment(_: WrapperSubject) -> Option<String> {
30 None
31}
32
33inventory::submit! {
34 WrapperRegistration {
35 name: NAME,
36 owned_fields: &[],
37 triggers,
38 requires_inner: &[],
39 forbids_outer: &[],
40 mutually_exclusive_with: &[],
41 describe_assignment,
42 levels: &[crate::wrapper_registry::WrapperLevel::Op],
43 }
44}
45
46pub struct TraversalStats {
48 pub metrics: Arc<crate::activity::ActivityMetrics>,
49}
50
51pub struct TraversingDispenser {
60 inner: Arc<dyn OpDispenser>,
61 stats: Arc<TraversalStats>,
62 captures: Vec<bindpoints::CapturePoint>,
65 spec: Option<nmbrs_workload::model::TraverseSpec>,
68}
69
70impl TraversingDispenser {
71 pub fn wrap(
78 inner: Arc<dyn OpDispenser>,
79 template: &nmbrs_workload::model::ParsedOp,
80 stats: Arc<TraversalStats>,
81 ) -> Arc<dyn OpDispenser> {
82 Arc::new(Self {
83 inner,
84 stats,
85 captures: template.captures.clone(),
86 spec: template.traverse.clone(),
87 })
88 }
89}
90
91#[cfg(test)]
110fn extract_captures_from_json(
111 body: &dyn crate::adapter::ResultBody,
112 specs: &[bindpoints::CapturePoint],
113) -> HashMap<String, polydat::ast::Value> {
114 extract_captures_rooted(body, specs, None)
115}
116
117fn extract_captures_rooted(
126 body: &dyn crate::adapter::ResultBody,
127 specs: &[bindpoints::CapturePoint],
128 base: Option<&str>,
129) -> HashMap<String, polydat::ast::Value> {
130 if specs.is_empty() {
131 return HashMap::new();
132 }
133 let full = body.to_json();
134 let json = match base.filter(|b| !b.is_empty()) {
135 None => full,
136 Some(b) => match full.pointer(b) {
137 Some(sub) => sub.clone(),
138 None => return HashMap::new(),
139 },
140 };
141 let mut captures = HashMap::new();
142 for spec in specs {
143 if let Some(path) = spec.path.as_deref() {
149 let sub = json.pointer(path);
150 let value = if spec.count {
151 polydat::ast::Value::U64(count_of_subtree(sub))
152 } else if let Some(agg) = &spec.agg {
153 aggregate_rows(sub, agg, spec.row_filter.as_ref())
154 } else {
155 match sub {
156 Some(v) => json_subtree_to_value(v),
157 None => polydat::ast::Value::None,
158 }
159 };
160 captures.insert(spec.as_name.clone(), value);
161 continue;
162 }
163 if spec.slurp {
164 let collected = slurp_column(&json, &spec.source_name);
166 captures.insert(
167 spec.as_name.clone(),
168 polydat::ast::Value::Json(std::sync::Arc::new(serde_json::Value::Array(collected))),
169 );
170 continue;
171 }
172 if spec.source_name == "*" {
174 let target = match &json {
177 serde_json::Value::Array(rows) => {
178 rows.first().cloned().unwrap_or(serde_json::Value::Null)
179 }
180 other => other.clone(),
181 };
182 if let serde_json::Value::Object(map) = target {
183 for (k, v) in map {
184 captures.insert(k, json_to_value(&v));
185 }
186 }
187 continue;
188 }
189 if let Some(val) = first_row_field(&json, &spec.source_name) {
190 captures.insert(spec.as_name.clone(), json_to_value(&val));
191 }
192 }
193 captures
194}
195
196fn count_of_subtree(v: Option<&serde_json::Value>) -> u64 {
203 let Some(v) = v else { return 0 };
204 match v {
205 serde_json::Value::Array(a) => a.len() as u64,
206 serde_json::Value::Object(m) => m.len() as u64,
207 serde_json::Value::Number(n) => n
208 .as_u64()
209 .or_else(|| n.as_i64().map(|i| i.max(0) as u64))
210 .or_else(|| n.as_f64().map(|f| f.max(0.0) as u64))
211 .unwrap_or(0),
212 serde_json::Value::Bool(b) => {
213 if *b {
214 1
215 } else {
216 0
217 }
218 }
219 serde_json::Value::String(s) if s.is_empty() => 0,
220 serde_json::Value::String(_) => 1,
221 serde_json::Value::Null => 0,
222 }
223}
224
225fn captures_for_empty_result(
262 specs: &[bindpoints::CapturePoint],
263) -> std::collections::HashMap<String, polydat::ast::Value> {
264 use bindpoints::CaptureAgg;
265 let mut out = std::collections::HashMap::new();
266 for spec in specs {
267 let value = if spec.count {
268 polydat::ast::Value::U64(0)
269 } else {
270 match &spec.agg {
271 Some(CaptureAgg::Sum(_)) => polydat::ast::Value::U64(0),
272 Some(CaptureAgg::Min(_)) | Some(CaptureAgg::Max(_)) => polydat::ast::Value::None,
273 None => polydat::ast::Value::None,
274 }
275 };
276 out.insert(spec.as_name.clone(), value);
277 }
278 out
279}
280
281fn publish_capture(ctx: &crate::adapter::ExecCtx<'_>, name: &str, value: polydat::ast::Value) {
286 if matches!(value, polydat::ast::Value::None) {
287 let _ = ctx.wires.reset(name);
288 } else {
289 let _ = ctx.wires.write(name, value);
290 }
291}
292
293fn aggregate_rows(
294 sub: Option<&serde_json::Value>,
295 agg: &bindpoints::CaptureAgg,
296 row_filter: Option<&(String, String)>,
297) -> polydat::ast::Value {
298 use bindpoints::CaptureAgg;
299 let rows = match sub {
300 Some(serde_json::Value::Array(rows)) => rows,
301 _ => return polydat::ast::Value::None,
302 };
303 let field = match agg {
304 CaptureAgg::Min(f) | CaptureAgg::Max(f) | CaptureAgg::Sum(f) => f.as_str(),
305 };
306 let keep = |row: &serde_json::Value| -> bool {
313 let Some((k, want)) = row_filter else {
314 return true;
315 };
316 match row.get(k.as_str()) {
317 Some(serde_json::Value::String(s)) => s == want,
318 Some(other) => other.to_string().trim_matches('"') == want,
319 None => false,
320 }
321 };
322 let nums: Vec<&serde_json::Number> = rows
323 .iter()
324 .filter(|row| keep(row))
325 .filter_map(|row| row.get(field))
326 .filter_map(|v| v.as_number())
327 .collect();
328 if nums.is_empty() {
329 return match agg {
338 CaptureAgg::Sum(_) => polydat::ast::Value::U64(0),
339 CaptureAgg::Min(_) | CaptureAgg::Max(_) => polydat::ast::Value::None,
340 };
341 }
342 match agg {
343 CaptureAgg::Sum(_) => {
344 if nums.iter().all(|n| n.as_u64().is_some()) {
345 polydat::ast::Value::U64(nums.iter().map(|n| n.as_u64().unwrap()).sum())
346 } else {
347 polydat::ast::Value::F64(nums.iter().filter_map(|n| n.as_f64()).sum())
348 }
349 }
350 CaptureAgg::Min(_) | CaptureAgg::Max(_) => {
351 let want_min = matches!(agg, CaptureAgg::Min(_));
352 let mut best = nums[0];
353 for n in &nums[1..] {
354 let (a, b) = (
355 n.as_f64().unwrap_or(f64::NAN),
356 best.as_f64().unwrap_or(f64::NAN),
357 );
358 if (want_min && a < b) || (!want_min && a > b) {
359 best = n;
360 }
361 }
362 json_to_value(&serde_json::Value::Number((*best).clone()))
363 }
364 }
365}
366
367fn json_subtree_to_value(v: &serde_json::Value) -> polydat::ast::Value {
368 match v {
369 serde_json::Value::Array(_) | serde_json::Value::Object(_) => {
370 polydat::ast::Value::Json(std::sync::Arc::new(v.clone()))
371 }
372 scalar => json_to_value(scalar),
373 }
374}
375
376fn first_row_field(json: &serde_json::Value, name: &str) -> Option<serde_json::Value> {
380 match json {
381 serde_json::Value::Array(rows) => rows.first().and_then(|row| row.get(name)).cloned(),
382 serde_json::Value::Object(_) => json.get(name).cloned(),
383 _ => None,
384 }
385}
386
387fn slurp_column(json: &serde_json::Value, name: &str) -> Vec<serde_json::Value> {
391 match json {
392 serde_json::Value::Array(rows) => rows
393 .iter()
394 .filter_map(|row| row.get(name).cloned())
395 .collect(),
396 serde_json::Value::Object(_) => json.get(name).map(|v| vec![v.clone()]).unwrap_or_default(),
397 _ => Vec::new(),
398 }
399}
400
401pub(crate) fn json_to_value(v: &serde_json::Value) -> polydat::ast::Value {
409 match v {
410 serde_json::Value::Null => polydat::ast::Value::None,
411 serde_json::Value::Number(n) => {
412 if let Some(i) = n.as_u64() {
413 polydat::ast::Value::U64(i)
414 } else if let Some(f) = n.as_f64() {
415 polydat::ast::Value::F64(f)
416 } else {
417 polydat::ast::Value::Str(n.to_string().into())
418 }
419 }
420 serde_json::Value::Bool(b) => polydat::ast::Value::Bool(*b),
421 serde_json::Value::String(s) => polydat::ast::Value::Str(s.as_str().into()),
422 other => polydat::ast::Value::Str(other.to_string().into()),
423 }
424}
425
426impl WrappingDispenser for TraversingDispenser {}
427
428impl OpDispenser for TraversingDispenser {
429 fn execute<'a>(
430 &'a self,
431 cycle: u64,
432 ctx: &'a crate::fixture::ExecCtx<'a>,
433 ) -> std::pin::Pin<
434 Box<dyn std::future::Future<Output = Result<OpResult, ExecutionError>> + Send + 'a>,
435 > {
436 Box::pin(async move {
437 let result = self.inner.execute(cycle, ctx).await?;
439
440 if let Some(body) = &result.body {
442 self.stats
443 .metrics
444 .result_elements
445 .inc_by(body.element_count());
446 if let Some(bytes) = body.byte_count() {
447 self.stats.metrics.result_bytes.inc_by(bytes);
448 }
449 }
450
451 if !self.captures.is_empty() && result.body.is_none() {
460 for (name, value) in captures_for_empty_result(&self.captures) {
461 publish_capture(ctx, &name, value);
462 }
463 }
464 if !self.captures.is_empty()
465 && let Some(body) = &result.body
466 {
467 let base = self.spec.as_ref().and_then(|s| s.path.as_deref());
468 let extracted = extract_captures_rooted(body.as_ref(), &self.captures, base);
469 let policy = self.spec.as_ref().map(|s| s.on_missing).unwrap_or_default();
474 if !matches!(policy, nmbrs_workload::model::OnMissing::Ignore) {
475 for cp in &self.captures {
476 let missing = match extracted.get(&cp.as_name) {
477 None => true,
478 Some(polydat::ast::Value::None) => true,
479 Some(_) => false,
480 };
481 if !missing {
482 continue;
483 }
484 let detail = format!(
485 "op capture '{}' resolved to nothing{}",
486 cp.as_name,
487 match base {
488 Some(b) => format!(" (traverse path '{b}')"),
489 None => String::new(),
490 }
491 );
492 match policy {
493 nmbrs_workload::model::OnMissing::Warn => {
494 crate::diag!(crate::observer::LogLevel::Warn, "{detail}")
495 }
496 nmbrs_workload::model::OnMissing::Error => {
497 return Err(ExecutionError::Op(crate::adapter::AdapterError {
498 error_name: "capture_missing".into(),
499 message: detail,
500 retryable: false,
501 }));
502 }
503 nmbrs_workload::model::OnMissing::Ignore => {}
504 }
505 }
506 }
507 for (name, value) in extracted {
508 publish_capture(ctx, &name, value);
509 }
510 }
511
512 Ok(result)
513 })
514 }
515 fn inner_dispenser(&self) -> Option<&dyn OpDispenser> {
516 Some(self.inner.as_ref())
517 }
518}
519
520#[cfg(test)]
521mod tests {
522 use super::*;
523 use crate::adapter::ResultBody;
524
525 fn agg_cap(
526 alias: &str,
527 agg: Option<bindpoints::CaptureAgg>,
528 count: bool,
529 ) -> bindpoints::CapturePoint {
530 bindpoints::CapturePoint {
531 row_filter: None,
532 source_name: alias.into(),
533 as_name: alias.into(),
534 cast_type: None,
535 slurp: false,
536 path: Some(String::new()),
537 count,
538 agg,
539 }
540 }
541
542 #[test]
549 fn empty_result_publishes_identity_for_count_and_sum() {
550 let specs = vec![
551 agg_cap("n", None, true),
552 agg_cap("s", Some(bindpoints::CaptureAgg::Sum("x".into())), false),
553 ];
554 let out = super::captures_for_empty_result(&specs);
555 assert!(
556 matches!(out.get("n"), Some(polydat::ast::Value::U64(0))),
557 "counting nothing is 0, not 'leave the old count': {:?}",
558 out.get("n")
559 );
560 assert!(
561 matches!(out.get("s"), Some(polydat::ast::Value::U64(0))),
562 "summing nothing is 0: {:?}",
563 out.get("s")
564 );
565 }
566
567 #[test]
572 fn empty_result_clears_min_and_max_rather_than_inventing_a_value() {
573 let specs = vec![
574 agg_cap("lo", Some(bindpoints::CaptureAgg::Min("x".into())), false),
575 agg_cap("hi", Some(bindpoints::CaptureAgg::Max("x".into())), false),
576 ];
577 let out = super::captures_for_empty_result(&specs);
578 assert!(
579 matches!(out.get("lo"), Some(polydat::ast::Value::None)),
580 "min of nothing must not invent 0: {:?}",
581 out.get("lo")
582 );
583 assert!(
584 matches!(out.get("hi"), Some(polydat::ast::Value::None)),
585 "max of nothing must not invent 0: {:?}",
586 out.get("hi")
587 );
588 }
589
590 #[test]
592 fn empty_result_leaves_plain_captures_absent() {
593 let specs = vec![agg_cap("v", None, false)];
594 let out = super::captures_for_empty_result(&specs);
595 assert!(matches!(out.get("v"), Some(polydat::ast::Value::None)));
596 }
597
598 #[test]
604 fn empty_fold_totality_sum_is_zero_min_max_are_reset_markers() {
605 let rows = serde_json::json!([{"other": 1}, {"other": 2}]);
611 let v = super::aggregate_rows(
612 Some(&rows),
613 &bindpoints::CaptureAgg::Sum("missing".into()),
614 None,
615 );
616 assert!(
617 matches!(v, polydat::ast::Value::U64(0)),
618 "sum-of-nothing is its identity 0: {v:?}"
619 );
620 for agg in [
621 bindpoints::CaptureAgg::Min("missing".into()),
622 bindpoints::CaptureAgg::Max("missing".into()),
623 ] {
624 let v = super::aggregate_rows(Some(&rows), &agg, None);
625 assert!(
626 matches!(v, polydat::ast::Value::None),
627 "min/max-of-nothing is the reset marker: {v:?}"
628 );
629 }
630 }
631
632 fn cap(source: &str, alias: &str, slurp: bool) -> bindpoints::CapturePoint {
633 bindpoints::CapturePoint {
634 row_filter: None,
635 source_name: source.into(),
636 as_name: alias.into(),
637 cast_type: None,
638 slurp,
639 path: None,
640 count: false,
641 agg: None,
642 }
643 }
644
645 #[test]
646 fn parse_captures_from_template() {
647 let parsed =
648 bindpoints::parse_capture_points("SELECT [username], [age as user_age] FROM users");
649 assert_eq!(parsed.captures.len(), 2);
650 assert_eq!(parsed.captures[0].source_name, "username");
651 assert_eq!(parsed.captures[0].as_name, "username");
652 assert!(!parsed.captures[0].slurp);
653 assert_eq!(parsed.captures[1].source_name, "age");
654 assert_eq!(parsed.captures[1].as_name, "user_age");
655 assert_eq!(parsed.raw_template, "SELECT username, age FROM users");
656 }
657
658 #[test]
659 fn parse_slurp_capture() {
660 let parsed = bindpoints::parse_capture_points("SELECT [@keys] FROM t");
661 assert_eq!(parsed.captures.len(), 1);
662 assert_eq!(parsed.captures[0].source_name, "keys");
663 assert!(parsed.captures[0].slurp);
664 assert_eq!(parsed.raw_template, "SELECT keys FROM t");
665 }
666
667 #[derive(Debug)]
668 struct JsonBody(serde_json::Value);
669 impl ResultBody for JsonBody {
670 fn to_json(&self) -> serde_json::Value {
671 self.0.clone()
672 }
673 fn as_any(&self) -> &dyn std::any::Any {
674 self
675 }
676 }
677
678 #[test]
679 fn extract_from_json_top_level() {
680 let body = JsonBody(serde_json::json!({
681 "user_id": 42,
682 "name": "alice",
683 "balance": 99.5
684 }));
685 let specs = vec![cap("user_id", "uid", false), cap("name", "name", false)];
686 let captures = extract_captures_from_json(&body, &specs);
687 assert_eq!(captures.len(), 2);
688 assert_eq!(captures["uid"].as_u64(), 42);
689 match &captures["name"] {
690 polydat::ast::Value::Str(s) => assert_eq!(&**s, "alice"),
691 other => panic!("expected Str, got {other:?}"),
692 }
693 }
694
695 #[test]
696 fn extract_wildcard() {
697 let body = JsonBody(serde_json::json!({"a": 1, "b": 2}));
698 let specs = vec![cap("*", "*", false)];
699 let captures = extract_captures_from_json(&body, &specs);
700 assert_eq!(captures.len(), 2);
701 }
702
703 #[test]
704 fn extract_slurp_array_of_rows() {
705 let body = JsonBody(serde_json::json!([
706 {"key": 4, "value": 0.5},
707 {"key": 17, "value": 0.4},
708 {"key": 42, "value": 0.3},
709 ]));
710 let specs = vec![cap("key", "key", true)];
711 let captures = extract_captures_from_json(&body, &specs);
712 assert_eq!(captures.len(), 1);
713 match &captures["key"] {
714 polydat::ast::Value::Json(arc) => {
715 let serde_json::Value::Array(items) = arc.as_ref() else {
716 panic!("expected Value::Json(array), got {arc:?}");
717 };
718 assert_eq!(items.len(), 3);
719 assert_eq!(items[0], serde_json::json!(4));
720 assert_eq!(items[1], serde_json::json!(17));
721 assert_eq!(items[2], serde_json::json!(42));
722 }
723 other => panic!("expected Value::Json(array), got {other:?}"),
724 }
725 }
726
727 #[test]
728 fn extract_single_first_row_of_array() {
729 let body = JsonBody(serde_json::json!([
730 {"key": 4}, {"key": 17}, {"key": 42},
731 ]));
732 let specs = vec![cap("key", "first_key", false)];
733 let captures = extract_captures_from_json(&body, &specs);
734 assert_eq!(captures.len(), 1);
735 assert_eq!(captures["first_key"].as_u64(), 4);
736 }
737
738 fn cap_path(name: &str, path: &str, count: bool) -> bindpoints::CapturePoint {
739 bindpoints::CapturePoint {
740 source_name: name.into(),
741 as_name: name.into(),
742 cast_type: None,
743 slurp: false,
744 path: Some(path.into()),
745 count,
746 agg: None,
747 row_filter: None,
748 }
749 }
750
751 #[test]
754 fn traverse_path_re_roots_the_document() {
755 let body = JsonBody(serde_json::json!({
756 "status": 200,
757 "value": [{"progress": 7u64}],
758 }));
759 let spec = |name: &str, path: &str| bindpoints::CapturePoint {
760 source_name: name.into(),
761 as_name: name.into(),
762 cast_type: None,
763 slurp: false,
764 path: Some(path.to_string()),
765 count: false,
766 agg: None,
767 row_filter: None,
768 };
769 let long = extract_captures_rooted(&body, &[spec("p", "/value/0/progress")], None);
771 assert_eq!(long["p"].as_u64(), 7);
772
773 let short = extract_captures_rooted(&body, &[spec("p", "/0/progress")], Some("/value"));
775 assert_eq!(short["p"].as_u64(), 7);
776 }
777
778 #[test]
781 fn an_unresolvable_traverse_path_yields_nothing() {
782 let body = JsonBody(serde_json::json!({"value": 1}));
783 let spec = bindpoints::CapturePoint {
784 source_name: "x".into(),
785 as_name: "x".into(),
786 cast_type: None,
787 slurp: false,
788 path: Some("/x".into()),
789 count: false,
790 agg: None,
791 row_filter: None,
792 };
793 let caps = extract_captures_rooted(&body, &[spec], Some("/nonesuch"));
794 assert!(caps.is_empty(), "unresolvable base must not invent values");
795 }
796
797 #[test]
802 fn aggregate_captures_filter_rows_by_kind() {
803 let body = JsonBody(serde_json::json!([
804 {"kind": "compaction", "progress": 47048035855u64},
805 {"kind": "secondary index build", "progress": 4855601u64},
806 ]));
807 fn cap_filtered(
808 name: &str,
809 field: &str,
810 filter: Option<(&str, &str)>,
811 ) -> bindpoints::CapturePoint {
812 bindpoints::CapturePoint {
813 source_name: name.into(),
814 as_name: name.into(),
815 cast_type: None,
816 slurp: false,
817 path: Some(String::new()),
818 count: false,
819 agg: Some(bindpoints::CaptureAgg::Sum(field.into())),
820 row_filter: filter.map(|(k, v)| (k.to_string(), v.to_string())),
821 }
822 }
823 let specs = vec![
824 cap_filtered("all", "progress", None),
825 cap_filtered("index", "progress", Some(("kind", "secondary index build"))),
826 cap_filtered("data", "progress", Some(("kind", "compaction"))),
827 ];
828 let caps = extract_captures_from_json(&body, &specs);
829 let num = |k: &str| caps[k].as_u64();
830 assert_eq!(num("index"), 4_855_601, "index build only");
831 assert_eq!(num("data"), 47_048_035_855, "data compaction only");
832 assert_eq!(num("all"), num("index") + num("data"));
835 }
836
837 #[test]
840 fn aggregate_filter_matching_no_rows_folds_to_sum_identity() {
841 let body = JsonBody(serde_json::json!([
842 {"kind": "compaction", "progress": 5u64},
843 ]));
844 let specs = vec![bindpoints::CapturePoint {
845 source_name: "x".into(),
846 as_name: "x".into(),
847 cast_type: None,
848 slurp: false,
849 path: Some(String::new()),
850 count: false,
851 agg: Some(bindpoints::CaptureAgg::Sum("progress".into())),
852 row_filter: Some(("kind".into(), "nonesuch".into())),
853 }];
854 let caps = extract_captures_from_json(&body, &specs);
855 assert!(
859 matches!(caps["x"], polydat::ast::Value::U64(0)),
860 "a filtered-empty sum folds to its identity 0; got {:?}",
861 caps["x"]
862 );
863 }
864
865 #[test]
866 fn aggregate_captures_fold_rows_with_mixed_units() {
867 let body = JsonBody(serde_json::json!([
872 {"completion_ratio": 1.0, "progress": 31357891323u64, "total": 31357891323u64},
873 {"completion_ratio": 0.4, "progress": 8000000u64, "total": 20000000u64},
874 ]));
875 fn cap_agg(name: &str, agg: bindpoints::CaptureAgg) -> bindpoints::CapturePoint {
876 bindpoints::CapturePoint {
877 source_name: name.into(),
878 as_name: name.into(),
879 cast_type: None,
880 slurp: false,
881 path: Some(String::new()),
882 count: false,
883 agg: Some(agg),
884 row_filter: None,
885 }
886 }
887 let specs = vec![
888 cap_agg(
889 "completion_ratio",
890 bindpoints::CaptureAgg::Min("completion_ratio".into()),
891 ),
892 cap_agg(
893 "max_ratio",
894 bindpoints::CaptureAgg::Max("completion_ratio".into()),
895 ),
896 cap_agg("progress", bindpoints::CaptureAgg::Sum("progress".into())),
897 ];
898 let captures = extract_captures_from_json(&body, &specs);
899 assert_eq!(captures["completion_ratio"].as_f64(), 0.4);
900 assert_eq!(captures["max_ratio"].as_f64(), 1.0);
901 assert_eq!(captures["progress"].as_u64(), 31357891323 + 8000000);
902 let empty = JsonBody(serde_json::json!([]));
904 let c2 = extract_captures_from_json(&empty, &specs[..1]);
905 assert!(matches!(c2["completion_ratio"], polydat::ast::Value::None));
906 }
907
908 #[test]
909 fn extract_json_pointer_scalar_from_bulk_response() {
910 let body = JsonBody(serde_json::json!([
911 {"value": 7, "status": 200},
912 {"value": [], "status": 200},
913 {"value": 0, "status": 200},
914 ]));
915 let specs = vec![
916 cap_path("sstables", "/0/value", false),
917 cap_path("pending_for_cf", "/2/value", false),
918 ];
919 let captures = extract_captures_from_json(&body, &specs);
920 assert_eq!(captures["sstables"].as_u64(), 7);
921 assert_eq!(captures["pending_for_cf"].as_u64(), 0);
922 }
923
924 #[test]
925 fn extract_json_pointer_resolved_null_yields_none_not_string() {
926 let body = JsonBody(serde_json::json!([
927 {"value": null, "status": 200},
928 ]));
929 let specs = vec![cap_path("pending_for_cf", "/0/value", false)];
930 let captures = extract_captures_from_json(&body, &specs);
931 assert!(
932 matches!(captures["pending_for_cf"], polydat::ast::Value::None),
933 "JSON null at path should yield Value::None, got {:?}",
934 captures["pending_for_cf"],
935 );
936 }
937
938 #[test]
939 fn extract_json_pointer_count_on_resolved_null_returns_zero() {
940 let body = JsonBody(serde_json::json!([
941 {"value": null, "status": 200},
942 ]));
943 let specs = vec![cap_path("pending_for_cf", "/0/value", true)];
944 let captures = extract_captures_from_json(&body, &specs);
945 assert_eq!(
946 captures["pending_for_cf"].as_u64(),
947 0,
948 "`:count` on resolved-null should return 0, got {:?}",
949 captures["pending_for_cf"],
950 );
951 }
952
953 #[test]
954 fn extract_json_pointer_count_collapses_array_to_length() {
955 let body = JsonBody(serde_json::json!([
956 {"value": 7},
957 {"value": [
958 {"compactionId":"a", "keyspace":"ks", "columnfamily":"cf"},
959 {"compactionId":"b", "keyspace":"ks", "columnfamily":"cf"},
960 ]},
961 ]));
962 let specs = vec![cap_path("active_count", "/1/value", true)];
963 let captures = extract_captures_from_json(&body, &specs);
964 assert_eq!(captures["active_count"].as_u64(), 2);
965 }
966
967 #[test]
968 fn extract_json_pointer_missing_path_yields_none() {
969 let body = JsonBody(serde_json::json!({"value": 7}));
970 let specs = vec![cap_path("not_there", "/missing/path", false)];
971 let captures = extract_captures_from_json(&body, &specs);
972 assert!(
973 matches!(captures["not_there"], polydat::ast::Value::None),
974 "expected Value::None for unresolvable JSON-Pointer, got {:?}",
975 captures["not_there"],
976 );
977 }
978
979 #[test]
980 fn extract_json_pointer_count_of_missing_path_is_zero() {
981 let body = JsonBody(serde_json::json!({"value": 7}));
982 let specs = vec![cap_path("active_count", "/missing/value", true)];
983 let captures = extract_captures_from_json(&body, &specs);
984 assert_eq!(captures["active_count"].as_u64(), 0);
985 }
986
987 #[test]
988 fn extract_json_pointer_structural_sub_tree_captured_as_json() {
989 let body = JsonBody(serde_json::json!([
990 {"value": {"keyspace": "ks", "table": "cf", "ssTables": 3}},
991 ]));
992 let specs = vec![cap_path("state", "/0/value", false)];
993 let captures = extract_captures_from_json(&body, &specs);
994 match &captures["state"] {
995 polydat::ast::Value::Json(arc) => {
996 assert_eq!(arc.get("keyspace").and_then(|v| v.as_str()), Some("ks"));
997 assert_eq!(arc.get("ssTables").and_then(|v| v.as_u64()), Some(3));
998 }
999 other => panic!("expected Value::Json, got {other:?}"),
1000 }
1001 let _ = count_of_subtree;
1003 let _ = json_subtree_to_value;
1004 }
1005}