Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 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
20 changes: 18 additions & 2 deletions src/channel_manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,19 @@ export class ChannelManager extends WithSubscriptions {
`Maximum number of retries reached in queryChannels. Last error message is: ${err}`,
);

this.state.partialNext({ error: wrappedError });
const state = this.state.getLatestValue();
// If the offline support is enabled, and there are channels in the DB, we should not error out.
const isOfflineSupportEnabledWithChannels =
this.client.offlineDb && state.channels.length > 0;

this.state.partialNext({
error: isOfflineSupportEnabledWithChannels ? undefined : wrappedError,
pagination: {
...state.pagination,
isLoading: false,
isLoadingNext: false,
},
});
return;
}

Expand Down Expand Up @@ -444,7 +456,11 @@ export class ChannelManager extends WithSubscriptions {
this.client.logger('error', (error as Error).message);
this.state.next((currentState) => ({
...currentState,
pagination: { ...currentState.pagination, isLoadingNext: false },
pagination: {
...currentState.pagination,
isLoadingNext: false,
isLoading: false,
},
}));
throw error;
}
Expand Down
16 changes: 16 additions & 0 deletions src/offline-support/offline_sync_manager.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import type { ExecuteBatchDBQueriesType } from './types';
import type { StreamChat } from '../client';
import type { AbstractOfflineDB } from './offline_support_api';
import type { AxiosError } from 'axios';
import { isAxiosError } from 'axios';
import type { APIErrorResponse } from '../types';

/**
* Manages synchronization between the local offline database and the Stream backend.
Expand Down Expand Up @@ -174,8 +177,21 @@ export class OfflineDBSyncManager {
});
} catch (e) {
console.log('An error has occurred while syncing the DB.', e);

if (isAxiosError(e) && e.code === 'ECONNABORTED') {
// If the sync was aborted due to timeout, we can simply return
return;
}

const error = e as AxiosError<APIErrorResponse>;

if (error.response?.data?.code === 23) {
return;
}

// Error will be raised by the sync API if there are too many events.
// In that case reset the entire DB and start fresh.
// We avoid resetting the DB if the error is due to timeout.
await this.offlineDb.resetDB();
}
};
Expand Down
41 changes: 40 additions & 1 deletion test/unit/channel_manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ describe('ChannelManager', () => {
});

it('should properly set eventHandlerOverrides, options and queryChannelsRequest if they are passed', async () => {
const eventHandlerOverrides = { newMessageHandler: () => {} };
const eventHandlerOverrides = {
newMessageHandler: () => {},
};
const options = {
allowNotLoadedChannelPromotionForEvent: {
'channel.visible': false,
Expand Down Expand Up @@ -805,6 +807,43 @@ describe('ChannelManager', () => {
expect(initialized).to.be.false;
});

it('should not set error when offline support is enabled and there are channels in the DB', async () => {
clientQueryChannelsStub.callsFake(() => mockChannelPages[2]);
client.setOfflineDBApi(new MockOfflineDB({ client }));
await client.offlineDb!.init(client.userID as string);

channelManager.state.partialNext({
channels: mockChannelPages[2],
});

clientQueryChannelsStub.rejects(new Error('fail'));
const sleepSpy = vi.spyOn(utils, 'sleep');
const stateChangeSpy = sinon.spy();
channelManager.state.subscribeWithSelector(
(nextValue) => ({
error: nextValue.error,
}),
stateChangeSpy,
);
stateChangeSpy.resetHistory();

await channelManager['executeChannelsQuery']({
filters: { filterA: true },
sort: { asc: 1 },
options: { limit: 10, offset: 0 },
});

const { channels, initialized, error } = channelManager.state.getLatestValue();

expect(clientQueryChannelsStub.callCount).to.equal(
DEFAULT_QUERY_CHANNELS_RETRY_COUNT + 1,
); // // initial + however many retried are configured
expect(sleepSpy).toHaveBeenCalledTimes(DEFAULT_QUERY_CHANNELS_RETRY_COUNT);
expect(error).toEqual(undefined);
expect(channels.length).to.equal(5);
expect(initialized).to.be.false;
});

it('does not retry more than 3 times', async () => {
clientQueryChannelsStub.rejects(new Error('fail'));
const sleepSpy = vi.spyOn(utils, 'sleep');
Expand Down
36 changes: 36 additions & 0 deletions test/unit/offline-support/offline_support_api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2325,6 +2325,42 @@ describe('OfflineDBSyncManager', () => {
expect(upsertUserSyncStatusSpy).toHaveBeenCalled();
});

it('do not resets DB if sync API throws an AxiosError with request timeout', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

totally not important nitpick

Suggested change
it('do not resets DB if sync API throws an AxiosError with request timeout', async () => {
it('do not reset the DB if the sync API throws an AxiosError with request timeout', async () => {

const recentDate = new Date();
recentDate.setDate(recentDate.getDate() - 10);
getLastSyncedAtSpy.mockResolvedValueOnce(recentDate.toString());

const axiosError = {
isAxiosError: true,
code: 'ECONNABORTED',
response: { data: { code: 4 } },
} as AxiosError<APIErrorResponse>;

syncApiSpy.mockRejectedValueOnce(axiosError);

await (syncManager as any).sync();

expect(resetDBSpy).not.toHaveBeenCalled();
expect(upsertUserSyncStatusSpy).not.toHaveBeenCalled();
});

it('do not reset DB if sync API throws a BE error with response timeout', async () => {
const recentDate = new Date();
recentDate.setDate(recentDate.getDate() - 10);
getLastSyncedAtSpy.mockResolvedValueOnce(recentDate.toString());

const axiosError = {
response: { data: { code: 23 } },
} as AxiosError<APIErrorResponse>;

syncApiSpy.mockRejectedValueOnce(axiosError);

await (syncManager as any).sync();

expect(resetDBSpy).not.toHaveBeenCalled();
expect(upsertUserSyncStatusSpy).not.toHaveBeenCalled();
});

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the test just below this one, please add an additional check for the channelManager.state.isLoading value (it should now be false with the recent fixes)

it('resets DB if sync API throws an error', async () => {
const recentDate = new Date();
recentDate.setDate(recentDate.getDate() - 10);
Expand Down