use crate::corroborate::FunctionRun;
use crate::error::QueryResult;
use crate::runtime::{FunctionRuntime, RunLimits};
use crate::snapshot::Snapshot;
#[derive(Clone, Debug)]
pub struct Shard {
pub id: String,
pub snapshot: Snapshot,
pub reachable: bool,
}
impl Shard {
pub fn new(id: impl Into<String>, snapshot: Snapshot) -> Self {
Self {
id: id.into(),
snapshot,
reachable: true,
}
}
pub fn unreachable(mut self) -> Self {
self.reachable = false;
self
}
}
pub struct QueryPlan<'a> {
pub map_wasm: &'a [u8],
pub reduce_wasm: &'a [u8],
pub limits: RunLimits,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Coverage {
pub shards_total: usize,
pub shards_computed: usize,
}
impl Coverage {
pub fn is_complete(&self) -> bool {
self.shards_total > 0 && self.shards_computed == self.shards_total
}
pub fn missing(&self) -> usize {
self.shards_total - self.shards_computed
}
}
#[derive(Clone, Debug)]
pub struct QueryOutcome {
pub output: Option<Vec<u8>>,
pub coverage: Coverage,
pub map_runs: Vec<FunctionRun>,
}
fn frame_pair(a: &[u8], b: &[u8]) -> Vec<u8> {
let mut framed = Vec::with_capacity(4 + a.len() + b.len());
framed.extend_from_slice(&(a.len() as u32).to_le_bytes());
framed.extend_from_slice(a);
framed.extend_from_slice(b);
framed
}
pub fn run_query(
runtime: &FunctionRuntime,
plan: &QueryPlan,
shards: &[Shard],
) -> QueryResult<QueryOutcome> {
let mut partials: Vec<Vec<u8>> = Vec::new();
let mut map_runs: Vec<FunctionRun> = Vec::new();
for shard in shards {
if !shard.reachable {
continue;
}
let exec = runtime.run(plan.map_wasm, shard.snapshot.bytes(), &plan.limits)?;
partials.push(exec.output);
map_runs.push(exec.run);
}
let coverage = Coverage {
shards_total: shards.len(),
shards_computed: partials.len(),
};
let output = if partials.is_empty() {
None
} else {
let mut acc = partials[0].clone();
for partial in &partials[1..] {
let exec = runtime.run(plan.reduce_wasm, &frame_pair(&acc, partial), &plan.limits)?;
acc = exec.output;
}
Some(acc)
};
Ok(QueryOutcome {
output,
coverage,
map_runs,
})
}