119 lines · 5.4 KB · TypeScriptRaw
/** * The messages engine's driver over the object: cotton-rules' * `import::messages_engine` and `messages::resolve_contact` run as WASM * (`cotton_rules::import::asked`) and ask every read by name; `Reader` answers * each with its fixed statement, synchronously, from inside the plan. The * engine's changes name the phone's tables and carry its `workspace_id`; they * land here under the object's names, where one database is one object and * there is no workspace column. */import { tryPlan } from "../rules/index.ts";import type { HandleKind } from "./handles.ts";import type { Reader } from "./reader.ts";/** One row the batch owes the object: an upsert of `patch` onto (table, id), or a retract. */export interface Change { table: string; id: string; patch?: Record<string, unknown>; retract?: true;}export const upsert = (table: string, id: string, patch: Record<string, unknown>): Change => ({ table, id, patch });/** The phone's table → the object's. A change to any other table is the engine planning a row this object has no place for. */const TABLES: Record<string, string> = { cotton_msg_threads: "thread", cotton_msg_messages: "message", cotton_msg_thread_participants: "thread_member", cotton_msg_reactions: "message_reaction", cotton_msg_contacts: "message_contact", cotton_msg_contact_handles: "message_contact_handle",};/** The engine's changes as the object writes them. */export function objectChanges(planned: Change[]): Change[] { return planned.map((change) => { const table = TABLES[change.table]; if (table === undefined) throw new Error(`the messages engine planned a ${change.table} row, which this object does not hold`); if (change.retract) return { table, id: change.id, retract: true }; const { workspace_id: _workspace, ...patch } = change.patch ?? {}; return { table, id: change.id, patch }; });}/** A JSON column's value as the column's text, which is what the engine parses (`meta` on a minute's rows). */const text = (value: unknown): string | null => (value === null || value === undefined ? null : typeof value === "string" ? value : JSON.stringify(value));type Args = Record<string, unknown>;const s = (args: Args, key: string): string => args[key] as string;const ids = (args: Args): string[] => args.ids as string[];/** Every question the engine asks, answered over the object. */export function answer(db: Reader, newId: () => string): (question: string, args: Args) => unknown { return (question, args) => { switch (question) { case "people_handles": return db.peopleHandles(s(args, "kind") as HandleKind); case "contact_by_handle": return db.contactByHandle(s(args, "kind") as HandleKind, s(args, "value")); case "contact_by_phone": return db.contactByPhone(s(args, "phone")); case "dm_thread_for_contact": return db.dmThreadForContact(s(args, "contact_id")); case "thread_by_id": return db.threadById(s(args, "id"), s(args, "kind") as "dm" | "group"); case "known_external_ids": return [...db.knownExternalIds(s(args, "thread_id"), s(args, "channel"), ids(args))]; case "thread_stats": return db.threadStats(s(args, "thread_id"), s(args, "channel")); case "group_thread_by_key": return db.groupThreadByKey(s(args, "external_key")); case "jid_group_threads": return db.jidGroupThreads(); case "thread_by_overlap": return db.threadByOverlap(s(args, "channel"), s(args, "kind") as "dm" | "group", ids(args)); case "participants_of": return db.participantsOf(s(args, "thread_id")); case "thread_last_message_at": return db.threadLastMessageAt(s(args, "thread_id")); case "thread_external_key": return db.threadExternalKey(s(args, "thread_id")); case "unlinked_replies": return db.unlinkedReplies(s(args, "thread_id")); case "messages_by_external_ids": return db.messagesByExternalIds(s(args, "thread_id"), s(args, "channel"), ids(args)); case "held_without_media": return db.heldWithoutMedia(s(args, "thread_id"), s(args, "channel"), ids(args)).map((r) => ({ ...r, meta: text(r.meta) })); case "real_id_bodies_in_minute": return db.realIdBodiesInMinute(s(args, "thread_id"), s(args, "channel"), s(args, "minute")); case "rows_in_minute": return db.rowsInMinute(s(args, "thread_id"), s(args, "channel"), s(args, "minute")).map((r) => ({ ...r, meta: text(r.meta) })); case "message_by_external_id": return db.messageByExternalId(s(args, "channel"), s(args, "external_id")); case "owner_region": return db.ownerRegion(); case "new_id": return newId(); default: throw new Error(`the object does not answer ${question}`); } };}/** The engine's refusal: its words, and its code (`IMPORT_SHAPE` for a batch naming no counterpart). */export class EngineRefusal extends Error { readonly code: string; constructor(message: string, code: string) { super(message); this.code = code; }}/** Run the engine's `name` over `input`, asking `db`; its plan, or its refusal thrown. */export function runEngine<T>(name: string, input: unknown, db: Reader, newId: () => string = () => crypto.randomUUID()): T { const out = tryPlan<T>(name, input, answer(db, newId)); if ("error" in out) throw new EngineRefusal(out.error, out.code); return out.ok;}