Skip to content
Merged
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
10 changes: 10 additions & 0 deletions .changeset/36369-digest-conversion-snapshot.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@objectstack/service-messaging': patch
---

fix(messaging): the one-time digest conversion rewrites only the rows that held `none` when it started

Clause-②: no
Metadata-protocol: none

The one-time conversion of the old default digest `none` to empty now reads the ids of every row holding `none` first, in pages, then records itself in `sys_migration`, then rewrites exactly those rows. It no longer reads the rows again while it runs. The deployment is already serving during that boot pass, so a `none` someone picks during the pass (a new preference, a member switching to "No digest", a node still on the earlier release in a rolling upgrade) is that person's own choice and is kept. If the conversion cannot record itself in `sys_migration`, it rewrites nothing and runs again on the next start.
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,23 @@
* - No ledger on the kernel, or a ledger that cannot be read: the pass does
* NOT run, because it could not be recorded and would repeat.
*
* ## Only the rows that held `none` before the claim
*
* The pass reads the ids of every row holding `none` FIRST, in pages by id,
* then claims the ledger row, then rewrites exactly that snapshot — it never
* reads the filter again. The deployment is serving while the boot hook
* runs, so a `none` written during the pass (a member's own pick, a new row,
* a node still on the earlier release in a rolling deploy) is a real choice
* and is not part of the snapshot.
*
* Every organization's rows: the read is the platform's own, not a tenant's.
* Each rewrite is addressed by id AND the stored `none`, under the row's own
* organization, so a value written since the read is left alone.
*
* A claim that fails rewrites nothing, and the next boot takes a new
* snapshot: a `none` written between those two boots is converted with the
* rest. Nothing can record the earlier snapshot when the ledger itself cannot
* be written, so that failure is logged as an error naming the fix.
*/

import type { IDataEngine } from '@objectstack/spec/contracts';
Expand All @@ -58,8 +72,8 @@ const LEGACY_UNSET_DIGEST = 'none';
/** The table this conversion rewrites; the type ties it to `PREFERENCE_OBJECT`. */
const OBJECT: typeof PREFERENCE_OBJECT = 'sys_notification_preference';

/** How many rows one read takes — the same ceiling `PreferenceResolver.loadRows` reads with. */
const PASS_LIMIT = 10000;
/** How many rows one page of the snapshot read takes. */
const PAGE_SIZE = 10000;

const SYSTEM_CONTEXT = { isSystem: true } as const;

Expand All @@ -74,15 +88,28 @@ type ConversionEngine = Pick<IDataEngine, 'find' | 'findOne' | 'insert' | 'updat
getObject?(name: string): unknown;
};

export interface PreferenceDigestConversionOptions {
/** Rows per page of the snapshot read; defaults to 10000. */
pageSize?: number;
}

/** One row of the snapshot: what its rewrite is addressed by. */
interface LegacyRow {
id: string;
organizationId: string | undefined;
}

