11// Copyright (C) 2025 Intel Corporation
22// SPDX-License-Identifier: Apache-2.0
33
4+ import { v4 as uuid } from 'uuid' ;
5+
46import { fetchClient } from '../../../api/client' ;
57
68export type WebRTCConnectionStatus = 'idle' | 'connecting' | 'connected' | 'disconnected' | 'failed' ;
@@ -37,8 +39,7 @@ export class WebRTCConnection {
3739 private timeoutId ?: ReturnType < typeof setTimeout > ;
3840
3941 constructor ( ) {
40- // TODO: replace with uuid
41- this . webrtcId = Math . random ( ) . toString ( 36 ) . substring ( 7 ) ;
42+ this . webrtcId = uuid ( ) ;
4243 }
4344
4445 public getStatus ( ) : WebRTCConnectionStatus {
@@ -80,9 +81,11 @@ export class WebRTCConnection {
8081 } catch ( err ) {
8182 clearTimeout ( this . timeoutId ) ;
8283 console . error ( 'Error setting up WebRTC:' , err ) ;
84+
8385 this . emit ( { type : 'error' , error : err as Error } ) ;
8486 this . updateStatus ( 'failed' ) ;
85- this . stop ( ) ;
87+
88+ await this . stop ( ) ;
8689 }
8790
8891 if ( this . peerConnection ) {
@@ -109,21 +112,26 @@ export class WebRTCConnection {
109112 }
110113
111114 private async waitForIceGathering ( ) : Promise < void > {
112- await new Promise < void > ( ( resolve ) => {
113- if ( ! this . peerConnection || this . peerConnection . iceGatheringState === 'complete' ) {
114- resolve ( ) ;
115- return ;
116- }
117-
118- const checkState = ( ) => {
119- if ( this . peerConnection && this . peerConnection . iceGatheringState === 'complete' ) {
120- this . peerConnection . removeEventListener ( 'icegatheringstatechange' , checkState ) ;
115+ await Promise . race ( [
116+ new Promise < void > ( ( resolve ) => {
117+ if ( ! this . peerConnection || this . peerConnection . iceGatheringState === 'complete' ) {
121118 resolve ( ) ;
119+ return ;
122120 }
123- } ;
124121
125- this . peerConnection ?. addEventListener ( 'icegatheringstatechange' , checkState ) ;
126- } ) ;
122+ const checkState = ( ) => {
123+ if ( this . peerConnection && this . peerConnection . iceGatheringState === 'complete' ) {
124+ this . peerConnection . removeEventListener ( 'icegatheringstatechange' , checkState ) ;
125+ resolve ( ) ;
126+ }
127+ } ;
128+
129+ this . peerConnection ?. addEventListener ( 'icegatheringstatechange' , checkState ) ;
130+ } ) ,
131+ new Promise < void > ( ( _ , reject ) =>
132+ setTimeout ( ( ) => reject ( new Error ( 'ICE gathering timed out' ) ) , CONNECTION_TIMEOUT )
133+ ) ,
134+ ] ) ;
127135 }
128136
129137 private async sendOffer ( ) : Promise < SessionData | undefined > {
0 commit comments