Repository navigation
Expand file tree
/
Copy pathclient-wrapper.ts
More file actions
507 lines (452 loc) · 16.9 KB
/
Copy pathclient-wrapper.ts
File metadata and controls
507 lines (452 loc) · 16.9 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
import type {
ExerciseAction,
ExerciseKey,
UUID,
StartExerciseAction,
PauseExerciseAction,
ParallelExerciseId,
Client,
CollectionEntityId,
CollectionMembershipRole,
} from 'fuesim-digital-shared';
import {
Marketplace,
ReducerError,
newClient,
newClientRole,
cloneDeepMutable,
checkCollectionMembershipRole,
} from 'fuesim-digital-shared';
import {
Subject,
filter,
takeUntil,
throttleTime,
type Subscription,
} from 'rxjs';
import cookie from 'cookie';
import type { z } from 'zod';
import type { ExerciseSocket } from '../exercise-server.js';
import { Config, isDevelopment } from '../config.js';
import type { SessionInformation } from '../auth/auth-service.js';
import type { ParallelExerciseDetailsEntry } from '../database/schema.js';
import { PermissionDeniedError } from '../utils/http.js';
import type { Services } from '../database/services/index.js';
import type { Repositories } from '../database/repositories/index.js';
import type { ActiveExercise } from './active-exercise.js';
import { clientMap } from './client-map.js';
/**
* Wraps a {@link ExerciseSocket} for different types of clients.
*/
export abstract class ClientWrapper {
public session?: SessionInformation;
public constructor(
public readonly socket: ExerciseSocket,
public readonly services: Services,
public readonly repositories: Repositories
) {}
public static init<T extends typeof ClientWrapper>(
wrapperClass: T,
socket: ExerciseSocket,
services: Services,
repositories: Repositories
): InstanceType<T> | undefined {
if (clientMap.get(socket)) {
// Already registered
return;
}
// @ts-expect-error typing
const wrapper = new wrapperClass(socket, services, repositories);
clientMap.set(socket, wrapper);
return wrapper;
}
public async getSessionInformation() {
const cookies = cookie.parse(this.socket.request.headers.cookie ?? '');
const sessionToken =
cookies[this.services.authService.SESSION_COOKIE_NAME] ?? '';
this.session =
await this.services.authService.getDataFromSessionToken(
sessionToken
);
}
public disconnect() {
this.socket.disconnect();
}
}
export class ExerciseClientWrapper extends ClientWrapper {
private chosenExercise?: ActiveExercise;
private relatedExerciseClient?: Client;
/**
* @param exerciseKey The exercise key to be used for the client.
* @param clientName The public name of the client.
* @returns The joined client's id, or undefined when the exercise doesn't exist.
*/
public async joinExercise(
exerciseKey: ExerciseKey,
clientName: string
): Promise<UUID> {
this.chosenExercise =
await this.services.exerciseService.getExerciseByKey(
exerciseKey,
this.session
);
// Although getRoleFromUsedId may throw an error, this should never happen here
// as the provided id is guaranteed to be one of the ids of the exercise as the exercise
// was fetched with this exact id from the exercise map.
const role = this.chosenExercise.getRoleFromUsedKey(exerciseKey);
this.relatedExerciseClient = newClient(
clientName,
newClientRole(role, role === 'trainer' ? 'trainer' : 'mapOperator'),
Config.devNoWaitingRoom && isDevelopment()
? false
: role !== 'trainer'
);
this.chosenExercise.addClient(this);
return this.relatedExerciseClient.id;
}
/**
* Reconnect to an existing inactive client in an exercise.
* @param exerciseKey The exercise key to use.
* @param clientId The id of the existing (inactive) client to set active.
* @returns The client's id on success, or null if the client could not be reconnected.
*/
public async reconnectToExercise(
exerciseKey: ExerciseKey,
clientId: UUID
): Promise<UUID | null> {
this.chosenExercise =
await this.services.exerciseService.getExerciseByKey(
exerciseKey,
this.session
);
const existingClient =
this.chosenExercise.getStateSnapshot().clients[clientId];
if (existingClient?.isActive) {
this.chosenExercise = undefined;
return null;
}
this.relatedExerciseClient = existingClient;
this.chosenExercise.setClientActive(this);
return existingClient?.id ?? null;
}
/**
* Note that this method simply returns when the client did not join an exercise.
*/
public leaveExercise() {
if (this.chosenExercise === undefined) {
// The client has not joined an exercise. Do nothing.
return;
}
this.chosenExercise.removeClient(this);
this.chosenExercise = undefined;
}
public get exercise(): ActiveExercise | undefined {
return this.chosenExercise;
}
public get client(): Client | undefined {
return this.relatedExerciseClient;
}
public emitAction(action: ExerciseAction) {
this.socket.emit('performAction', action);
}
public override disconnect() {
if (
this.chosenExercise !== undefined &&
this.relatedExerciseClient !== undefined
) {
this.chosenExercise.setClientInactive(this);
this.chosenExercise = undefined;
}
super.disconnect();
}
}
export class ParallelExerciseClientWrapper extends ClientWrapper {
private chosenExercise: ParallelExerciseDetailsEntry | null = null;
private readonly subscriptions: Subscription[] = [];
private readonly cachedActiveExercises: ActiveExercise[] = [];
private readonly aggregatedActions = new Subject<void>();
public async joinParallelExercise(id: ParallelExerciseId) {
if (!this.session) {
throw new PermissionDeniedError();
}
this.chosenExercise =
await this.services.parallelExerciseService.getParallelExerciseById(
id,
this.session
);
const activeExercises =
await this.services.parallelExerciseService.getParallelExerciseInstancesById(
id,
this.session
);
// One throttled subscription drives all client updates
const throttledSub = this.aggregatedActions
.pipe(
throttleTime(200, undefined, {
leading: true,
trailing: true, // Ensures the last value is emitted when enough time has passed. This prevents latest changes not being propagated due to throttling.
})
)
.subscribe(() => this.emitUpdateExerciseInstances());
this.subscriptions.push(throttledSub);
// We watch for new exercise instances to join the parallel exercise
// to register watchers for them
const joinSub = this.services.parallelExerciseService.newJoin
.pipe(filter((join) => id === join.parallelExerciseId))
.subscribe((join) => {
this.cachedActiveExercises.push(join.activeExercise);
const sub = join.activeExercise.actionApplied.subscribe(() =>
this.aggregatedActions.next()
);
this.subscriptions.push(sub);
this.emitUpdateExerciseInstances();
});
this.subscriptions.push(joinSub);
// Watch for changes in the exercise instances to send updates
for (const activeExercise of activeExercises) {
this.cachedActiveExercises.push(activeExercise);
const sub = activeExercise.actionApplied.subscribe(() =>
this.aggregatedActions.next()
);
this.subscriptions.push(sub);
}
}
public emitUpdateExerciseInstances() {
this.socket.emit('updateExerciseInstances', {
exerciseInstances: this.getInstanceSummaries(),
});
}
/**
* Get summaries of all exercise instances
*/
public getInstanceSummaries() {
return this.services.parallelExerciseService.getParallelExerciseInstanceSummaries(
this.cachedActiveExercises
);
}
public async applyActionToAll(action: ExerciseAction) {
const isEditorOrAdmin =
await this.repositories.organisationRepository.isMemberWithRoleOfOrganisationById(
this.chosenExercise!.organisationId,
this.session!.user.id,
['editor', 'admin']
);
if (!isEditorOrAdmin) {
throw new PermissionDeniedError();
}
for (const activeExercise of this.cachedActiveExercises) {
try {
activeExercise.applyAction(action, null);
} catch (e: unknown) {
if (!(e instanceof ReducerError)) {
throw e;
}
console.error(e);
}
}
}
public async start() {
await this.applyActionToAll({
type: '[Exercise] Start',
} satisfies StartExerciseAction);
}
public async pause() {
await this.applyActionToAll({
type: '[Exercise] Pause',
} satisfies PauseExerciseAction);
}
/**
* Leave this parallel exercise
*/
public leaveParallelExercise() {
for (const sub of this.subscriptions) {
sub.unsubscribe();
}
}
public get exercise() {
return this.chosenExercise;
}
/**
* Disconnect the websocket client
*/
public override disconnect() {
this.leaveParallelExercise();
super.disconnect();
}
}
export class CollectionClientWrapper extends ClientWrapper {
private chosenCollection?: CollectionEntityId;
private dependencies: CollectionEntityId[] = [];
private readonly stopListen$ = new Subject<void>();
public async startCollectionListener(
collectionEntityId: CollectionEntityId
) {
this.stopListen$.next();
this.chosenCollection = collectionEntityId;
const initialData = await this.getInitialData(collectionEntityId);
await this.loadDependencies(collectionEntityId);
this.startListen(collectionEntityId);
return initialData;
}
public async stopCollectionListener(
collectionEntityId: CollectionEntityId
) {
// we dont want to stop listening based on old data
if (this.chosenCollection !== collectionEntityId) return;
this.stopListen$.next();
this.chosenCollection = undefined;
this.dependencies = [];
}
public override disconnect() {
this.stopListen$.next();
this.stopListen$.complete();
super.disconnect();
}
public abort(reason: string) {
console.warn(
`Aborting collection listener for collection ${this.chosenCollection}:`,
reason
);
this.disconnect();
}
// this needs to be any, bc schema.encode removed the
// brand causing typescript errors when an encoded value
// (without brand) is passed to notifyChange (expecting a brand)
private notifyChange(
update: z.input<typeof Marketplace.Collection.Events.SSEvent.schema>
) {
this.socket.emit('collectionUpdate', update);
}
private startListen(collectionEntityId: CollectionEntityId) {
this.services.collectionService.events
.pipe(
filter(
(update) =>
update.collectionEntityId === collectionEntityId ||
this.dependencies.includes(update.collectionEntityId)
),
takeUntil(this.stopListen$)
)
.subscribe(async (update) => {
switch (update.event) {
case 'dependency:change': {
await this.loadDependencies(collectionEntityId);
this.notifyChange(update);
const latestDependencyElements =
await this.services.collectionService.getLatestDraftElementsOfCollection(
collectionEntityId
);
this.notifyChange(
Marketplace.Collection.Events.DependencyReplaceData.schema.encode(
{
event: 'dependency:replace-data',
collectionEntityId,
data: {
imported: cloneDeepMutable(
latestDependencyElements.imported
),
references: cloneDeepMutable(
latestDependencyElements.references
),
},
} satisfies typeof Marketplace.Collection.Events.DependencyReplaceData.Type
)
);
break;
}
default:
this.notifyChange(
Marketplace.Collection.Events.SSEvent.schema.encode(
cloneDeepMutable(update)
)
);
}
});
}
private async loadDependencies(collectionEntityId: CollectionEntityId) {
const latestCollection =
await this.services.collectionService.getLatestCollectionById(
collectionEntityId,
{ draftState: true }
);
if (!latestCollection) {
this.abort('Collection not found');
return;
}
this.dependencies = (
await this.services.collectionService.getCollectionDependencies(
latestCollection.versionId
)
).map((dependency) => dependency.entityId);
}
private async getInitialData(collectionEntityId: CollectionEntityId) {
const latestDraftStateVersion =
await this.services.collectionService.getLatestCollectionById(
collectionEntityId,
{ draftState: true }
);
const latestPubishedVersion =
await this.services.collectionService.getLatestCollectionById(
collectionEntityId,
{ draftState: false }
);
if (!latestDraftStateVersion || !latestPubishedVersion) {
this.abort('Collection not found');
return;
}
const draftStateElements =
await this.services.collectionService.getElementsOfCollectionVersion(
latestDraftStateVersion.versionId,
{ allowDraftState: true }
);
const publishedElements =
await this.services.collectionService.getElementsOfCollectionVersion(
latestPubishedVersion.versionId,
{
allowDraftState: false,
}
);
let userRelationship: CollectionMembershipRole | null = null;
if (this.session) {
userRelationship =
await this.services.collectionService.getUserRoleInCollection(
latestDraftStateVersion.entityId,
this.session
);
}
return Marketplace.Collection.Events.InitialData.schema.encode({
collectionEntityId,
event: 'initialdata',
data: {
collection: latestDraftStateVersion,
elements: cloneDeepMutable(draftStateElements),
userRelationship: userRelationship ?? 'other',
publishedCollection: latestPubishedVersion,
publishedElements: cloneDeepMutable(publishedElements),
},
});
}
public async canAccessCollection(collectionEntityId: CollectionEntityId) {
let canAccessCollection = false;
if (this.session) {
const relationship =
await this.services.collectionService.getUserRoleInCollectionTransitive(
collectionEntityId,
this.session
);
if (relationship !== null) {
canAccessCollection =
checkCollectionMembershipRole(relationship).isAtLeast(
'other'
);
}
}
if (!canAccessCollection) {
canAccessCollection =
await this.services.collectionService.isCollectionPublic(
collectionEntityId
);
}
return canAccessCollection;
}
}