SPB Git

Repository Public

snooze.ts 21.2 KB 319 lines typescript

1// SP Mail Next — mises en veille et rappels de suivi : état durable en base, travail JMAP dans les routes et les travailleurs2// (jamais dans un crochet du veilleur), baux pour qu'un redémarrage ou une seconde instance ne déclenche rien deux fois.3import type { FastifyInstance } from "fastify"4import { z } from "zod"5import { config } from "../config.js"6import { sql, type Sql } from "../db.js"7import { folders, invalidateFolders, jmapOk, mailboxById, type Mbx } from "../mailjmap.js"8import { bad, parse, zUuid } from "../util.js"9import { nextUser, userMailbox, userMailboxes } from "./common.js"10import type { NextWorker } from "./index.js"11import { enqueueUserPush } from "./push.js"1213// ------- formes et validation14type Party = { name: string | null; email: string } | null15type SnoozeRow = { id: string; user_id: string; mailbox_id: string; email_id: string; thread_id: string | null; subject: string; sender: Party; origin_folder_ids: string[]; snoozed_folder_id: string; until: Date; status: string; attempts: number; created_at: Date }16type ReminderRow = { id: string; user_id: string; mailbox_id: string; email_id: string; thread_id: string | null; subject: string; counterpart: Party; due_at: Date; only_if_no_reply: boolean; thread_email_ids: string[]; note: string | null; status: string; attempts: number; created_at: Date; fired_at: Date | null }1718const SNOOZED = "Snoozed"19const iso = (d: unknown) => (d ? new Date(d as string).toISOString() : null)20const zWhen = z.string().max(40).refine((s) => !Number.isNaN(Date.parse(s)), "invalid date").transform((s) => new Date(s))21const zEmailId = z.string().min(1).max(100)22const zNote = z.string().trim().max(500)23const future = (d: Date, field: string) => { if (d.getTime() <= Date.now()) throw bad("invalid_request", 400, `${field}: must be in the future`) }24const idParam = (req: { params: unknown }) => {25  const { id } = req.params as { id: string }26  if (!zUuid.safeParse(id).success) throw bad("not_found", 404)27  return id28}29const partyOf = (a: { name?: string | null; email?: string | null } | undefined): Party => (a?.email ? { name: a.name || null, email: a.email } : null)30const snoozeOut = (s: SnoozeRow) => ({ id: s.id, mailbox_id: s.mailbox_id, email_id: s.email_id, thread_id: s.thread_id, subject: s.subject, from: s.sender, until: iso(s.until), status: s.status, created_at: iso(s.created_at) })31const reminderOut = (r: ReminderRow) => ({ id: r.id, mailbox_id: r.mailbox_id, email_id: r.email_id, thread_id: r.thread_id, subject: r.subject, counterpart: r.counterpart, due_at: iso(r.due_at), only_if_no_reply: r.only_if_no_reply, note: r.note, status: r.status, fired_at: iso(r.fired_at), created_at: iso(r.created_at) })3233// ------- aides JMAP34/** Dossier « Snoozed » de la boîte (sans rôle, à la racine) ; créé s'il manque. */35async function snoozedFolder(mb: Mbx): Promise<string> {36  const find = async () => (await folders(mb, true)).find((f) => f.name === SNOOZED && !f.parentId && !f.role)?.id37  const known = await find()38  if (known) return known39  const [r] = await jmapOk(mb, [["Mailbox/set", { create: { n: { name: SNOOZED, parentId: null } } }]])40  invalidateFolders(mb.id)41  const id = (r.created?.n?.id as string | undefined) ?? (await find()) // créé entre-temps par une autre requête42  if (!id) throw bad("mail_server_error", 502, JSON.stringify(r.notCreated ?? {}).slice(0, 200))43  return id44}45/** Adresses de l'utilisateur (ses boîtes et leurs alias) et de la boîte concernée : un message qui en vient n'est pas une réponse d'autrui. */46async function ownAddresses(userId: string, mailboxId: string): Promise<Set<string>> {47  const rows = await sql`select a.address from addresses a join mailboxes m on m.id = a.mailbox_id where m.user_id = ${userId} or m.id = ${mailboxId}48    union select address from mailboxes where user_id = ${userId} or id = ${mailboxId}`49  return new Set(rows.map((r) => String(r.address).toLowerCase()))50}51const canStillRead = async (userId: string, mailboxId: string) => (await userMailboxes(userId)).some((m) => m.id === mailboxId)52async function setKeyword(mb: Mbx, emailId: string, keyword: string, on: boolean) {53  const [g] = await jmapOk(mb, [["Email/get", { ids: [emailId], properties: ["keywords"] }]])54  const e = (g.list as { keywords?: Record<string, boolean> }[])[0]55  if (!e || !!e.keywords?.[keyword] === on) return56  await jmapOk(mb, [["Email/set", { update: { [emailId]: { [`keywords/${keyword}`]: on ? true : null } } }]])57}5859// ------- mise en veille60/**61 * Met des messages en veille jusqu'à `until` : déplacés dans « Snoozed », mot-clé `$snoozed`. Un message déjà en veille voit62 * seulement son échéance changer ; un message introuvable ou un brouillon est ignoré. Rend les lignes actives concernées.63 */64export async function snoozeMessages(userId: string, mailboxId: string, emailIds: string[], until: Date): Promise<{ id: string; email_id: string }[]> {65  const mb = await userMailbox(userId, mailboxId)66  const ids = [...new Set(emailIds)].slice(0, 200)67  if (!ids.length) return []68  const folder = await snoozedFolder(mb)69  const [g] = await jmapOk(mb, [["Email/get", { ids, properties: ["threadId", "mailboxIds", "keywords", "subject", "from"] }]])70  const out: { id: string; email_id: string; inserted: boolean }[] = []71  const update: Record<string, Record<string, unknown>> = {}72  for (const e of g.list as Record<string, any>[]) {73    if (e.keywords?.$draft) continue74    const origin = Object.keys(e.mailboxIds ?? {}).filter((id) => id !== folder)75    // La ligne est écrite AVANT le déplacement : après un arrêt brutal entre les deux, l'échéance trouve un message76    // resté à sa place et clôt simplement la ligne — jamais un message coincé dans « Snoozed » sans échéance.77    const [row] = await sql`insert into snoozes (user_id, mailbox_id, email_id, thread_id, subject, sender, origin_folder_ids, snoozed_folder_id, until)78      values (${userId}, ${mb.id}, ${e.id}, ${e.threadId ?? null}, ${String(e.subject ?? "").slice(0, 500)}, ${sql.json(partyOf((e.from ?? [])[0]) as never)}, ${origin}, ${folder}, ${until})79      on conflict (mailbox_id, email_id) where status = 'active' do update set until = excluded.until, user_id = excluded.user_id, locked_until = null, attempts = 0, last_error = null80      returning id, (xmax = 0) as inserted`81    out.push({ id: row.id, email_id: e.id, inserted: row.inserted })82    if (!e.mailboxIds?.[folder] || origin.length || !e.keywords?.$snoozed) update[e.id] = { mailboxIds: { [folder]: true }, "keywords/$snoozed": true }83  }84  if (Object.keys(update).length) {85    const undo = (emails: string[]) => sql`delete from snoozes where id = any(${out.filter((o) => o.inserted && emails.includes(o.email_id)).map((o) => o.id)}::uuid[])`86    let failed: string[]87    try {88      const [r] = await jmapOk(mb, [["Email/set", { update }]])89      failed = Object.keys(r.notUpdated ?? {})90    } catch (e) {91      await undo(Object.keys(update))92      throw e93    }94    if (failed.length) await undo(failed)95    const lost = new Set(failed)96    return out.filter((o) => !lost.has(o.email_id)).map(({ id, email_id }) => ({ id, email_id }))97  }98  return out.map(({ id, email_id }) => ({ id, email_id }))99}100101/**102 * Réveille un message : retour dans ses dossiers d'origine (à défaut la boîte de réception), `$snoozed` retiré ; à l'échéance il103 * redevient non lu. Rend `moved` (remis en place par nous), `elsewhere` (déjà sorti de « Snoozed » à la main) ou `missing`.104 */105async function wake(row: SnoozeRow, unread: boolean): Promise<"moved" | "elsewhere" | "missing"> {106  const mb = await mailboxById(row.mailbox_id)107  if (!mb) return "missing"108  const [g] = await jmapOk(mb, [["Email/get", { ids: [row.email_id], properties: ["mailboxIds", "keywords"] }]])109  const e = (g.list as { mailboxIds?: Record<string, boolean>; keywords?: Record<string, boolean> }[])[0]110  if (!e) return "missing"111  const keywords = { ...(e.keywords ?? {}) }112  delete keywords.$snoozed113  if (!e.mailboxIds?.[row.snoozed_folder_id]) {114    if (e.keywords?.$snoozed) await jmapOk(mb, [["Email/set", { update: { [row.email_id]: { keywords } } }]])115    return "elsewhere"116  }117  if (unread) delete keywords.$seen118  const fl = await folders(mb, true)119  let target = row.origin_folder_ids.filter((id) => fl.some((f) => f.id === id))120  if (!target.length) target = fl.filter((f) => f.role === "inbox").map((f) => f.id).slice(0, 1)121  if (!target.length) throw new Error("no inbox folder")122  const [r] = await jmapOk(mb, [["Email/set", { update: { [row.email_id]: { mailboxIds: Object.fromEntries(target.map((t) => [t, true])), keywords } } }]])123  if (r.notUpdated?.[row.email_id]) throw new Error(`Email/set: ${String(r.notUpdated[row.email_id]?.type ?? "notUpdated")}`)124  return "moved"125}126127/** Échéances arrivées : bail de 2 minutes par ligne ; l'état final et la notification sont écrits dans la même transaction. */128async function wakeDue() {129  const rows = (await sql`update snoozes set locked_until = now() + interval '2 minutes', attempts = attempts + 1130    where id in (select id from snoozes where status = 'active' and until <= now() and (locked_until is null or locked_until < now()) order by until limit 20 for update skip locked)131    returning *`) as unknown as SnoozeRow[]132  for (const row of rows) {133    try {134      const res = await wake(row, true)135      const notify = res === "moved" && (await canStillRead(row.user_id, row.mailbox_id))136      await sql.begin(async (tx) => {137        const done = await tx`update snoozes set status = ${res === "missing" ? "missing" : "done"}, woken_at = now(), locked_until = null, last_error = null where id = ${row.id} and status = 'active' returning 1`138        if (done.length && notify) await enqueueUserPush(tx as unknown as Sql, row.user_id, {139          kind: "snooze", title: row.sender?.name || row.sender?.email || "", body: row.subject, mailboxId: row.mailbox_id, emailId: row.email_id, threadId: row.thread_id ?? undefined, dedup: row.id, category: "MAIL_REMINDER",140        })141      })142    } catch (e) {143      // Serveur de courrier indisponible : le bail sert de délai, allongé à chaque tentative (10 minutes au plus).144      await sql`update snoozes set locked_until = now() + make_interval(secs => ${Math.min(600, 15 * row.attempts)}), last_error = ${String((e as Error).message ?? e).slice(0, 200)} where id = ${row.id} and status = 'active'`145    }146  }147}148149// ------- rappels150/** Crée un rappel de suivi sur un message existant. L'interlocuteur est le destinataire si le message vient de l'utilisateur, sinon l'expéditeur. */151export async function createReminder(userId: string, input: { mailboxId: string; emailId: string; dueAt: Date; onlyIfNoReply?: boolean; note?: string }): Promise<{ id: string }> {152  const mb = await userMailbox(userId, input.mailboxId)153  const [g] = await jmapOk(mb, [["Email/get", { ids: [input.emailId], properties: ["threadId", "subject", "from", "to"] }]])154  const e = (g.list as Record<string, any>[])[0]155  if (!e) throw bad("not_found", 404)156  const own = await ownAddresses(userId, mb.id)157  const from = (e.from ?? [])[0] as { name?: string; email?: string } | undefined158  const mine = !!from?.email && own.has(from.email.toLowerCase())159  const counterpart = partyOf(mine ? (e.to ?? [])[0] : from)160  // Le fil tel qu'il est maintenant : « une réponse » sera un message qui n'y figure pas encore (aucune comparaison d'horloges).161  const known = await threadEmailIds(mb, e.threadId ?? null)162  const [row] = await sql`insert into reminders (user_id, mailbox_id, email_id, thread_id, subject, counterpart, due_at, only_if_no_reply, thread_email_ids, note)163    values (${userId}, ${mb.id}, ${e.id}, ${e.threadId ?? null}, ${String(e.subject ?? "").slice(0, 500)}, ${sql.json(counterpart as never)}, ${input.dueAt}, ${!!input.onlyIfNoReply}, ${[...new Set([e.id as string, ...known])]}, ${input.note?.slice(0, 500) || null})164    returning id`165  return { id: row.id as string }166}167168async function threadEmailIds(mb: Mbx, threadId: string | null): Promise<string[]> {169  if (!threadId) return []170  const [t] = await jmapOk(mb, [["Thread/get", { ids: [threadId] }]])171  return ((t.list as { emailIds?: string[] }[])[0]?.emailIds) ?? []172}173/** Le fil a-t-il reçu, depuis la création du rappel, un message d'un autre que l'utilisateur ? */174async function repliedByOther(mb: Mbx, row: ReminderRow): Promise<boolean> {175  const before = new Set([row.email_id, ...(row.thread_email_ids ?? [])])176  const ids = (await threadEmailIds(mb, row.thread_id)).filter((id) => !before.has(id))177  if (!ids.length) return false178  const [g] = await jmapOk(mb, [["Email/get", { ids, properties: ["from", "keywords"] }]])179  const own = await ownAddresses(row.user_id, mb.id)180  return (g.list as Record<string, any>[]).some((m) => !m.keywords?.$draft && (m.from ?? []).some((f: { email?: string }) => !!f.email && !own.has(f.email.toLowerCase())))181}182183async function fireDue() {184  const rows = (await sql`update reminders set locked_until = now() + interval '2 minutes', attempts = attempts + 1185    where id in (select id from reminders where status = 'pending' and due_at <= now() and (locked_until is null or locked_until < now()) order by due_at limit 20 for update skip locked)186    returning *`) as unknown as ReminderRow[]187  for (const row of rows) {188    try {189      const mb = await mailboxById(row.mailbox_id)190      const close = (status: string, note: string | null) => sql`update reminders set status = ${status}, locked_until = null, last_error = ${note} where id = ${row.id} and status = 'pending'`191      if (!mb) { await close("cancelled", "mailbox removed"); continue }192      const [g] = await jmapOk(mb, [["Email/get", { ids: [row.email_id], properties: ["keywords"] }]])193      if (!(g.list as unknown[]).length) { await close("cancelled", "message deleted"); continue }194      if (row.only_if_no_reply && (await repliedByOther(mb, row))) { await close("resolved", null); continue }195      await jmapOk(mb, [["Email/set", { update: { [row.email_id]: { "keywords/$followup": true } } }]])196      const notify = await canStillRead(row.user_id, row.mailbox_id)197      await sql.begin(async (tx) => {198        const done = await tx`update reminders set status = 'due', fired_at = now(), locked_until = null, last_error = null where id = ${row.id} and status = 'pending' returning 1`199        if (done.length && notify) await enqueueUserPush(tx as unknown as Sql, row.user_id, {200          kind: "reminder", title: row.counterpart?.name || row.counterpart?.email || "", body: row.note || row.subject, mailboxId: row.mailbox_id, emailId: row.email_id, threadId: row.thread_id ?? undefined, dedup: `${row.id}:${new Date(row.due_at).getTime()}`, category: "MAIL_REMINDER",201        })202      })203    } catch (e) {204      await sql`update reminders set locked_until = now() + make_interval(secs => ${Math.min(600, 15 * row.attempts)}), last_error = ${String((e as Error).message ?? e).slice(0, 200)} where id = ${row.id} and status = 'pending'`205    }206  }207}208/** Retire `$followup` quand un rappel échu est clos (au mieux : le rappel reste clos si le serveur de courrier ne répond pas). */209async function clearFollowup(r: ReminderRow) {210  const [other] = await sql`select 1 from reminders where mailbox_id = ${r.mailbox_id} and email_id = ${r.email_id} and status = 'due' and id <> ${r.id} limit 1`211  if (other) return212  const mb = await mailboxById(r.mailbox_id)213  if (mb) await setKeyword(mb, r.email_id, "$followup", false).catch(() => {})214}215216// ------- routes217export function snoozeRoutes(app: FastifyInstance) {218  app.post("/api/next/snoozes", async (req) => {219    const a = await nextUser(req)220    const b = parse(z.object({ mailbox_id: zUuid, email_ids: z.array(zEmailId).min(1).max(200), until: zWhen }), req.body)221    future(b.until, "until")222    const done = await snoozeMessages(a.userId, b.mailbox_id, b.email_ids, b.until)223    if (!done.length) throw bad("not_found", 404)224    const rows = (await sql`select * from snoozes where id = any(${done.map((d) => d.id)}::uuid[]) order by created_at, id`) as unknown as SnoozeRow[]225    return { data: rows.map(snoozeOut) }226  })227228  app.get("/api/next/snoozes", async (req) => {229    const a = await nextUser(req)230    const q = parse(z.object({ status: z.enum(["active", "done", "cancelled", "missing"]).optional() }), req.query)231    const rows = (await sql`select * from snoozes where user_id = ${a.userId} ${q.status ? sql`and status = ${q.status}` : sql``} order by until, id limit 1000`) as unknown as SnoozeRow[]232    return { data: rows.map(snoozeOut) }233  })234235  app.patch("/api/next/snoozes/:id", async (req) => {236    const a = await nextUser(req)237    const id = idParam(req)238    const b = parse(z.object({ until: zWhen }), req.body)239    future(b.until, "until")240    const [row] = await sql`update snoozes set until = ${b.until}, attempts = 0, last_error = null where id = ${id} and user_id = ${a.userId} and status = 'active' returning *`241    if (!row) {242      const [any] = await sql`select 1 from snoozes where id = ${id} and user_id = ${a.userId}`243      throw any ? bad("not_active", 409, "This snooze is no longer active") : bad("not_found", 404)244    }245    return snoozeOut(row as unknown as SnoozeRow)246  })247248  // Réveil immédiat : le message retourne à sa place sans redevenir non lu ni déclencher de notification.249  app.delete("/api/next/snoozes/:id", async (req) => {250    const a = await nextUser(req)251    const id = idParam(req)252    const [row] = (await sql`select * from snoozes where id = ${id} and user_id = ${a.userId}`) as unknown as SnoozeRow[]253    if (!row) throw bad("not_found", 404)254    if (row.status !== "active") return { ok: true, status: row.status }255    // Pas de bail ici : si le travailleur réveille le même message au même instant, le second passage le trouve déjà256    // sorti de « Snoozed » et ne fait rien ; l'état final est gardé par `status = 'active'`.257    const res = await wake(row, false)258    const status = res === "missing" ? "missing" : "cancelled"259    const r = await sql`update snoozes set status = ${status}, woken_at = now(), locked_until = null where id = ${id} and status = 'active' returning 1`260    return { ok: true, status: r.length ? status : ((await sql`select status from snoozes where id = ${id}`)[0]?.status as string) }261  })262263  app.post("/api/next/reminders", async (req) => {264    const a = await nextUser(req)265    const b = parse(z.object({ mailbox_id: zUuid, email_id: zEmailId, due_at: zWhen, only_if_no_reply: z.boolean().optional(), note: zNote.optional() }), req.body)266    future(b.due_at, "due_at")267    const { id } = await createReminder(a.userId, { mailboxId: b.mailbox_id, emailId: b.email_id, dueAt: b.due_at, onlyIfNoReply: b.only_if_no_reply, note: b.note })268    const [row] = await sql`select * from reminders where id = ${id}`269    return reminderOut(row as unknown as ReminderRow)270  })271272  app.get("/api/next/reminders", async (req) => {273    const a = await nextUser(req)274    const q = parse(z.object({ status: z.enum(["pending", "due", "done", "resolved", "cancelled"]).optional() }), req.query)275    const rows = (await sql`select * from reminders where user_id = ${a.userId} ${q.status ? sql`and status = ${q.status}` : sql``} order by due_at, id limit 1000`) as unknown as ReminderRow[]276    return { data: rows.map(reminderOut) }277  })278279  app.patch("/api/next/reminders/:id", async (req) => {280    const a = await nextUser(req)281    const id = idParam(req)282    const b = parse(z.object({ due_at: zWhen.optional(), note: zNote.nullable().optional(), status: z.literal("done").optional() }), req.body)283    const raw = (req.body ?? {}) as Record<string, unknown>284    const [cur] = (await sql`select * from reminders where id = ${id} and user_id = ${a.userId}`) as unknown as ReminderRow[]285    if (!cur) throw bad("not_found", 404)286    if (!["pending", "due"].includes(cur.status)) throw bad("not_active", 409, "This reminder is closed")287    const done = "status" in raw && b.status === "done"288    const rearm = !done && "due_at" in raw && b.due_at !== undefined289    if (rearm) future(b.due_at!, "due_at")290    // Seules les clés présentes sont appliquées ; une nouvelle échéance réarme un rappel déjà échu.291    const [row] = await sql`update reminders set292        note = ${"note" in raw && b.note !== undefined ? (b.note || null) : cur.note},293        due_at = ${rearm ? b.due_at! : cur.due_at},294        status = ${done ? "done" : rearm ? "pending" : cur.status},295        fired_at = ${rearm ? null : cur.fired_at}, attempts = ${rearm ? 0 : cur.attempts}, locked_until = ${rearm || done ? null : sql`locked_until`}296      where id = ${id} and status in ('pending','due') returning *`297    if (!row) throw bad("not_active", 409, "This reminder is closed")298    if (cur.status === "due" && (done || rearm)) await clearFollowup(cur)299    return reminderOut(row as unknown as ReminderRow)300  })301302  app.delete("/api/next/reminders/:id", async (req) => {303    const a = await nextUser(req)304    const id = idParam(req)305    const [cur] = (await sql`select * from reminders where id = ${id} and user_id = ${a.userId}`) as unknown as ReminderRow[]306    if (!cur) throw bad("not_found", 404)307    const r = await sql`update reminders set status = 'cancelled', locked_until = null where id = ${id} and status in ('pending','due') returning 1`308    if (r.length && cur.status === "due") await clearFollowup(cur)309    return { ok: true, status: r.length ? "cancelled" : cur.status }310  })311}312313export function snoozeWorkers(): NextWorker[] {314  return [315    { name: "snooze waker", intervalMs: config.workerTickMs, run: wakeDue },316    { name: "reminder evaluator", intervalMs: config.workerTickMs, run: fireDue },317  ]318}319
Files main
Menu

Theme