-
Notifications
You must be signed in to change notification settings - Fork 404
Expand file tree
/
Copy pathindex.ts
More file actions
3169 lines (2885 loc) · 103 KB
/
Copy pathindex.ts
File metadata and controls
3169 lines (2885 loc) · 103 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 {isEqual, assignWith, cloneDeep, isEmpty} from 'lodash';
import uuid from 'uuid';
import {webexTrackingIdSequenceNumbers} from '@webex/webex-core';
import LoggerProxy from '../common/logs/logger-proxy';
import EventsScope from '../common/events/events-scope';
import {
EVENTS,
LOCUSEVENT,
_USER_,
_CALL_,
_SIP_BRIDGE_,
MEETING_STATE,
_MEETING_,
_SPACE_SHARE_,
LOCUSINFO,
LOCUS,
_LEFT_,
MEETING_REMOVED_REASON,
CALL_REMOVED_REASON,
RECORDING_STATE,
Enum,
SELF_ROLES,
} from '../constants';
import InfoUtils from './infoUtils';
import FullState from './fullState';
import SelfUtils from './selfUtils';
import HostUtils from './hostUtils';
import ControlsUtils from './controlsUtils';
import EmbeddedAppsUtils from './embeddedAppsUtils';
import MediaSharesUtils from './mediaSharesUtils';
import LocusDeltaParser from './parser';
import Metrics from '../metrics';
import BEHAVIORAL_METRICS from '../metrics/constants';
import HashTreeParser, {
DataSet,
HashTreeMessage,
LocusInfoUpdate,
LocusInfoUpdateType,
Metadata,
SyncLatencyTracker,
} from '../hashTree/hashTreeParser';
import {HashTreeObject, ObjectType, ObjectTypeToLocusKeyMap} from '../hashTree/types';
import {isMetadata, isSelf} from '../hashTree/utils';
import {Links, LocusDTO, ReplacesInfo} from './types';
import MeetingsUtil from '../meetings/util';
import {MEETING_KEY} from '../meetings/meetings.types';
import MeetingCollection from '../meetings/collection';
export type LocusLLMEvent = {
trackingId?: string;
data: {
eventType: typeof LOCUSEVENT.HASH_TREE_DATA_UPDATED;
stateElementsMessage: HashTreeMessage;
};
};
// list of top level keys in Locus DTO relevant for Hash Tree DTOs processing
// it does not contain fields specific to classic Locus DTOs like sequence or baseSequence
const LocusDtoTopLevelKeys = [
'controls',
'fullState',
'embeddedApps',
'host',
'info',
'links',
'mediaShares',
'meetings',
'participants',
'replaces',
'self',
'sequence',
'syncUrl',
'url',
'htMeta', // only exists when hash trees are used
];
export type LocusApiResponseBody =
| {
dataSets?: DataSet[];
locus: LocusDTO; // this LocusDTO here might not be the full one (for example it won't have all the participants, but it should have self)
metadata?: Metadata;
}
| LocusDTO; // when we invoke APIs on the whole Locus like "mute all" backend returns the whole Locus in the response like this
const LocusObjectStateAfterUpdates = {
unchanged: 'unchanged',
removed: 'removed',
updated: 'updated',
} as const;
type LocusObjectStateAfterUpdates = Enum<typeof LocusObjectStateAfterUpdates>;
export type HashTreeParserEntry = {
parser: HashTreeParser;
replacedAt?: string;
initializedFromHashTree: boolean;
};
export type LocusInfoCallbacks = {
updateMeeting: (object: any) => void;
syncLatencyTracker?: SyncLatencyTracker;
};
/**
* Gets the replacement information
*
* @param {any} self - "self" object from Locus DTO
* @param {string} deviceUrl - The URL of the specified device
* @returns {any} The replace information if available, otherwise undefined
*/
function getReplaceInfoFromSelf(self: any, deviceUrl: string): ReplacesInfo | undefined {
if (self) {
const device = MeetingsUtil.getThisDevice({self}, deviceUrl);
if (device?.replaces?.length > 0) {
return device.replaces[0];
}
}
return undefined;
}
/**
* Finds a meeting by its locus URL in meeting collection. It checks all HashTreeParsers of all meetings in the collection.
*
* @param {MeetingCollection} meetingCollection - The collection of meetings to search
* @param {string} locusUrl - The locus URL to search for
* @returns {any} The meeting if found, otherwise undefined
*/
function findLocusUrlInAnyHashTreeParser(
meetingCollection: MeetingCollection,
locusUrl: string
): any {
for (const meeting of Object.values(meetingCollection.getAll()) as any[]) {
if (meeting?.locusInfo?.hashTreeParsers?.has(locusUrl)) {
return meeting;
}
}
return undefined;
}
/**
* Finds a meeting for a given hash tree message.
*
* @param {HashTreeMessage} message - The hash tree message to find the meeting for
* @param {MeetingCollection} meetingCollection - The collection of meetings to search
* @returns {any} The meeting if found, otherwise undefined
*/
export function findMeetingForHashTreeMessage(
message: HashTreeMessage | undefined,
meetingCollection: MeetingCollection
): any {
if (!message) {
return undefined;
}
let foundMeeting = findLocusUrlInAnyHashTreeParser(meetingCollection, message.locusUrl);
if (foundMeeting) {
return foundMeeting;
}
// if we haven't found anything, it may mean that message has a new locusUrl
// check if it indicates that it replaces some existing current locusUrl (this is indicated in "self")
const self = message.locusStateElements?.find((el) => isSelf(el))?.data;
const replaces = getReplaceInfoFromSelf(self, self?.deviceUrl);
if (replaces?.locusUrl) {
foundMeeting = findLocusUrlInAnyHashTreeParser(meetingCollection, replaces.locusUrl);
return foundMeeting;
}
return undefined;
}
/**
* Creates a locus object from the objects received in a hash tree message. It usually will be
* incomplete, because hash tree messages only contain the parts of locus that have changed,
* and some updates come separately over Mercury or LLM in separate messages.
*
* @param {HashTreeMessage} message hash tree message to created the locus from
* @returns {Object} the created locus object and metadata if present
*/
export function createLocusFromHashTreeMessage(message: HashTreeMessage): {
locus: LocusDTO;
metadata?: Metadata;
} {
const locus: LocusDTO = {
participants: [],
url: message.locusUrl,
};
let metadata: Metadata | undefined;
if (!message.locusStateElements) {
return {locus, metadata};
}
for (const element of message.locusStateElements) {
if (!element.data) {
// eslint-disable-next-line no-continue
continue;
}
const type = element.htMeta.elementId.type.toLowerCase();
switch (type) {
case ObjectType.locus: {
// spread locus object data onto the top level, but remove keys managed by other ObjectTypes
const locusObjectData = {...element.data};
Object.values(ObjectTypeToLocusKeyMap).forEach((locusDtoKey) => {
delete locusObjectData[locusDtoKey];
});
Object.assign(locus, locusObjectData);
break;
}
case ObjectType.participant:
locus.participants.push(element.data);
break;
case ObjectType.mediaShare:
if (!locus.mediaShares) {
locus.mediaShares = [];
}
locus.mediaShares.push(element.data);
break;
case ObjectType.embeddedApp:
if (!locus.embeddedApps) {
locus.embeddedApps = [];
}
locus.embeddedApps.push(element.data);
break;
case ObjectType.control:
if (!locus.controls) {
locus.controls = {};
}
Object.assign(locus.controls, element.data);
break;
case ObjectType.links:
case ObjectType.info:
case ObjectType.fullState:
case ObjectType.self: {
const locusDtoKey = ObjectTypeToLocusKeyMap[type];
locus[locusDtoKey] = element.data;
break;
}
case ObjectType.metadata:
// metadata is not part of Locus DTO
metadata = {...element.data, htMeta: element.htMeta} as Metadata;
break;
default:
break;
}
}
return {locus, metadata};
}
/**
* @description LocusInfo extends ChildEmitter to convert locusInfo info a private emitter to parent object
* @export
* @private
* @class LocusInfo
*/
export default class LocusInfo extends EventsScope {
compareAndUpdateFlags: any;
emitChange: any;
locusParser: any;
meetingId: any;
parsedLocus: any;
webex: any;
aclUrl: any;
baseSequence: any;
created: any;
participants: any;
replaces: any;
scheduledMeeting: any;
sequence: any;
controls: any;
conversationUrl: any;
embeddedApps: any;
fullState: any;
host: any;
info: any;
roles: any;
mediaShares: any;
url: any;
links?: Links;
mainSessionLocusCache: any;
self: any;
hashTreeParsers: Map<string, HashTreeParserEntry>;
hashTreeObjectId2ParticipantId: Map<number, string>; // mapping of hash tree object ids to participant ids
classicVsHashTreeMismatchMetricCounter = 0;
private callbacks: LocusInfoCallbacks;
private destroyMeetingSuspended = false;
/**
* Constructor
* @param {Object} callbacks callbacks used by LocusInfo
* @param {function} callbacks.updateMeeting callback to update the meeting object from an object
* @param {object} webex
* @param {string} meetingId
* @returns {undefined}
*/
constructor(callbacks: LocusInfoCallbacks, webex: any, meetingId: any) {
super();
this.parsedLocus = {
states: [],
};
this.callbacks = callbacks;
this.webex = webex;
this.emitChange = false;
this.compareAndUpdateFlags = {};
this.meetingId = meetingId;
this.locusParser = new LocusDeltaParser();
this.hashTreeParsers = new Map();
this.hashTreeObjectId2ParticipantId = new Map();
}
/**
* Does a Locus sync. It tries to get the latest delta DTO or if it can't, it falls back to getting the full Locus DTO.
* WARNING: This function must not be used for hash tree based Locus meetings.
*
* @param {Meeting} meeting
* @param {boolean} isLocusUrlChanged
* @param {Locus} locus
* @returns {undefined}
*/
private doLocusSync(meeting: any, isLocusUrlChanged: boolean, locus: any) {
let url;
let isDelta = false;
let meetingDestroyed = false;
if (isLocusUrlChanged) {
// for the locus url changed case from breakout to main session, we should always do a full sync, in this case, the url from locus is always on main session,
// so use the main session locus url to get the full locus(full participants list in the response).
// for the locus url changed case from main session to breakout, we don't need to care about it here,
// because it is a USE_INCOMING case, it will not be executed here.
url = locus.url;
} else if (this.locusParser.workingCopy?.syncUrl) {
url = this.locusParser.workingCopy.syncUrl;
isDelta = true;
} else {
url = meeting.locusUrl;
}
LoggerProxy.logger.info(
`Locus-info:index#doLocusSync --> doing Locus sync (getting ${
isDelta ? 'delta' : 'full'
} DTO)`
);
// return value ignored on purpose
meeting.meetingRequest
.getLocusDTO({url})
.catch((e) => {
if (isDelta) {
LoggerProxy.logger.info(
'Locus-info:index#doLocusSync --> delta sync failed, falling back to full sync'
);
Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.LOCUS_DELTA_SYNC_FAILED, {
correlationId: meeting.correlationId,
url,
reason: e.message,
errorName: e.name,
stack: e.stack,
code: e.code,
});
isDelta = false;
// Locus sometimes returns 403, for example if meeting has ended, no point trying the fallback to full sync in that case
if (e.statusCode !== 403) {
return meeting.meetingRequest.getLocusDTO({url: meeting.locusUrl}).catch((err) => {
LoggerProxy.logger.info(
'Locus-info:index#doLocusSync --> fallback full sync failed, destroying the meeting'
);
this.webex.meetings.destroy(meeting, MEETING_REMOVED_REASON.LOCUS_DTO_SYNC_FAILED);
meetingDestroyed = true;
throw err;
});
}
LoggerProxy.logger.info(
'Locus-info:index#doLocusSync --> got 403 from Locus, skipping fallback to full sync, destroying the meeting'
);
} else {
LoggerProxy.logger.info(
'Locus-info:index#doLocusSync --> fallback full sync failed, destroying the meeting'
);
}
this.webex.meetings.destroy(meeting, MEETING_REMOVED_REASON.LOCUS_DTO_SYNC_FAILED);
meetingDestroyed = true;
throw e;
})
.then((res) => {
if (isEmpty(res.body)) {
if (isDelta) {
LoggerProxy.logger.info(
'Locus-info:index#doLocusSync --> received empty body from syncUrl, so we already have latest Locus DTO'
);
} else {
LoggerProxy.logger.info(
'Locus-info:index#doLocusSync --> received empty body from full DTO sync request'
);
}
return;
}
if (isDelta) {
if (res.body.baseSequence) {
meeting.locusInfo.handleLocusDelta(res.body, meeting);
return;
}
// in some cases Locus might return us full DTO even when we asked for a delta
LoggerProxy.logger.info(
'Locus-info:index#doLocusSync --> got full DTO when we asked for delta'
);
}
meeting.locusInfo.onFullLocus('classic Locus sync', res.body);
})
.catch((e) => {
LoggerProxy.logger.info(
`Locus-info:index#doLocusSync --> getLocusDTO succeeded but failed to handle result, locus parser will resume but not all data may be synced (${e.toString()})`
);
Metrics.sendBehavioralMetric(BEHAVIORAL_METRICS.LOCUS_SYNC_HANDLING_FAILED, {
correlationId: meeting.correlationId,
url,
reason: e.message,
errorName: e.name,
stack: e.stack,
code: e.code,
});
})
.finally(() => {
if (!meetingDestroyed) {
// Notify parser to resume processing delta events.
// Any deltas in the queue that have now been superseded by this sync will simply be ignored
this.locusParser.resume();
}
});
}
/**
* Apply locus delta data to meeting
* @param {string} action Locus delta action
* @param {Locus} locus
* @param {Meeting} meeting
* @returns {undefined}
*/
applyLocusDeltaData(action: string, locus: any, meeting: any) {
const {DESYNC, USE_CURRENT, USE_INCOMING, WAIT, LOCUS_URL_CHANGED} = LocusDeltaParser.loci;
const isLocusUrlChanged = action === LOCUS_URL_CHANGED;
switch (action) {
case USE_INCOMING:
meeting.locusInfo.onDeltaLocus(locus);
break;
case USE_CURRENT:
case WAIT:
// do nothing
break;
case DESYNC:
case LOCUS_URL_CHANGED:
this.doLocusSync(meeting, isLocusUrlChanged, locus);
break;
default:
LoggerProxy.logger.info(
`Locus-info:index#applyLocusDeltaData --> Unknown locus delta action: ${action}`
);
}
}
/**
* Adds locus delta to parser's queue
* and registers a function handler
* to recieve parsed actions from queue.
* @param {Locus} locus
* @param {Meeting} meeting
* @returns {undefined}
*/
handleLocusDelta(locus: any, meeting: any) {
// register a function to process delta actions
if (!this.locusParser.onDeltaAction) {
// delta action, along with associated loci
// is passed into the function.
this.locusParser.onDeltaAction = (action, parsedLoci) => {
this.applyLocusDeltaData(action, parsedLoci, meeting);
};
}
// queue delta event with parser
this.locusParser.onDeltaEvent(locus);
}
/**
* @param {Locus} locus
* @returns {undefined}
* @memberof LocusInfo
*/
init(locus: any = {}) {
this.created = locus.created || null;
this.scheduledMeeting = locus.meeting || null;
this.replaces = locus.replaces || null;
this.aclUrl = locus.aclUrl || null;
this.baseSequence = locus.baseSequence || null;
this.sequence = locus.sequence || null;
this.participants = locus.participants || null;
/**
* Stores the delta values for a changed participant.
*
* @typedef {Object} DeltaParticipant
* @property {Record<string, boolean>} delta - Contains changed streams.
* @property {Object} person - Contains person data.
*/
this.updateLocusCache(locus);
// above section only updates the locusInfo object
// The below section makes sure it updates the locusInfo as well as updates the meeting object
this.updateParticipants(locus.participants, []);
// For 1:1 space meeting the conversation Url does not exist in locus.conversation
this.updateConversationUrl(locus.conversationUrl, locus.info);
this.updateControls(locus.controls, locus.self);
this.updateLocusUrl(locus.url, ControlsUtils.isMainSessionDTO(locus));
this.updateFullState(locus.fullState);
this.updateMeetingInfo(locus.info, locus.self);
this.updateEmbeddedApps(locus.embeddedApps);
// self and participants generate sipUrl for 1:1 meeting
this.updateSelf(locus.self);
this.updateHostInfo(locus.host);
this.updateMediaShares(locus.mediaShares);
this.updateLinks(locus.links);
}
/**
* Creates a HashTreeParser instance for a given locusUrl and stores it in the map.
* @param {Object} params
* @param {string} params.locusUrl - the locus URL used as the map key
* @param {Object} params.initialLocus - initial locus data
* @param {Object} params.metadata - hash tree metadata
* @param {string} params.replacedAt - timestamp from Locus indicating when the replacement happened
* @returns {HashTreeParser} the newly created parser
*/
private createHashTreeParser({
locusUrl,
initialLocus,
metadata,
replacedAt,
}: {
locusUrl: string;
initialLocus: {
dataSets: Array<DataSet>;
locus: any;
};
metadata: Metadata | null;
replacedAt?: string;
}): HashTreeParser {
const parser = new HashTreeParser({
initialLocus,
metadata,
webexRequest: this.webex.request.bind(this.webex),
callbacks: {
locusInfoUpdateCallback: this.updateFromHashTree.bind(this, locusUrl),
syncLatencyTracker: this.callbacks.syncLatencyTracker,
isLlmExpected: () => this.parsedLocus.self?.joinedWith?.state === 'JOINED',
// Reuse webex-core's tracking-id interceptor sequence (exposed publicly via
// webexTrackingIdSequenceNumbers) so Locus requests share the client's unified
// ${sessionId}_${sequence} tracking id space instead of minting an unrelated id. Fall
// back to a uuid on the rare chance the interceptor hasn't issued any request yet (and so
// isn't in the map). The value is opaque to the metrics layer and is forced onto the
// /hashtree and /sync request headers.
generateTrackingId: () => {
const interceptor = [...webexTrackingIdSequenceNumbers.keys()].find(
(candidate) => candidate?.webex === this.webex
);
return `${this.webex.sessionId}_${interceptor ? interceptor.sequence : uuid.v4()}`;
},
},
debugId: `HT-${locusUrl.split('/')?.pop()?.substring(0, 4)}`,
excludedDataSets: this.webex.config.meetings.locus?.excludedDataSets,
syncLatencyMeetingId: this.meetingId,
});
// When a new HashTreeParser is created, previous one should be stopped.
// Locus will only be sending us updates for the current one.
for (const [existingLocusUrl, existingEntry] of this.hashTreeParsers) {
if (existingEntry.parser.state !== 'stopped') {
existingEntry.parser.stop();
if (replacedAt) {
existingEntry.replacedAt = replacedAt;
} else {
LoggerProxy.logger.warn(
`Locus-info:index#createHashTreeParser --> no replacedAt timestamp provided for new HashTreeParser with locusUrl ${locusUrl}, replacing ${existingLocusUrl}`
);
}
}
}
this.hashTreeParsers.set(locusUrl, {parser, initializedFromHashTree: false});
this.hashTreeObjectId2ParticipantId.clear();
return parser;
}
/**
* @param {Object} data - data to initialize locus info with. It may be from a join or GET /loci response or from a Mercury event that triggers a creation of meeting object
* @param {Function} [onLocusSynced] - optional callback that will be called at the end of initial setup, when locus info is fully synced. It will be called with the full locus snapshot as an argument (which may be null if we haven't received any full locus DTOs during the initial setup, for example in case we receive only hash tree messages without full locus DTOs)
* @returns {undefined}
* @memberof LocusInfo
*/
async initialSetup(
data:
| {
trigger: 'join-response';
locus: LocusDTO;
dataSets?: DataSet[];
metadata?: Metadata;
}
| {
trigger: 'locus-message';
locus?: LocusDTO;
hashTreeMessage?: HashTreeMessage;
}
| {
trigger: 'get-loci-response';
locus?: LocusDTO;
},
onLocusSynced?: (locus: LocusDTO) => void
) {
let initialFullLocus: LocusDTO | null = null;
switch (data.trigger) {
case 'locus-message':
if (data.hashTreeMessage) {
// we need the Metadata object to be in the received message, because it contains visibleDataSets
// and these are needed to initialize all the hash trees
const metadataObject = data.hashTreeMessage.locusStateElements?.find((el) =>
isMetadata(el)
);
if (!metadataObject?.data?.visibleDataSets) {
// this is a common case (not an error)
// it happens for example after we leave the meeting and still get some heartbeats or delayed messages
LoggerProxy.logger.info(
`Locus-info:index#initialSetup --> cannot initialize HashTreeParser, Metadata object with visibleDataSets is missing in the message`
);
// throw so that handleLocusEvent() catches it and destroys the partially created meeting object
throw new Error('Metadata object with visibleDataSets is missing in the message');
}
LoggerProxy.logger.info(
'Locus-info:index#initialSetup --> creating HashTreeParser from message'
);
// first create the HashTreeParser, but don't initialize it with any data yet
const hashTreeParser = this.createHashTreeParser({
locusUrl: data.hashTreeMessage.locusUrl,
initialLocus: {
locus: null,
dataSets: data.hashTreeMessage.dataSets,
},
metadata: {
htMeta: metadataObject.htMeta,
visibleDataSets: metadataObject.data.visibleDataSets,
},
});
// now handle the message - that should populate all the visible datasets
await hashTreeParser.initializeFromMessage(data.hashTreeMessage);
} else {
// "classic" Locus case, no hash trees involved
this.updateLocusCache(data.locus);
this.onFullLocus('classic locus message', data.locus, undefined);
}
break;
case 'join-response':
this.updateLocusCache(data.locus);
this.onFullLocus('join response', data.locus, undefined, data.dataSets, data.metadata);
initialFullLocus = data.locus;
break;
case 'get-loci-response':
if (data.locus?.links?.resources?.visibleDataSets?.url) {
LoggerProxy.logger.info(
'Locus-info:index#initialSetup --> creating HashTreeParser from get-loci-response'
);
// first create the HashTreeParser, but don't initialize it with any data yet
const hashTreeParser = this.createHashTreeParser({
locusUrl: data.locus.url as string,
initialLocus: {
locus: null,
dataSets: [], // empty, because we don't have them yet
},
metadata: null, // get-loci-response doesn't contain Metadata object
});
// now initialize all the data
await hashTreeParser.initializeFromGetLociResponse(data.locus);
} else {
// "classic" Locus case, no hash trees involved
this.updateLocusCache(data.locus);
this.onFullLocus('classic get-loci-response', data.locus, undefined);
initialFullLocus = data.locus || null;
}
}
if (onLocusSynced) {
try {
onLocusSynced(initialFullLocus || this.getCurrentLocusSnapshot());
} catch (error) {
LoggerProxy.logger.warn(
`Locus-info:index#initialSetup --> onLocusSynced callback failed: ${error}`
);
}
}
// Change it to true after it receives it first locus object
this.emitChange = true;
}
/**
* Builds a full locus DTO snapshot from current internal locus state.
*
* @returns {LocusDTO}
*/
private getCurrentLocusSnapshot(): LocusDTO {
const locus: Record<string, any> = {};
LocusDtoTopLevelKeys.forEach((key) => {
const value = (this as Record<string, any>)[key];
if (value !== undefined && value !== null) {
locus[key] = cloneDeep(value);
}
});
if (!Array.isArray(locus.participants)) {
locus.participants = [];
}
return locus as LocusDTO;
}
/**
* Handles HTTP response from Locus API call.
* @param {Meeting} meeting meeting object
* @param {LocusApiResponseBody} responseBody body of the http response from Locus API call
* @returns {void}
*/
handleLocusAPIResponse(meeting: any, responseBody: LocusApiResponseBody): void {
const isWrapped = 'locus' in responseBody;
const locusUrl = isWrapped ? responseBody.locus?.url : responseBody.url;
const hashTreeParserEntry = locusUrl && this.hashTreeParsers.get(locusUrl);
const locus = isWrapped
? (responseBody as {locus: LocusDTO}).locus
: (responseBody as LocusDTO);
if (this.hashTreeParsers.size > 0) {
// We are in hash tree mode. Check if we need to create/reactivate a parser for this locusUrl.
if (!hashTreeParserEntry || hashTreeParserEntry.parser.state === 'stopped') {
if (!locusUrl) {
LoggerProxy.logger.warn(
'Locus-info:index#handleLocusAPIResponse --> API response has no locusUrl, cannot handle hash tree parser switch'
);
return;
}
this.handleHashTreeParserSwitchForAPIResponse(locusUrl, locus);
return;
}
// Active parser found - pass the API response to it
if (isWrapped) {
// update the data in our hash trees
hashTreeParserEntry.parser.handleLocusUpdate(responseBody);
} else {
// LocusDTO without wrapper - pass it through as if it had no dataSets nor metadata
hashTreeParserEntry.parser.handleLocusUpdate({locus: responseBody});
}
return;
}
// No hash tree parsers - classic Locus mode
if (isWrapped && responseBody.dataSets) {
this.sendClassicVsHashTreeMismatchMetric(
meeting,
`unexpected hash tree dataSets in API response`
);
}
// classic Locus delta
this.handleLocusDelta(locus, meeting);
}
/**
* @param {HashTreeObject} object data set object
* @param {any} locus
* @returns {void}
*/
updateLocusFromHashTreeObject(object: HashTreeObject, locus: LocusDTO): LocusDTO {
const type = object.htMeta.elementId.type.toLowerCase();
const addParticipantObject = (obj: HashTreeObject) => {
if (!locus.participants) {
locus.participants = [];
}
locus.participants.push(obj.data);
this.hashTreeObjectId2ParticipantId.set(obj.htMeta.elementId.id, obj.data.id);
};
switch (type) {
case ObjectType.locus: {
if (!object.data) {
// not doing anything here, as we need Locus to always be there (at least some fields)
// and that's already taken care of in updateFromHashTree()
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> LOCUS object removed, version=${object.htMeta.elementId.version}`
);
return locus;
}
// replace the main locus
// The Locus object we receive from backend has empty participants array,
// and may have (although it shouldn't) other fields that are managed by other ObjectTypes
// like "fullState" or "info", so we're making sure to delete them here
const locusObjectFromData = object.data;
Object.values(ObjectTypeToLocusKeyMap).forEach((locusDtoKey) => {
delete locusObjectFromData[locusDtoKey];
});
locus = {...locus, ...locusObjectFromData};
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> LOCUS object updated to version=${object.htMeta.elementId.version}`
);
break;
}
case ObjectType.mediaShare:
if (object.data) {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> mediaShare id=${
object.htMeta.elementId.id
} name='${object.data.name}' updated ${
object.data.name === 'content'
? `floor=${object.data.floor?.disposition}, ${object.data.floor?.beneficiary?.id}`
: ''
} version=${object.htMeta.elementId.version}`
);
const existingMediaShare = locus.mediaShares?.find(
(ms) => ms.htMeta.elementId.id === object.htMeta.elementId.id
);
if (existingMediaShare) {
Object.assign(existingMediaShare, object.data);
} else {
locus.mediaShares = locus.mediaShares || [];
locus.mediaShares.push(object.data);
}
} else {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> mediaShare id=${object.htMeta.elementId.id} removed, version=${object.htMeta.elementId.version}`
);
locus.mediaShares = locus.mediaShares?.filter(
(ms) => ms.htMeta.elementId.id !== object.htMeta.elementId.id
);
}
break;
case ObjectType.embeddedApp:
if (object.data) {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> embeddedApp id=${object.htMeta.elementId.id} url='${object.data.url}' updated version=${object.htMeta.elementId.version}:`,
object.data
);
const existingEmbeddedApp = locus.embeddedApps?.find(
(ms) => ms.htMeta.elementId.id === object.htMeta.elementId.id
);
if (existingEmbeddedApp) {
Object.assign(existingEmbeddedApp, object.data);
} else {
locus.embeddedApps = locus.embeddedApps || [];
locus.embeddedApps.push(object.data);
}
} else {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> embeddedApp id=${object.htMeta.elementId.id} removed, version=${object.htMeta.elementId.version}`
);
locus.embeddedApps = locus.embeddedApps?.filter(
(ms) => ms.htMeta.elementId.id !== object.htMeta.elementId.id
);
}
break;
case ObjectType.participant:
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> participant id=${
object.htMeta.elementId.id
} ${object.data ? 'updated' : 'removed'} version=${object.htMeta.elementId.version}`
);
if (object.data) {
addParticipantObject(object);
} else {
const participantId = this.hashTreeObjectId2ParticipantId.get(object.htMeta.elementId.id);
if (!locus.jsSdkMeta) {
locus.jsSdkMeta = {removedParticipantIds: []};
}
locus.jsSdkMeta.removedParticipantIds.push(participantId);
this.hashTreeObjectId2ParticipantId.delete(object.htMeta.elementId.id);
}
// Create self from the participant if it matches self identity and is being moved.
// We need this, because participant update comes in LLM message often before the self update from Mercury.
// Other parts of the code detect move only by looking at self, while some other parts of the SDK/webapp code
// look at participant for roles etc, so if participant is updated but not self, then it looks like we our lost roles temporarily
// (until self is updated)
// This will be fixed properly in SPARK-790239
if (
object.data &&
object.data.identity === locus.self?.identity &&
object.data.state === 'LEFT' &&
object.data.reason === 'MOVED'
) {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> FOUND a match for MOVED self in participant object ${object.htMeta.elementId.id}`
);
Object.assign(locus[ObjectTypeToLocusKeyMap[ObjectType.self]], object.data);
}
break;
case ObjectType.control:
if (object.data) {
Object.keys(object.data).forEach((controlKey) => {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> control ${controlKey} updated:`,
object.data[controlKey]
);
if (!locus.controls) {
locus.controls = {};
}
locus.controls[controlKey] = object.data[controlKey];
});
} else {
LoggerProxy.logger.warn(
`Locus-info:index#updateLocusFromHashTreeObject --> control object update without data - this is not expected!`
);
}
break;
case ObjectType.links:
case ObjectType.info:
case ObjectType.fullState:
case ObjectType.self:
if (!object.data) {
// self without data is handled inside HashTreeParser and results in LocusInfoUpdateType.MEETING_ENDED, so we should never get here
// all other types info, fullstate, etc - Locus should never send them without data
// but we end up with this method being called without the data for them when the main dataset is removed from visible datasets list
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> received ${type} object without data, version=${object.htMeta.elementId.version}`
);
} else {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> ${type} object updated to version ${object.htMeta.elementId.version}`
);
if (type === ObjectType.self) {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> self data: removed=${object.data.removed} state=${object.data.state} reason=${object.data.reason}`
);
}
const locusDtoKey = ObjectTypeToLocusKeyMap[type] as keyof LocusDTO;
locus[locusDtoKey] = object.data;
/* Hash tree based webinar attendees don't receive a Participant object for themselves from Locus,
but a lot of existing code in SDK and web app expects a member object for self to exist,
so whenever SELF changes for a webinar attendee, we copy it into a participant object.
We can do it, because SELF has always all the same properties as a participant object.
*/
if (
type === ObjectType.self &&
locus.info?.isWebinar &&
object.data.controls?.role?.roles?.find(
(r) => r.type === SELF_ROLES.ATTENDEE && r.hasRole
)
) {
LoggerProxy.logger.info(
`Locus-info:index#updateLocusFromHashTreeObject --> webinar attendee: creating participant object from self`
);
addParticipantObject(object);
}
}
break;
case ObjectType.metadata:
LoggerProxy.logger.info(