@@ -2,7 +2,7 @@ import { SDK } from "@ringcentral/sdk";
22import EventEmitter from "events" ;
33import RingCentral from "@rc-ex/core" ;
44import RcSdkExtension from "@rc-ex/rcsdk" ;
5- import WebSocketExtension from "@rc-ex/ws" ;
5+ import WebSocketExtension , { Events as WsEvents } from "@rc-ex/ws" ;
66import waitFor from "wait-for-async" ;
77import WsSubscription from "@rc-ex/ws/subscription" ;
88
@@ -23,9 +23,55 @@ export class Subscription extends EventEmitter {
2323 return this ;
2424 }
2525
26+ private isWsOpen ( wsExtension : WebSocketExtension ) : boolean {
27+ return Boolean ( wsExtension . ws && wsExtension . ws . readyState === 1 ) ;
28+ }
29+
30+ private async waitForWsReady ( wsExtension : WebSocketExtension , timeoutMs = 30000 ) : Promise < void > {
31+ if ( this . isWsOpen ( wsExtension ) ) {
32+ return ;
33+ }
34+
35+ await new Promise < void > ( ( resolve , reject ) => {
36+ let timeoutHandle : ReturnType < typeof setTimeout > ;
37+
38+ const onReady = ( ) => {
39+ cleanup ( ) ;
40+ resolve ( ) ;
41+ } ;
42+
43+ const onError = ( err : Error ) => {
44+ cleanup ( ) ;
45+ reject ( err ) ;
46+ } ;
47+
48+ const onTimeout = ( ) => {
49+ cleanup ( ) ;
50+ reject ( new Error ( `WebSocket connection timeout after ${ timeoutMs } ms` ) ) ;
51+ } ;
52+
53+ const cleanup = ( ) => {
54+ clearTimeout ( timeoutHandle ) ;
55+ wsExtension . eventEmitter . off ( WsEvents . connectionReady , onReady ) ;
56+ wsExtension . eventEmitter . off ( WsEvents . autoRecoverError , onError ) ;
57+ } ;
58+
59+ wsExtension . eventEmitter . once ( WsEvents . connectionReady , onReady ) ;
60+ wsExtension . eventEmitter . once ( WsEvents . autoRecoverError , onError ) ;
61+
62+ if ( this . isWsOpen ( wsExtension ) ) {
63+ onReady ( ) ;
64+ return ;
65+ }
66+
67+ timeoutHandle = setTimeout ( onTimeout , timeoutMs ) ;
68+ } ) ;
69+ }
70+
2671 public async register ( ) : Promise < WsSubscription > {
2772 await this . subscriptions . init ( ) ;
2873 const wsExtension = await this . subscriptions . newWsExtension ( ) ;
74+ await this . waitForWsReady ( wsExtension ) ;
2975 return await wsExtension . subscribe ( this . eventFilters , ( event ) => {
3076 this . emit ( this . events . notification , event ) ;
3177 } ) ;
0 commit comments