From 79c3dcc2ebd2b2e120a4b6e60a6c54ddae5c9866 Mon Sep 17 00:00:00 2001 From: Ivan Sekovanikj Date: Wed, 2 Dec 2026 19:13:03 +0100 Subject: [PATCH 1/2] feat(offline-support): delete a rewound message range Implements the offline DB's deleteMessagesForChannelInRange: deletes a channel's messages created after a lower bound and at or before an upper one, as a channel rewind hides them. Their reactions go with them through the schema's cascade, as with truncation. --- package/src/store/OfflineDB.ts | 2 + .../deleteMessagesForChannelInRange.test.ts | 82 +++++++++++++++++++ .../apis/deleteMessagesForChannelInRange.ts | 43 ++++++++++ package/src/store/apis/index.ts | 1 + 4 files changed, 128 insertions(+) create mode 100644 package/src/store/apis/__tests__/deleteMessagesForChannelInRange.test.ts create mode 100644 package/src/store/apis/deleteMessagesForChannelInRange.ts diff --git a/package/src/store/OfflineDB.ts b/package/src/store/OfflineDB.ts index 9e3784ba68..74cc0f463a 100644 --- a/package/src/store/OfflineDB.ts +++ b/package/src/store/OfflineDB.ts @@ -100,6 +100,8 @@ export class OfflineDB extends AbstractOfflineDB { deleteMessagesForChannel = api.deleteMessagesForChannel; + deleteMessagesForChannelInRange = api.deleteMessagesForChannelInRange; + dropPendingTasks = api.dropPendingTasks; hardDeleteMessage = api.deleteMessage; diff --git a/package/src/store/apis/__tests__/deleteMessagesForChannelInRange.test.ts b/package/src/store/apis/__tests__/deleteMessagesForChannelInRange.test.ts new file mode 100644 index 0000000000..5404a393e0 --- /dev/null +++ b/package/src/store/apis/__tests__/deleteMessagesForChannelInRange.test.ts @@ -0,0 +1,82 @@ +import type { ChannelStateResponseFields, TimestampNS } from 'stream-chat'; + +import { generateChannelResponse } from '../../../mock-builders/generator/channel'; +import { generateMessage } from '../../../mock-builders/generator/message'; +import { BetterSqlite } from '../../../test-utils/BetterSqlite'; +import { SqliteClient } from '../../SqliteClient'; +import { deleteMessagesForChannelInRange } from '../deleteMessagesForChannelInRange'; +import { upsertChannels } from '../upsertChannels'; + +// unix nanoseconds of minute `minute`, as the messages table stores `createdAt` +const at = (minute: number) => (Date.UTC(2026, 0, 1, 0, minute) * 1e6) as TimestampNS; + +describe('deleteMessagesForChannelInRange', () => { + let cid: string; + let otherCid: string; + + const storeChannel = async (minutes: number[]) => { + const channelResponse = generateChannelResponse({ members: [], messages: [] }); + const channelCid = channelResponse.channel.cid as string; + channelResponse.messages = minutes.map((minute) => + generateMessage({ cid: channelCid, created_at: at(minute), id: `${channelCid}-m${minute}` }), + ) as unknown as typeof channelResponse.messages; + await upsertChannels({ + channels: [channelResponse] as unknown as ChannelStateResponseFields[], + isLatestMessagesSet: true, + }); + return channelCid; + }; + + const storedIds = async (channelCid: string) => + (await BetterSqlite.selectFromTable<{ cid: string; id: string }>('messages')) + .filter((row) => row.cid === channelCid) + .map((row) => row.id.replace(`${channelCid}-`, '')) + .sort(); + + beforeEach(async () => { + await SqliteClient.initializeDatabase(); + await BetterSqlite.openDB(); + cid = await storeChannel([1, 2, 3, 4]); + otherCid = await storeChannel([3]); + }); + + afterEach(() => { + BetterSqlite.dropAllTables(); + BetterSqlite.closeDB(); + }); + + it('deletes the messages created after `after` and at or before `upTo`', async () => { + await deleteMessagesForChannelInRange({ after: at(1), cid, upTo: at(3) }); + + expect(await storedIds(cid)).toEqual(['m1', 'm4']); + }); + + it('deletes from the first message when there is no `after`', async () => { + await deleteMessagesForChannelInRange({ after: null, cid, upTo: at(2) }); + + expect(await storedIds(cid)).toEqual(['m3', 'm4']); + }); + + it("leaves other channels' messages", async () => { + await deleteMessagesForChannelInRange({ after: at(1), cid, upTo: at(4) }); + + expect(await storedIds(otherCid)).toEqual(['m3']); + }); + + it('only returns the query with execute=false', async () => { + const queries = await deleteMessagesForChannelInRange({ + after: at(1), + cid, + execute: false, + upTo: at(4), + }); + + expect(queries).toEqual([ + [ + 'DELETE FROM messages WHERE cid = ? AND createdAt > ? AND createdAt <= ?', + [cid, at(1), at(4)], + ], + ]); + expect(await storedIds(cid)).toEqual(['m1', 'm2', 'm3', 'm4']); + }); +}); diff --git a/package/src/store/apis/deleteMessagesForChannelInRange.ts b/package/src/store/apis/deleteMessagesForChannelInRange.ts new file mode 100644 index 0000000000..d2c8f94a76 --- /dev/null +++ b/package/src/store/apis/deleteMessagesForChannelInRange.ts @@ -0,0 +1,43 @@ +import type { TimestampNS } from 'stream-chat'; + +import { SqliteClient } from '../SqliteClient'; + +/** + * Deletes the channel's messages created after `after` (from the first one when it is not set) and + * at or before `upTo`, as a rewind hides them. Their reactions go with them (`ON DELETE CASCADE`). + */ +export const deleteMessagesForChannelInRange = async ({ + after, + cid, + execute = true, + upTo, +}: { + cid: string; + /** Unix nanoseconds, as the API sends it. */ + after?: TimestampNS | null; + /** Unix nanoseconds, as the API sends it. */ + upTo: TimestampNS; + execute?: boolean; +}) => { + // `createdAt` holds unix nanoseconds, so the bounds are too and the comparison is numeric. + const query: [string, (string | number)[]] = + after == null + ? [`DELETE FROM messages WHERE cid = ? AND createdAt <= ?`, [cid, upTo]] + : [ + `DELETE FROM messages WHERE cid = ? AND createdAt > ? AND createdAt <= ?`, + [cid, after, upTo], + ]; + + SqliteClient.logger?.('info', 'deleteMessagesForChannelInRange', { + after, + cid, + execute, + upTo, + }); + + if (execute) { + await SqliteClient.executeSql.apply(null, query); + } + + return [query]; +}; diff --git a/package/src/store/apis/index.ts b/package/src/store/apis/index.ts index 08de16ac9b..9f86481ba8 100644 --- a/package/src/store/apis/index.ts +++ b/package/src/store/apis/index.ts @@ -2,6 +2,7 @@ export * from './deleteChannel'; export * from './deleteMember'; export * from './deleteMessage'; export * from './deleteMessagesForChannel'; +export * from './deleteMessagesForChannelInRange'; export * from './getAllChannelIds'; export * from './getAppSettings'; export * from './getChannelMessages'; From 6b9442841f61f13f808a2e8fa2af1156c3bd7299 Mon Sep 17 00:00:00 2001 From: Ivan Sekovanikj Date: Thu, 3 Dec 2026 12:41:55 +0100 Subject: [PATCH 2/2] feat(offline-support): keep the listed messages in a rewound range delete `deleteMessagesForChannelInRange` takes `keepMessageIds` and leaves those rows, which the LLC fills with the channel's unsent messages, so a rewind no longer deletes a failed message that memory keeps. --- .../deleteMessagesForChannelInRange.test.ts | 11 +++++++ .../apis/deleteMessagesForChannelInRange.ts | 30 ++++++++++++++----- 2 files changed, 33 insertions(+), 8 deletions(-) diff --git a/package/src/store/apis/__tests__/deleteMessagesForChannelInRange.test.ts b/package/src/store/apis/__tests__/deleteMessagesForChannelInRange.test.ts index 5404a393e0..f2cb86db65 100644 --- a/package/src/store/apis/__tests__/deleteMessagesForChannelInRange.test.ts +++ b/package/src/store/apis/__tests__/deleteMessagesForChannelInRange.test.ts @@ -57,6 +57,17 @@ describe('deleteMessagesForChannelInRange', () => { expect(await storedIds(cid)).toEqual(['m3', 'm4']); }); + it('keeps the messages in `keepMessageIds`', async () => { + await deleteMessagesForChannelInRange({ + after: at(1), + cid, + keepMessageIds: [`${cid}-m2`, `${cid}-m4`], + upTo: at(4), + }); + + expect(await storedIds(cid)).toEqual(['m1', 'm2', 'm4']); + }); + it("leaves other channels' messages", async () => { await deleteMessagesForChannelInRange({ after: at(1), cid, upTo: at(4) }); diff --git a/package/src/store/apis/deleteMessagesForChannelInRange.ts b/package/src/store/apis/deleteMessagesForChannelInRange.ts index d2c8f94a76..0dafa15338 100644 --- a/package/src/store/apis/deleteMessagesForChannelInRange.ts +++ b/package/src/store/apis/deleteMessagesForChannelInRange.ts @@ -4,12 +4,14 @@ import { SqliteClient } from '../SqliteClient'; /** * Deletes the channel's messages created after `after` (from the first one when it is not set) and - * at or before `upTo`, as a rewind hides them. Their reactions go with them (`ON DELETE CASCADE`). + * at or before `upTo`, as a rewind hides them, except those in `keepMessageIds`. Their reactions go + * with them (`ON DELETE CASCADE`). */ export const deleteMessagesForChannelInRange = async ({ after, cid, execute = true, + keepMessageIds, upTo, }: { cid: string; @@ -17,21 +19,33 @@ export const deleteMessagesForChannelInRange = async ({ after?: TimestampNS | null; /** Unix nanoseconds, as the API sends it. */ upTo: TimestampNS; + /** Messages kept even inside the range: the unsent ones, which the server never had. */ + keepMessageIds?: string[]; execute?: boolean; }) => { // `createdAt` holds unix nanoseconds, so the bounds are too and the comparison is numeric. - const query: [string, (string | number)[]] = - after == null - ? [`DELETE FROM messages WHERE cid = ? AND createdAt <= ?`, [cid, upTo]] - : [ - `DELETE FROM messages WHERE cid = ? AND createdAt > ? AND createdAt <= ?`, - [cid, after, upTo], - ]; + const conditions = ['cid = ?']; + const params: (string | number)[] = [cid]; + if (after != null) { + conditions.push('createdAt > ?'); + params.push(after); + } + conditions.push('createdAt <= ?'); + params.push(upTo); + if (keepMessageIds?.length) { + conditions.push(`id NOT IN (${keepMessageIds.map(() => '?').join(', ')})`); + params.push(...keepMessageIds); + } + const query: [string, (string | number)[]] = [ + `DELETE FROM messages WHERE ${conditions.join(' AND ')}`, + params, + ]; SqliteClient.logger?.('info', 'deleteMessagesForChannelInRange', { after, cid, execute, + keepMessageIds, upTo, });