This repository has been archived by the owner on Jun 10, 2022. It is now read-only.
/
session.ts
473 lines (425 loc) · 16.1 KB
/
session.ts
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
/*!
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*/
import deepmerge from 'deepmerge';
import { EventEmitter } from 'events';
import { AnimationLike, Guid, newGuid, log, UserLike } from '../../..';
import {
Client,
Connection,
EventedConnection,
filterEmpty,
InitializeActorMessage,
Message,
MissingRule,
Payloads,
Protocols,
Rules,
SessionExecution,
SessionHandshake,
SessionSync,
SyncActor,
SyncAnimation,
SyncAsset,
validateJsonFieldName
} from '../../../internal';
type AssetCreationMessage = Message<Payloads.LoadAssets | Payloads.CreateAsset>;
type AnimationCreationMessage = Message<Payloads.CreateAnimation2 | Payloads.CreateActorCommon>;
/**
* @hidden
* Class for associating multiple client connections with a single app session.
*/
export class Session extends EventEmitter {
private _clientSet = new Map<Guid, Client>();
private _actorSet = new Map<Guid, Partial<SyncActor>>();
private _assetSet = new Map<Guid, Partial<SyncAsset>>();
private _assetCreatorSet = new Map<Guid, AssetCreationMessage>();
/** Maps animation IDs to animation sync structs */
private _animationSet = new Map<Guid, Partial<SyncAnimation>>();
/** Maps IDs of messages that can create animations to the messages themselves */
private _animationCreatorSet = new Map<Guid, AnimationCreationMessage>();
private _userSet = new Map<Guid, Partial<UserLike>>();
private _protocol: Protocols.Protocol;
private _disconnect: () => void;
private actorLastUpdate = new Map<Guid, number>();
public get conn() { return this._conn; }
public get sessionId() { return this._sessionId; }
public get protocol() { return this._protocol; }
public get clients() {
return [...this._clientSet.values()].sort((a, b) => a.order - b.order);
}
public get actors() { return [...this._actorSet.values()]; }
public get assets() { return [...this._assetSet.values()]; }
public get assetCreators() { return [...this._assetCreatorSet.values()]; }
public get animationSet() { return this._animationSet; }
public get animations() { return this._animationSet.values(); }
public get animationCreators() { return [...this._animationCreatorSet.values()]; }
public get animationCreatorSet() { return this._animationCreatorSet; }
public get actorSet() { return this._actorSet; }
public get assetSet() { return this._assetSet; }
public get assetCreatorSet() { return this._assetCreatorSet; }
public get userSet() { return this._userSet; }
public get rootActors() {
return this.actors.filter(a => !a.initialization.message.payload.actor.parentId);
}
public get authoritativeClient() { return this.clients.find(client => client.authoritative); }
public get peerAuthoritative() { return this._peerAuthoritative; }
public client = (clientId: Guid) => this._clientSet.get(clientId);
public actor = (actorId: Guid) => this._actorSet.get(actorId);
public user = (userId: Guid) => this._userSet.get(userId);
public childrenOf = (parentId: Guid) => {
return this.actors.filter(actor => actor.initialization.message.payload.actor.parentId === parentId);
};
public creatableChildrenOf = (parentId: Guid) => {
return this.actors.filter(actor =>
actor.initialization.message.payload.actor.parentId === parentId
&& !!actor.initialization.message.payload.type);
};
/**
* Creates a new Session instance
*/
constructor(private _conn: Connection, private _sessionId: string, private _peerAuthoritative: boolean) {
super();
this.recvFromClient = this.recvFromClient.bind(this);
this.recvFromApp = this.recvFromApp.bind(this);
this._disconnect = this.disconnect.bind(this);
this._conn.on('close', this._disconnect);
this._conn.on('error', this._disconnect);
}
/**
* Performs handshake and sync with the app
*/
public async connect() {
try {
const handshake = this._protocol = new SessionHandshake(this);
await handshake.run();
const sync = this._protocol = new SessionSync(this);
await sync.run();
const execution = this._protocol = new SessionExecution(this);
execution.on('recv', message => this.recvFromApp(message));
execution.startListening();
} catch (e) {
log.error('network', e);
this.disconnect();
}
}
public disconnect() {
try {
this._conn.off('close', this._disconnect);
this._conn.off('error', this._disconnect);
this._conn.close();
this.emit('close');
} catch { }
}
/**
* Adds the client to the session
*/
public async join(client: Client) {
try {
this._clientSet.set(client.id, client);
client.on('close', () => this.leave(client.id));
// Synchronize app state to the client.
await client.join(this);
// Once the client is joined, further messages from the client will be processed by the session
// (as opposed to a protocol class).
client.on('recv', (_: Client, message: Message) => this.recvFromClient(client, message));
// If we don't have an authoritative client, make this client authoritative.
if (!this.authoritativeClient) {
this.setAuthoritativeClient(client.id);
}
} catch (e) {
log.error('network', e);
this.leave(client.id);
}
}
/**
* Removes the client from the session
*/
public leave(clientId: Guid) {
try {
const client = this._clientSet.get(clientId);
this._clientSet.delete(clientId);
if (client) {
// If the client is associated with a userId, inform app the user is leaving
if (client.userId) {
this.protocol.sendPayload({
type: 'user-left',
userId: client.userId
} as Payloads.UserLeft);
}
// Select another client to be the authoritative peer.
// TODO: Make selection criteria more intelligent (look at latency, prefer non-mobile, ...)
if (client.authoritative) {
const nextClient = this.clients.find(c => c.isJoined());
if (nextClient) {
this.setAuthoritativeClient(nextClient.id);
}
}
}
// If this was the last client then shutdown the session
if (!this.clients.length) {
this._conn.close();
}
} catch { }
}
private setAuthoritativeClient(clientId: Guid) {
const newAuthority = this._clientSet.get(clientId);
if (!newAuthority) {
log.error('network', `[ERROR] setAuthoritativeClient: client ${clientId} does not exist.`);
return;
}
const oldAuthority = this.authoritativeClient;
newAuthority.setAuthoritative(true);
for (const client of this.clients.filter(c => c !== newAuthority)) {
client.setAuthoritative(false);
}
// if client user id is known emit signal about authoritative simulation owner
if (newAuthority.userId) {
newAuthority.session.emit('set-authoritative', newAuthority.userId);
}
// forward connection quality metrics
if (this.conn instanceof EventedConnection) {
this.conn.linkConnectionQuality(newAuthority.conn.quality);
}
// forward network stats from the authoritative peer connection to the app
const toApp = this.conn instanceof EventedConnection ? this.conn : null;
const forwardIncoming = (bytes: number) => toApp.statsTracker.recordIncoming(bytes);
const forwardOutgoing = (bytes: number) => toApp.statsTracker.recordOutgoing(bytes);
const toNewAuthority = newAuthority.conn instanceof EventedConnection ? newAuthority.conn : null;
if (toNewAuthority) {
toNewAuthority.statsTracker.on('incoming', forwardIncoming);
toNewAuthority.statsTracker.on('outgoing', forwardOutgoing);
}
// turn off old authority
const toOldAuthority = oldAuthority && oldAuthority.conn instanceof EventedConnection
? oldAuthority.conn : null;
if (toOldAuthority) {
toOldAuthority.statsTracker.off('incoming', forwardIncoming);
toOldAuthority.statsTracker.off('outgoing', forwardOutgoing);
}
}
private recvFromClient = (client: Client, message: Message) => {
message = this.preprocessFromClient(client, message);
if (message) {
this.sendToApp(message);
}
};
private recvFromApp = (message: Message) => {
message = this.preprocessFromApp(message);
if (message) {
this.sendToClients(message);
}
};
public preprocessFromApp(message: Message): Message {
const rule = Rules[message.payload.type] || MissingRule;
const beforeReceiveFromApp = rule.session.beforeReceiveFromApp || (() => message);
return beforeReceiveFromApp(this, message);
}
public preprocessFromClient(client: Client, message: Message): Message {
// Precaution: If we don't recognize this client, drop the message.
if (!this._clientSet.has(client.id)) {
return undefined;
}
if (message.payload && message.payload.type && message.payload.type.length) {
const rule = Rules[message.payload.type] || MissingRule;
const beforeReceiveFromClient = rule.session.beforeReceiveFromClient || (() => message);
message = beforeReceiveFromClient(this, client, message);
}
return message;
}
public sendToApp(message: Message) {
this.protocol.sendMessage(message);
}
public sendToClients(message: Message, filterFn?: (value: Client, index: number) => any) {
const clients = this.clients.filter(filterFn || (() => true));
if (!message.id) {
message.id = newGuid();
}
const msgBuffer = Buffer.from(
JSON.stringify(message, (key, value) => {
validateJsonFieldName(key);
return filterEmpty(value);
}), 'utf8');
for (const client of clients) {
client.send(message, null, msgBuffer);
}
}
public sendPayloadToClients(payload: Partial<Payloads.Payload>, filterFn?: (value: Client, index: number) => any) {
this.sendToClients({ payload }, filterFn);
}
public isAnimating(syncActor: Partial<SyncActor>): boolean {
const actorAnims = [...this.animationSet.values()]
.filter(syncAnim => syncAnim.targetIds.includes(syncActor.actorId) && syncAnim.active);
if (actorAnims.length > 0) {
return true;
}
const parent = this._actorSet.get(syncActor.initialization?.message?.payload?.actor?.parentId);
if (parent) {
return this.isAnimating(parent);
}
return false;
}
public cacheInitializeActorMessage(message: InitializeActorMessage) {
let syncActor = this.actorSet.get(message.payload.actor.id);
if (!syncActor) {
const parent = this.actorSet.get(message.payload.actor.parentId);
syncActor = {
actorId: message.payload.actor.id,
exclusiveToUser: parent && parent.exclusiveToUser
|| message.payload.actor.exclusiveToUser,
initialization: deepmerge({ message }, {})
};
this.actorSet.set(message.payload.actor.id, syncActor);
// update reserved actor init message with something the client can use
} else if (syncActor.initialization.message.payload.type === 'x-reserve-actor') {
// send real init message, but with session's initial actor state
message.payload = {
...message.payload,
actor: syncActor.initialization.message.payload.actor
};
// write the merged message back to the session
syncActor.initialization.message = message;
}
}
public cacheActorUpdateMessage(message: Message<Payloads.ActorUpdate>) {
const syncActor = this.actorSet.get(message.payload.actor.id);
if (syncActor) {
// Merge the update into the existing actor.
syncActor.initialization.message.payload.actor
= deepmerge(syncActor.initialization.message.payload.actor, message.payload.actor);
// strip out transform data that wasn't updated
// so it doesn't desync from the updated one
const cacheTransform = syncActor.initialization.message.payload.actor.transform;
const patchTransform = message.payload.actor.transform;
if (patchTransform && patchTransform.app && cacheTransform.local) {
delete cacheTransform.local.position;
delete cacheTransform.local.rotation;
} else if (patchTransform && patchTransform.local) {
delete cacheTransform.app;
}
}
}
public cacheAssetCreationRequest(message: AssetCreationMessage) {
this.assetCreatorSet.set(message.id, message);
}
public cacheAssetCreation(assetId: Guid, creatorId: Guid, duration?: number) {
const syncAsset = {
id: assetId,
creatorMessageId: creatorId,
duration
} as Partial<SyncAsset>;
this.assetSet.set(assetId, syncAsset);
const creator = this.assetCreatorSet.get(creatorId);
// Updates are cached on send, creates are cached on receive,
// so it's possible something was updated while it was loading.
// Merge those updates into creation once the create comes back.
if (creator.payload.type === 'create-asset' && syncAsset.update) {
creator.payload.definition = deepmerge(
creator.payload.definition,
syncAsset.update.payload.asset
);
syncAsset.update = undefined;
}
// update end times on playing media instances with the now-known duration
for (const syncActor of this.actorSet.values()) {
for (const activeMediaInstance of (syncActor.activeMediaInstances || [])) {
if (activeMediaInstance.message.payload.mediaAssetId !== assetId ||
activeMediaInstance.message.payload.options.looping === true ||
activeMediaInstance.message.payload.options.paused === true ||
duration === undefined) {
continue;
}
let timeRemaining: number = syncAsset.duration;
if (activeMediaInstance.message.payload.options.time !== undefined) {
timeRemaining -= activeMediaInstance.message.payload.options.time;
}
if (activeMediaInstance.message.payload.options.pitch !== undefined) {
timeRemaining /= Math.pow(2.0,
(activeMediaInstance.message.payload.options.pitch / 12.0));
}
activeMediaInstance.expirationTime = activeMediaInstance.basisTime + timeRemaining;
}
}
}
public cacheAssetUpdate(update: Message<Payloads.AssetUpdate>) {
if (!this.assetSet.has(update.payload.asset.id)) {
this.assetSet.set(update.payload.asset.id, { id: update.payload.asset.id });
}
const syncAsset = this.assetSet.get(update.payload.asset.id);
const creator = this.assetCreatorSet.get(syncAsset.creatorMessageId);
if (creator && creator.payload.type === 'create-asset') {
// roll update into creation message
creator.payload.definition = deepmerge(
creator.payload.definition,
update.payload.asset);
} else if (syncAsset.update) {
// merge with previous update message
syncAsset.update.payload.asset = deepmerge(
syncAsset.update.payload.asset,
update.payload.asset);
} else {
// just save it
syncAsset.update = update;
}
}
public cacheAssetUnload(containerId: Guid) {
const creators = this.assetCreators.filter(c => c.payload.containerId === containerId);
for (const creator of creators) {
// un-cache creation message
this.assetCreatorSet.delete(creator.id);
// un-cache created assets
const assets = this.assets.filter(a => a.creatorMessageId === creator.id);
for (const asset of assets) {
this.assetSet.delete(asset.id);
}
}
}
public cacheAnimationCreationRequest(message: AnimationCreationMessage) {
this._animationCreatorSet.set(message.id, message);
if (message.payload.type === 'create-animation-2') {
const createAnim = message.payload as Payloads.CreateAnimation2;
this._animationSet.set(createAnim.animation.id, {
id: createAnim.animation.id,
creatorMessageId: message.id,
targetIds: Object.values(createAnim.targets)
});
}
}
public cacheAnimationCreation(creatorId: Guid, def: Partial<AnimationLike>) {
const animCreationResult: Partial<SyncAnimation> = {
id: def.id,
creatorMessageId: creatorId,
targetIds: [...def.targetIds],
active: def.weight > 0 && def.speed !== 0
};
const oldAnim = this._animationSet.get(def.id);
if (!oldAnim) {
this._animationSet.set(def.id, animCreationResult);
} else {
// the only field we didn't already know at creation
oldAnim.active = def.weight > 0 && def.speed !== 0;
}
}
public cacheAnimationUpdate(update: Message<Payloads.AnimationUpdate>) {
const syncAnim = this._animationSet.get(update.payload.animation.id);
if (syncAnim.update) {
// merge with previous update message
syncAnim.update.payload.animation = deepmerge(
syncAnim.update.payload.animation,
update.payload.animation);
} else {
// just save it
syncAnim.update = update;
}
syncAnim.active = syncAnim.update.payload.animation.weight > 0 &&
syncAnim.update.payload.animation.speed !== 0;
}
public cacheAnimationUnload(message: Message<Payloads.DestroyAnimations>) {
for (const id of message.payload.animationIds) {
const syncAnim = this._animationSet.get(id);
this._animationCreatorSet.delete(syncAnim.creatorMessageId);
this._animationSet.delete(id);
}
}
}