Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 0 additions & 3 deletions src/api/SignalClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@
const self = this;

return withMutex(
safeTry<U, ConnectionError>(async function* () {

Check warning on line 277 in src/api/SignalClient.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed async generator function
self.connectOptions = opts;

const clientInfo = getClientInfo();
Expand Down Expand Up @@ -883,7 +883,7 @@
connection: WebSocketConnection,
): ResultAsync<SignalResponse, ConnectionError> {
// TODO: If inferring from the return type this could be more granular here than ConnectionError
return safeTry<SignalResponse, ConnectionError>(async function* () {

Check warning on line 886 in src/api/SignalClient.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed async generator function
const signalReader = connection.readable.getReader();

const firstMessage = await signalReader.read().finally(() => signalReader.releaseLock());
Expand Down Expand Up @@ -986,9 +986,6 @@
);
}
} catch (e) {
if (!(e instanceof ConnectionError)) {
console.warn('received unexpected error', e);
}
return err(
e instanceof ConnectionError
? e
Expand Down
69 changes: 38 additions & 31 deletions src/room/PCTransportManager.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Mutex } from '@livekit/mutex';
import { SignalTarget } from '@livekit/protocol';
import { ResultAsync, ok, okAsync } from 'neverthrow';
import log, { LoggerNames, getLogger } from '../logger';
import PCTransport, { PCEvents } from './PCTransport';
import { roomConnectOptionDefaults } from './defaults';
Expand Down Expand Up @@ -198,7 +199,10 @@ export class PCTransportManager {
}
}

async ensurePCTransportConnection(abortController?: AbortController, timeout?: number) {
async ensurePCTransportConnection(
abortController?: AbortController,
timeout?: number,
): Promise<ResultAsync<void, ConnectionError>> {
const unlock = await this.connectionLock.lock();
try {
if (
Expand All @@ -209,11 +213,11 @@ export class PCTransportManager {
this.log.debug('negotiation required, start negotiating', this.logContext);
this.publisher.negotiate();
}
await Promise.all(
return await ResultAsync.combine(
this.requiredTransports?.map((transport) =>
this.ensureTransportConnected(transport, abortController, timeout),
),
);
).andThen(() => ok());
} finally {
unlock();
}
Expand Down Expand Up @@ -330,43 +334,46 @@ export class PCTransportManager {
}
};

private async ensureTransportConnected(
private ensureTransportConnected(
pcTransport: PCTransport,
abortController?: AbortController,
timeout: number = this.peerConnectionTimeout,
) {
): ResultAsync<void, ConnectionError> {
const connectionState = pcTransport.getConnectionState();
if (connectionState === 'connected') {
return;
return okAsync();
}

return new Promise<void>(async (resolve, reject) => {
const abortHandler = () => {
this.log.warn('abort transport connection', this.logContext);
CriticalTimers.clearTimeout(connectTimeout);

reject(ConnectionError.cancelled('room connection has been cancelled'));
};
if (abortController?.signal.aborted) {
abortHandler();
}
abortController?.signal.addEventListener('abort', abortHandler);

const connectTimeout = CriticalTimers.setTimeout(() => {
abortController?.signal.removeEventListener('abort', abortHandler);
reject(ConnectionError.internal('could not establish pc connection'));
}, timeout);
return ResultAsync.fromPromise(
new Promise<void>(async (resolve, reject) => {
const abortHandler = () => {
this.log.warn('abort transport connection', this.logContext);
CriticalTimers.clearTimeout(connectTimeout);

while (this.state !== PCTransportState.CONNECTED) {
await sleep(50); // FIXME we shouldn't rely on `sleep` in the connection paths, as it invokes `setTimeout` which can be drastically throttled by browser implementations
if (abortController?.signal.aborted) {
reject(ConnectionError.cancelled('room connection has been cancelled'));
return;
};
if (abortController?.signal.aborted) {
abortHandler();
}
}
CriticalTimers.clearTimeout(connectTimeout);
abortController?.signal.removeEventListener('abort', abortHandler);
resolve();
});
abortController?.signal.addEventListener('abort', abortHandler);

const connectTimeout = CriticalTimers.setTimeout(() => {
abortController?.signal.removeEventListener('abort', abortHandler);
reject(ConnectionError.internal('could not establish pc connection'));
}, timeout);

while (this.state !== PCTransportState.CONNECTED) {
await sleep(50); // FIXME we shouldn't rely on `sleep` in the connection paths, as it invokes `setTimeout` which can be drastically throttled by browser implementations
if (abortController?.signal.aborted) {
reject(ConnectionError.cancelled('room connection has been cancelled'));
return;
}
}
CriticalTimers.clearTimeout(connectTimeout);
abortController?.signal.removeEventListener('abort', abortHandler);
resolve();
}),
(e: unknown) => e as ConnectionError,
);
}
}
26 changes: 18 additions & 8 deletions src/room/RTCEngine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1079,7 +1079,7 @@
regionUrl?: string,
): Promise<Result<void, UnexpectedConnectionState | SignalReconnectError>> {
const self = this;
const restartResultAsync = safeTry(async function* () {

Check warning on line 1082 in src/room/RTCEngine.ts

View workflow job for this annotation

GitHub Actions / test

Unexpected unnamed async generator function
if (!self.url || !self.token) {
// permanent failure, don't attempt reconnection
return err(new UnexpectedConnectionState('could not reconnect, url or token not saved'));
Expand Down Expand Up @@ -1119,7 +1119,7 @@
self.client.setReconnected();
self.emit(EngineEvent.SignalRestarted, joinResult.value);

await self.waitForPCReconnected();
yield* await self.waitForPCReconnected();
Copy link
Contributor Author

Choose a reason for hiding this comment

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

the other error was caused by self.waitForPCReconnected throwing.

This is the pitfall of doing a gradual adoption of this pattern. Extra care needed for ensuring that if a method is expected to not throw anymore it actually won't


// re-check signal connection state before setting engine as resumed
if (self.client.currentState !== SignalConnectionState.CONNECTED) {
Expand Down Expand Up @@ -1150,7 +1150,7 @@

private async resumeConnection(
reason?: ReconnectReason,
): Promise<Result<void, SignalReconnectError>> {
): Promise<Result<void, SignalReconnectError | UnexpectedConnectionState>> {
if (!this.url || !this.token) {
// permanent failure, don't attempt reconnection
return errAsync(new UnexpectedConnectionState('could not reconnect, url or token not saved'));
Expand All @@ -1172,7 +1172,11 @@
);

if (reconnectResult.isErr()) {
return err(reconnectResult.error);
return err(
new SignalReconnectError(
Copy link
Contributor Author

Choose a reason for hiding this comment

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

one of the errors was caused by this method returning a ConnectionError for some reason the return type on the resumeConnection method isn't being type checked here it seems.

This led to the reconnect flow triggering a "full reconnect" instead of a "resume" as "resumes" can only happen for SignalReconnectErrors

`${reconnectResult.error.reasonName}: ${reconnectResult.error.message}`,
),
);
}

this.emit(EngineEvent.SignalResumed);
Expand Down Expand Up @@ -1224,24 +1228,30 @@
if (!this.pcManager) {
throw new UnexpectedConnectionState('PC manager is closed');
}
await this.pcManager.ensurePCTransportConnection(abortController, timeout);
return this.pcManager.ensurePCTransportConnection(abortController, timeout);
}

private async waitForPCReconnected() {
private async waitForPCReconnected(): Promise<
Result<void, UnexpectedConnectionState | ConnectionError>
> {
this.pcState = PCState.Reconnecting;

this.log.debug('waiting for peer connection to reconnect', this.logContext);
try {
await sleep(minReconnectWait); // FIXME setTimeout again not ideal for a connection critical path
if (!this.pcManager) {
throw new UnexpectedConnectionState('PC manager is closed');
return err(new UnexpectedConnectionState('PC manager is closed'));
}
await this.pcManager.ensurePCTransportConnection(undefined, this.peerConnectionTimeout);
const res = await this.pcManager.ensurePCTransportConnection(
undefined,
this.peerConnectionTimeout,
);
this.pcState = PCState.Connected;
return res;
} catch (e: any) {
// TODO do we need a `failed` state here for the PC?
this.pcState = PCState.Disconnected;
throw ConnectionError.internal(`could not establish PC connection: ${e.message}`);
return err(ConnectionError.internal(`could not establish PC connection: ${e.message}`));
}
}

Expand Down
7 changes: 6 additions & 1 deletion src/room/Room.ts
Original file line number Diff line number Diff line change
Expand Up @@ -925,10 +925,15 @@ class Room extends (EventEmitter as new () => TypedEmitter<RoomEventCallbacks>)
}

try {
await this.engine.waitForPCInitialConnection(
const result = await this.engine.waitForPCInitialConnection(
this.connOptions.peerConnectionTimeout,
abortController,
);
if (result.isErr()) {
await this.engine.close();
this.recreateEngine();
throw result.error;
}
} catch (e) {
await this.engine.close();
this.recreateEngine();
Expand Down
Loading