-
Notifications
You must be signed in to change notification settings - Fork 218
/
piggyback.ts
308 lines (260 loc) · 11.2 KB
/
piggyback.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
/*
* Copyright (c) 2023 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
/* eslint-disable arrow-parens */
/* eslint-disable prefer-const */
/* eslint-disable require-jsdoc */
import * as API from '../api.js';
import * as Utils from '../utils.js';
import piggybackHTML from './piggyback.html';
import piggybackPlaceholders from './piggybackPlaceholders.json';
import * as Templates from './templates.js';
const EDITOR_INVALID_JSON_MNSSAGE = 'Invalid json!'
const HEADER_IS_REQUIRED_MESSAGE = 'Headers field is required!';
const COMMAND_IS_REQUIRED = 'Command field is required!';
const TIMEOUT_IS_REQUIRED_MESSAGE = 'Timeout field is required!';
const ACTOR_PATH_IS_REQUIRED_MESSAGE = 'Actor path field is required!';
const NO_SERVICES_MESSAGE = 'No services available!';
const SERVICES_LOADING = 'Loading...';
const REQUEST_IN_PROGRESS_MESSAGE = 'request in progress';
const REQUEST_ERROR_MESSAGE = 'error';
let chosenTemplate;
let serviceOverall = 'Overall';
let servicesAvailable = {};
let chosenService;
let instancesAll = 'All';
let chosenInstance;
let aceHeadersEditor;
let aceCommandEditor;
let aceResponse;
let editorValidatorMap = new Map();
let dom = {
showTemplates: null,
serviceSelector: null,
instanceContainer: null,
instanceSelector: null,
timeout: null,
buttonLoadServiceInstances: null,
targetActorSelection: null,
buttonSubmit: null,
buttonCancel: null,
responseStatus: null,
commandValidationElement: null,
headerValidationElement: null,
}
document.getElementById('piggybackHTML').innerHTML = piggybackHTML;
export async function ready() {
Utils.getAllElementsById(dom);
dom.showTemplates.onclick = function () {
let service = dom.serviceSelector.value
if (service === SERVICES_LOADING) {
service = serviceOverall;
}
Templates.setSelectedService(service);
}
await loadServicesAndInstances();
initAceEditors();
dom.targetActorSelection.placeholder = piggybackPlaceholders.targetActorSelection;
dom.buttonLoadServiceInstances.onclick = loadServicesAndInstances;
dom.buttonSubmit.onclick = submitPiggybackCommand;
dom.serviceSelector.onchange = onServiceSelected;
dom.instanceSelector.onchange = onInstanceSelected;
dom.timeout.onchange = onTimeoutChange;
dom.targetActorSelection.onchange = onActorPathChange;
}
export function onInsertTemplate(template) {
chosenTemplate = template;
dom.serviceSelector.value = chosenTemplate.service;
chosenInstance = undefined;
onServiceSelected();
dom.timeout.value = chosenTemplate.timeout;
dom.targetActorSelection.value = chosenTemplate.targetActorSelection;
Utils.setEditorValue(aceHeadersEditor, stringifyPretty(chosenTemplate.headers));
Utils.setEditorValue(aceCommandEditor, stringifyPretty(chosenTemplate.command));
}
async function loadServicesAndInstances() {
servicesAvailable[serviceOverall] = [];
Utils.setOptions(dom.serviceSelector, [SERVICES_LOADING]);
await API.callDittoREST('GET', '/devops/logging', null, null, false, true)
.then((result) => {
let servicesJsonArray = Object.entries(result).sort();
if (servicesJsonArray.length > 0) {
servicesJsonArray.forEach(service => {
let jsonServiceInstances = Object.values(service[1]);
let instances = jsonServiceInstances.map((jsonServiceInstance) => {
return jsonServiceInstance.instance;
}).sort();
instances.unshift(instancesAll);
servicesAvailable[service[0]] = instances;
});
} else {
servicesAvailable = [];
}
})
.catch((_err) => {
servicesAvailable = [];
});
setServices(servicesAvailable);
function setServices(services) {
let serviceNames = Object.keys(services);
if (!chosenService) {
if (chosenTemplate && serviceNames.indexOf(chosenTemplate.service) !== -1) {
chosenService = chosenTemplate.service;
} else if (serviceNames.length > 0) {
chosenService = serviceNames[0];
}
} else {
if (serviceNames.indexOf(chosenService) == -1) {
chosenService = undefined;
}
}
Utils.setOptions(dom.serviceSelector, serviceNames);
dom.serviceSelector.value = chosenService;
onServiceSelected();
}
}
function onServiceSelected() {
if (!dom.serviceSelector.value !== chosenService) {
validateAndReturn(dom.serviceSelector.value !== '', NO_SERVICES_MESSAGE, dom.serviceSelector);
chosenService = dom.serviceSelector.value;
if (chosenService && chosenService !== serviceOverall) {
dom.instanceContainer.removeAttribute('hidden', '');
setInstances(servicesAvailable[chosenService]);
} else {
dom.instanceContainer.setAttribute('hidden', '');
}
}
function setInstances(serviceInstances) {
if (!chosenInstance) {
if (serviceInstances.length > 0) {
chosenInstance = serviceInstances[0];
}
} else {
if (serviceInstances.indexOf(chosenInstance) == -1) {
chosenInstance = undefined;
}
}
Utils.setOptions(dom.instanceSelector, serviceInstances);
dom.instanceSelector.value = chosenInstance;
}
}
function initAceEditors() {
aceHeadersEditor = Utils.createAceEditor('aceHeaders', 'ace/mode/json');
aceHeadersEditor.setOption('wrap', true);
editorValidatorMap.set(aceHeadersEditor.getSession(), dom.headerValidationElement);
aceCommandEditor = Utils.createAceEditor('aceCommand', 'ace/mode/json');
aceCommandEditor.setOption('wrap', true);
editorValidatorMap.set(aceCommandEditor.getSession(), dom.commandValidationElement);
aceResponse = Utils.createAceEditor('acePiggybackResponse', 'ace/mode/json');
aceResponse.setReadOnly(true);
aceResponse.setOption('wrap', true);
aceHeadersEditor.setOption('placeholder', stringifyPretty(piggybackPlaceholders.headers));
aceCommandEditor.setOption('placeholder', stringifyPretty(piggybackPlaceholders.command));
aceHeadersEditor.getSession().on('changeAnnotation', onEditorChangeAnnotation);
aceCommandEditor.getSession().on('changeAnnotation', onEditorChangeAnnotation);
}
function onEditorChangeAnnotation(_event, editorSession) {
validateAndReturn(!hasEditorError(editorSession), EDITOR_INVALID_JSON_MNSSAGE, editorValidatorMap.get(editorSession));
}
function hasEditorError(editorSession) {
return editorSession.getAnnotations().filter((a) => a.type === 'error').length > 0;
}
async function submitPiggybackCommand() {
if (isCommandValid()) {
dom.responseStatus.innerHTML = REQUEST_IN_PROGRESS_MESSAGE;
Utils.setEditorValue(aceResponse, '');
try {
let path = buildPath(
dom.serviceSelector.value,
dom.instanceSelector.value,
dom.timeout.value
);
let piggybackCommandBody = Templates.buildPiggybackCommand(
dom.targetActorSelection.value,
JSON.parse(aceHeadersEditor.getValue()),
JSON.parse(aceCommandEditor.getValue())
);
let promise = new Promise((resolve, reject) => {
onRequestInProgress(reject);
API.callDittoREST('POST', path, piggybackCommandBody, null, true, true)
.then(result => resolve(result))
.catch(err => reject(err));
});
promise.then((result: any) => {
onRequestDone();
result.json().then(resultJson => {
Utils.setEditorValue(aceResponse, stringifyPretty(resultJson));
dom.responseStatus.innerHTML = result.status;
});
}).catch(err => {
onRequestDone();
Utils.setEditorValue(aceResponse, err.message);
dom.responseStatus.innerHTML = REQUEST_ERROR_MESSAGE;
});
} catch (err) {
Utils.showError(`Error when executing piggyback command${err}`);
dom.responseStatus.innerHTML = REQUEST_ERROR_MESSAGE;
}
}
function isCommandValid() {
let isTimeoutValid = validateAndReturn(dom.timeout.value.trim() !== '', TIMEOUT_IS_REQUIRED_MESSAGE, dom.timeout);
let isServiceValid = validateAndReturn(dom.serviceSelector.value !== '' && dom.serviceSelector.value !== SERVICES_LOADING, NO_SERVICES_MESSAGE, dom.serviceSelector);
let isActorPathValid = validateAndReturn(dom.targetActorSelection.value.trim() !== '', ACTOR_PATH_IS_REQUIRED_MESSAGE, dom.targetActorSelection);
let areHeadersValid = validateAndReturn(aceHeadersEditor.getValue().trim() !== '', HEADER_IS_REQUIRED_MESSAGE, dom.headerValidationElement);
areHeadersValid &&= validateAndReturn(!hasEditorError(aceHeadersEditor.getSession()), EDITOR_INVALID_JSON_MNSSAGE, dom.headerValidationElement);
let isCommandValid = validateAndReturn(aceCommandEditor.getValue().trim() !== '', COMMAND_IS_REQUIRED, dom.commandValidationElement);
isCommandValid &&= validateAndReturn(!hasEditorError(aceCommandEditor.getSession()), EDITOR_INVALID_JSON_MNSSAGE, dom.commandValidationElement);
return isTimeoutValid && isServiceValid && isActorPathValid && areHeadersValid && isCommandValid;
}
function buildPath(service, instance, timeout) {
let path = '';
if (service && service !== serviceOverall) {
path = `/${service}`;
if (instance && instance != instancesAll) {
path += `/${instance}`;
}
}
return `/devops/piggyback/${path}?timeout=${timeout}`;
}
function onRequestInProgress(rejectCallback) {
dom.buttonCancel.onclick = function () {
rejectCallback({ 'message': 'Cancelled' });
}
dom.buttonCancel.removeAttribute('hidden', '');
dom.buttonSubmit.setAttribute('hidden', '')
}
function onRequestDone() {
dom.buttonCancel.setAttribute('hidden', '');
dom.buttonSubmit.removeAttribute('hidden', '')
dom.buttonCancel.onclick = undefined;
}
}
function onInstanceSelected() {
chosenInstance = dom.instanceSelector.value;
}
function onTimeoutChange() {
validateAndReturn(dom.timeout.value.trim() !== '', TIMEOUT_IS_REQUIRED_MESSAGE, dom.timeout);
}
function onActorPathChange() {
validateAndReturn(dom.targetActorSelection.value.trim() !== '', ACTOR_PATH_IS_REQUIRED_MESSAGE, dom.targetActorSelection);
}
function validateAndReturn(condition, message, validatedElement) {
try {
Utils.assert(condition, message, validatedElement);
} catch (err) {
return false;
}
return true;
}
function stringifyPretty(jsonObject) {
return JSON.stringify(jsonObject, null, 4);
}