-
Notifications
You must be signed in to change notification settings - Fork 396
Expand file tree
/
Copy pathregister.ts
More file actions
1128 lines (1009 loc) · 35.2 KB
/
register.ts
File metadata and controls
1128 lines (1009 loc) · 35.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {v4 as uuid} from 'uuid';
import {Mutex} from 'async-mutex';
import {METHOD_START_MESSAGE} from '../../common/constants';
import {emitFinalFailure, handleRegistrationErrors, uploadLogs} from '../../common';
import webWorkerStr from './webWorkerStr';
import {
IMetricManager,
METRIC_EVENT,
METRIC_TYPE,
REG_ACTION,
SERVER_TYPE,
} from '../../Metrics/types';
import {getMetricManager} from '../../Metrics';
import {ICallManager} from '../calling/types';
import {getCallManager} from '../calling';
import {LOGGER} from '../../Logger/types';
import log from '../../Logger';
import {FailoverCacheState, IRegistration} from './types';
import SDKConnector from '../../SDKConnector';
import {
ALLOWED_SERVICES,
Devices,
HTTP_METHODS,
IDeviceInfo,
RegistrationStatus,
ServiceData,
ServiceIndicator,
WebexRequestPayload,
WorkerMessageType,
} from '../../common/types';
import {ISDKConnector, WebexSDK} from '../../SDKConnector/types';
import {
CALLING_USER_AGENT,
CISCO_DEVICE_URL,
DEVICES_ENDPOINT_RESOURCE,
SPARK_USER_AGENT,
WEBEX_WEB_CLIENT,
BASE_REG_RETRY_TIMER_VAL_IN_SEC,
BASE_REG_TIMER_MFACTOR,
SEC_TO_MSEC_MFACTOR,
REG_RANDOM_T_FACTOR_UPPER_LIMIT,
REG_TRY_BACKUP_TIMER_VAL_IN_SEC,
MINUTES_TO_SEC_MFACTOR,
REG_429_RETRY_UTIL,
REG_FAILBACK_429_MAX_RETRIES,
FAILBACK_UTIL,
REGISTRATION_FILE,
DEFAULT_REHOMING_INTERVAL_MIN,
DEFAULT_REHOMING_INTERVAL_MAX,
DEFAULT_KEEPALIVE_INTERVAL,
FAILOVER_UTIL,
REGISTER_UTIL,
RETRY_TIMER_UPPER_LIMIT,
KEEPALIVE_UTIL,
REGISTRATION_UTIL,
METHODS,
URL_ENDPOINT,
RECONNECT_ON_FAILURE_UTIL,
FAILOVER_CACHE_PREFIX,
} from '../constants';
import {LINE_EVENTS, LineEmitterCallback} from '../line/types';
import {LineError} from '../../Errors/catalog/LineError';
/**
*
*/
export class Registration implements IRegistration {
private sdkConnector: ISDKConnector;
private webex: WebexSDK;
private userId = '';
private serviceData: ServiceData;
private failback429RetryAttempts: number;
private registrationStatus: RegistrationStatus;
private failbackTimer?: NodeJS.Timeout;
private activeMobiusUrl!: string;
private rehomingIntervalMin: number;
private rehomingIntervalMax: number;
private mutex: Mutex;
private metricManager: IMetricManager;
private lineEmitter: LineEmitterCallback;
private callManager: ICallManager;
private deviceInfo: IDeviceInfo = {};
private primaryMobiusUris: string[];
private backupMobiusUris: string[];
private registerRetry = false;
private reconnectPending = false;
private jwe?: string;
private isCCFlow = false;
private failoverImmediately = false;
private retryAfter: number | undefined;
private scheduled429Retry = false;
private webWorker: Worker | undefined;
/**
*/
constructor(
webex: WebexSDK,
serviceData: ServiceData,
mutex: Mutex,
lineEmitter: LineEmitterCallback,
logLevel: LOGGER,
jwe?: string
) {
this.jwe = jwe;
this.sdkConnector = SDKConnector;
this.serviceData = serviceData;
this.isCCFlow = serviceData.indicator === ServiceIndicator.CONTACT_CENTER;
if (!this.sdkConnector.getWebex()) {
SDKConnector.setWebex(webex);
}
this.webex = this.sdkConnector.getWebex();
this.userId = this.webex.internal.device.userId;
this.registrationStatus = RegistrationStatus.IDLE;
this.failback429RetryAttempts = 0;
log.setLogger(logLevel, REGISTRATION_FILE);
this.rehomingIntervalMin = DEFAULT_REHOMING_INTERVAL_MIN;
this.rehomingIntervalMax = DEFAULT_REHOMING_INTERVAL_MAX;
this.mutex = mutex;
this.callManager = getCallManager(this.webex, serviceData.indicator);
this.metricManager = getMetricManager(this.webex, serviceData.indicator);
this.lineEmitter = lineEmitter;
this.primaryMobiusUris = [];
this.backupMobiusUris = [];
}
private getFailoverCacheKey(): string {
return `${FAILOVER_CACHE_PREFIX}.${this.userId || 'unknown'}`;
}
private saveFailoverState(failoverState: FailoverCacheState): void {
try {
localStorage.setItem(this.getFailoverCacheKey(), JSON.stringify(failoverState));
} catch (error) {
log.warn(`Storing failover state in cache failed with error: ${String(error)}`, {
file: REGISTRATION_FILE,
method: 'saveFailoverState',
});
}
}
private clearFailoverState(): void {
try {
localStorage.removeItem(this.getFailoverCacheKey());
} catch {
log.warn('Clearing failover state from localStorage failed', {
file: REGISTRATION_FILE,
method: 'clearFailoverState',
});
}
}
private async resumeFailover(): Promise<boolean> {
try {
const cachedState = localStorage.getItem(this.getFailoverCacheKey());
const failoverState = cachedState
? (JSON.parse(cachedState) as FailoverCacheState)
: undefined;
if (failoverState && !this.isDeviceRegistered()) {
const currentTime = Math.floor(Date.now() / 1000);
const newElapsed =
failoverState.timeElapsed + (currentTime - failoverState.retryScheduledTime);
this.clearFailoverState();
await this.startFailoverTimer(failoverState.attempt, newElapsed);
return true;
}
} catch (error) {
log.warn(`No failover state found in cache`, {
file: REGISTRATION_FILE,
method: 'triggerRegistration',
});
}
return false;
}
public getActiveMobiusUrl(): string {
return this.activeMobiusUrl;
}
public setActiveMobiusUrl(url: string) {
url = "https://mobius.asinwxt-prd-3.p4.prod.infra.webex.com/api/v1/calling/web/";
log.info(`${METHOD_START_MESSAGE} with ${url}`, {
method: METHODS.UPDATE_ACTIVE_MOBIUS,
file: REGISTRATION_FILE,
});
this.activeMobiusUrl = url;
this.callManager.updateActiveMobius(url);
}
/**
* Populate deviceInfo using a devices response body.
*/
public setDeviceInfo(devicesInfo: Devices): void {
const [device] = devicesInfo.devices;
this.deviceInfo = {
userId: devicesInfo.userId,
device,
devices: devicesInfo.devices,
};
}
public setMobiusServers(primaryMobiusUris: string[], backupMobiusUris: string[]) {
log.log(METHOD_START_MESSAGE, {method: METHODS.SET_MOBIUS_SERVERS, file: REGISTRATION_FILE});
this.primaryMobiusUris = primaryMobiusUris;
this.backupMobiusUris = backupMobiusUris;
}
/**
* Implementation of delete device.
*
*/
private async deleteRegistration(url: string, deviceId: string, deviceUrl: string) {
let response;
try {
response = await fetch(`${url}${DEVICES_ENDPOINT_RESOURCE}/${deviceId}`, {
method: HTTP_METHODS.DELETE,
headers: {
[CISCO_DEVICE_URL]: deviceUrl,
Authorization: await this.webex.credentials.getUserToken(),
trackingId: `${WEBEX_WEB_CLIENT}_${uuid()}`,
[SPARK_USER_AGENT]: CALLING_USER_AGENT,
},
});
} catch (error) {
log.warn(`Delete failed with Mobius: ${JSON.stringify(error)}`, {
file: REGISTRATION_FILE,
method: METHODS.DELETE_REGISTRATION,
});
await uploadLogs();
}
this.setStatus(RegistrationStatus.INACTIVE);
this.lineEmitter(LINE_EVENTS.UNREGISTERED);
return <WebexRequestPayload>response?.json();
}
/**
* Implementation of POST request for device registration.
*
*/
private async postRegistration(url: string) {
const deviceInfo = {
userId: this.userId,
clientDeviceUri: this.webex.internal.device.url,
serviceData: this.jwe ? {...this.serviceData, jwe: this.jwe} : this.serviceData,
};
return <WebexRequestPayload>this.webex.request({
uri: `${url}device`,
method: HTTP_METHODS.POST,
headers: {
[CISCO_DEVICE_URL]: deviceInfo.clientDeviceUri,
[SPARK_USER_AGENT]: CALLING_USER_AGENT,
},
body: deviceInfo,
service: ALLOWED_SERVICES.MOBIUS,
});
}
/**
* Re-attempts registration with the mobius url it was last registered
* to, that mobius url is expected to be updated already in this.activeMobiusUrl.
*/
private async restorePreviousRegistration(caller: string): Promise<boolean> {
let abort = false;
if (this.activeMobiusUrl) {
abort = await this.attemptRegistrationWithServers(caller, [this.activeMobiusUrl]);
if (this.retryAfter) {
if (this.retryAfter < RETRY_TIMER_UPPER_LIMIT) {
// If retry-after is less than threshold, honor it and schedule retry
setTimeout(async () => {
await this.restartRegistration(caller);
}, this.retryAfter * 1000);
} else if (
this.primaryMobiusUris.includes(this.activeMobiusUrl) &&
this.backupMobiusUris.length > 0
) {
// If we are using primary and got 429, switch to backup
abort = await this.attemptRegistrationWithServers(caller, this.backupMobiusUris);
} else {
// If we are using backup and got 429, restart registration
this.restartRegistration(caller);
}
this.retryAfter = undefined;
return true;
}
}
return abort;
}
/**
* Callback for handling 404 response from the server for register keepalive
*/
private async handle404KeepaliveFailure(caller: string): Promise<void> {
if (caller === KEEPALIVE_UTIL) {
const abort = await this.attemptRegistrationWithServers(caller);
if (!abort && !this.isDeviceRegistered()) {
await this.startFailoverTimer();
}
}
}
/**
* Callback for handling 429 retry response from the server
*/
private async handle429Retry(retryAfter: number, caller: string): Promise<void> {
if (caller === FAILBACK_UTIL) {
if (this.failback429RetryAttempts >= REG_FAILBACK_429_MAX_RETRIES) {
return;
}
this.clearFailbackTimer();
this.failback429RetryAttempts += 1;
log.log(`Received 429 while rehoming, 429 retry count : ${this.failback429RetryAttempts}`, {
file: REGISTRATION_FILE,
method: REG_429_RETRY_UTIL,
});
const interval = this.getRegRetryInterval(this.failback429RetryAttempts);
this.startFailbackTimer(interval);
this.scheduled429Retry = true;
const abort = await this.restorePreviousRegistration(REG_429_RETRY_UTIL);
if (!abort && !this.isDeviceRegistered()) {
await this.restartRegistration(REG_429_RETRY_UTIL);
}
} else if (caller === KEEPALIVE_UTIL) {
this.clearKeepaliveTimer();
setTimeout(async () => {
log.log(`Resuming keepalive after ${retryAfter} seconds`, {
file: REGISTRATION_FILE,
method: REG_429_RETRY_UTIL,
});
// Resume the keepalive after waiting for the retry after period
await this.startKeepaliveTimer(
this.deviceInfo.device?.uri as string,
this.deviceInfo.keepaliveInterval as number,
'UNKNOWN'
);
}, retryAfter * 1000);
} else {
this.retryAfter = retryAfter;
}
}
/**
* Calculates and returns a random interval value using input argument
* attempt as the variable factor.
*
* attempted already.
*/
private getRegRetryInterval(attempt = 1): number {
return (
BASE_REG_RETRY_TIMER_VAL_IN_SEC +
BASE_REG_TIMER_MFACTOR ** attempt +
Math.floor(
(Math.random() * (REG_RANDOM_T_FACTOR_UPPER_LIMIT - SEC_TO_MSEC_MFACTOR + 1) +
SEC_TO_MSEC_MFACTOR) /
SEC_TO_MSEC_MFACTOR
)
);
}
/**
* Schedules registration retry with primary mobius servers at a random
* interval calculated based on the number of times registration retry is already done
* Once the time taken since the beginning of retry attempt exceeds the
* retry threshold, it switches over to backup mobius servers.
*
*/
private async startFailoverTimer(attempt = 1, timeElapsed = 0) {
const loggerContext = {
file: REGISTRATION_FILE,
method: FAILOVER_UTIL,
};
let interval = this.getRegRetryInterval(attempt);
const TIMER_THRESHOLD = REG_TRY_BACKUP_TIMER_VAL_IN_SEC;
if (timeElapsed + interval > TIMER_THRESHOLD) {
const excessVal = timeElapsed + interval - TIMER_THRESHOLD;
interval -= excessVal;
}
if (this.retryAfter != null && interval < this.retryAfter) {
this.failoverImmediately = this.retryAfter + timeElapsed > TIMER_THRESHOLD;
}
let abort;
if (interval > BASE_REG_RETRY_TIMER_VAL_IN_SEC && !this.failoverImmediately) {
const scheduledTime = Math.floor(Date.now() / 1000);
if (this.retryAfter != null) {
interval = Math.max(interval, this.retryAfter);
}
this.saveFailoverState({
attempt,
timeElapsed,
retryScheduledTime: scheduledTime,
serverType: 'primary',
});
setTimeout(async () => {
await this.mutex.runExclusive(async () => {
abort = await this.attemptRegistrationWithServers(FAILOVER_UTIL);
const currentTime = Math.floor(Date.now() / 1000);
if (!abort && !this.isDeviceRegistered()) {
await this.startFailoverTimer(attempt + 1, timeElapsed + (currentTime - scheduledTime));
}
});
}, interval * SEC_TO_MSEC_MFACTOR);
log.log(
`Scheduled retry with primary in ${interval} seconds, number of attempts : ${attempt}`,
loggerContext
);
} else if (this.backupMobiusUris.length) {
this.saveFailoverState({
attempt,
timeElapsed,
retryScheduledTime: Math.floor(Date.now() / 1000),
serverType: 'backup',
});
log.info('Failing over to backup servers.', loggerContext);
this.failoverImmediately = false;
abort = await this.attemptRegistrationWithServers(FAILOVER_UTIL, this.backupMobiusUris);
if (!abort && !this.isDeviceRegistered()) {
interval = this.getRegRetryInterval();
if (this.retryAfter != null && this.retryAfter < RETRY_TIMER_UPPER_LIMIT) {
interval = interval < this.retryAfter ? this.retryAfter : interval;
}
setTimeout(async () => {
await this.mutex.runExclusive(async () => {
abort = await this.attemptRegistrationWithServers(FAILOVER_UTIL, this.backupMobiusUris);
if (!abort && !this.isDeviceRegistered()) {
await uploadLogs();
emitFinalFailure((clientError: LineError) => {
this.lineEmitter(LINE_EVENTS.ERROR, undefined, clientError);
}, loggerContext);
}
});
}, interval * SEC_TO_MSEC_MFACTOR);
log.log(`Scheduled retry with backup servers in ${interval} seconds.`, loggerContext);
}
} else {
await uploadLogs();
emitFinalFailure((clientError: LineError) => {
this.lineEmitter(LINE_EVENTS.ERROR, undefined, clientError);
}, loggerContext);
}
}
/**
* Clears the failback timer if running.
*/
private clearFailbackTimer() {
if (this.failbackTimer) {
clearTimeout(this.failbackTimer);
this.failbackTimer = undefined;
}
}
private async isPrimaryActive() {
let status;
for (const mobiusUrl of this.primaryMobiusUris) {
try {
const baseUri = mobiusUrl.replace(URL_ENDPOINT, '/');
// eslint-disable-next-line no-await-in-loop
const response = await this.webex.request({
uri: `${baseUri}ping`,
method: HTTP_METHODS.GET,
headers: {
[CISCO_DEVICE_URL]: this.webex.internal.device.url,
[SPARK_USER_AGENT]: CALLING_USER_AGENT,
},
service: ALLOWED_SERVICES.MOBIUS,
});
const {statusCode} = response as WebexRequestPayload;
if (statusCode === 200) {
log.info(`Ping successful for primary Mobius: ${mobiusUrl}`, {
file: REGISTRATION_FILE,
method: FAILBACK_UTIL,
});
status = 'up';
break;
}
} catch (error) {
log.warn(
`Ping failed for primary Mobius: ${mobiusUrl} with error: ${JSON.stringify(error)}`,
{
file: REGISTRATION_FILE,
method: FAILBACK_UTIL,
}
);
status = 'down';
}
}
return status === 'up';
}
/**
* Returns true if device is registered with a backup mobius.
*/
private isFailbackRequired(): boolean {
return this.isDeviceRegistered() && this.primaryMobiusUris.indexOf(this.activeMobiusUrl) === -1;
}
/**
* Calculates and returns a random value between rehomingIntervalMin and
* rehomingIntervalMax.
*/
private getFailbackInterval(): number {
return Math.floor(
Math.random() * (this.rehomingIntervalMax - this.rehomingIntervalMin + 1) +
this.rehomingIntervalMin
);
}
/**
* Starts failback timer to move to primary mobius if device
* is registered with a backup mobius.
*/
private initiateFailback() {
if (this.isFailbackRequired()) {
if (!this.failbackTimer) {
this.failback429RetryAttempts = 0;
const intervalInMinutes = this.getFailbackInterval();
this.startFailbackTimer(intervalInMinutes * MINUTES_TO_SEC_MFACTOR);
}
} else {
this.failback429RetryAttempts = 0;
this.clearFailbackTimer();
}
}
/**
* Starts failback timer with the interval value received.
*
*/
private startFailbackTimer(intervalInSeconds: number) {
this.failbackTimer = setTimeout(
async () => this.executeFailback(),
intervalInSeconds * SEC_TO_MSEC_MFACTOR
);
log.log(`Failback scheduled after ${intervalInSeconds} seconds.`, {
file: REGISTRATION_FILE,
method: this.startFailbackTimer.name,
});
}
/**
* Core logic for the failback processing, scheduled and executed
* at failback timer expiry.
*/
private async executeFailback() {
await this.mutex.runExclusive(async () => {
if (this.isFailbackRequired()) {
const primaryServerStatus = await this.isPrimaryActive();
if (Object.keys(this.callManager.getActiveCalls()).length === 0 && primaryServerStatus) {
log.info(`Attempting failback to primary.`, {
file: REGISTRATION_FILE,
method: this.executeFailback.name,
});
await this.deregister();
const abort = await this.attemptRegistrationWithServers(FAILBACK_UTIL);
if (this.scheduled429Retry || abort || this.isDeviceRegistered()) {
return;
}
const abortNew = await this.restorePreviousRegistration(FAILBACK_UTIL);
if (abortNew) {
this.clearFailbackTimer();
return;
}
if (!this.isDeviceRegistered()) {
await this.restartRegistration(this.executeFailback.name);
} else {
this.failbackTimer = undefined;
this.initiateFailback();
}
} else {
log.info(
'Active calls present or primary Mobius is down, deferring failback to next cycle.',
{
file: REGISTRATION_FILE,
method: this.executeFailback.name,
}
);
this.failbackTimer = undefined;
this.initiateFailback();
}
}
});
}
/**
* Updates rehomingIntervalMin and rehomingIntervalMax values
* if received in registration response from a primary mobius
* server.
*
*/
private setIntervalValues(deviceInfo: IDeviceInfo) {
if (this.primaryMobiusUris.indexOf(this.activeMobiusUrl) !== -1) {
this.rehomingIntervalMin = deviceInfo?.rehomingIntervalMin
? deviceInfo.rehomingIntervalMin
: DEFAULT_REHOMING_INTERVAL_MIN;
this.rehomingIntervalMax = deviceInfo?.rehomingIntervalMax
? deviceInfo.rehomingIntervalMax
: DEFAULT_REHOMING_INTERVAL_MAX;
}
}
/**
* Retrieves information about the device as {@link IDeviceInfo}.
*
*/
public getDeviceInfo(): IDeviceInfo {
return this.deviceInfo;
}
/**
* Checks if the device is currently registered.
*
* by checking if isRegistered state is set to
* ACTIVE, else false.
*/
public isDeviceRegistered(): boolean {
return this.registrationStatus === RegistrationStatus.ACTIVE;
}
public getStatus(): RegistrationStatus {
return this.registrationStatus;
}
public setStatus(value: RegistrationStatus) {
this.registrationStatus = value;
}
/**
* Start fresh registration cycle with the mobius
* server list already present.
*
*/
private async restartRegistration(caller: string) {
/*
* Cancel any failback timer running
* and start fresh registration attempt with retry as true.
*/
this.clearFailbackTimer();
this.failback429RetryAttempts = 0;
const abort = await this.attemptRegistrationWithServers(caller, this.primaryMobiusUris);
if (!abort && !this.isDeviceRegistered()) {
await this.startFailoverTimer();
}
}
/**
* Restores the connection and attempts refreshing existing registration with server.
* Allows retry if not restored in the first attempt.
*
*/
public async handleConnectionRestoration(retry: boolean): Promise<boolean> {
log.info(METHOD_START_MESSAGE, {
method: METHODS.HANDLE_CONNECTION_RESTORATION,
file: REGISTRATION_FILE,
});
await this.mutex.runExclusive(async () => {
/* Check retry once again to see if another timer thread has not finished the job already. */
if (retry) {
log.log('Network is up again, re-registering with Webex Calling if needed', {
file: REGISTRATION_FILE,
method: METHODS.HANDLE_CONNECTION_RESTORATION,
});
this.clearKeepaliveTimer();
if (this.isDeviceRegistered()) {
// eslint-disable-next-line no-await-in-loop
await this.deregister();
}
/*
* Do not attempt registration if mobius url is not set in this.activeMobiusUrl
* as that'd mean initial registration itself is not finished yet, let
* failover timer handle the registration in that case.
*/
if (this.activeMobiusUrl) {
/*
* When restoring connectivity, register with same url first
* where it was registered last even if it was a backup url,
* because failback timer may already be running to register
* it back to primary.
*/
const abort = await this.restorePreviousRegistration(
METHODS.HANDLE_CONNECTION_RESTORATION
);
if (!abort && !this.isDeviceRegistered()) {
await this.restartRegistration(METHODS.HANDLE_CONNECTION_RESTORATION);
}
}
retry = false;
}
});
return retry;
}
/**
* Callback function for restoring registration in case of failure during initial registration
* due to device registration already exists.
*
*/
private restoreRegistrationCallBack() {
return async (restoreData: IDeviceInfo, caller: string) => {
const logContext = {file: REGISTRATION_FILE, method: caller};
if (!this.isRegRetry()) {
log.info('Registration restoration in progress.', logContext);
const restore = this.getExistingDevice(restoreData);
if (restore) {
this.setRegRetry(true);
await this.deregister();
const finalError = await this.restorePreviousRegistration(caller);
this.setRegRetry(false);
if (this.isDeviceRegistered()) {
log.info('Registration restored successfully.', logContext);
}
return finalError;
}
this.lineEmitter(LINE_EVENTS.UNREGISTERED);
} else {
this.lineEmitter(LINE_EVENTS.UNREGISTERED);
}
return false;
};
}
/**
* Triggers the registration with the given list of Mobius servers
* Registration is attempted with primary and backup until it succeeds or the list is exhausted
*/
public async triggerRegistration() {
if (await this.resumeFailover()) {
return;
}
if (this.primaryMobiusUris.length > 0) {
const abort = await this.attemptRegistrationWithServers(
REGISTRATION_UTIL,
this.primaryMobiusUris
);
if (!this.isDeviceRegistered() && !abort) {
await this.startFailoverTimer();
}
}
}
/**
* Attempts registration with the server list received in
* argument one by one until registration either succeeds with
* one or all of them are tried.
*
* attempt has hit a final error and a retry should not be scheduled
* else false.
*/
private async attemptRegistrationWithServers(
caller: string,
servers: string[] = this.primaryMobiusUris
): Promise<boolean> {
let abort = false;
this.retryAfter = undefined;
if (this.failoverImmediately) {
return abort;
}
if (this.isDeviceRegistered()) {
log.info(`[${caller}] : Device already registered with : ${this.activeMobiusUrl}`, {
file: REGISTRATION_FILE,
method: REGISTER_UTIL,
});
return abort;
}
servers = ["https://mobius.asinwxt-prd-3.p4.prod.infra.webex.com/api/v1/calling/web/"];
for (const url of servers) {
const serverType =
(this.primaryMobiusUris.includes(url) && 'PRIMARY') ||
(this.backupMobiusUris?.includes(url) && 'BACKUP') ||
'UNKNOWN';
try {
abort = false;
this.registrationStatus = RegistrationStatus.INACTIVE;
this.lineEmitter(LINE_EVENTS.CONNECTING);
log.info(`[${caller}] : Mobius url to contact: ${url}`, {
file: REGISTRATION_FILE,
method: REGISTER_UTIL,
});
// eslint-disable-next-line no-await-in-loop
const resp = await this.postRegistration(url);
this.clearFailoverState();
this.deviceInfo = resp.body as IDeviceInfo;
this.registrationStatus = RegistrationStatus.ACTIVE;
this.setActiveMobiusUrl(url);
this.lineEmitter(LINE_EVENTS.REGISTERED, resp.body as IDeviceInfo);
log.log(
`Registration successful for deviceId: ${this.deviceInfo.device?.deviceId} userId: ${this.userId} responseTrackingId: ${resp.headers?.trackingid}`,
{
file: REGISTRATION_FILE,
method: METHODS.REGISTER,
}
);
this.setIntervalValues(this.deviceInfo);
this.metricManager.setDeviceInfo(this.deviceInfo);
this.metricManager.submitRegistrationMetric(
METRIC_EVENT.REGISTRATION,
REG_ACTION.REGISTER,
METRIC_TYPE.BEHAVIORAL,
caller,
serverType,
resp.headers?.trackingid ?? '',
undefined,
undefined
);
this.startKeepaliveTimer(
this.deviceInfo.device?.uri as string,
this.deviceInfo.keepaliveInterval as number,
serverType
);
this.initiateFailback();
break;
} catch (err: unknown) {
const body = err as WebexRequestPayload;
// eslint-disable-next-line no-await-in-loop, @typescript-eslint/no-unused-vars
abort = await handleRegistrationErrors(
body,
(clientError, finalError) => {
if (finalError) {
this.lineEmitter(LINE_EVENTS.ERROR, undefined, clientError);
} else {
this.lineEmitter(LINE_EVENTS.UNREGISTERED);
}
this.metricManager.submitRegistrationMetric(
METRIC_EVENT.REGISTRATION_ERROR,
REG_ACTION.REGISTER,
METRIC_TYPE.BEHAVIORAL,
caller,
serverType,
body.headers?.trackingid ?? '',
undefined,
clientError
);
},
{method: caller, file: REGISTRATION_FILE},
(retryAfter: number, retryCaller: string) => this.handle429Retry(retryAfter, retryCaller),
this.restoreRegistrationCallBack()
);
if (this.registrationStatus === RegistrationStatus.ACTIVE) {
log.info(
`[${caller}] : Device is already restored, active mobius url: ${this.activeMobiusUrl}`,
{
file: REGISTRATION_FILE,
method: this.attemptRegistrationWithServers.name,
}
);
break;
}
if (abort) {
this.setStatus(RegistrationStatus.INACTIVE);
// eslint-disable-next-line no-await-in-loop
await uploadLogs();
break;
}
}
}
return abort;
}
/**
* This method sets up a timer to periodically send keep-alive requests to maintain a connection.
* It handles retries, error handling, and re-registration attempts based on the response, ensuring continuous connectivity with the server.
*/
private async startKeepaliveTimer(url: string, interval: number, serverType: SERVER_TYPE) {
this.clearKeepaliveTimer();
const RETRY_COUNT_THRESHOLD = this.isCCFlow ? 4 : 5;
await this.mutex.runExclusive(async () => {
if (this.isDeviceRegistered()) {
const accessToken = await this.webex.credentials.getUserToken();
if (!this.webWorker) {
const blob = new Blob([webWorkerStr], {type: 'application/javascript'});
const blobUrl = URL.createObjectURL(blob);
this.webWorker = new Worker(blobUrl);
URL.revokeObjectURL(blobUrl);
this.webWorker.postMessage({
type: WorkerMessageType.START_KEEPALIVE,
accessToken: String(accessToken),
deviceUrl: String(this.webex.internal.device.url),
interval,
retryCountThreshold: RETRY_COUNT_THRESHOLD,
url,
});
this.webWorker.onmessage = async (event: MessageEvent) => {
const logContext = {
file: REGISTRATION_FILE,
method: KEEPALIVE_UTIL,
};
if (event.data.type === WorkerMessageType.KEEPALIVE_SUCCESS) {
log.info(`Sent Keepalive, status: ${event.data.statusCode}`, logContext);
this.lineEmitter(LINE_EVENTS.RECONNECTED);
}
if (event.data.type === WorkerMessageType.KEEPALIVE_FAILURE) {
const error = <WebexRequestPayload>event.data.err;
log.warn(
`Keep-alive missed ${event.data.keepAliveRetryCount} times. Status -> ${error.statusCode} `,
logContext
);
const abort = await handleRegistrationErrors(
error,
(clientError, finalError) => {
if (finalError) {
this.lineEmitter(LINE_EVENTS.ERROR, undefined, clientError);
}
this.metricManager.submitRegistrationMetric(
METRIC_EVENT.KEEPALIVE_ERROR,
REG_ACTION.KEEPALIVE_FAILURE,
METRIC_TYPE.BEHAVIORAL,
KEEPALIVE_UTIL,
serverType,
error.headers?.trackingid ?? '',
event.data.keepAliveRetryCount,
clientError
);
},
{method: KEEPALIVE_UTIL, file: REGISTRATION_FILE},
(retryAfter: number, retryCaller: string) =>
this.handle429Retry(retryAfter, retryCaller)
);
if (abort || event.data.keepAliveRetryCount >= RETRY_COUNT_THRESHOLD) {
this.failoverImmediately = this.isCCFlow;
this.setStatus(RegistrationStatus.INACTIVE);
this.clearKeepaliveTimer();
this.clearFailbackTimer();
this.lineEmitter(LINE_EVENTS.UNREGISTERED);
await uploadLogs();
if (!abort) {
/* In case of non-final error, re-attempt registration */
await this.reconnectOnFailure(RECONNECT_ON_FAILURE_UTIL);
} else if (error.statusCode === 404) {
this.handle404KeepaliveFailure(KEEPALIVE_UTIL);
}
} else {
this.lineEmitter(LINE_EVENTS.RECONNECTING);
}