@remit/drizzle-service 0.0.56 → 0.0.58
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { or, type SQL, sql } from "drizzle-orm";
|
|
1
|
+
import { eq, or, type SQL, sql } from "drizzle-orm";
|
|
2
2
|
import { addressTable } from "../schema/i4-address.js";
|
|
3
3
|
|
|
4
4
|
// The address search seam. A term is matched as a substring of the display name,
|
|
@@ -49,10 +49,12 @@ export const addressSearchMatch = (term: string): SQL => {
|
|
|
49
49
|
* spells out ranks above every prefix of it: a display name is free text the
|
|
50
50
|
* sender picks, and a domain somebody else registered is a prefix away from the
|
|
51
51
|
* address the reader typed, so neither may take the suggestion slot from the
|
|
52
|
-
* address that matches whole.
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
52
|
+
* address that matches whole. A term that spells out a domain whole ranks next,
|
|
53
|
+
* so `ischen.nl` reaches the domain it names before `ischen.nl.co`, which only
|
|
54
|
+
* starts with it (#829). Below that, a match at the start of a column outranks
|
|
55
|
+
* one in the middle, and within each the whole address, the local part and the
|
|
56
|
+
* display name outrank the domain they share. A mid-string match still comes
|
|
57
|
+
* back — this only decides the order.
|
|
56
58
|
*/
|
|
57
59
|
export const addressMatchRank = (term: string | undefined): SQL<number> => {
|
|
58
60
|
// Not the bare literal `0`: SQLite reads an integer literal in ORDER BY as a
|
|
@@ -60,7 +62,10 @@ export const addressMatchRank = (term: string | undefined): SQL<number> => {
|
|
|
60
62
|
if (!term) return sql<number>`cast(0 as integer)`;
|
|
61
63
|
const { leading, anywhere } = patterns(term);
|
|
62
64
|
const tiers = [
|
|
63
|
-
|
|
65
|
+
eq(addressTable.normalizedEmail, term.toLowerCase()),
|
|
66
|
+
// `domain` is stored as the envelope spelled it, so `Ischen.NL` only meets
|
|
67
|
+
// a folded term through `lower()`; `like` folds ASCII on its own.
|
|
68
|
+
sql`lower(${addressTable.domain}) = ${term.toLowerCase()}`,
|
|
64
69
|
...SEARCH_COLUMNS.map((column) => like(column, leading)),
|
|
65
70
|
...SEARCH_COLUMNS.map((column) => like(column, anywhere)),
|
|
66
71
|
];
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { after, before, describe, test } from "node:test";
|
|
3
|
+
import type { AddressFlags } from "@remit/data-ports";
|
|
4
|
+
import { createTestDb, randomId, type TestDb } from "../test-db.js";
|
|
5
|
+
import { serializeSqliteWrites } from "../tx.js";
|
|
6
|
+
import { AddressRepo } from "./i4-address.js";
|
|
7
|
+
|
|
8
|
+
const FLAG_KEYS = [
|
|
9
|
+
"trusted",
|
|
10
|
+
"blocked",
|
|
11
|
+
"muted",
|
|
12
|
+
"vip",
|
|
13
|
+
"wellknown",
|
|
14
|
+
"junkOnly",
|
|
15
|
+
"autoArchive",
|
|
16
|
+
"unsubscribed",
|
|
17
|
+
] as const;
|
|
18
|
+
|
|
19
|
+
const CONCURRENT_CALLS = 50;
|
|
20
|
+
|
|
21
|
+
describe("concurrent flag merges on one address", () => {
|
|
22
|
+
let db: TestDb;
|
|
23
|
+
let close: () => Promise<void>;
|
|
24
|
+
let repo: AddressRepo;
|
|
25
|
+
|
|
26
|
+
before(async () => {
|
|
27
|
+
({ db, close } = await createTestDb());
|
|
28
|
+
repo = new AddressRepo(serializeSqliteWrites(db) as never);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
after(async () => {
|
|
32
|
+
await close();
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const address = async () => {
|
|
36
|
+
const accountConfigId = randomId();
|
|
37
|
+
return repo.createAddress({
|
|
38
|
+
addressId: randomId(),
|
|
39
|
+
accountConfigId,
|
|
40
|
+
localPart: "sender",
|
|
41
|
+
domain: "example.com",
|
|
42
|
+
normalizedEmail: "sender@example.com",
|
|
43
|
+
normalizedCompound: "sender@example.com:sender",
|
|
44
|
+
});
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
test("fifty concurrent merges all survive", async () => {
|
|
48
|
+
const addr = await address();
|
|
49
|
+
const writtenAt = new Map<string, Set<number>>();
|
|
50
|
+
|
|
51
|
+
await Promise.all(
|
|
52
|
+
Array.from({ length: CONCURRENT_CALLS }, (_, index) => {
|
|
53
|
+
const key = FLAG_KEYS[index % FLAG_KEYS.length];
|
|
54
|
+
const setAt = 1_000 + index;
|
|
55
|
+
const stamps = writtenAt.get(key) ?? new Set<number>();
|
|
56
|
+
stamps.add(setAt);
|
|
57
|
+
writtenAt.set(key, stamps);
|
|
58
|
+
return repo.mergeFlags(addr.accountConfigId, addr.addressId, {
|
|
59
|
+
[key]: { value: true, setAt },
|
|
60
|
+
});
|
|
61
|
+
}),
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
const merged = await repo.getAddress(addr.accountConfigId, addr.addressId);
|
|
65
|
+
const flags: AddressFlags = merged.flags ?? {};
|
|
66
|
+
for (const key of FLAG_KEYS) {
|
|
67
|
+
const flag = flags[key];
|
|
68
|
+
assert.ok(flag, `${key} was lost by a concurrent merge`);
|
|
69
|
+
assert.ok(
|
|
70
|
+
writtenAt.get(key)?.has(flag.setAt),
|
|
71
|
+
`${key} holds a value no merge wrote`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
await repo.deleteAddress(addr.accountConfigId, addr.addressId);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("a concurrent merge does not resurrect a deleted flag", async () => {
|
|
79
|
+
const addr = await address();
|
|
80
|
+
await repo.mergeFlags(addr.accountConfigId, addr.addressId, {
|
|
81
|
+
muted: { value: true, setAt: 1 },
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
await Promise.all([
|
|
85
|
+
repo.mergeFlags(addr.accountConfigId, addr.addressId, { muted: null }),
|
|
86
|
+
repo.mergeFlags(addr.accountConfigId, addr.addressId, {
|
|
87
|
+
vip: { value: true, setAt: 2 },
|
|
88
|
+
}),
|
|
89
|
+
]);
|
|
90
|
+
|
|
91
|
+
const merged = await repo.getAddress(addr.accountConfigId, addr.addressId);
|
|
92
|
+
assert.equal(merged.flags?.muted, undefined, "muted must stay deleted");
|
|
93
|
+
assert.equal(merged.flags?.vip?.value, true, "vip must survive the delete");
|
|
94
|
+
|
|
95
|
+
await repo.deleteAddress(addr.accountConfigId, addr.addressId);
|
|
96
|
+
});
|
|
97
|
+
});
|
|
@@ -474,6 +474,85 @@ describe("AddressRepo", () => {
|
|
|
474
474
|
]);
|
|
475
475
|
});
|
|
476
476
|
|
|
477
|
+
test("listByAccountConfig ranks the domain a bare term names above one that only starts with it", async () => {
|
|
478
|
+
const accountConfigId = randomId();
|
|
479
|
+
const lookalike = await repo.createAddress({
|
|
480
|
+
...makeAddressInput(accountConfigId, "matthijs@ischen.nl.co"),
|
|
481
|
+
displayName: "Ischen Support",
|
|
482
|
+
normalizedCompound: "ischen support matthijs@ischen.nl.co",
|
|
483
|
+
inboundCount: 900,
|
|
484
|
+
});
|
|
485
|
+
// The envelope's own spelling: `domain` is stored unfolded.
|
|
486
|
+
const own = await repo.createAddress({
|
|
487
|
+
...makeAddressInput(accountConfigId, "matthijs@ischen.nl"),
|
|
488
|
+
domain: "Ischen.NL",
|
|
489
|
+
displayName: "Matthijs van Henten",
|
|
490
|
+
normalizedCompound: "matthijs van henten matthijs@ischen.nl",
|
|
491
|
+
inboundCount: 1,
|
|
492
|
+
});
|
|
493
|
+
|
|
494
|
+
const found = await repo.listByAccountConfig({
|
|
495
|
+
accountConfigId,
|
|
496
|
+
search: "ischen.nl",
|
|
497
|
+
});
|
|
498
|
+
assert.deepEqual(
|
|
499
|
+
found.items.map((a) => a.normalizedEmail),
|
|
500
|
+
[own.normalizedEmail, lookalike.normalizedEmail],
|
|
501
|
+
"the domain the term names leads one that registered a suffix of it",
|
|
502
|
+
);
|
|
503
|
+
|
|
504
|
+
const onlySuggestion = await repo.listByAccountConfig({
|
|
505
|
+
accountConfigId,
|
|
506
|
+
search: "ischen.nl",
|
|
507
|
+
limit: 1,
|
|
508
|
+
});
|
|
509
|
+
assert.deepEqual(
|
|
510
|
+
onlySuggestion.items.map((a) => a.normalizedEmail),
|
|
511
|
+
[own.normalizedEmail],
|
|
512
|
+
"volume on the lookalike must not take the single suggestion slot",
|
|
513
|
+
);
|
|
514
|
+
|
|
515
|
+
await repo.deleteManyAddresses(accountConfigId, [
|
|
516
|
+
lookalike.addressId,
|
|
517
|
+
own.addressId,
|
|
518
|
+
]);
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
test("listByAccountConfig keeps an address the term spells out whole above a row that only owns the domain", async () => {
|
|
522
|
+
const accountConfigId = randomId();
|
|
523
|
+
// A harvested header that carried the bare domain where an address belongs.
|
|
524
|
+
const bare = await repo.createAddress({
|
|
525
|
+
addressId: randomId(),
|
|
526
|
+
accountConfigId,
|
|
527
|
+
localPart: "ischen.nl",
|
|
528
|
+
domain: "",
|
|
529
|
+
normalizedEmail: "ischen.nl",
|
|
530
|
+
normalizedCompound: "ischen.nl",
|
|
531
|
+
displayName: "Ischen",
|
|
532
|
+
});
|
|
533
|
+
const domainOwner = await repo.createAddress({
|
|
534
|
+
...makeAddressInput(accountConfigId, "matthijs@ischen.nl"),
|
|
535
|
+
displayName: "Matthijs van Henten",
|
|
536
|
+
normalizedCompound: "matthijs van henten matthijs@ischen.nl",
|
|
537
|
+
inboundCount: 900,
|
|
538
|
+
});
|
|
539
|
+
|
|
540
|
+
const found = await repo.listByAccountConfig({
|
|
541
|
+
accountConfigId,
|
|
542
|
+
search: "ischen.nl",
|
|
543
|
+
});
|
|
544
|
+
assert.deepEqual(
|
|
545
|
+
found.items.map((a) => a.normalizedEmail),
|
|
546
|
+
[bare.normalizedEmail, domainOwner.normalizedEmail],
|
|
547
|
+
"the address that matches whole stays above the domain tier below it",
|
|
548
|
+
);
|
|
549
|
+
|
|
550
|
+
await repo.deleteManyAddresses(accountConfigId, [
|
|
551
|
+
bare.addressId,
|
|
552
|
+
domainOwner.addressId,
|
|
553
|
+
]);
|
|
554
|
+
});
|
|
555
|
+
|
|
477
556
|
test("listByAccountConfig keeps a leading display-name match above a domain that only contains the term", async () => {
|
|
478
557
|
const accountConfigId = randomId();
|
|
479
558
|
const shop = await repo.createAddress({
|
package/src/repos/i4-address.ts
CHANGED
|
@@ -32,6 +32,7 @@ import {
|
|
|
32
32
|
} from "../repair/junk-only-address.js";
|
|
33
33
|
import { addressTable } from "../schema/i4-address.js";
|
|
34
34
|
import { envelopeAddressTable } from "../schema/message-data.js";
|
|
35
|
+
import { runInTransaction } from "../tx.js";
|
|
35
36
|
import {
|
|
36
37
|
addressCorrespondence,
|
|
37
38
|
addressListable,
|
|
@@ -49,6 +50,23 @@ type AddressUpdate = Partial<{
|
|
|
49
50
|
| SQL;
|
|
50
51
|
}>;
|
|
51
52
|
|
|
53
|
+
const MERGE_FLAGS_ATTEMPTS = 8;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The stored flags exactly as they sit in the column, so a merge can guard its
|
|
57
|
+
* write on the bytes it read rather than on a re-serialization of them.
|
|
58
|
+
*/
|
|
59
|
+
const storedFlagsSql = sql<string>`cast(${addressTable.flags} as text)`;
|
|
60
|
+
|
|
61
|
+
/** A row harvested before the column existed carries `''`, not `'{}'`. */
|
|
62
|
+
const parseStoredFlags = (stored: string): AddressFlags =>
|
|
63
|
+
stored === "" ? {} : (JSON.parse(stored) as AddressFlags);
|
|
64
|
+
|
|
65
|
+
type MergeAttempt =
|
|
66
|
+
| { outcome: "merged"; address: AddressItem }
|
|
67
|
+
| { outcome: "missing" }
|
|
68
|
+
| { outcome: "contended" };
|
|
69
|
+
|
|
52
70
|
/**
|
|
53
71
|
* The stored `"<display name> <email>"` compound, folded in JavaScript exactly
|
|
54
72
|
* as message sync folds it — SQL `lower()` stops at ASCII, and the search reads
|
|
@@ -400,36 +418,77 @@ export class AddressRepo implements IAddressRepository {
|
|
|
400
418
|
return rowToAddress(row);
|
|
401
419
|
}
|
|
402
420
|
|
|
421
|
+
/**
|
|
422
|
+
* Read the flags, fold `merge` over them, and write the result back only if
|
|
423
|
+
* the column still holds the bytes the read returned. Read and write share
|
|
424
|
+
* one serialized unit, so the only writer that can slip between them is the
|
|
425
|
+
* junk-only reconcile, which runs its raw statement outside the write queue;
|
|
426
|
+
* that write fails the guard and the merge folds again over the winner
|
|
427
|
+
* instead of overwriting it. The unit never throws, so a reconcile statement
|
|
428
|
+
* landing inside its savepoint is never rolled back with it.
|
|
429
|
+
*/
|
|
430
|
+
private async mergeStoredFlags(
|
|
431
|
+
accountConfigId: string,
|
|
432
|
+
addressId: string,
|
|
433
|
+
merge: (current: AddressFlags) => AddressFlags,
|
|
434
|
+
extra: AddressUpdate = {},
|
|
435
|
+
): Promise<AddressItem> {
|
|
436
|
+
const key = and(
|
|
437
|
+
eq(addressTable.accountConfigId, accountConfigId),
|
|
438
|
+
eq(addressTable.addressId, addressId),
|
|
439
|
+
);
|
|
440
|
+
for (let attempt = 0; attempt < MERGE_FLAGS_ATTEMPTS; attempt++) {
|
|
441
|
+
const result = await runInTransaction(
|
|
442
|
+
this.db,
|
|
443
|
+
async (tx): Promise<MergeAttempt> => {
|
|
444
|
+
const [current] = await tx
|
|
445
|
+
.select({ stored: storedFlagsSql })
|
|
446
|
+
.from(addressTable)
|
|
447
|
+
.where(key);
|
|
448
|
+
if (!current) return { outcome: "missing" };
|
|
449
|
+
const [row] = await tx
|
|
450
|
+
.update(addressTable)
|
|
451
|
+
.set({
|
|
452
|
+
...extra,
|
|
453
|
+
flags: merge(parseStoredFlags(current.stored)) as never,
|
|
454
|
+
updatedAt: Date.now(),
|
|
455
|
+
})
|
|
456
|
+
.where(and(key, eq(storedFlagsSql, current.stored)))
|
|
457
|
+
.returning();
|
|
458
|
+
return row
|
|
459
|
+
? { outcome: "merged", address: rowToAddress(row) }
|
|
460
|
+
: { outcome: "contended" };
|
|
461
|
+
},
|
|
462
|
+
);
|
|
463
|
+
if (result.outcome === "merged") return result.address;
|
|
464
|
+
if (result.outcome === "missing")
|
|
465
|
+
throw new NotFoundError(`Address not found: ${addressId}`);
|
|
466
|
+
}
|
|
467
|
+
throw new Error(
|
|
468
|
+
`Address flags stayed contended after ${MERGE_FLAGS_ATTEMPTS} attempts: ${addressId}`,
|
|
469
|
+
);
|
|
470
|
+
}
|
|
471
|
+
|
|
403
472
|
async mergeFlags(
|
|
404
473
|
accountConfigId: string,
|
|
405
474
|
addressId: string,
|
|
406
475
|
patch: FlagsMergePatch,
|
|
407
476
|
): Promise<AddressItem> {
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
477
|
+
return this.mergeStoredFlags(accountConfigId, addressId, (current) => {
|
|
478
|
+
const next: AddressFlags = { ...current };
|
|
479
|
+
for (const [key, value] of Object.entries(patch) as [
|
|
480
|
+
keyof AddressFlags,
|
|
481
|
+
AddressFlags[keyof AddressFlags] | null | undefined,
|
|
482
|
+
][]) {
|
|
483
|
+
if (value === undefined) continue;
|
|
484
|
+
if (value === null) {
|
|
485
|
+
delete next[key];
|
|
486
|
+
continue;
|
|
487
|
+
}
|
|
488
|
+
(next[key] as AddressFlags[keyof AddressFlags]) = value;
|
|
418
489
|
}
|
|
419
|
-
|
|
420
|
-
}
|
|
421
|
-
const [row] = await this.db
|
|
422
|
-
.update(addressTable)
|
|
423
|
-
.set({ flags: next as never, updatedAt: Date.now() })
|
|
424
|
-
.where(
|
|
425
|
-
and(
|
|
426
|
-
eq(addressTable.accountConfigId, accountConfigId),
|
|
427
|
-
eq(addressTable.addressId, addressId),
|
|
428
|
-
),
|
|
429
|
-
)
|
|
430
|
-
.returning();
|
|
431
|
-
if (!row) throw new NotFoundError(`Address not found: ${addressId}`);
|
|
432
|
-
return rowToAddress(row);
|
|
490
|
+
return next;
|
|
491
|
+
});
|
|
433
492
|
}
|
|
434
493
|
|
|
435
494
|
async promoteWellknownByUser(
|
|
@@ -437,23 +496,10 @@ export class AddressRepo implements IAddressRepository {
|
|
|
437
496
|
addressId: string,
|
|
438
497
|
now: number,
|
|
439
498
|
): Promise<AddressItem> {
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
...(current.flags ?? {}),
|
|
499
|
+
return this.mergeStoredFlags(accountConfigId, addressId, (current) => ({
|
|
500
|
+
...current,
|
|
443
501
|
wellknown: { value: true, setAt: now, setBy: "user-junk-rescue" },
|
|
444
|
-
};
|
|
445
|
-
const [row] = await this.db
|
|
446
|
-
.update(addressTable)
|
|
447
|
-
.set({ flags: next as never, updatedAt: Date.now() })
|
|
448
|
-
.where(
|
|
449
|
-
and(
|
|
450
|
-
eq(addressTable.accountConfigId, accountConfigId),
|
|
451
|
-
eq(addressTable.addressId, addressId),
|
|
452
|
-
),
|
|
453
|
-
)
|
|
454
|
-
.returning();
|
|
455
|
-
if (!row) throw new NotFoundError(`Address not found: ${addressId}`);
|
|
456
|
-
return rowToAddress(row);
|
|
502
|
+
}));
|
|
457
503
|
}
|
|
458
504
|
|
|
459
505
|
async demoteSenderTrust(
|
|
@@ -461,25 +507,12 @@ export class AddressRepo implements IAddressRepository {
|
|
|
461
507
|
addressId: string,
|
|
462
508
|
_now: number,
|
|
463
509
|
): Promise<AddressItem> {
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
inboundCount: 0,
|
|
471
|
-
replyCount: 0,
|
|
472
|
-
updatedAt: Date.now(),
|
|
473
|
-
})
|
|
474
|
-
.where(
|
|
475
|
-
and(
|
|
476
|
-
eq(addressTable.accountConfigId, accountConfigId),
|
|
477
|
-
eq(addressTable.addressId, addressId),
|
|
478
|
-
),
|
|
479
|
-
)
|
|
480
|
-
.returning();
|
|
481
|
-
if (!row) throw new NotFoundError(`Address not found: ${addressId}`);
|
|
482
|
-
return rowToAddress(row);
|
|
510
|
+
return this.mergeStoredFlags(
|
|
511
|
+
accountConfigId,
|
|
512
|
+
addressId,
|
|
513
|
+
({ wellknown: _w, vip: _v, ...rest }) => rest,
|
|
514
|
+
{ inboundCount: 0, replyCount: 0 },
|
|
515
|
+
);
|
|
483
516
|
}
|
|
484
517
|
|
|
485
518
|
async deleteAddress(
|