Cotton code
94 lines · 4.0 KB · TypeScriptRaw
/** * A batch of the phone's call history — the shape of `DeviceCall` * (`crates/cotton-client/src/ingest/mod.rs`, camelCase), decided here and * nowhere else: the row id is derived from (namespace, source, external id), so a re-read writes the same * rows; the handle is stored normalised where it can be and verbatim where it * cannot; a number nobody holds snaps to the one person the phone named. */import { findContactByHandle, peopleByHandle, upsert, type Change } from "./contacts.ts";import { handleKey, normalizeHandle } from "./handles.ts";import { callLogId } from "./ids.ts";import type { Reader } from "./reader.ts";import { collapse, isRecord } from "./text.ts";export interface DeviceCall {  source: string;  externalId: string;  provider: string;  direction: string;  outcome: string;  startedAt: string;  durationS: number;  handle: string | null;  handleKind: string;  name: string | null;  device: string | null;  meta: Record<string, unknown>;}export const MAX_BATCH_CALLS = 5000;/** The first field of the first call serde would refuse, said as the envelope's validator says one; null when every call reads. */export function callsProblem(body: unknown): string | null {  if (!isRecord(body) || !Array.isArray(body.calls)) return "calls: expected an array";  if (body.calls.length > MAX_BATCH_CALLS) return `calls: ${body.calls.length} exceeds the ${MAX_BATCH_CALLS}-call cap`;  for (const [i, call] of (body.calls as unknown[]).entries()) {    const at = `calls[${i}]`;    if (!isRecord(call)) return `${at}: expected an object`;    for (const field of ["source", "externalId", "provider", "direction", "outcome", "startedAt", "handleKind"]) if (typeof call[field] !== "string") return `${at}.${field}: expected a string`;    if (typeof call.durationS !== "number" || !Number.isInteger(call.durationS)) return `${at}.durationS: expected a whole number`;    for (const field of ["handle", "name", "device"]) if (call[field] !== undefined && call[field] !== null && typeof call[field] !== "string") return `${at}.${field}: expected a string or null`;    if (!isRecord(call.meta)) return `${at}.meta: expected an object`;  }  return null;}export function callChanges(db: Reader, namespace: string, calls: DeviceCall[], now: string): Change[] {  const people = peopleByHandle(db);  const region = db.ownerRegion();  let changes: Change[] = [];  const seen = new Set<string>();  let byName: Map<string, string[]> | null = null;  for (const call of calls) {    const id = callLogId(namespace, call.source, call.externalId);    // The same call twice in one batch: the last is kept, as last-write-wins would.    if (seen.has(id)) changes = changes.filter((c) => c.id !== id);    seen.add(id);    const handle = call.handle == null ? null : normalizeHandle(call.handleKind === "email" ? "email" : "phone", call.handle, region);    const contact = handle ? findContactByHandle(db, handle) : null;    let personId = contact?.person_id ?? (handle ? (people.get(handleKey(handle))?.id ?? null) : null);    if (personId === null && call.name != null) {      if (byName === null) {        byName = new Map();        for (const p of db.peopleByName()) {          const key = collapse(p.full_name).toLowerCase();          if (key) byName.set(key, [...(byName.get(key) ?? []), p.id]);        }      }      const ids = byName.get(collapse(call.name).toLowerCase());      personId = ids && ids.length === 1 ? ids[0]! : null;    }    changes.push(      upsert("call", id, {        id,        source: call.source,        external_id: call.externalId,        provider: call.provider,        direction: call.direction,        outcome: call.outcome,        started_at: call.startedAt,        duration_s: call.durationS,        handle: handle ? handle.value : (call.handle ?? null),        contact_id: contact?.id ?? null,        person_id: personId,        device: call.device ?? null,        meta: call.meta,        created_at: now,        updated_at: now,      }),    );  }  return changes;}