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
5 changes: 5 additions & 0 deletions .changeset/silent-lamps-grin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-client": patch
---

Signal leave on failed connection attempts if signalling is connected
5 changes: 5 additions & 0 deletions .changeset/silly-views-win.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"livekit-client": patch
---

Vendored ts-debounce and added critical timers to debounce function
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,6 @@
"jose": "^6.1.0",
"loglevel": "^1.9.2",
"sdp-transform": "^2.15.0",
"ts-debounce": "^4.0.0",
"tslib": "2.8.1",
"typed-emitter": "^2.1.0",
"webrtc-adapter": "^9.0.1"
Expand Down
26 changes: 9 additions & 17 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/room/PCTransport.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Mutex } from '@livekit/mutex';
import { EventEmitter } from 'events';
import { parse, write } from 'sdp-transform';
import { debounce } from 'ts-debounce';
import type { MediaDescription, SessionDescription } from 'sdp-transform';
import log, { LoggerNames, getLogger } from '../logger';
import { debounce } from './debounce';
import { NegotiationError, UnexpectedConnectionState } from './errors';
import type { LoggerOptions } from './types';
import { ddExtensionURI, isSVCCodec, isSafari } from './utils';
Expand Down
14 changes: 10 additions & 4 deletions src/room/Room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -740,7 +740,7 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
`Initial connection failed with ConnectionError: ${error.message}. Retrying with another region: ${nextUrl}`,
this.logContext,
);
this.recreateEngine();
this.recreateEngine(true);
await connectFn(resolve, reject, nextUrl);
} else {
this.handleDisconnect(
Expand Down Expand Up @@ -866,7 +866,7 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
) {
this.log.info('Reconnection attempt replaced by new connection attempt', this.logContext);
// make sure we close and recreate the existing engine in order to get rid of any potentially ongoing reconnection attempts
this.recreateEngine();
this.recreateEngine(true);
} else {
// create engine if previously disconnected
this.maybeCreateEngine();
Expand Down Expand Up @@ -1380,8 +1380,14 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
);
}

private recreateEngine() {
this.engine?.close();
private recreateEngine(sendLeave?: boolean) {
const oldEngine = this.engine;

if (sendLeave && oldEngine && !oldEngine.client.isDisconnected) {
oldEngine.client.sendLeave().finally(() => oldEngine.close());
} else {
oldEngine?.close();
}
/* @ts-ignore */
this.engine = undefined;
this.isResuming = false;
Expand Down
115 changes: 115 additions & 0 deletions src/room/debounce.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* Originally from ts-debounce (https://github.com/chodorowicz/ts-debounce)
* with the following license:
*
* MIT License
*
* Copyright (c) 2017 Jakub Chodorowicz
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* Modified to use CriticalTimers for reliable timer execution.
*/
/* eslint-disable @typescript-eslint/no-this-alias, @typescript-eslint/no-unused-expressions, @typescript-eslint/no-shadow */
import CriticalTimers from './timers';

export type Options<Result> = {
isImmediate?: boolean;
maxWait?: number;
callback?: (data: Result) => void;
};

export interface DebouncedFunction<Args extends any[], F extends (...args: Args) => any> {
(this: ThisParameterType<F>, ...args: Args & Parameters<F>): Promise<ReturnType<F>>;
cancel: (reason?: any) => void;
}

interface DebouncedPromise<FunctionReturn> {
resolve: (result: FunctionReturn) => void;
reject: (reason?: any) => void;
}

export function debounce<Args extends any[], F extends (...args: Args) => any>(
func: F,
waitMilliseconds = 50,
options: Options<ReturnType<F>> = {},
): DebouncedFunction<Args, F> {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
const isImmediate = options.isImmediate ?? false;
const callback = options.callback ?? false;
const maxWait = options.maxWait;
let lastInvokeTime = Date.now();

let promises: DebouncedPromise<ReturnType<F>>[] = [];

function nextInvokeTimeout() {
if (maxWait !== undefined) {
const timeSinceLastInvocation = Date.now() - lastInvokeTime;

if (timeSinceLastInvocation + waitMilliseconds >= maxWait) {
return maxWait - timeSinceLastInvocation;
}
}

return waitMilliseconds;
}

const debouncedFunction = function (this: ThisParameterType<F>, ...args: Parameters<F>) {

Check warning on line 73 in src/room/debounce.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed function

Check warning on line 73 in src/room/debounce.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed function
const context = this;
return new Promise<ReturnType<F>>((resolve, reject) => {
const invokeFunction = function () {

Check warning on line 76 in src/room/debounce.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed function

Check warning on line 76 in src/room/debounce.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed function
timeoutId = undefined;
lastInvokeTime = Date.now();
if (!isImmediate) {
const result = func.apply(context, args);
callback && callback(result);
// biome-ignore lint/suspicious/useIterableCallbackReturn: vendored code
promises.forEach(({ resolve }) => resolve(result));
promises = [];
}
};

const shouldCallNow = isImmediate && timeoutId === undefined;

if (timeoutId !== undefined) {
CriticalTimers.clearTimeout(timeoutId);
}

timeoutId = CriticalTimers.setTimeout(invokeFunction, nextInvokeTimeout());

if (shouldCallNow) {
const result = func.apply(context, args);
callback && callback(result);
return resolve(result);
}
promises.push({ resolve, reject });
});
};

debouncedFunction.cancel = function (reason?: any) {

Check warning on line 105 in src/room/debounce.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed function

Check warning on line 105 in src/room/debounce.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed function
if (timeoutId !== undefined) {
CriticalTimers.clearTimeout(timeoutId);
}
// biome-ignore lint/suspicious/useIterableCallbackReturn: vendored code
promises.forEach(({ reject }) => reject(reason));
promises = [];
};

return debouncedFunction;
}
2 changes: 1 addition & 1 deletion src/room/track/LocalTrack.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Mutex } from '@livekit/mutex';
import { debounce } from 'ts-debounce';
import { getBrowser } from '../../utils/browserParser';
import DeviceManager from '../DeviceManager';
import { debounce } from '../debounce';
import { DeviceUnsupportedError, TrackInvalidError } from '../errors';
import { TrackEvent } from '../events';
import type { LoggerOptions } from '../types';
Expand Down
2 changes: 1 addition & 1 deletion src/room/track/RemoteVideoTrack.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { debounce } from 'ts-debounce';
import { debounce } from '../debounce';
import { TrackEvent } from '../events';
import type { VideoReceiverStats } from '../stats';
import { computeBitrate } from '../stats';
Expand Down
Loading