forked from hpi-sam/digital-fuesim-manv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise.service.ts
284 lines (274 loc) · 10.1 KB
/
exercise.service.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
import { Injectable } from '@angular/core';
import { Store } from '@ngrx/store';
import type {
ClientToServerEvents,
ExerciseAction,
ExerciseState,
ServerToClientEvents,
SocketResponse,
UUID,
} from 'digital-fuesim-manv-shared';
import { socketIoTransports } from 'digital-fuesim-manv-shared';
import { freeze } from 'immer';
import {
debounceTime,
filter,
pairwise,
Subject,
switchMap,
takeUntil,
} from 'rxjs';
import type { Socket } from 'socket.io-client';
import { io } from 'socket.io-client';
import { handleChanges } from '../shared/functions/handle-changes';
import type { AppState } from '../state/app.state';
import {
createApplyServerActionAction,
createJoinExerciseAction,
createLeaveExerciseAction,
createSetExerciseStateAction,
} from '../state/application/application.actions';
import { selectExerciseStateMode } from '../state/application/selectors/application.selectors';
import {
selectClients,
selectExerciseState,
} from '../state/application/selectors/exercise.selectors';
import {
selectCurrentRole,
selectOwnClient,
selectVisibleVehicles,
} from '../state/application/selectors/shared.selectors';
import { selectStateSnapshot } from '../state/get-state-snapshot';
import { websocketOrigin } from './api-origins';
import { MessageService } from './messages/message.service';
import { OptimisticActionHandler } from './optimistic-action-handler';
/**
* This Service deals with the state synchronization of a live exercise.
* In addition, it notifies the user during an exercise of certain events (new client connected, vehicle arrived etc.).
*
* While this service should be used for proposing all actions (= changing the state) all
* read operations should be done via the central frontend store (with the help of selectors).
*/
@Injectable({
providedIn: 'root',
})
export class ExerciseService {
private readonly socket: Socket<
ServerToClientEvents,
ClientToServerEvents
> = io(websocketOrigin, {
...socketIoTransports,
});
private optimisticActionHandler?: OptimisticActionHandler<
ExerciseAction,
ExerciseState,
SocketResponse
>;
constructor(
private readonly store: Store<AppState>,
private readonly messageService: MessageService
) {
this.socket.on('performAction', (action: ExerciseAction) => {
freeze(action, true);
this.optimisticActionHandler?.performAction(action);
});
this.socket.on('disconnect', (reason) => {
if (reason === 'io client disconnect') {
return;
}
this.messageService.postError(
{
title: 'Die Verbindung zum Server wurde unterbrochen',
body: 'Laden Sie die Seite neu, um die Verbindung wieder herzustellen.',
error: reason,
},
'alert',
null
);
});
}
/**
* Use the function in ApplicationService instead
*
* Join an exercise and retrieve its state
* Displays an error message if the join failed
* @returns whether the join was successful
*/
public async joinExercise(
exerciseId: string,
clientName: string
): Promise<boolean> {
this.socket.connect().on('connect_error', (error) => {
this.messageService.postError({
title: 'Fehler beim Verbinden zum Server',
error,
});
});
const joinResponse = await new Promise<SocketResponse<UUID>>(
(resolve) => {
this.socket.emit(
'joinExercise',
exerciseId,
clientName,
resolve
);
}
);
if (!joinResponse.success) {
this.messageService.postError({
title: 'Fehler beim Beitreten der Übung',
error: joinResponse.message,
});
return false;
}
const getStateResponse = await new Promise<
SocketResponse<ExerciseState>
>((resolve) => {
this.socket.emit('getState', resolve);
});
freeze(getStateResponse, true);
if (!getStateResponse.success) {
this.messageService.postError({
title: 'Fehler beim Laden der Übung',
error: getStateResponse.message,
});
return false;
}
this.store.dispatch(
createJoinExerciseAction(
joinResponse.payload,
getStateResponse.payload,
exerciseId,
clientName
)
);
// Only do this after the correct state is in the store
this.optimisticActionHandler = new OptimisticActionHandler<
ExerciseAction,
ExerciseState,
SocketResponse
>(
(exercise) =>
this.store.dispatch(createSetExerciseStateAction(exercise)),
() => selectStateSnapshot(selectExerciseState, this.store),
(action) =>
this.store.dispatch(createApplyServerActionAction(action)),
async (action) => {
const response = await new Promise<SocketResponse>(
(resolve) => {
this.socket.emit('proposeAction', action, resolve);
}
);
if (!response.success) {
if (!response.expected) {
this.messageService.postError({
title: 'Fehler beim Senden der Aktion',
error: response.message,
});
} else {
this.messageService.postError({
title: 'Diese Aktion ist nicht gestattet!',
error: response.message,
});
}
}
return response;
}
);
this.startNotifications();
return true;
}
/**
* Use the function in ApplicationService instead
*/
public leaveExercise() {
this.socket.disconnect();
this.stopNotifications();
this.optimisticActionHandler = undefined;
this.store.dispatch(createLeaveExerciseAction());
}
/**
*
* @param optimistic wether the action should be applied before the server responds (to reduce latency) (this update is guaranteed to be synchronous)
* @returns the response of the server
*/
public async proposeAction(action: ExerciseAction, optimistic = false) {
if (
selectStateSnapshot(selectExerciseStateMode, this.store) !==
'exercise' ||
this.optimisticActionHandler === undefined
) {
// Especially during timeTravel, buttons that propose actions are only deactivated via best effort
this.messageService.postError({
title: 'Änderungen konnten nicht vorgenommen werden',
body: 'Treten Sie der Übung wieder bei.',
});
return { success: false };
}
// TODO: throw if `response.success` is false
return this.optimisticActionHandler.proposeAction(action, optimistic);
}
private readonly stopNotifications$ = new Subject<void>();
private startNotifications() {
// If the user is a trainer, display a message for each joined or disconnected client
this.store
.select(selectCurrentRole)
.pipe(
filter((role) => role === 'trainer'),
switchMap(() => this.store.select(selectClients)),
pairwise(),
takeUntil(this.stopNotifications$)
)
.subscribe(([oldClients, newClients]) => {
handleChanges(oldClients, newClients, {
createHandler: (newClient) => {
this.messageService.postMessage({
title: `${newClient.name} ist als ${
newClient.role === 'trainer'
? 'Trainer'
: 'Teilnehmer'
} beigetreten.`,
color: 'info',
});
},
deleteHandler: (oldClient) => {
this.messageService.postMessage({
title: `${oldClient.name} hat die Übung verlassen.`,
color: 'info',
});
},
});
});
// If the user is restricted to a viewport, display a message for each vehicle that arrived at this viewport
this.store
.select(selectOwnClient)
.pipe(
filter(
(client) =>
client?.viewRestrictedToViewportId !== undefined &&
!client.isInWaitingRoom
),
switchMap((client) =>
this.store
.select(selectVisibleVehicles)
// pipe in here so no pairs of events from different viewports are built
// Do not trigger the message if the vehicle was removed and added again at the same time
.pipe(debounceTime(0), pairwise())
),
takeUntil(this.stopNotifications$)
)
.subscribe(([oldVehicles, newVehicles]) => {
handleChanges(oldVehicles, newVehicles, {
createHandler: (newVehicle) => {
this.messageService.postMessage({
title: `${newVehicle.name} ist eingetroffen.`,
color: 'info',
});
},
});
});
}
private stopNotifications() {
this.stopNotifications$.next();
}
}