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
31 changes: 31 additions & 0 deletions src/client/initMatrix.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,37 @@ describe('startupSyncStore', () => {
expect(deleteDatabase).not.toHaveBeenCalled();
});

it('recovers when the sync row comes back as a null value', async () => {
const original = IDBObjectStore.prototype.openCursor;
let reads = 0;
vi.spyOn(IDBObjectStore.prototype, 'openCursor').mockImplementation(function (
this: IDBObjectStore,
...args
) {
if (this.name !== 'sync' || reads > 0) return original.apply(this, args);
reads += 1;
const request: IDBRequest<IDBCursorWithValue | null> = new IDBRequest();
let cursor: unknown = {
value: null,
continue: () => {
cursor = null;
queueMicrotask(() => request.onsuccess?.(new Event('success')));
},
};
Object.defineProperty(request, 'result', { get: () => cursor });
queueMicrotask(() => request.onsuccess?.(new Event('success')));
return request;
});
const deleteDatabase = vi.spyOn(indexedDB, 'deleteDatabase');

await expect(startupSyncStore(mx, dbName)).resolves.toBeUndefined();

expect(await mx.store.getSavedSync()).toBeNull();
expect(await mx.store.getOldestToDeviceBatch()).toMatchObject({ txnId: 'pending-message' });
expect(mx.getAccessToken()).toBe('session-token');
expect(deleteDatabase).not.toHaveBeenCalled();
});

it('keeps a readable sync snapshot', async () => {
await startupSyncStore(mx, dbName);
expect(await mx.store.getSavedSyncToken()).toBe('cached-token');
Expand Down
7 changes: 6 additions & 1 deletion src/client/initMatrix.ts
Original file line number Diff line number Diff line change
Expand Up @@ -456,13 +456,18 @@ type ClientInitializationResult =
| { ok: true; mx: MatrixClient }
| { ok: false; error: unknown; phase: 'sync_store' | 'rust_crypto' };

const isUnreadableSyncSnapshot = (error: unknown): boolean => {
if (error instanceof TypeError) return error.message.includes('nextBatch');
return error instanceof Error && error.message === 'selectQuery failed for sync';
};

export const startupSyncStore = async (mx: MatrixClient, dbName: string): Promise<void> => {
try {
await mx.store.startup();
return;
} catch (error) {
await mx.store.destroy();
if (!(error instanceof Error) || error.message !== 'selectQuery failed for sync') throw error;
if (!isUnreadableSyncSnapshot(error)) throw error;
debugLog.warn('sync', 'Rebuilding unreadable sync snapshot', { error });
}

Expand Down
Loading