-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathModel.js
More file actions
370 lines (332 loc) · 11.9 KB
/
Model.js
File metadata and controls
370 lines (332 loc) · 11.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
/**
* @license
* Copyright 2019-2020 CERN and copyright holders of ALICE O2.
* See http://alice-o2.web.cern.ch/copyright for details of the copyright holders.
* All rights not expressly granted are reserved.
*
* This software is distributed under the terms of the GNU General Public
* License v3 (GPL Version 3), copied verbatim in the file "COPYING".
*
* In applying this license CERN does not waive the privileges and immunities
* granted to it by virtue of its status as an Intergovernmental Organization
* or submit itself to any jurisdiction.
*/
// Import frontend framework
import {
Observable, WebSocketClient, QueryRouter, Loader, sessionService, RemoteData, showNativeBrowserNotification
} from '/js/src/index.js';
import {Notification as O2Notification} from '/js/src/index.js';
import Lock from './lock/Lock.js';
import Environment from './environment/Environment.js';
import About from './about/About.js';
import Workflow from './workflow/Workflow.js';
import TaskPageModel from './pages/TaskList/TaskList.model.js';
import Config from './configuration/ConfigByCru.js';
import DetectorService from './services/DetectorService.js';
import {PREFIX, ROLES} from './../workflow/constants.js';
import { SERVICE_STATES } from './common/constants/serviceStates.js';
import {STATUS_COMPONENTS_KEYS} from './common/constants/statusComponents.enum.js';
import { BroadcastKeys } from './common/enums/BroadcastKeys.enum.js';
import {di} from './utilities/di.js';
import {EnvironmentCreationModel} from './pages/EnvironmentCreation/EnvironmentCreation.model.js';
import {CalibrationRunsModel} from './pages/CalibrationRuns/CalibrationRuns.model.js';
/**
* Root of model tree
* Handle global events: keyboard, websocket and router location change
*/
export default class Model extends Observable {
/**
* Load all sub-models and bind event handlers
*/
constructor() {
super();
this.session = sessionService.get();
this.session.personid = parseInt(this.session.personid, 10); // cast, sessionService has only strings
this.session.role = this.getRole();
di.session = this.session;
this.loader = new Loader(this);
this.loader.bubbleTo(this);
this.lock = new Lock(this);
this.lock.bubbleTo(this);
// Setup router
this.router = new QueryRouter();
this.router.observe(this.handleLocationChange.bind(this));
this.router.bubbleTo(this);
// Services
this.detectors = new DetectorService(this);
this.services = {
detectors: this.detectors
};
this.cache = {
dcs: {
sor: {}
}
};
di.cache = this.cache;
this.configuration = new Config(this);
this.configuration.bubbleTo(this);
// Pages Models
this.environment = new Environment(this);
this.environment.bubbleTo(this);
this.workflow = new Workflow(this);
this.workflow.bubbleTo(this);
this.envCreationModel = new EnvironmentCreationModel(this);
this.envCreationModel.bubbleTo(this);
this.calibrationRunsModel = new CalibrationRunsModel(this);
this.calibrationRunsModel.bubbleTo(this);
this.taskPageModel = new TaskPageModel(this);
this.taskPageModel.bubbleTo(this);
this.about = new About(this);
this.about.bubbleTo(this);
this.notification = new O2Notification();
this.notification.bubbleTo(this);
di.notification = this.notification;
// Setup WS connection
this.ws = new WebSocketClient();
this.ws.addListener('command', this.handleWSCommand.bind(this));
this.ws.addListener('close', this.handleWSClose.bind(this));
// Load some initial data
this.lock.synchronizeState();
// General visuals
this.accountMenuEnabled = false;
this.sideBarMenu = true;
this.init();
}
/**
* Returns user role
* @returns {object} User's role
*/
getRole() {
if (this.session.access.includes('admin')) {
return ROLES.Admin;
} else if (this.session.access.includes('global')) {
return ROLES.Global;
} else if (this.session.access.some((role) => role.toUpperCase().startsWith(PREFIX.SSO_DET_ROLE.toUpperCase()))) {
return ROLES.Detector;
}
return ROLES.Guest;
}
/**
* Evaluate whether action is allowed for given role
* @param {ROLES} role - target role
* @param {bool} [strict=false] - The target role must equal current role
* @returns {bool} Whether current role (= model.role) is equal or superior to target role
*/
isAllowed(role, strict = false) {
return strict ? this.session.role === role : this.session.role <= role;
}
/**
* If no detector view is selected:
* * load a list of detectors
* * wait for user to make their selection
*/
async init() {
if (!this.router.params.page) {
// if page is loaded as host:port only, a default route has to be passed
this.router.go('?page=environments');
}
await this.detectors.init();
if (this.detectors.selected || this.session.role == ROLES.Guest) {
this.handleLocationChange();
}
this.notify();
}
/**
* Delegates sub-model actions depending on incoming command from server
* @param {WebSocketMessage} message
*/
handleWSCommand(message) {
switch (message.command) {
case BroadcastKeys.PADLOCK_UPDATE:
this.lock.padlockState = message.payload;
break;
case BroadcastKeys.NOTIFICATION: {
const { payload: task } = message;
if (task?.taskId) {
// Notification is for the first task in error from an environment
showNativeBrowserNotification({
title: `TASK in ${task.state ?? 'unknown'} state`,
body: `Task ${task.id} in environment ${task.environmentId} is in ${task.state ?? 'unknown'} state`,
icon: '/o2_icon.png',
onclick: (event) => {
event?.preventDefault();
this.router.go(`?page=environment&id=${task.environmentId}`, '_blank');
}
});
}
break;
}
case BroadcastKeys.O2_ROC_CONFIG:
this.configuration.setConfigurationRequest(message.payload);
break;
case BroadcastKeys.COMPONENT_STATUS:
if (message?.payload[STATUS_COMPONENTS_KEYS.GENERAL_SYSTEM_KEY]) {
this.about.updateComponentStatus('system', message.payload[STATUS_COMPONENTS_KEYS.GENERAL_SYSTEM_KEY]);
}
this.detectors.availability = message.payload['INTEG_SERVICE-DCS']?.extras?.detectors ?? {};
this.notify();
break;
case BroadcastKeys.CALIBRATION_RUNS_BY_DETECTOR:
if (message.payload) {
this.calibrationRunsModel.calibrationRuns = RemoteData.success(message?.payload);
this.notify();
}
break;
case BroadcastKeys.CALIBRATION_RUNS_REQUESTS:
if (message.payload && this.calibrationRunsModel.calibrationRuns.isSuccess()) {
const {detector, runType} = message.payload;
this.calibrationRunsModel.calibrationRuns.payload[detector][runType].ongoingCalibrationRun =
RemoteData.success(message.payload);
this.calibrationRunsModel.notify();
}
break;
case BroadcastKeys.DCS.SOR:
this.cache.dcs.sor = message.payload;
this.notify();
break;
case BroadcastKeys.ENVIRONMENTS_OVERVIEW:
this.environment.list = RemoteData.success({ environments: message.payload ?? [] });
this.environment.updateItemEnvironment(message.payload, this.router.params?.panel ?? '');
this.notify();
break;
case BroadcastKeys.ENVIRONMENT_EVENTS:
if (this.environment.item.isSuccess()) {
const { id } = this.environment.item.payload;
const eventPayload = message.payload;
if (id === eventPayload.id) {
Object.assign(this.environment.item.payload, eventPayload);
this.environment.notify();
}
}
if (this.environment.list.isSuccess()) {
const environmentEvent = message.payload;
this.environment.list.payload.environments.forEach((environment) => {
if (environment.id === environmentEvent.id) {
Object.assign(environment, environmentEvent);
this.notify();
}
});
}
break;
}
}
/**
* Handle close event from WS when connection has been lost (server restart, etc.)
* * Releases the lock if taken
* * Displays informative message to the client
* * Retries to connect to server every 10 seconds; If successful, informs de user
*/
handleWSClose() {
clearInterval(this.taskPageModel.refreshInterval);
// Release client-side
this.lock.padlockState = {};
this.notification.show(`Connection to server has been lost. Retrying to connect in 10 seconds...`, 'danger', 10000);
this.about.setWsInfo(SERVICE_STATES.IN_ERROR, {
status: {ok: false, configured: true, message: 'Cannot establish connection to server'}
});
const wsReconnectInterval = setInterval(() => {
// Setup WS connection
try {
this.ws = new WebSocketClient();
this.ws.addListener('command', this.handleWSCommand.bind(this));
this.ws.addListener('close', this.handleWSClose.bind(this));
clearInterval(wsReconnectInterval);
this.about.setWsInfo(SERVICE_STATES.IN_SUCCESS, {
status: {ok: true, configured: true}, message: 'WebSocket connection is alive'
});
this.notification.show(`Connection to server has been restored`, 'success', 3000);
} catch (error) {
console.error(error);
}
}, 10000);
}
/**
* Delegates sub-model actions depending new location of the page
*/
handleLocationChange() {
clearInterval(this.taskPageModel.refreshInterval);
this.about.retrieveInfo();
switch (this.router.params.page) {
case 'environments':
this.environment.getEnvironments();
break;
case 'environment':
if (!this.router.params.id) {
this.notification.show('The id in URL is missing, going to list instead', 'warning');
this.router.go('?page=environments');
return;
}
if (!this.router.params.panel) {
this.router.go(`?page=environment&id=${this.router.params.id}&panel=general`, true, true);
}
this.environment.getEnvironment({id: this.router.params.id}, true, this.router.params.panel);
break;
case 'newEnvironmentAdvanced':
this.workflow.initWorkflowPage();
break;
case 'newEnvironment':
this.envCreationModel.initPage();
break;
case 'calibrationRuns':
this.calibrationRunsModel.initPage();
break;
case 'taskList':
this.taskPageModel.init();
break;
case 'about':
break;
case 'configuration':
this.configuration.init();
this.configuration.getCRUsConfig();
this.configuration.getCRUsAliases();
break;
case 'locks':
break;
case 'hardware':
break;
default:
this.router.go('?page=environments');
break;
}
}
/**
* Toggle account menu dropdown
*/
toggleAccountMenu() {
this.accountMenuEnabled = !this.accountMenuEnabled;
this.notify();
}
/**
* Toggles the sidebar size
* * minimal - icons only
* * normal - icons + text
*/
toggleSideBarMenu() {
this.sideBarMenu = !this.sideBarMenu;
this.notify();
}
/**
* Update detector selection view
* @param {String} detector
* @returns {vnode}
*/
setDetectorView(detector) {
this.detectors.saveSelection(detector);
this.handleLocationChange();
this.notify();
}
/**
* Reset detector view by:
* * removing current selection
* * retrieving a list of detectors
* * opening modal and allowing the user to make a new selection
*/
async resetDetectorView() {
this.detectors.saveSelection('');
this.notify();
if (!this.detectors.listRemote.isSuccess() || !this.detectors.hostsByDetectorRemote.isSuccess()) {
await this.detectors.init();
this.notify();
}
}
}