mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-23 14:17:06 +00:00
perf(notifications): notify and mark-ack skip their primary read-backs (#4547)
* perf(notifications): notify returns the row it wrote instead of reading it back The service hands the driver the row the store built on insert, and a group replacement builds the row it leaves from the one it looked up, so neither path reads the row back from the primary. * perf(notifications): mark-ack reads the row's fixed columns from a replica The type, app uid and audience the dismissal event carries never change, so they are read from a replica alongside the update, and from the primary only when the replica has no row yet. * test(notifications): cover a repeat dismissal and tidy notify docs * fix(notifications): a repeat mark-ack returns without waiting for the replica read, and a failed replica read is logged * refactor(notifications): NotificationRow spells out the row's columns, and a replacement passes the app uid it already has
This commit is contained in:
1 parent
c3ff8ca3b2
commit
e7ee778985
8 files changed
+358
-78
No files matched your search
@@ -504,3 +504,95 @@ describe.runIf(process.env.PUTER_TEST_DB_ENGINE === 'postgres')(
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
describe('an immediate send answers with the row it wrote', () => {
|
||||
/** What the driver returns for a row. */
|
||||
const clientShape = (row: Record<string, unknown> | null) => ({
|
||||
uid: row?.uid,
|
||||
value: row?.value,
|
||||
app_uid: row?.app_uid ?? null,
|
||||
shown: row?.shown ?? null,
|
||||
acknowledged: row?.acknowledged ?? null,
|
||||
created_at: row?.created_at ?? null,
|
||||
});
|
||||
|
||||
/** `fn`'s result, with the notification writes and uid lookups it made. */
|
||||
const traced = async <T>(fn: () => Promise<T>) => {
|
||||
const reads = [vi.spyOn(db(), 'read'), vi.spyOn(db(), 'pread')];
|
||||
const write = vi.spyOn(db(), 'write');
|
||||
try {
|
||||
const result = await fn();
|
||||
const sql = (calls: unknown[][]) =>
|
||||
calls
|
||||
.map(([q]) => String(q))
|
||||
.filter((q) => /`notification`/u.test(q));
|
||||
return {
|
||||
result: result as Record<string, unknown>,
|
||||
writes: sql(write.mock.calls),
|
||||
uidReads: reads
|
||||
.flatMap((spy) => sql(spy.mock.calls))
|
||||
.filter((q) =>
|
||||
/FROM `notification` WHERE `uid` = \?/u.test(q),
|
||||
),
|
||||
};
|
||||
} finally {
|
||||
for (const spy of [...reads, write]) spy.mockRestore();
|
||||
}
|
||||
};
|
||||
|
||||
const stored = (uid: unknown) =>
|
||||
server.stores.notification.getByUid(String(uid), {
|
||||
userId: holder.user!.id,
|
||||
primary: true,
|
||||
});
|
||||
|
||||
it('a new row: one insert and no read of it', async () => {
|
||||
setSchedules(undefined);
|
||||
const { result, writes, uidReads } = await traced(() =>
|
||||
notify({ text: 'new' }),
|
||||
);
|
||||
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0]).toMatch(/^INSERT INTO `notification`/u);
|
||||
expect(uidReads).toEqual([]);
|
||||
expect(result).toEqual(clientShape(await stored(result.uid)));
|
||||
});
|
||||
|
||||
it('a group replacement: one update and no read of the row after it', async () => {
|
||||
setSchedules(undefined);
|
||||
const first = (await notify({ group: 'g', text: 'one' })) as {
|
||||
uid: string;
|
||||
};
|
||||
const { result, writes, uidReads } = await traced(() =>
|
||||
notify({ group: 'g', text: 'two' }),
|
||||
);
|
||||
|
||||
expect(result.uid).toBe(first.uid);
|
||||
expect(writes).toHaveLength(1);
|
||||
expect(writes[0]).toMatch(/^UPDATE `notification`/u);
|
||||
expect(uidReads).toEqual([]);
|
||||
expect(result).toEqual(clientShape(await stored(first.uid)));
|
||||
expect(result.value).toMatchObject({ text: 'two' });
|
||||
});
|
||||
|
||||
it('a replacement of the row a delayed send wrote', async () => {
|
||||
setSchedules(undefined);
|
||||
const token = uuidv4();
|
||||
const key = uuidv4();
|
||||
const id = await claimed(token);
|
||||
await write(key, txFor(id, token), {
|
||||
payload: JSON.stringify({
|
||||
message: { title: 'Later', group: 'g' },
|
||||
}),
|
||||
});
|
||||
const { result, uidReads } = await traced(() =>
|
||||
notify({ group: 'g', text: 'now' }),
|
||||
);
|
||||
|
||||
expect(result.uid).toBe(key);
|
||||
expect(uidReads).toEqual([]);
|
||||
const row = await stored(key);
|
||||
expect(row?.send_key).toBeNull();
|
||||
expect(result).toEqual(clientShape(row));
|
||||
});
|
||||
});
|
||||
@@ -161,6 +161,44 @@ describe('NotificationDriver.create', () => {
|
||||
expect(result?.value).toEqual({ type: NOTIF_TYPE, title: 'lagged' });
|
||||
});
|
||||
|
||||
it('writes once and returns the row without reading it back', async () => {
|
||||
const { actor, userId } = await makeUser();
|
||||
const db = server.clients.db;
|
||||
const read = vi.spyOn(db, 'read');
|
||||
const pread = vi.spyOn(db, 'pread');
|
||||
const write = vi.spyOn(db, 'write');
|
||||
let result: Record<string, unknown> | null;
|
||||
let writes: unknown[][];
|
||||
let reads: unknown[][];
|
||||
try {
|
||||
result = (await withActor(actor, () =>
|
||||
driver.create({
|
||||
object: { value: { type: NOTIF_TYPE, title: 'once' } },
|
||||
}),
|
||||
)) as Record<string, unknown> | null;
|
||||
} finally {
|
||||
writes = write.mock.calls;
|
||||
reads = [...read.mock.calls, ...pread.mock.calls];
|
||||
for (const spy of [read, pread, write]) spy.mockRestore();
|
||||
}
|
||||
|
||||
const touches = (q: unknown) => /`notification`/u.test(String(q));
|
||||
expect(writes.filter(([q]) => touches(q))).toHaveLength(1);
|
||||
expect(reads.filter(([q]) => touches(q))).toEqual([]);
|
||||
const row = await server.stores.notification.getByUid(
|
||||
result!.uid as string,
|
||||
{ userId, primary: true },
|
||||
);
|
||||
expect(result).toEqual({
|
||||
uid: row?.uid,
|
||||
value: row?.value,
|
||||
app_uid: row?.app_uid ?? null,
|
||||
shown: row?.shown ?? null,
|
||||
acknowledged: row?.acknowledged ?? null,
|
||||
created_at: row?.created_at ?? null,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects a `value` with no `type` with 400', async () => {
|
||||
const { actor } = await makeUser();
|
||||
await expect(
|
||||
|
||||
@@ -64,6 +64,7 @@ import { PuterDriver } from '../types.js';
|
||||
import type { Actor } from '../../core/actor.js';
|
||||
import type { DriverRateLimitConfig } from '../meta.js';
|
||||
import { CRUD_CONCURRENT } from '../util/crudLimits.js';
|
||||
import type { NotificationRow } from '../../services/notification/NotificationService.js';
|
||||
|
||||
const MAX_SELECT_LIMIT = 200;
|
||||
const MINUTE_MS = 60_000;
|
||||
@@ -289,12 +290,12 @@ export class NotificationDriver extends PuterDriver {
|
||||
// Silent: a driver `create` has never pushed to the live socket, only
|
||||
// ever written the row — moving through the registry does not change
|
||||
// that.
|
||||
const uid = await this.#write(actor.user.id, value, {
|
||||
const row = await this.#write(actor.user.id, value, {
|
||||
type: registeredType,
|
||||
appUid,
|
||||
silent: true,
|
||||
});
|
||||
return this.#readBack(uid, actor.user.id);
|
||||
return this.#toClient(row);
|
||||
}
|
||||
|
||||
async read(args: Record<string, unknown>): Promise<unknown> {
|
||||
@@ -447,12 +448,9 @@ export class NotificationDriver extends PuterDriver {
|
||||
return this.#scheduleAppMessage(actor, message, handle, timing);
|
||||
|
||||
if (handle === undefined) {
|
||||
const uid = await this.#sendAppMessage(
|
||||
actor.user.id,
|
||||
appUid,
|
||||
message,
|
||||
return this.#toClient(
|
||||
await this.#sendAppMessage(actor.user.id, appUid, message),
|
||||
);
|
||||
return this.#readBack(uid, actor.user.id);
|
||||
}
|
||||
try {
|
||||
const recipient =
|
||||
@@ -484,7 +482,7 @@ export class NotificationDriver extends PuterDriver {
|
||||
recipientId: number,
|
||||
appUid: string,
|
||||
message: AppMessage,
|
||||
): Promise<string> {
|
||||
): Promise<NotificationRow> {
|
||||
return this.#oneSendPerGroup(recipientId, appUid, message, () =>
|
||||
this.#replaceOrWriteAppMessage(recipientId, appUid, message),
|
||||
);
|
||||
@@ -675,7 +673,7 @@ export class NotificationDriver extends PuterDriver {
|
||||
recipientId: number,
|
||||
appUid: string,
|
||||
message: AppMessage,
|
||||
): Promise<string> {
|
||||
): Promise<NotificationRow> {
|
||||
// Primary: a lagging replica would turn a replacement into a new
|
||||
// notification, which spends a day slot.
|
||||
const open = message.group
|
||||
@@ -698,17 +696,13 @@ export class NotificationDriver extends PuterDriver {
|
||||
);
|
||||
|
||||
if (open) {
|
||||
const uid = String(open.uid);
|
||||
if (
|
||||
await this.services.notification.notifyUpdate(
|
||||
uid,
|
||||
recipientId,
|
||||
message,
|
||||
{ type: APP_MESSAGE_TYPE, replace: true },
|
||||
)
|
||||
) {
|
||||
return uid;
|
||||
}
|
||||
const replaced = await this.services.notification.replaceUnseen(
|
||||
open,
|
||||
recipientId,
|
||||
message,
|
||||
{ type: APP_MESSAGE_TYPE },
|
||||
);
|
||||
if (replaced) return replaced;
|
||||
// Shown or dismissed since the lookup, so this one is new after all.
|
||||
await this.#spendAppMessageLimits(recipientId, appUid, ['day']);
|
||||
}
|
||||
@@ -760,7 +754,7 @@ export class NotificationDriver extends PuterDriver {
|
||||
}
|
||||
}
|
||||
|
||||
/** Writes for `userId`, who need not be the actor, and names the row. */
|
||||
/** Writes for `userId`, who need not be the actor, and returns the row. */
|
||||
async #write(
|
||||
userId: number,
|
||||
value: Record<string, unknown>,
|
||||
@@ -770,31 +764,18 @@ export class NotificationDriver extends PuterDriver {
|
||||
silent: boolean;
|
||||
group?: string | null;
|
||||
},
|
||||
): Promise<string> {
|
||||
const uid = await this.services.notification.notify(
|
||||
): Promise<NotificationRow> {
|
||||
const [row] = await this.services.notification.notifyRows(
|
||||
[userId],
|
||||
value,
|
||||
opts,
|
||||
);
|
||||
if (!uid) {
|
||||
if (!row) {
|
||||
throw new HttpError(500, 'Notification could not be created', {
|
||||
legacyCode: 'internal_error',
|
||||
});
|
||||
}
|
||||
return uid;
|
||||
}
|
||||
|
||||
/** The service hands back only the uid; the primary has the rest. */
|
||||
async #readBack(
|
||||
uid: string,
|
||||
userId: number,
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
return this.#toClient(
|
||||
await this.stores.notification.getByUid(uid, {
|
||||
userId,
|
||||
primary: true,
|
||||
}),
|
||||
);
|
||||
return row;
|
||||
}
|
||||
|
||||
// -- Permissions -------------------------------------------------
|
||||
|
||||
@@ -520,7 +520,7 @@ describe("NotificationService — 'notif.written'", () => {
|
||||
const user = await makeUser();
|
||||
const uid = uuidv4();
|
||||
const appUid = `app-${uuidv4()}`;
|
||||
await server.stores.notification.insert({
|
||||
await server.stores.notification.create({
|
||||
userId: user.id,
|
||||
value: { title: 'one', type: 'share.received' },
|
||||
uid,
|
||||
|
||||
@@ -40,6 +40,7 @@ import {
|
||||
resolveNotificationWrite,
|
||||
} from './notificationTypes.js';
|
||||
import type { NotificationTypeName } from './notificationTypes.js';
|
||||
import type { NotificationRow } from '../../stores/notification/NotificationStore.js';
|
||||
|
||||
export {
|
||||
NOTIFICATION_TYPES,
|
||||
@@ -52,6 +53,15 @@ export type {
|
||||
} from './notificationTypes.js';
|
||||
export { canViewNotification } from './notificationAudience.js';
|
||||
|
||||
export type { NotificationRow };
|
||||
|
||||
type NotifyOptions = {
|
||||
type: NotificationTypeName;
|
||||
appUid?: string | null;
|
||||
silent?: boolean;
|
||||
group?: string | null;
|
||||
};
|
||||
|
||||
const RETENTION_SWEEP_JOB = 'notifications.retention';
|
||||
const RETENTION_SWEEP_EVERY_MS = 60 * 60 * 1000;
|
||||
const RETENTION_SWEEP_LEASE_MS = 15 * 60 * 1000;
|
||||
@@ -152,13 +162,18 @@ export class NotificationService extends PuterService {
|
||||
async notify(
|
||||
userIds: number[],
|
||||
notification: Record<string, unknown>,
|
||||
opts: {
|
||||
type: NotificationTypeName;
|
||||
appUid?: string | null;
|
||||
silent?: boolean;
|
||||
group?: string | null;
|
||||
},
|
||||
opts: NotifyOptions,
|
||||
): Promise<string | null> {
|
||||
const [first] = await this.notifyRows(userIds, notification, opts);
|
||||
return first?.uid ?? null;
|
||||
}
|
||||
|
||||
/** `notify`, returning each row written; failed recipients are left out. */
|
||||
async notifyRows(
|
||||
userIds: number[],
|
||||
notification: Record<string, unknown>,
|
||||
opts: NotifyOptions,
|
||||
): Promise<NotificationRow[]> {
|
||||
const appUid = opts.appUid ?? null;
|
||||
const registered = resolveNotificationWrite(opts.type, appUid);
|
||||
const payload = { ...notification, type: registered.type };
|
||||
@@ -167,8 +182,9 @@ export class NotificationService extends PuterService {
|
||||
const written = await Promise.all(
|
||||
userIds.map(async (userId) => {
|
||||
const uid = uuidv4();
|
||||
let row: NotificationRow;
|
||||
try {
|
||||
await this.stores.notification.insert({
|
||||
row = await this.stores.notification.create({
|
||||
userId,
|
||||
value: payload,
|
||||
uid,
|
||||
@@ -200,11 +216,11 @@ export class NotificationService extends PuterService {
|
||||
{ sendId: uuidv4() },
|
||||
);
|
||||
}
|
||||
return uid;
|
||||
return row;
|
||||
}),
|
||||
);
|
||||
|
||||
return written.find((uid) => uid !== null) ?? null;
|
||||
return written.filter((row) => row !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -230,28 +246,70 @@ export class NotificationService extends PuterService {
|
||||
replace?: boolean;
|
||||
},
|
||||
): Promise<boolean> {
|
||||
const replacedAt = opts.replace ? Date.now() : undefined;
|
||||
const payload = await this.#rewrite(uid, userId, notification, {
|
||||
type: opts.type,
|
||||
silent: opts.silent,
|
||||
replacedAt,
|
||||
});
|
||||
return payload !== null;
|
||||
}
|
||||
|
||||
/** Replaces a row already read; null if it was shown or dismissed since. */
|
||||
async replaceUnseen(
|
||||
row: NotificationRow,
|
||||
userId: number,
|
||||
notification: Record<string, unknown>,
|
||||
opts: { type: NotificationTypeName },
|
||||
): Promise<NotificationRow | null> {
|
||||
const replacedAt = Date.now();
|
||||
const payload = await this.#rewrite(row.uid, userId, notification, {
|
||||
type: opts.type,
|
||||
replacedAt,
|
||||
appUid: row.app_uid,
|
||||
});
|
||||
if (!payload) return null;
|
||||
return this.stores.notification.replacedRow(row, payload, replacedAt);
|
||||
}
|
||||
|
||||
/** The payload written, or null; `appUid` saves reading the row for it. */
|
||||
async #rewrite(
|
||||
uid: string,
|
||||
userId: number,
|
||||
notification: Record<string, unknown>,
|
||||
opts: {
|
||||
type: NotificationTypeName;
|
||||
silent?: boolean;
|
||||
replacedAt?: number;
|
||||
appUid?: string | null;
|
||||
},
|
||||
): Promise<Record<string, unknown> | null> {
|
||||
const registered = findNotificationType(opts.type);
|
||||
if (!registered?.groupable) {
|
||||
throw new Error(`notification type is not groupable: ${opts.type}`);
|
||||
}
|
||||
const payload = { ...notification, type: registered.type };
|
||||
const replacedAt = opts.replace ? Date.now() : undefined;
|
||||
const { replacedAt } = opts;
|
||||
const updated = await this.stores.notification.updateValue(
|
||||
uid,
|
||||
userId,
|
||||
payload,
|
||||
replacedAt === undefined ? {} : { onlyUnseen: true, replacedAt },
|
||||
);
|
||||
if (!updated) return false;
|
||||
if (opts.silent) return true;
|
||||
if (!updated) return null;
|
||||
if (opts.silent) return payload;
|
||||
|
||||
// Before the read, so the desktop copy updates even if it fails.
|
||||
// Before any read, so the desktop copy updates even if that fails.
|
||||
const desktop = inAccountMailbox(registered.type);
|
||||
if (desktop) this.#sendRewrite(userId, uid, payload);
|
||||
const row = await this.stores.notification.getByUid(uid, { userId });
|
||||
const rowAppUid =
|
||||
opts.appUid !== undefined
|
||||
? opts.appUid
|
||||
: (await this.stores.notification.getByUid(uid, { userId }))
|
||||
?.app_uid;
|
||||
const app = notification.app as { uid?: unknown } | undefined;
|
||||
const appUid =
|
||||
row?.app_uid ?? (typeof app?.uid === 'string' ? app.uid : null);
|
||||
rowAppUid ?? (typeof app?.uid === 'string' ? app.uid : null);
|
||||
await this.emitWritten(
|
||||
{
|
||||
userId,
|
||||
@@ -265,7 +323,7 @@ export class NotificationService extends PuterService {
|
||||
},
|
||||
{ sendId: uuidv4(), rewriteSent: desktop },
|
||||
);
|
||||
return true;
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,14 +3,14 @@ import { EventClient } from '../../clients/event/EventClient.js';
|
||||
import type { EventMap } from '../../clients/event/types.js';
|
||||
import { NotificationStore } from './NotificationStore.js';
|
||||
|
||||
const setup = (row: Record<string, unknown> | null, changed = true) => {
|
||||
const setup = (row: Record<string, unknown> | null, changed = true, replica: Record<string, unknown> | null = null) => {
|
||||
const event = new EventClient({} as never);
|
||||
const emitted: EventMap['notif.acknowledged'][] = [];
|
||||
event.on('notif.acknowledged', (_key, data) => { emitted.push(data); });
|
||||
const db = {
|
||||
write: vi.fn(async () => ({ anyRowsAffected: changed })),
|
||||
pread: vi.fn(async () => row ? [row] : []),
|
||||
read: vi.fn(async () => []),
|
||||
read: vi.fn(async (): Promise<unknown[]> => replica ? [replica] : []),
|
||||
};
|
||||
const store = new NotificationStore({}, { event, db } as never, {});
|
||||
return { store, emitted, db };
|
||||
@@ -22,14 +22,51 @@ const appRow = {
|
||||
};
|
||||
|
||||
describe('acknowledgement emission', () => {
|
||||
it('announces a committed app message dismissal without content', async () => {
|
||||
const { store, emitted, db } = setup(appRow);
|
||||
it('announces a committed app message dismissal without content, from a replica', async () => {
|
||||
const { store, emitted, db } = setup(null, true, appRow);
|
||||
await expect(store.markAcknowledged('one', 7)).resolves.toBe(true);
|
||||
expect(db.write.mock.calls[0][0]).toContain('`acknowledged` IS NULL');
|
||||
expect(db.read).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('`user_id` = ?'), ['one', 7]);
|
||||
expect(db.pread).not.toHaveBeenCalled();
|
||||
expect(emitted).toEqual([{ userId: 7, uid: 'one', type: 'app.message', audience: 'app-user', appUid: 'app-one' }]);
|
||||
});
|
||||
|
||||
it('reads the primary when the replica has no row yet', async () => {
|
||||
const { store, emitted, db } = setup(appRow);
|
||||
await expect(store.markAcknowledged('one', 7)).resolves.toBe(true);
|
||||
expect(db.read).toHaveBeenCalledWith(expect.stringContaining('`user_id` = ?'), ['one', 7]);
|
||||
expect(db.pread).toHaveBeenCalledWith(expect.stringContaining('`user_id` = ?'), ['one', 7]);
|
||||
expect(emitted).toEqual([{ userId: 7, uid: 'one', type: 'app.message', audience: 'app-user', appUid: 'app-one' }]);
|
||||
});
|
||||
|
||||
it('reads the primary and logs when the replica read fails', async () => {
|
||||
const { store, emitted, db } = setup(appRow, true, appRow);
|
||||
const failure = new Error('unavailable');
|
||||
db.read.mockRejectedValueOnce(failure);
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
try {
|
||||
await expect(store.markAcknowledged('one', 7)).resolves.toBe(true);
|
||||
expect(warn).toHaveBeenCalledExactlyOnceWith('[notification] dismissal replica read failed', failure);
|
||||
} finally {
|
||||
warn.mockRestore();
|
||||
}
|
||||
expect(db.read).toHaveBeenCalledOnce();
|
||||
expect(db.pread).toHaveBeenCalledOnce();
|
||||
expect(emitted).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('answers a repeat dismissal without waiting for the replica read', async () => {
|
||||
const { store, emitted, db } = setup(appRow, false, appRow);
|
||||
db.read.mockReturnValueOnce(new Promise(() => {}));
|
||||
const settled = await Promise.race([
|
||||
store.markAcknowledged('one', 7),
|
||||
new Promise((resolve) => setTimeout(resolve, 200, 'waiting')),
|
||||
]);
|
||||
expect(settled).toBe(false);
|
||||
expect(db.pread).not.toHaveBeenCalled();
|
||||
expect(emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ ...appRow, type: 'share.received' },
|
||||
{ ...appRow, app_uid: null },
|
||||
@@ -47,6 +84,13 @@ describe('acknowledgement emission', () => {
|
||||
expect(emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not announce a repeat dismissal the replica still has', async () => {
|
||||
const { store, emitted, db } = setup(appRow, false, appRow);
|
||||
await expect(store.markAcknowledged('one', 7)).resolves.toBe(false);
|
||||
expect(db.pread).not.toHaveBeenCalled();
|
||||
expect(emitted).toEqual([]);
|
||||
});
|
||||
|
||||
it('preserves a committed acknowledgement if the announcement read fails', async () => {
|
||||
const { store, db, emitted } = setup(appRow);
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
@@ -33,6 +33,27 @@ import { PuterStore } from '../types';
|
||||
* }} NotificationInsert
|
||||
*/
|
||||
|
||||
/**
|
||||
* A `notification` row as this store returns it. `send_key` is absent on a
|
||||
* table that has no such column yet.
|
||||
*
|
||||
* @typedef {{
|
||||
* id: number;
|
||||
* uid: string;
|
||||
* user_id: number;
|
||||
* value: Record<string, unknown> | string;
|
||||
* acknowledged: number | null;
|
||||
* shown: number | null;
|
||||
* created_at: Date | string;
|
||||
* app_uid: string | null;
|
||||
* audience: string;
|
||||
* type: string;
|
||||
* group_key: string | null;
|
||||
* replaced_at: number | null;
|
||||
* send_key?: string | null;
|
||||
* }} NotificationRow
|
||||
*/
|
||||
|
||||
/** How long a probe that found no `send_key` column stands. */
|
||||
const SEND_KEY_REPROBE_MS = 60_000;
|
||||
|
||||
@@ -43,6 +64,9 @@ const SEND_KEY_REPROBE_MS = 60_000;
|
||||
const groupKey = (group) =>
|
||||
group ? createHash('sha256').update(group, 'utf8').digest('hex') : null;
|
||||
|
||||
const serialize = (value) =>
|
||||
typeof value === 'string' ? value : JSON.stringify(value ?? {});
|
||||
|
||||
const pageLimit = (limit) => {
|
||||
const n = Number(limit);
|
||||
return Number.isFinite(n) ? Math.max(0, Math.floor(n)) : 50;
|
||||
@@ -131,6 +155,7 @@ export class NotificationStore extends PuterStore {
|
||||
* @param {string} appUid
|
||||
* @param {string} group
|
||||
* @param {{ primary?: boolean }} [opts]
|
||||
* @returns {Promise<NotificationRow | null>}
|
||||
*/
|
||||
async getUnseenByGroup(userId, appUid, group, { primary = false } = {}) {
|
||||
const sql =
|
||||
@@ -391,6 +416,7 @@ export class NotificationStore extends PuterStore {
|
||||
* `group` is kept as a key `getUnseenByGroup` finds the row by.
|
||||
*
|
||||
* @param {NotificationInsert} args
|
||||
* @returns {Promise<NotificationRow>}
|
||||
*/
|
||||
async create({
|
||||
userId,
|
||||
@@ -403,8 +429,7 @@ export class NotificationStore extends PuterStore {
|
||||
}) {
|
||||
if (!userId) throw new Error('create: userId is required');
|
||||
const db = this.clients.db;
|
||||
const serialized =
|
||||
typeof value === 'string' ? value : JSON.stringify(value ?? {});
|
||||
const serialized = serialize(value);
|
||||
const createdAt = Math.floor(Date.now() / 1000);
|
||||
const key = groupKey(group);
|
||||
const { insertId } = await db.write(
|
||||
@@ -430,16 +455,6 @@ export class NotificationStore extends PuterStore {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* `create` for a caller that needs only the uid.
|
||||
*
|
||||
* @param {NotificationInsert} args
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
async insert(args) {
|
||||
return (await this.create(args)).uid;
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements that write a delayed send's notification, for the caller's
|
||||
* transaction. Each runs only while `guard` holds. With `replaceUid` the
|
||||
@@ -554,8 +569,7 @@ export class NotificationStore extends PuterStore {
|
||||
{ onlyUnseen = false, replacedAt = undefined } = {},
|
||||
) {
|
||||
const db = this.clients.db;
|
||||
const serialized =
|
||||
typeof value === 'string' ? value : JSON.stringify(value ?? {});
|
||||
const serialized = serialize(value);
|
||||
const set = ['`value` = ?', '`shown` = NULL'];
|
||||
if (await this.#hasSendKey()) set.push('`send_key` = NULL');
|
||||
const params = [serialized];
|
||||
@@ -575,18 +589,49 @@ export class NotificationStore extends PuterStore {
|
||||
return result.anyRowsAffected;
|
||||
}
|
||||
|
||||
/**
|
||||
* The row `updateValue` leaves on a replacement at `replacedAt` (ms).
|
||||
*
|
||||
* @param {NotificationRow} row @param {unknown} value
|
||||
* @param {number} replacedAt
|
||||
* @returns {NotificationRow}
|
||||
*/
|
||||
replacedRow(row, value, replacedAt) {
|
||||
const replaced = {
|
||||
...row,
|
||||
value: serialize(value),
|
||||
shown: null,
|
||||
created_at: this.clients.db.timestampValue(
|
||||
Math.floor(replacedAt / 1000),
|
||||
),
|
||||
replaced_at: replacedAt,
|
||||
};
|
||||
if ('send_key' in row) replaced.send_key = null;
|
||||
return this.#normalizeRow(replaced);
|
||||
}
|
||||
|
||||
// The event's columns never change: replica first, primary when it lags.
|
||||
async markAcknowledged(uid, userId) {
|
||||
const db = this.clients.db;
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const result = await this.clients.db.write(
|
||||
const fixed =
|
||||
'SELECT `type`, `app_uid`, `audience` FROM `notification` WHERE `uid` = ? AND `user_id` = ? LIMIT 1';
|
||||
// Starts with the UPDATE; awaited only when a row changed.
|
||||
const replica = db.read(fixed, [uid, userId]).catch((error) => {
|
||||
console.warn('[notification] dismissal replica read failed', error);
|
||||
return [];
|
||||
});
|
||||
const result = await db.write(
|
||||
'UPDATE `notification` SET `acknowledged` = ? WHERE `uid` = ? AND `user_id` = ? AND `acknowledged` IS NULL',
|
||||
[now, uid, userId],
|
||||
);
|
||||
if (result.anyRowsAffected) {
|
||||
try {
|
||||
const [row] = await this.clients.db.pread(
|
||||
'SELECT `type`, `app_uid`, `audience` FROM `notification` WHERE `uid` = ? AND `user_id` = ? LIMIT 1',
|
||||
[uid, userId],
|
||||
);
|
||||
const found = await replica;
|
||||
const [row] =
|
||||
found.length > 0
|
||||
? found
|
||||
: await db.pread(fixed, [uid, userId]);
|
||||
if (row?.type === 'app.message' && row.app_uid) {
|
||||
this.clients.event.emit(
|
||||
'notif.acknowledged',
|
||||
|
||||
@@ -112,6 +112,28 @@ describe('NotificationStore', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('builds the row a replacement leaves as the table holds it', async () => {
|
||||
const created = await store.create({
|
||||
userId: user.id,
|
||||
value: { title: 'before' },
|
||||
type: 'app.message',
|
||||
audience: 'app-user',
|
||||
appUid: `app-${uuidv4()}`,
|
||||
group: 'g',
|
||||
});
|
||||
const replacedAt = Date.now();
|
||||
await store.updateValue(
|
||||
created.uid,
|
||||
user.id,
|
||||
{ title: 'after' },
|
||||
{ onlyUnseen: true, replacedAt },
|
||||
);
|
||||
|
||||
expect(
|
||||
store.replacedRow(created, { title: 'after' }, replacedAt),
|
||||
).toEqual(await store.getByUid(created.uid, { primary: true }));
|
||||
});
|
||||
|
||||
it('rejects a create with no user', async () => {
|
||||
await expect(store.create({ value: {} })).rejects.toThrow(
|
||||
'userId is required',
|
||||
|
||||
Reference in new issue
Block a user