Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
47 changes: 41 additions & 6 deletions packages/client/src/StreamVideoClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import type {
import {
AllClientEvents,
ClientEventListener,
ErrorFromResponse,
StreamClientOptions,
TokenOrProvider,
TokenProvider,
Expand Down Expand Up @@ -180,12 +181,7 @@ export class StreamVideoClient {
.map((call) => call.cid);
if (callsToReWatch.length <= 0) return;

this.logger.info(`Rewatching calls ${callsToReWatch.join(', ')}`);
this.queryCalls({
watch: true,
filter_conditions: { cid: { $in: callsToReWatch } },
sort: [{ field: 'cid', direction: 1 }],
}).catch((err) => {
this.rewatchCalls(callsToReWatch).catch((err) => {
this.logger.error('Failed to re-watch calls', err);
});
}),
Expand Down Expand Up @@ -252,6 +248,45 @@ export class StreamVideoClient {
}
};

/**
* Rewatches the given calls with retry logic.
* @param callsToReWatch array of call IDs to rewatch
*/
private rewatchCalls = async (callsToReWatch: string[]): Promise<void> => {
this.logger.info(`Rewatching calls ${callsToReWatch.join(', ')}`);
const maxRetries = 3;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
this.logger.info(
`Rewatching calls ${callsToReWatch.join(', ')} attempt ${attempt + 1}`,
);

await this.queryCalls({
watch: true,
filter_conditions: { cid: { $in: callsToReWatch } },
sort: [{ field: 'cid', direction: 1 }],
});

return;
} catch (err) {
if (err instanceof ErrorFromResponse && err.unrecoverable) {
throw err;
}

this.logger.warn(
`Failed to re-watch calls (attempt ${attempt + 1}/${maxRetries}), retrying.`,
err,
);

if (attempt === maxRetries - 1) {
throw err;
}
}

await sleep(retryInterval(attempt));
}
};

/**
* Connects the given user to the client.
* Only one user can connect at a time, if you want to change users, call `disconnectUser` before connecting a new user.
Expand Down
106 changes: 106 additions & 0 deletions packages/client/src/__tests__/StreamVideoClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,3 +275,109 @@ describe('StreamVideoClient.connectUser retries', () => {
await client.disconnectUser();
});
});

describe('StreamVideoClient.watchCalls retries', () => {
it('should retry queryCalls up to 3 times after reconnecting', async () => {
vi.useFakeTimers();
const client = new StreamVideoClient(apiKey, {
browser: true,
});

const user = { id: 'jane' };
const token = serverClient.generateUserToken({ user_id: user.id });
await client.connectUser(user, token);

const call = client.call('default', generateUUIDv4());
await call.getOrCreate();

const queryCallsSpy = vi
.spyOn(client, 'queryCalls')
.mockRejectedValueOnce(new Error('fail 1'))
.mockRejectedValueOnce(new Error('fail 2'))
.mockResolvedValue({
calls: [],
duration: '0ms',
});

client.streamClient.dispatchEvent({
type: 'connection.changed',
online: true,
});

await vi.runAllTimersAsync();

expect(queryCallsSpy).toHaveBeenCalledTimes(3);

await client.disconnectUser();

vi.useRealTimers();
});

it('should stop retrying after 3 failures on reconnect', async () => {
vi.useFakeTimers();

const client = new StreamVideoClient(apiKey, {
browser: true,
});

const user = { id: 'jane' };
const token = serverClient.generateUserToken({ user_id: user.id });
await client.connectUser(user, token);

const call = client.call('default', generateUUIDv4());
await call.getOrCreate();

const queryCallsSpy = vi
.spyOn(client, 'queryCalls')
.mockRejectedValueOnce(new Error('fail 1'))
.mockRejectedValueOnce(new Error('fail 2'))
.mockRejectedValueOnce(new Error('fail 3'))
.mockResolvedValue({
calls: [],
duration: '0ms',
});

client.streamClient.dispatchEvent({
type: 'connection.changed',
online: true,
});

await vi.runAllTimersAsync();

expect(queryCallsSpy).toHaveBeenCalledTimes(3);

await client.disconnectUser();
vi.useRealTimers();
});

it('should call only once when no errors occur', async () => {
vi.useFakeTimers();
const client = new StreamVideoClient(apiKey, {
browser: true,
});

const user = { id: 'jane' };
const token = serverClient.generateUserToken({ user_id: user.id });
await client.connectUser(user, token);

const call = client.call('default', generateUUIDv4());
await call.getOrCreate();

const queryCallsSpy = vi.spyOn(client, 'queryCalls').mockResolvedValue({
calls: [],
duration: '0ms',
});

client.streamClient.dispatchEvent({
type: 'connection.changed',
online: true,
});

await vi.runAllTimersAsync();

expect(queryCallsSpy).toHaveBeenCalledTimes(1);

await client.disconnectUser();
vi.useRealTimers();
});
});
Loading