diff --git a/src/backend/drivers/notification/NotificationDriver.sendAt.test.ts b/src/backend/drivers/notification/NotificationDriver.sendAt.test.ts index e246abda5..710d454f4 100644 --- a/src/backend/drivers/notification/NotificationDriver.sendAt.test.ts +++ b/src/backend/drivers/notification/NotificationDriver.sendAt.test.ts @@ -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 | 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 (fn: () => Promise) => { + 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, + 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)); + }); +}); diff --git a/src/backend/drivers/notification/NotificationDriver.test.ts b/src/backend/drivers/notification/NotificationDriver.test.ts index e27039eb0..7b78cf432 100644 --- a/src/backend/drivers/notification/NotificationDriver.test.ts +++ b/src/backend/drivers/notification/NotificationDriver.test.ts @@ -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 | null; + let writes: unknown[][]; + let reads: unknown[][]; + try { + result = (await withActor(actor, () => + driver.create({ + object: { value: { type: NOTIF_TYPE, title: 'once' } }, + }), + )) as Record | 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( diff --git a/src/backend/drivers/notification/NotificationDriver.ts b/src/backend/drivers/notification/NotificationDriver.ts index 7aac42f41..d9af6639e 100644 --- a/src/backend/drivers/notification/NotificationDriver.ts +++ b/src/backend/drivers/notification/NotificationDriver.ts @@ -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): Promise { @@ -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 { + ): Promise { 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 { + ): Promise { // 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, @@ -770,31 +764,18 @@ export class NotificationDriver extends PuterDriver { silent: boolean; group?: string | null; }, - ): Promise { - const uid = await this.services.notification.notify( + ): Promise { + 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 | null> { - return this.#toClient( - await this.stores.notification.getByUid(uid, { - userId, - primary: true, - }), - ); + return row; } // -- Permissions ------------------------------------------------- diff --git a/src/backend/services/notification/NotificationService.test.ts b/src/backend/services/notification/NotificationService.test.ts index 28353f928..919b86b87 100644 --- a/src/backend/services/notification/NotificationService.test.ts +++ b/src/backend/services/notification/NotificationService.test.ts @@ -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, diff --git a/src/backend/services/notification/NotificationService.ts b/src/backend/services/notification/NotificationService.ts index 43b337a1e..9e32e95fc 100644 --- a/src/backend/services/notification/NotificationService.ts +++ b/src/backend/services/notification/NotificationService.ts @@ -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, - opts: { - type: NotificationTypeName; - appUid?: string | null; - silent?: boolean; - group?: string | null; - }, + opts: NotifyOptions, ): Promise { + 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, + opts: NotifyOptions, + ): Promise { 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 { + 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, + opts: { type: NotificationTypeName }, + ): Promise { + 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, + opts: { + type: NotificationTypeName; + silent?: boolean; + replacedAt?: number; + appUid?: string | null; + }, + ): Promise | 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; } /** diff --git a/src/backend/stores/notification/NotificationStore.dismissal.test.ts b/src/backend/stores/notification/NotificationStore.dismissal.test.ts index 46279bd23..9381f605a 100644 --- a/src/backend/stores/notification/NotificationStore.dismissal.test.ts +++ b/src/backend/stores/notification/NotificationStore.dismissal.test.ts @@ -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 | null, changed = true) => { +const setup = (row: Record | null, changed = true, replica: Record | 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 => 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(() => {}); diff --git a/src/backend/stores/notification/NotificationStore.js b/src/backend/stores/notification/NotificationStore.js index 4ea5bd693..9aca8e0d8 100644 --- a/src/backend/stores/notification/NotificationStore.js +++ b/src/backend/stores/notification/NotificationStore.js @@ -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; + * 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} */ 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} */ 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} - */ - 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', diff --git a/src/backend/stores/notification/NotificationStore.test.js b/src/backend/stores/notification/NotificationStore.test.js index ba15f64eb..83dd1510b 100644 --- a/src/backend/stores/notification/NotificationStore.test.js +++ b/src/backend/stores/notification/NotificationStore.test.js @@ -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',