Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions docs/dev/GLOSSARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions docs/storage/schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
|---|---|---|---|---|
Expand All @@ -865,15 +865,15 @@ 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 |
|---|---|---|---|---|
| `id` | integer | PK | | |
| `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:<id>` or `sender-bot:<id>` it was held by; for `organization`, `held` when it already was |
| `before` | text | | | `person:<id>` or `sender-bot:<id>` 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 |
Expand Down
6 changes: 3 additions & 3 deletions scripts/schema/mail-sorting.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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`" }),
Expand Down Expand Up @@ -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" }),
Expand All @@ -46,7 +46,7 @@ const mailSortEffectsTable = {
}),
c("action", "text", { notnull: true, note: "`sender` or `organization`" }),
c("before", "text", {
note: "`person:<id>` or `sender-bot:<id>` it was held by; for `organization`, `held` when it already was",
note: "`person:<id>` or `sender-bot:<id>` 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 }),
Expand Down
18 changes: 16 additions & 2 deletions src/mail/sort-rules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
49 changes: 31 additions & 18 deletions src/mail/sort-rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<R extends SortRuleFacts> {
/** One author's rules filed by what they name, each list newest first. */
interface AuthorIndex<R extends SortRuleFacts> {
byKey: Map<string, R[]>
subjects: R[]
}

/** Rules filed by author, then by what they name. @experimental */
export interface SortIndex<R extends SortRuleFacts> {
owner: AuthorIndex<R>
program: AuthorIndex<R>
size: number
}

const keyOf = (scope: SortScope, value: string) => `${scope}\u0000${value}`

/** @experimental */
export const sortIndexOf = <R extends SortRuleFacts>(rules: readonly R[]): SortIndex<R> => {
const authorIndexOf = <R extends SortRuleFacts>(rules: readonly R[]): AuthorIndex<R> => {
const byKey = new Map<string, R[]>()
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 = <R extends SortRuleFacts>(rules: readonly R[]): SortIndex<R> => ({
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 = <R extends SortRuleFacts>(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 = <R extends SortRuleFacts>(index: SortIndex<R>, mail: SortedMail): R | undefined => {
if (index.size === 0) return undefined
const ruleOfAuthor = <R extends SortRuleFacts>(index: AuthorIndex<R>, 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))
Expand All @@ -102,7 +105,7 @@ export const sortRuleFor = <R extends SortRuleFacts>(index: SortIndex<R>, 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))
Expand All @@ -111,6 +114,16 @@ export const sortRuleFor = <R extends SortRuleFacts>(index: SortIndex<R>, 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 = <R extends SortRuleFacts>(index: SortIndex<R>, 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]

Expand Down
71 changes: 70 additions & 1 deletion src/store/mail-sorting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand All @@ -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}`,
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading