diff --git a/docs/dev/GLOSSARY.md b/docs/dev/GLOSSARY.md index 69cc0cc29..125a95fb3 100644 --- a/docs/dev/GLOSSARY.md +++ b/docs/dev/GLOSSARY.md @@ -127,9 +127,9 @@ email itself carries (a part, schema.org markup, list headers), never by an addr | `personal` | a person writing, to the owner or to a few people | primary, direct | | `other` | a program's mail no rule above names | unknown | -A sorting rule decides before these: the first scope that has a rule wins (one mail; a List-Id or a subject pattern; an -address; a domain), and within a scope the owner's rule beats the program's and the newest wins. A domain rule may say -it beats the address rules. Addresses match whole and domains on a label boundary: `ann@` never matches `joann@`. A +A sorting rule decides before these. Every rule of the owner's comes before every rule of the program's, whatever its +scope. Within one author the first scope that has a rule wins (one mail; a List-Id or a subject pattern; an address; a +domain), and within a scope the newest wins. A domain rule may say it beats the same author's address rules. Addresses match whole and domains on a label boundary: `ann@` never matches `joann@`. A domain rule on a free-mail or throwaway domain (`gmail.com`) is the owner's only and is set only after a dry run. ## Output keys diff --git a/docs/storage/schema.md b/docs/storage/schema.md index 66bf7b408..107fbc3a8 100644 --- a/docs/storage/schema.md +++ b/docs/storage/schema.md @@ -841,7 +841,7 @@ A mail rule of one account: conditions an email must match, and what to do with ### `mail_sort_rules` -A sorting rule over mail, the owner's or the program's: what one mail, a List-Id, a subject pattern, an address or a registrable domain is. The first scope that matches wins in that order, then the header classifier; within a scope the owner's rule beats the program's and the newest wins. Not `mail_rules`, which decides how one account's sync stores mail. +A sorting rule over mail, the owner's or the program's: what one mail, a List-Id, a subject pattern, an address or a registrable domain is. Every owner's rule comes before every program's; within one author the first scope that matches wins in that order, and within a scope the newest; then the header classifier. Not `mail_rules`, which decides how one account's sync stores mail. | Column | Type | Constraints | References | Meaning | |---|---|---|---|---| @@ -865,7 +865,7 @@ A sorting rule over mail, the owner's or the program's: what one mail, a List-Id ### `mail_sort_effects` -What a sorting rule did to one sender identity beyond its mail types: the sender moved to a bot or a person, or its address filed under an organization. A removal of the rule puts back `before`. A trigger drops an identity's rows with it. +What a sorting rule did to one sender identity beyond its mail types: the sender moved to a bot or a person, or its address filed under an organization. A removal of the rule puts back `before`, author included, unless the sender moved since. A trigger drops an identity's rows with it. | Column | Type | Constraints | References | Meaning | |---|---|---|---|---| @@ -873,7 +873,7 @@ What a sorting rule did to one sender identity beyond its mail types: the sender | `rule_id` | integer | not null | | the `mail_sort_rules` row | | `identity_id` | integer | not null | | no foreign key, as the bot tables: an older build purging an account does not know this table | | `action` | text | not null | | `sender` or `organization` | -| `before` | text | | | `person:` or `sender-bot:` it was held by; for `organization`, `held` when it already was | +| `before` | text | | | `person:` or `sender-bot:` it was held by, then who put it there: `sender-bot:4 rules`, `person:9 owner`; for `organization`, `held` when it already was | | `after` | text | | | where the rule put it; equal to `before` when the rule left it, as for past senders | | `created_at` | integer | not null | | when this row was saved here | | `undone_at` | integer | | | put back when the rule was removed | diff --git a/scripts/schema/mail-sorting.mjs b/scripts/schema/mail-sorting.mjs index cfee29f21..68b30322b 100644 --- a/scripts/schema/mail-sorting.mjs +++ b/scripts/schema/mail-sorting.mjs @@ -2,7 +2,7 @@ import { c, id, ts } from "./columns.mjs" const mailSortRulesTable = { name: "mail_sort_rules", - doc: "A sorting rule over mail, the owner's or the program's: what one mail, a List-Id, a subject pattern, an address or a registrable domain is. The first scope that matches wins in that order, then the header classifier; within a scope the owner's rule beats the program's and the newest wins. Not `mail_rules`, which decides how one account's sync stores mail.", + doc: "A sorting rule over mail, the owner's or the program's: what one mail, a List-Id, a subject pattern, an address or a registrable domain is. Every owner's rule comes before every program's; within one author the first scope that matches wins in that order, and within a scope the newest; then the header classifier. Not `mail_rules`, which decides how one account's sync stores mail.", cols: [ id(), c("scope", "text", { notnull: true, note: "`mail`, `list`, `subject`, `address` or `domain`" }), @@ -36,7 +36,7 @@ const mailSortRulesTable = { const mailSortEffectsTable = { name: "mail_sort_effects", - doc: "What a sorting rule did to one sender identity beyond its mail types: the sender moved to a bot or a person, or its address filed under an organization. A removal of the rule puts back `before`. A trigger drops an identity's rows with it.", + doc: "What a sorting rule did to one sender identity beyond its mail types: the sender moved to a bot or a person, or its address filed under an organization. A removal of the rule puts back `before`, author included, unless the sender moved since. A trigger drops an identity's rows with it.", cols: [ id(), c("rule_id", "integer", { notnull: true, note: "the `mail_sort_rules` row" }), @@ -46,7 +46,7 @@ const mailSortEffectsTable = { }), c("action", "text", { notnull: true, note: "`sender` or `organization`" }), c("before", "text", { - note: "`person:` or `sender-bot:` it was held by; for `organization`, `held` when it already was", + note: "`person:` or `sender-bot:` it was held by, then who put it there: `sender-bot:4 rules`, `person:9 owner`; for `organization`, `held` when it already was", }), c("after", "text", { note: "where the rule put it; equal to `before` when the rule left it, as for past senders" }), c("created_at", "integer", { notnull: true }), diff --git a/src/mail/sort-rules.test.ts b/src/mail/sort-rules.test.ts index e56d0567c..d6c460e5c 100644 --- a/src/mail/sort-rules.test.ts +++ b/src/mail/sort-rules.test.ts @@ -34,14 +34,28 @@ describe("which sorting rule decides a mail", () => { expect(winner(all, mail("news@mail.shop.example"))).toBe(domain.id) }) - it("puts the owner's rule over the program's within a scope, then the newest", () => { + it("puts every owner's rule over every program's, at any scope, then the newest", () => { const owner = rule("address", "ann@shop.example") const program = rule("address", "ann@shop.example", { author: "program" }) const newer = rule("address", "ann@shop.example") expect(winner([owner, program], mail("ann@shop.example"))).toBe(owner.id) expect(winner([owner, program, newer], mail("ann@shop.example"))).toBe(newer.id) const programMail = rule("mail", "1", { author: "program" }) - expect(winner([newer, programMail], mail("ann@shop.example"))).toBe(programMail.id) + const programList = rule("list", "deals.shop.example", { author: "program" }) + const ownerDomain = rule("domain", "shop.example") + expect(winner([newer, programMail], mail("ann@shop.example"))).toBe(newer.id) + expect( + winner([ownerDomain, programMail, programList], mail("bob@shop.example", { list: "deals.shop.example" })), + ).toBe(ownerDomain.id) + expect(winner([programMail, programList], mail("bob@shop.example", { list: "deals.shop.example" }))).toBe( + programMail.id, + ) + }) + + it("lets a program's rule at a subdomain lose to the owner's at the domain", () => { + const program = rule("domain", "mail.shop.example", { author: "program" }) + const owner = rule("domain", "shop.example") + expect(winner([program, owner], mail("news@mail.shop.example"))).toBe(owner.id) }) it("lets a domain rule beat the address rules only when it says so", () => { diff --git a/src/mail/sort-rules.ts b/src/mail/sort-rules.ts index 82ae948be..96a9ec316 100644 --- a/src/mail/sort-rules.ts +++ b/src/mail/sort-rules.ts @@ -50,44 +50,47 @@ const suffixesOf = (host: string): string[] => { return labels.slice(0, -1).map((_, at) => labels.slice(at).join(".")) } -/** The owner's rule first, then the newest. */ -const before = (a: SortRuleFacts, b: SortRuleFacts) => - (a.author === "owner" ? 0 : 1) - (b.author === "owner" ? 0 : 1) || b.createdAt - a.createdAt || b.id - a.id +const newestFirst = (a: SortRuleFacts, b: SortRuleFacts) => b.createdAt - a.createdAt || b.id - a.id -/** Rules filed by what they name, each list in the order a match takes them. @experimental */ -export interface SortIndex { +/** One author's rules filed by what they name, each list newest first. */ +interface AuthorIndex { byKey: Map subjects: R[] +} + +/** Rules filed by author, then by what they name. @experimental */ +export interface SortIndex { + owner: AuthorIndex + program: AuthorIndex size: number } const keyOf = (scope: SortScope, value: string) => `${scope}\u0000${value}` -/** @experimental */ -export const sortIndexOf = (rules: readonly R[]): SortIndex => { +const authorIndexOf = (rules: readonly R[]): AuthorIndex => { const byKey = new Map() const subjects: R[] = [] for (const rule of rules) { if (rule.scope === "subject") subjects.push(rule) else byKey.set(keyOf(rule.scope, rule.value), [...(byKey.get(keyOf(rule.scope, rule.value)) ?? []), rule]) } - for (const list of byKey.values()) list.sort(before) - return { byKey, subjects: subjects.sort(before), size: rules.length } + for (const list of byKey.values()) list.sort(newestFirst) + return { byKey, subjects: subjects.sort(newestFirst) } } +/** @experimental */ +export const sortIndexOf = (rules: readonly R[]): SortIndex => ({ + owner: authorIndexOf(rules.filter((rule) => rule.author === "owner")), + program: authorIndexOf(rules.filter((rule) => rule.author !== "owner")), + size: rules.length, +}) + const applies = (rule: SortRuleFacts, mail: SortedMail) => rule.past || (mail.at !== null && mail.at >= rule.createdAt) const first = (rules: readonly R[], mail: SortedMail): R | undefined => rules.find((rule) => applies(rule, mail)) -/** - * The rule that decides this email, the first scope that has one: the mail, its List-Id or a subject pattern, its - * address, its domain. Within a scope the owner's rule beats the program's and the newest wins. A domain rule marked - * `overAddresses` beats the address rules. Addresses match whole and domains on a label boundary, so `ann@` never - * matches `joann@` and `shop.example` never matches `myshop.example`. @experimental - */ -export const sortRuleFor = (index: SortIndex, mail: SortedMail): R | undefined => { - if (index.size === 0) return undefined +const ruleOfAuthor = (index: AuthorIndex, mail: SortedMail): R | undefined => { const at = (scope: SortScope, value: string | null) => value === null ? undefined : first(index.byKey.get(keyOf(scope, value)) ?? [], mail) const own = at("mail", String(mail.id)) @@ -102,7 +105,7 @@ export const sortRuleFor = (index: SortIndex, mail: mail, ), ].filter((rule): rule is R => rule !== undefined) - if (second.length > 0) return second.sort(before)[0] + if (second.length > 0) return second.sort(newestFirst)[0] if (mail.from === null || !mail.from.includes("@")) return undefined const domain = suffixesOf(hostOf(mail.from)) .map((host) => at("domain", host)) @@ -111,6 +114,16 @@ export const sortRuleFor = (index: SortIndex, mail: return at("address", mail.from) ?? domain } +/** + * The rule that decides this email. Every owner's rule comes before every program's, whatever its scope: the owner's + * choice always wins. Within one author the first scope that has a rule wins: the mail, its List-Id or a subject + * pattern, its address, its domain; within a scope the newest wins. A domain rule marked `overAddresses` beats the + * same author's address rules. Addresses match whole and domains on a label boundary, so `ann@` never matches `joann@` + * and `shop.example` never matches `myshop.example`. @experimental + */ +export const sortRuleFor = (index: SortIndex, mail: SortedMail): R | undefined => + index.size === 0 ? undefined : (ruleOfAuthor(index.owner, mail) ?? ruleOfAuthor(index.program, mail)) + /** Whether a scope is more specific than another. @experimental */ export const narrower = (a: SortScope, b: SortScope): boolean => LEVEL[a] < LEVEL[b] diff --git a/src/store/mail-sorting.test.ts b/src/store/mail-sorting.test.ts index f8ef9781a..a08ff0a1e 100644 --- a/src/store/mail-sorting.test.ts +++ b/src/store/mail-sorting.test.ts @@ -100,7 +100,7 @@ describe("mail sorting rules", () => { }) }) - it("orders scopes and authors: mail over address over domain, the owner over the program", async () => { + it("orders scopes and authors: every owner's rule over every program's, then mail, address, domain", async () => { const { store } = await opened([ email("orders@shop.example", "Receipt 1"), email("orders@shop.example", "Receipt 2"), @@ -123,6 +123,11 @@ describe("mail sorting rules", () => { "owner", ) expect(program.preview.retyped).toBe(0) + const programMail = await store.mail.sorting.add( + { scope: "mail", value: await idOf(store, "Weekly"), mailType: "bill", applyTo: "all" }, + { bot: "sorter", reason: "learned" }, + ) + expect(programMail.preview.retyped).toBe(0) expect(await types(store)).toEqual({ "Receipt 1": `order rule:${address.rule?.id}`, "Receipt 2": `shipping rule:${one.rule?.id}`, @@ -218,6 +223,70 @@ describe("mail sorting rules", () => { expect(person.rule?.sender).toBe("person") }) + it("puts a removed rule's senders back with the author they had, so the program sorts them again", async () => { + const { store, db } = await opened([ + email("noreply@shop.ru", "Receipt"), + email("ann@shop.ru", "Hi from Ann"), + email("bo@shop.ru", "Hi from Bo"), + ]) + await store.people.list({ limit: 100, kind: "all" }) + const bots = async () => + Object.fromEntries( + (await store.people.listBots({ limit: 10 })).items.flatMap(({ identities, author }) => + identities.map(({ id }) => [id, author]), + ), + ) + expect(await bots()).toEqual({ "noreply@shop.ru": "rules" }) + await store.people.moveToPerson({ provider: "email", id: "bo@shop.ru" }, "owner") + const lastMove = (address: string) => + db + .prepare( + "SELECT m.author, m.to_bot_id IS NOT NULL AS bot FROM sender_bot_moves m JOIN identities i ON " + + "i.id = m.identity_id WHERE i.external_id = ? ORDER BY m.id DESC LIMIT 1", + ) + .get(address) + + const person = await store.mail.sorting.add( + { scope: "address", value: "noreply@shop.ru", sender: "person", applyTo: "all" }, + "owner", + ) + const bot = await store.mail.sorting.add( + { scope: "address", value: "ann@shop.ru", sender: "bot", applyTo: "all" }, + "owner", + ) + const bo = await store.mail.sorting.add( + { scope: "address", value: "bo@shop.ru", sender: "bot", applyTo: "all" }, + "owner", + ) + expect(await bots()).toEqual({ "ann@shop.ru": "owner", "bo@shop.ru": "owner" }) + + expect(await store.mail.sorting.undo("owner")).toMatchObject({ undid: "add", rule: { id: bo.rule?.id } }) + await store.mail.sorting.remove(person.rule?.id as number, "owner") + await store.mail.sorting.remove(bot.rule?.id as number, "owner") + expect(await bots()).toEqual({ "noreply@shop.ru": "rules" }) + expect(lastMove("noreply@shop.ru")).toEqual({ author: "rules", bot: 1 }) + expect(lastMove("ann@shop.ru")).toEqual({ author: "rules", bot: 0 }) + expect(lastMove("bo@shop.ru")).toEqual({ author: "owner", bot: 0 }) + + db.prepare("UPDATE persons SET kind = NULL").run() + await store.people.list({ limit: 100, kind: "all" }) + expect(await bots()).toEqual({ "noreply@shop.ru": "rules" }) + }) + + it("puts more senders back than one write takes, and finishes a stopped put-back on the next removal", async () => { + const { store, db } = await opened(Array.from({ length: 120 }, (_, i) => email(`desk${i}@bigshop.ru`, `Note ${i}`))) + const held = () => Number(db.prepare("SELECT count(*) AS n FROM sender_bot_identities").get()?.n) + const { rule } = await store.mail.sorting.add( + { scope: "domain", value: "bigshop.ru", sender: "bot", applyTo: "all" }, + "owner", + ) + expect(held()).toBe(120) + db.prepare("UPDATE mail_sort_rules SET removed_at = 1 WHERE id = ?").run(rule?.id as number) + expect(held()).toBe(120) + await store.mail.sorting.remove(rule?.id as number, "owner") + expect(held()).toBe(0) + }) + it("files a sender under an organization and takes it out again", async () => { const { store, db } = await opened([email("orders@shop.example", "Receipt")]) const organization = Number( diff --git a/src/store/sqlite/mail-sorting.ts b/src/store/sqlite/mail-sorting.ts index 3a0e19f9b..9859e1929 100644 --- a/src/store/sqlite/mail-sorting.ts +++ b/src/store/sqlite/mail-sorting.ts @@ -19,10 +19,11 @@ import { import type { Decider } from "../decisions.js" import type { CacheDatabase } from "../driver.js" import { holdAddress } from "./address-organization.js" +import { currentPerson } from "./merged-persons.js" import type { StoreContext } from "./open.js" -import { moveToBot, moveToPerson } from "./sender-bots.js" +import { holdingAuthorOf, moveToBot, moveToPerson, putBack } from "./sender-bots.js" import { LIST_ID } from "./sender-signals.js" -import { read, write } from "./transaction.js" +import { letWaitersIn, read, write } from "./transaction.js" /** One sorting rule. @experimental */ export interface SortRule { @@ -218,6 +219,14 @@ const holderOf = (database: CacheDatabase, identity: number): string | null => { return person === undefined ? null : `person:${person.person_id}` } +/** Where an identity sits now and who put it there, as an effect's `before` keeps it: `sender-bot:4 rules`. */ +const heldOf = (database: CacheDatabase, identity: number): string | null => { + const holder = holderOf(database, identity) + return holder === null ? null : `${holder} ${holdingAuthorOf(database, identity)}` +} + +const holderIn = (held: string | null): string | null => (held === null ? null : (held.split(" ")[0] ?? null)) + const isWhere = (holder: string | null, sender: "bot" | "person") => holder?.startsWith(sender === "bot" ? SENDER_BOT_PREFIX : "person:") === true @@ -287,7 +296,7 @@ export const settleSenders = (context: StoreContext, identities?: readonly numbe const at = context.now() const mover = sortRuleFor(rules.sender, mail) if (mover?.sender && !hasEffect(database, mover.id, identity, "sender")) { - const before = holderOf(database, identity) + const before = heldOf(database, identity) if (!isWhere(before, mover.sender)) moveSender(context, address, mover) recordEffect(database, { rule: mover.id, @@ -332,41 +341,65 @@ const moveSender = (context: StoreContext, address: string, rule: SortRule) => { } } -/** Puts back what a rule did to its senders, then lets the rules still live settle them. */ -const undoEffects = (context: StoreContext, rule: number): void => { +/** + * Senders per write. A move to a bot takes about 10 ms, so 100 keep one write near 1 s, far from another writer's 5 s + * wait; putting one back is cheaper, but a write's commit costs the same. + */ +const SETTLE_CHUNK = 100 + +/** Whether the sender is still where the rule put it: else the owner moved it since, and that stands. */ +const stillAfter = (database: CacheDatabase, identity: number, after: string | null): boolean => { + const now = holderOf(database, identity) + if (now === after) return true + return ( + after?.startsWith("person:") === true && + now === `person:${currentPerson(database, Number(after.slice("person:".length)))}` + ) +} + +/** + * Puts back what removed rules did to up to `SETTLE_CHUNK` senders, newest effect first, each to its holder and author + * before the rule, then lets the rules still live settle them. Answers whether more may be left. The caller holds + * the write lock. + */ +const putBackChunk = (context: StoreContext): boolean => { const { database } = context + const identities = database + .prepare( + "SELECT DISTINCT f.identity_id AS identity FROM mail_sort_effects f JOIN mail_sort_rules r ON r.id = f.rule_id " + + "WHERE r.removed_at IS NOT NULL AND f.undone_at IS NULL ORDER BY f.identity_id LIMIT ?", + ) + .all(SETTLE_CHUNK) + .map((row) => Number(row.identity)) + if (identities.length === 0) return false const effects = database .prepare( - "SELECT f.id, f.identity_id, f.action, f.before, f.after, i.external_id AS address FROM mail_sort_effects f " + - "JOIN identities i ON i.id = f.identity_id WHERE f.rule_id = ? AND f.undone_at IS NULL ORDER BY f.id DESC", + "SELECT f.id, f.identity_id, f.action, f.before, f.after FROM mail_sort_effects f " + + "JOIN mail_sort_rules r ON r.id = f.rule_id WHERE r.removed_at IS NOT NULL AND f.undone_at IS NULL " + + "AND f.identity_id IN (SELECT value FROM json_each(?)) ORDER BY f.id DESC", ) - .all(rule) + .all(JSON.stringify(identities)) const at = context.now() for (const effect of effects) { const identity = Number(effect.identity_id) - const subject = { provider: "email" as const, id: String(effect.address) } const before = effect.before == null ? null : String(effect.before) - if (effect.action === "sender" && before !== effect.after && before !== null) { - const now = holderOf(database, identity) - if (before.startsWith("person:") && !isWhere(now, "person")) moveToPerson(context, subject, { reason: "undo" }) - if (before.startsWith(SENDER_BOT_PREFIX) && !isWhere(now, "bot")) - moveToBot(context, subject, { - reason: "undo", - ...(database - .prepare("SELECT 1 FROM sender_bots WHERE id = ?") - .get(Number(before.slice(SENDER_BOT_PREFIX.length))) - ? { bot: before } - : {}), - }) - } + const after = effect.after == null ? null : String(effect.after) + const holder = holderIn(before) + if (effect.action === "sender" && holder !== null && holder !== after && stillAfter(database, identity, after)) + putBack(context, identity, holder, before?.endsWith(" owner") ? "owner" : "rules") if (effect.action === "organization" && before === null) database .prepare("DELETE FROM organization_identities WHERE identity_id = ? AND organization_id = ? AND method = ?") - .run(identity, Number(String(effect.after).slice("organization:".length)), SORT_METHOD) + .run(identity, Number(String(after).slice("organization:".length)), SORT_METHOD) database.prepare("UPDATE mail_sort_effects SET undone_at = ? WHERE id = ?").run(at, Number(effect.id)) } - const identities = [...new Set(effects.map((effect) => Number(effect.identity_id)))] - if (identities.length > 0) settleSenders(context, identities) + settleSenders(context, identities) + return identities.length === SETTLE_CHUNK +} + +/** Each removed rule's senders put back a write at a time; a stopped run resumes on the next change of rules. */ +const putBackInChunks = (context: StoreContext) => { + while (write(context.database, () => putBackChunk(context))) letWaitersIn() } const clearTypes = (database: CacheDatabase, ids: readonly number[]) => @@ -526,12 +559,13 @@ const applyRule = (context: StoreContext, rule: SortRule): number[] => { if (!rule.past) for (const { identity } of sendersOf(database, identities)) { const holder = holderOf(database, identity) + const held = heldOf(database, identity) for (const action of [...(rule.sender ? ["sender"] : []), ...(rule.organization ? ["organization"] : [])]) recordEffect(database, { rule: rule.id, identity, action, - before: action === "sender" ? holder : "held", + before: action === "sender" ? held : "held", after: action === "sender" ? holder : "held", at: context.now(), }) @@ -539,13 +573,12 @@ const applyRule = (context: StoreContext, rule: SortRule): number[] => { return identities } -/** Each move takes about 10 ms: 100 per write keeps another writer's 5 s wait for the lock far away. */ -const SETTLE_CHUNK = 100 - /** Settles senders a write at a time; a sender already settled is skipped, so a stopped run resumes on the next. */ const settleInChunks = (context: StoreContext, identities: readonly number[]) => { - for (let at = 0; at < identities.length; at += SETTLE_CHUNK) + for (let at = 0; at < identities.length; at += SETTLE_CHUNK) { + if (at > 0) letWaitersIn() write(context.database, () => settleSenders(context, identities.slice(at, at + SETTLE_CHUNK))) + } } /** A change's time, later than every change before it, so undo takes changes back in order within one millisecond. */ @@ -562,7 +595,6 @@ const takeOut = (context: StoreContext, rule: SortRule, undone: boolean) => { .run(at, at, undone ? at : null, rule.id) const removed = ruleById(context.database, rule.id) clearRuleTypes(context.database, removed) - undoEffects(context, rule.id) return removed } @@ -657,14 +689,17 @@ export const mailSortingOver = (context: StoreContext): MailSorting => { settleInChunks(context, identities) return result }, - remove: async (id, by) => - write(database, () => { + remove: async (id, by) => { + const removed = write(database, () => { const rule = ruleById(database, id) if (by !== "owner" && (rule.author !== "program" || rule.decidedBy !== by.bot)) fail("a program removes only the rules it made", "mail-sort.owner-only") if (rule.removedAt !== null) return rule return takeOut(context, rule, false) - }), + }) + putBackInChunks(context) + return removed + }, undo: async (by) => { const { identities, undone } = write(database, () => { ownerOnly(by, "undoes a sorting change") @@ -685,11 +720,12 @@ export const mailSortingOver = (context: StoreContext): MailSorting => { const back = ruleById(database, rule.id) return { identities: applyRule(context, back), undone: { undid: "remove" as const, rule: back } } }) + putBackInChunks(context) settleInChunks(context, identities) return undone }, - reset: async (sender, by) => - write(database, () => { + reset: async (sender, by) => { + const removed = write(database, () => { ownerOnly(by, "resets the manual sorting of a sender") const addresses = addressesOf(database, sender) const mails = database @@ -706,7 +742,10 @@ export const mailSortingOver = (context: StoreContext): MailSorting => { ) .all(JSON.stringify(addresses), JSON.stringify(mails)) .map((row) => takeOut(context, ruleOf(row), false)) - }), + }) + putBackInChunks(context) + return removed + }, } } diff --git a/src/store/sqlite/sender-bots.ts b/src/store/sqlite/sender-bots.ts index ec1993257..3f19acd47 100644 --- a/src/store/sqlite/sender-bots.ts +++ b/src/store/sqlite/sender-bots.ts @@ -594,3 +594,44 @@ export const moveToPerson = ( return recordOf(context, first ?? target ?? (chosen.person as number)) }) } + +/** Who put an identity where it is: its bot's author, else its last move's; `rules` when nothing moved it. */ +export const holdingAuthorOf = (database: CacheDatabase, identity: number): BotAuthor => { + const { bot } = holderOf(database, identity) + const row = + bot === undefined + ? database + .prepare("SELECT author FROM sender_bot_moves WHERE identity_id = ? ORDER BY id DESC LIMIT 1") + .get(identity) + : database.prepare("SELECT author FROM sender_bots WHERE id = ?").get(bot) + return row?.author === "owner" ? "owner" : "rules" +} + +/** + * Puts an identity back where it was held, `person:` or `sender-bot:`, under the author that put it there: a + * removed sorting rule leaves no owner's mark the owner never made, so the program may sort it again. A bot gone with + * its last identity comes back as a new one. The caller holds the write lock. + */ +export const putBack = (context: StoreContext, identity: number, holder: string, author: BotAuthor): void => { + const { database } = context + const at = context.now() + const log = { author, reason: "a mail sorting rule was removed", at } + if (holder.startsWith(SENDER_BOT_PREFIX)) { + const kept = Number(holder.slice(SENDER_BOT_PREFIX.length)) + const bot = + database.prepare("SELECT 1 FROM sender_bots WHERE id = ?").get(kept) === undefined + ? createBot(database, log) + : kept + for (const [person, gone] of intoBot(database, [identity], bot, log)) + if (identitiesOf(database, person).length > 0) renameAfterLeaving(context, person, gone) + groupByDomain(database, [{ id: bot, displayName: null, holds: true, bot: true }], at) + return + } + const person = Number(holder.slice("person:".length)) + const target = + database.prepare("SELECT 1 FROM persons WHERE id = ?").get(person) === undefined + ? undefined + : currentPerson(database, person) + outOfBot(database, [identity], target, log) + releaseDomainHolds(database, [identity]) +} diff --git a/src/store/sqlite/transaction.ts b/src/store/sqlite/transaction.ts index abb5ede55..f513370ee 100644 --- a/src/store/sqlite/transaction.ts +++ b/src/store/sqlite/transaction.ts @@ -87,6 +87,12 @@ export const writeBatch = (database: CacheDatabase, body: () => T): T => tran const BATCH_PAUSE_MS = 2 +/** + * A short pause between two writes of one loop: another process waiting for the lock tries every millisecond, and a + * loop that begins again at once leaves it a gap of microseconds, so it waits out its 5 s however short each write is. + */ +export const letWaitersIn = (): void => void Atomics.wait(pause, 0, 0, BATCH_PAUSE_MS) + const transact = (database: CacheDatabase, body: () => T, drain: boolean, beforeCommit?: () => void): T => { const connection = connectionOf(database) if (connection.reading) throw new Error("a store write cannot run inside a read") @@ -109,7 +115,7 @@ const transact = (database: CacheDatabase, body: () => T, drain: boolean, bef if (outer) committedWrites(database) // A write that had to wait has others waiting behind it, and its caller's next write would begin before they see // the lock free. Pausing only then costs an uncontended write nothing. - if (outer && (waited || !drain)) Atomics.wait(pause, 0, 0, BATCH_PAUSE_MS) + if (outer && (waited || !drain)) letWaitersIn() return result } catch (error) { rollBack(database, outer ? "ROLLBACK" : `ROLLBACK TO ${name}; RELEASE ${name}`)