Cotton code
301 lines · 10.9 KB · RustRaw
//! `list_calls` and `get_call` — the call log's two reads (schema v38).//!//! A call log entry is the one record kind nothing in this product AUTHORS: the//! Mac ingestor reads it out of the phone's own log, and from then on it is a//! fact. So the surface is two verbs.//!//! THE HANDLE IS THE TITLE, and this reader mints no name for a call it cannot//! attribute. A number that resolved to a person carries their name; one that//! did not carries the number, which is the truest thing anybody can say about//! it. "Ravi" over an unresolved number would be the server inventing an//! attribution out of a digit string.use std::collections::{BTreeMap, HashSet};use serde_json::{Map, Value};use crate::mcp::dispatch::{Ctx, HandlerGroup, ToolResult};use crate::mcp::handlers::common::{    bounded_limit, fail, in_chunks, is_uuid, iso_timestamp, optional_string, or_null, projects,    put, require_string, resolve_project, rows, text, Valid,};use crate::mcp::protocol::ToolFailure;use crate::mcp::read_db::{Filter, Query};mod reader;pub use reader::{has_person, people_on, read_calls, read_calls_for_ids, read_calls_for_person};pub fn handlers() -> HandlerGroup {    &[("list_calls", list_calls), ("get_call", get_call)]}/// Every column either read projects. One list, so the two cannot drift.pub const COLUMNS: &[&str] = &[    "id",    "source",    "external_id",    "provider",    "direction",    "outcome",    "started_at",    "duration_s",    "handle",    "contact_id",    "person_id",    "device",    "meta",    "created_at",];/// `CALL_LOG_DIRECTIONS` / `CALL_LOG_OUTCOMES` as the validator reads them.const DIRECTIONS: &[&str] = &["in", "out"];const OUTCOMES: &[&str] = &["answered", "missed", "cancelled", "failed"];// ── the validators ──────────────────────────────────────────────────────────pub struct ListCallsArgs {    pub person_id: Option<String>,    pub project: Option<String>,    pub since: Option<String>,    pub until: Option<String>,    pub provider: Option<String>,    pub direction: Option<String>,    pub outcome: Option<String>,    pub limit: i64,}pub fn validate_list_calls(args: &Map<String, Value>) -> Valid<ListCallsArgs> {    let person_id = optional_string(args, "personId");    if person_id.as_deref().is_some_and(|id| !is_uuid(id)) {        return fail("personId must be a uuid");    }    let mut window: [Option<String>; 2] = [None, None];    for (index, key) in ["since", "until"].into_iter().enumerate() {        let Some(raw) = optional_string(args, key) else {            continue;        };        match iso_timestamp(&raw) {            Some(parsed) => window[index] = Some(parsed),            None => return fail(format!("{key} must be an ISO 8601 timestamp")),        }    }    let direction = optional_string(args, "direction");    if direction        .as_deref()        .is_some_and(|value| !DIRECTIONS.contains(&value))    {        return fail(format!(            "direction must be one of: {}",            DIRECTIONS.join(", ")        ));    }    let outcome = optional_string(args, "outcome");    if outcome        .as_deref()        .is_some_and(|value| !OUTCOMES.contains(&value))    {        return fail(format!("outcome must be one of: {}", OUTCOMES.join(", ")));    }    let [since, until] = window;    Ok(ListCallsArgs {        person_id,        project: optional_string(args, "project"),        since,        until,        provider: optional_string(args, "provider"),        direction,        outcome,        limit: bounded_limit(args, 50, crate::mcp::handlers::common::MAX_LIST),    })}// ── the shapes ──────────────────────────────────────────────────────────────/// The people these calls resolved to, named. One read for the whole page.fn people_names(    ctx: &Ctx<'_>,    calls: &[Map<String, Value>],) -> Result<BTreeMap<String, String>, ToolFailure> {    let mut seen: Vec<String> = Vec::new();    let mut known: HashSet<String> = HashSet::new();    for call in calls {        if let Some(id) = text(call, "person_id") {            if known.insert(id.clone()) {                seen.push(id);            }        }    }    if seen.is_empty() {        return Ok(BTreeMap::new());    }    let people = in_chunks(&seen, |batch| {        rows(            ctx,            &Query::on("cotton_people")                .columns(&["id", "full_name"])                .filter(Filter::In(                    "id".to_string(),                    batch.iter().map(|id| id.clone().into()).collect(),                )),        )    })?;    Ok(people        .into_iter()        .filter_map(|row| Some((text(&row, "id")?, text(&row, "full_name")?)))        .collect())}/// `meta` as an object, whichever way the row came back — and anything else is/// an EMPTY object rather than a throw, because a malformed `meta` must not/// make a call unreadable.fn meta_of(value: Option<&Value>) -> Value {    match value {        Some(Value::Object(object)) => Value::Object(object.clone()),        Some(Value::String(raw)) => match serde_json::from_str::<Value>(raw) {            Ok(Value::Object(object)) => Value::Object(object),            _ => Value::Object(Map::new()),        },        _ => Value::Object(Map::new()),    }}/// The compact row a list answers with. Nulls are omitted, never spelled out.fn call_out(row: &Map<String, Value>, names: &BTreeMap<String, String>) -> Map<String, Value> {    let person_id = text(row, "person_id");    let mut out = Map::new();    out.insert("id".to_string(), or_null(text(row, "id")));    out.insert("startedAt".to_string(), or_null(text(row, "started_at")));    out.insert("provider".to_string(), or_null(text(row, "provider")));    out.insert("direction".to_string(), or_null(text(row, "direction")));    out.insert("outcome".to_string(), or_null(text(row, "outcome")));    out.insert(        "durationS".to_string(),        row.get("duration_s").cloned().unwrap_or(Value::Null),    );    out.insert("handle".to_string(), or_null(text(row, "handle")));    if let Some(person_id) = &person_id {        out.insert("personId".to_string(), Value::from(person_id.clone()));        put(            &mut out,            "person",            names.get(person_id).cloned().map(Value::from),        );    }    out}/// The record ids a project holds explicitly, and the people linked to it.fn project_membership(    ctx: &Ctx<'_>,    project_id: &str,) -> Result<(Vec<String>, Vec<String>), ToolFailure> {    let links = rows(        ctx,        &Query::on("cotton_project_links")            .columns(&["record_kind", "record_id"])            .eq("project_id", project_id.to_string())            .filter(Filter::In(                "record_kind".to_string(),                vec!["call".to_string().into(), "person".to_string().into()],            )),    )?;    let mut call_ids = Vec::new();    let mut person_ids = Vec::new();    for link in links {        let (Some(kind), Some(id)) = (text(&link, "record_kind"), text(&link, "record_id")) else {            continue;        };        match kind.as_str() {            "call" => call_ids.push(id),            "person" => person_ids.push(id),            _ => {}        }    }    Ok((call_ids, person_ids))}pub fn list_calls(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let args = validate_list_calls(args)?;    let membership = if args.project.is_some() {        let all = projects(ctx)?;        let project_id = resolve_project(&all, args.project.as_deref())?            .ok_or_else(|| ToolFailure::new("Name a project, or leave the project filter out"))?;        Some(project_membership(ctx, &project_id)?)    } else {        None    };    let mut found =        read_calls(ctx.db(), ctx.workspace_id).map_err(|e| ToolFailure::new(e.to_string()))?;    found.retain(|row| {        args.person_id            .as_deref()            .is_none_or(|person| has_person(row, person))            && membership.as_ref().is_none_or(|(calls, people)| {                text(row, "id").is_some_and(|id| calls.contains(&id))                    || people.iter().any(|p| has_person(row, p))            })            && [                ("provider", &args.provider),                ("direction", &args.direction),                ("outcome", &args.outcome),            ]            .iter()            .all(|(key, value)| {                value                    .as_deref()                    .is_none_or(|v| text(row, key).as_deref() == Some(v))            })            && args.since.as_deref().is_none_or(|since| {                text(row, "started_at")                    .and_then(|at| iso_timestamp(&at))                    .is_some_and(|at| at.as_str() >= since)            })            && args.until.as_deref().is_none_or(|until| {                text(row, "started_at")                    .and_then(|at| iso_timestamp(&at))                    .is_some_and(|at| at.as_str() <= until)            })    });    found.truncate(args.limit.max(0) as usize);    let names = people_names(ctx, &found)?;    let mut out = Map::new();    out.insert(        "calls".to_string(),        Value::Array(            found                .iter()                .map(|row| Value::Object(call_out(row, &names)))                .collect(),        ),    );    Ok(Value::Object(out))}pub fn get_call(ctx: &mut Ctx<'_>, args: &Map<String, Value>) -> ToolResult {    let id = require_string(args, "id").ok_or_else(|| ToolFailure::new("id is required"))?;    // One answer for "absent" and "not this workspace" — the probe-resistance    // rule every other expander here follows.    let row = read_calls(ctx.db(), ctx.workspace_id)        .map_err(|e| ToolFailure::new(e.to_string()))?        .into_iter()        .find(|row| text(row, "id").as_deref() == Some(id.as_str()))        .ok_or_else(|| ToolFailure::new("no such call in this workspace"))?;    let names = people_names(ctx, std::slice::from_ref(&row))?;    let mut out = call_out(&row, &names);    // The provenance half, which a list has no room for: WHICH reader produced    // the row, the source's own id (what makes a re-read free), the machine    // that read it, and whatever the reader kept that has no column of its own.    out.insert("source".to_string(), or_null(text(&row, "source")));    out.insert("externalId".to_string(), or_null(text(&row, "external_id")));    put(        &mut out,        "contactId",        text(&row, "contact_id").map(Value::from),    );    put(&mut out, "device", text(&row, "device").map(Value::from));    out.insert("meta".to_string(), meta_of(row.get("meta")));    out.insert("recordedAt".to_string(), or_null(text(&row, "created_at")));    Ok(Value::Object(out))}