export interface PreferenceDigestConversionResult {
/**
* - `converted` — the ledger row was claimed and every legacy `none` found
* was attempted (`failed` lists the ones left as stored);
* - `converted` — the ledger row was claimed and every row of the snapshot
* taken before the claim was attempted (`failed` lists the ones left as
* stored);
* - `already-run` — the ledger records an earlier pass; nothing was read;
* - `ledger-unavailable` — no `sys_migration` on this kernel; nothing ran;
* - `ledger-unreadable` — the ledger read failed; nothing ran;
* - `read-failed` — the preference rows could not be read; nothing was
* claimed or rewritten, and the next boot tries again;
* - `read-failed` — the preference rows could not be read (any page of
* the snapshot); nothing was claimed or rewritten, and the next boot
* tries again;
* - `claim-failed` — the ledger row could not be written; nothing was
* rewritten;
* - `no-engine` — no data engine that reads and writes rows.
Expand Down Expand Up @@ -114,13 +141,15 @@ export function buildDigestConversionRecord(details: Record<string, unknown>, no
}

/**
* Rewrite every legacy stored `digest = 'none'` to empty, across every
* organization, unless this deployment's ledger already records the pass.
* Never throws: it runs in a boot hook, which it must not break.
* Rewrite every stored `digest = 'none'` that existed before the ledger claim
* to empty, across every organization, unless this deployment's ledger
* already records the pass. Never throws: it runs in a boot hook, which it
* must not break.
*/
export async function convertLegacyNoneDigestsOnce(
engine: IDataEngine | undefined,
logger?: PreferenceDigestConversionLogger,
options: PreferenceDigestConversionOptions = {},
): Promise<PreferenceDigestConversionResult> {
const result = (status: PreferenceDigestConversionResult['status'], converted = 0, failed: string[] = []): PreferenceDigestConversionResult =>
({ status, converted, failed });
Expand Down Expand Up @@ -151,23 +180,39 @@ export async function convertLegacyNoneDigestsOnce(
return result('ledger-unreadable');
}

const readLegacy = async (): Promise<Array<Record<string, unknown>>> => {
try {
return ((await e.find(
OBJECT,
{ where: { digest: LEGACY_UNSET_DIGEST }, fields: ['id', 'organization_id'], limit: PASS_LIMIT },
{ context: SYSTEM_CONTEXT },
)) ?? []) as Array<Record<string, unknown>>;
} catch (err) {
// No table yet holds no legacy row: a fresh database.
if (isMissingTableError(err, OBJECT)) return [];
throw err;
// The snapshot: every row holding `none` now, read in pages in id order
// until a page comes back short. Taken before the claim, and the only
// rows the pass rewrites.
const size = Math.max(1, Math.floor(options.pageSize ?? PAGE_SIZE));
const readSnapshot = async (): Promise<LegacyRow[]> => {
const snapshot: LegacyRow[] = [];
for (let after: string | undefined; ;) {
let page: Array<Record<string, unknown>>;
try {
page = ((await e.find(
OBJECT,
{
where: { digest: LEGACY_UNSET_DIGEST, ...(after === undefined ? {} : { id: { $gt: after } }) },
fields: ['id', 'organization_id'],
orderBy: [{ field: 'id', order: 'asc' }],
limit: size,
},
{ context: SYSTEM_CONTEXT },
)) ?? []) as Array<Record<string, unknown>>;
} catch (err) {
// No table yet holds no legacy row: a fresh database.
if (after === undefined && isMissingTableError(err, OBJECT)) return [];
throw err;
}
for (const row of page) snapshot.push({ id: String(row.id), organizationId: textOrUndefined(row.organization_id) });
if (page.length < size) return snapshot;
after = String(page[page.length - 1]!.id);
}
};

let rows: Array<Record<string, unknown>>;
let rows: LegacyRow[];
try {
rows = await readLegacy();
rows = await readSnapshot();
} catch (err) {
logger?.error(
`[messaging] the one-time ${OBJECT} digest conversion could not read the rows it converts, so it did not ` +
Expand Down Expand Up @@ -207,49 +252,29 @@ export async function convertLegacyNoneDigestsOnce(

let converted = 0;
const failed: string[] = [];
const seen = new Set<string>();
// Pass until a read returns no row this run has not already handled. A row
// left as stored still matches the filter, so `seen` is what ends the loop.
for (;;) {
const fresh = rows.filter((row) => !seen.has(String(row.id)));
if (fresh.length === 0) break;
for (const row of fresh) {
const id = String(row.id);
seen.add(id);
try {
// A migration is an entry point, so it states the system
// context itself, with the row's own organization threaded.
// Compare-and-set: the predicate path honours both keys, so a
// digest written since the read is left alone (0 matched).
const matched = await e.update(
OBJECT,
{ digest: null },
{ where: { id, digest: LEGACY_UNSET_DIGEST }, multi: true, context: { ...SYSTEM_CONTEXT, tenantId: textOrUndefined(row.organization_id) } },
);
if (matched !== 0) converted += 1;
} catch (err) {
failed.push(id);
logger?.error(
`[messaging] the one-time ${OBJECT} digest conversion could not rewrite row ${id} (${messageOf(err)}): ` +
"it still holds the old default digest 'none', which now reads as that person's own choice of no " +
"digest. Fix: open the row in Setup, Notification Preferences, and clear its Digest.",
undefined,
{ object: OBJECT, id },
);
}
}
// The snapshot only: a row that came to hold `none` after it was taken is
// a choice made under this release, and is never read here.
for (const { id, organizationId } of rows) {
try {
rows = await readLegacy();
// A migration is an entry point, so it states the system
// context itself, with the row's own organization threaded.
// Compare-and-set: the predicate path honours both keys, so a
// digest written since the read is left alone (0 matched).
const matched = await e.update(
OBJECT,
{ digest: null },
{ where: { id, digest: LEGACY_UNSET_DIGEST }, multi: true, context: { ...SYSTEM_CONTEXT, tenantId: organizationId } },
);
if (matched !== 0) converted += 1;
} catch (err) {
failed.push(id);
logger?.error(
`[messaging] the one-time ${OBJECT} digest conversion stopped after ${converted} row(s): re-reading the ` +
`rows failed (${messageOf(err)}). It is recorded as run and will not run again, so any row still ` +
"holding digest 'none' reads as that person's own choice of no digest. Fix: clear Digest on those " +
'rows in Setup, Notification Preferences.',
`[messaging] the one-time ${OBJECT} digest conversion could not rewrite row ${id} (${messageOf(err)}): ` +
"it still holds the old default digest 'none', which now reads as that person's own choice of no " +
"digest. Fix: open the row in Setup, Notification Preferences, and clear its Digest.",
undefined,
{ object: OBJECT, error: messageOf(err) },
{ object: OBJECT, id },
);
break;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
* column still carries the old physical DEFAULT 'none' (the temporary
* owner-side hook, `preference-digest-unset.ts`, until #36245);
* - the legacy `none` nobody chose becomes empty ONCE, across every
* organization, recorded in `sys_migration`; a `none` written after that
* organization, recorded in `sys_migration`; only the rows read before the
* claim are rewritten, so a `none` written during the pass, or after it,
* survives every later boot (`preference-digest-conversion.ts`).
*/

Expand Down Expand Up @@ -91,6 +92,29 @@ async function insert(ql: ObjectQL, organization: string, row: Record<string, un
return String((await ql.insert(PREF, row, sys(organization))).id);
}

/**
* The engine `ql` with one interception: the first `method` call on `object`
* runs `before` first (whatever it throws is that call's failure), then the
* call itself. Every other member is `ql`'s own.
*/
function interceptOnce(ql: ObjectQL, method: 'update' | 'insert', object: string, before: () => Promise<void>): never {
let fired = false;
return new Proxy(ql, {
get(target, prop) {
const value = Reflect.get(target, prop, target);
if (typeof value !== 'function') return value;
if (prop !== method) return value.bind(target);
return async (name: string, ...rest: unknown[]) => {
if (name === object && !fired) {
fired = true;
await before();
}
return (value as (...args: unknown[]) => unknown).call(target, name, ...rest);
};
},
}) as never;
}

describe('an upgraded database: the digest column still carries the physical DEFAULT none', () => {
it('an insert that leaves the digest unset stores it empty, an explicit none stays none', async () => {
const file = dbFile();
Expand Down Expand Up @@ -152,6 +176,76 @@ describe('the one-time conversion of the legacy none', () => {
expect(await digestOf(second, 'org_a', fresh)).toBe('none');
});

it('a none written during the pass is not rewritten: only the rows read before the claim are', async () => {
const file = dbFile();
const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true });
const old = await insert(legacy, 'org_a', { user_id: 'u1', topic: '*', channel: '*', enabled: true });
const daily = await insert(legacy, 'org_a', { user_id: 'u2', topic: 'chosen', channel: '*', enabled: true, digest: 'daily' });
await close(legacy);

const ql = await boot(file, NotificationPreference, { hook: true });
let created: string | undefined;
// While the pass is rewriting, the deployment is serving: a new row
// with an explicit none, and a member switching daily to none.
const engine = interceptOnce(ql, 'update', PREF, async () => {
created = await insert(ql, 'org_b', { user_id: 'u2', topic: '*', channel: '*', enabled: true, digest: 'none' });
await ql.update(PREF, { digest: 'none' }, { where: { id: daily }, ...sys('org_a') } as never);
});
expect(await convertLegacyNoneDigestsOnce(engine, silent)).toEqual({ status: 'converted', converted: 1, failed: [] });
expect(created).toBeDefined();
expect(await digestOf(ql, 'org_a', old)).toBeNull();
expect(await digestOf(ql, 'org_b', created!)).toBe('none');
expect(await digestOf(ql, 'org_a', daily)).toBe('none');
});

it('reads the snapshot in pages by id, so every legacy none past the first page is converted', async () => {
const file = dbFile();
const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true });
const rows: Array<[string, string]> = [];
for (const [organization, user, topic] of [['org_a', 'u1', '*'], ['org_a', 'u2', '*'], ['org_b', 'u1', '*'], ['org_b', 'u2', '*'], ['org_a', 'u1', 'other']]) {
rows.push([organization, await insert(legacy, organization, { user_id: user, topic, channel: '*', enabled: true })]);
}
await close(legacy);

const ql = await boot(file, NotificationPreference, { hook: true });
expect(await convertLegacyNoneDigestsOnce(ql as never, silent, { pageSize: 2 })).toEqual({ status: 'converted', converted: 5, failed: [] });
for (const [organization, id] of rows) expect(await digestOf(ql, organization, id)).toBeNull();
});

it('a claim that fails after the read rewrites nothing, and leaves no record', async () => {
const file = dbFile();
const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true });
const row = await insert(legacy, 'org_a', { user_id: 'u1', topic: '*', channel: '*', enabled: true });
await close(legacy);

const ql = await boot(file, NotificationPreference, { hook: true });
const errors: string[] = [];
const engine = interceptOnce(ql, 'insert', 'sys_migration', async () => {
throw new Error('ledger is read-only');
});
const out = await convertLegacyNoneDigestsOnce(engine, { ...silent, error: (m: string) => errors.push(m) });
expect(out).toEqual({ status: 'claim-failed', converted: 0, failed: [] });
expect(errors).toHaveLength(1);
expect(await digestOf(ql, 'org_a', row)).toBe('none');
expect(await ql.findOne('sys_migration', { where: { id: PREFERENCE_DIGEST_NONE_CONVERSION_ID } }, { context: { isSystem: true } as ExecutionContext })).toBeFalsy();
});

it('another node claiming between the read and the claim counts as run, and this pass rewrites nothing', async () => {
const file = dbFile();
const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true });
const row = await insert(legacy, 'org_a', { user_id: 'u1', topic: '*', channel: '*', enabled: true });
await close(legacy);

const ql = await boot(file, NotificationPreference, { hook: true });
// The other node's claim lands first; this node's insert of the same
// ledger id is then refused by the store.
const engine = interceptOnce(ql, 'insert', 'sys_migration', async () => {
await ql.insert('sys_migration', { id: PREFERENCE_DIGEST_NONE_CONVERSION_ID, last_run_at: new Date().toISOString(), blocking: 0 }, { context: { isSystem: true } as ExecutionContext });
});
expect(await convertLegacyNoneDigestsOnce(engine, silent)).toEqual({ status: 'already-run', converted: 0, failed: [] });
expect(await digestOf(ql, 'org_a', row)).toBe('none');
});

it('without a ledger on the kernel it does not run, so nothing it could not record is rewritten', async () => {
const file = dbFile();
const legacy = await boot(file, LEGACY_PREFERENCE, { seed: true, ledger: false });
Expand Down
Loading