-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
516 lines (435 loc) · 13.7 KB
/
index.js
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
508
509
510
511
512
513
514
515
516
const get = require('lodash.get');
const createGqlReq = require('./src/utils/baseRequest');
const Satellite = require('./src/classes/Satellite');
const Command = require('./src/classes/Command');
const Gateway = require('./src/classes/Gateway');
const typesDoMatch = require('./src/utils/typesDoMatch');
const FINAL_STATES = ['cancelled', 'failed', 'completed'];
const mts = ({ host, token }) => {
let mission;
if (!(host && token)) {
throw new Error('Script instance requires a value for `host` `token` and `mission`');
}
const makeGqlReq = createGqlReq(host, token);
const getMissionId = () => new Promise((resolve, reject) => {
const query = `
query Mission {
agent {
script {
mission { id }
}
}
}
`;
makeGqlReq({ query })
.then(result => {
const missionId = get(result, 'data.data.agent.script.mission.id');
if (!missionId) {
return reject(new Error('Could not get mission ID'));
}
mission = missionId;
resolve(missionId);
})
.catch(err => {
reject(err);
});
});
/**
* Retrieve the most recent value for a subsystem metric on a Satellite.
* @param {object} input
* @param {string|number} input.system
* @param {string} input.subsystem
* @param {string} input.metric
* @returns {Promise<{ value: number, timestamp: number }>}
*/
const getLatestMetricValue = input => new Promise((resolve, reject) => {
const params = ['system', 'subsystem', 'metric'];
params.forEach(key => {
if (!input[key]) {
return reject(new Error(`Property ${key} is required on input to getLatestMetricValue`));
}
});
const { system, subsystem, metric } = input;
const systemSpec = typeof system === 'number' ? `id:${system}` : `name:"${system}", missionId:${mission}`;
const query = `
query GetLatestTelem {
system(${systemSpec}) {
subsystems(filters:{name:"${subsystem}"}) {
nodes {
metrics(filters:{name:"${metric}"}) {
nodes {
latest {
value
timestamp
}
}
}
}
}
}
}
`.trim();
makeGqlReq({ query })
.then(result => {
const parsed = get(result, 'data.data.system.subsystems.nodes[0].metrics.nodes[0].latest');
const { value, timestamp } = parsed || {};
if (!parsed) {
return reject(
new Error(
`Could not get value ${subsystem}.${metric} for satellite ${typeof system === 'number' ? 'ID ' : ''}${system}`
)
);
}
resolve({ value, timestamp });
});
});
/**
* @param {object} input
* @param {string} input.name
* @param {string|number} input.id
* @param {string|number} input.noradId
* @returns {Promise<Satellite>}
*/
const getSatellite = input => new Promise((resolve, reject) => {
const params = ['name', 'id', 'noradId'];
const queryParams = params.map(key => {
if (input[key]) {
return [key, input[key]];
}
return null;
}).filter(x => x);
if (queryParams.length !== 1) {
return reject(new Error('Method `getSatellite` requires exactly one of `id`, `name`, or `noradId`'));
}
const [[inputKey, value]] = queryParams;
const query = `query GetSatellite {system(${inputKey}:"${value}", missionId:${mission}){id name noradId}}`;
makeGqlReq({ query })
.then(result => {
const system = get(result, 'data.data.system');
if (!system) {
return reject(new Error(`Could not find system with ${inputKey} ${value}`));
}
const { id, name, noradId } = system;
resolve(new Satellite({ id, name, noradId, host, token, mission }));
})
.catch(err => reject(err));
});
/**
* @param {object} param0
* @param {Satellite} param0.system
* @param {string|Command} param0.command
* @param {string|number|Gateway} param0.gateway
* @param {object.<string, number|string>} param0.fields
* @returns {Promise<Command>}
*/
const createCommand = ({ system, command, fields = {}, gateway }) => new Promise((resolve, reject) => {
const commandTypeStr = typeof command === 'string' ? command : command.commandType;
if (!commandTypeStr) {
throw new Error(
'Method createCommand requires a `command` property that is either a string or a command definition'
);
}
if (!system instanceof Satellite) {
throw new Error('Method createCommand requires a `system` property that is a Satellite');
}
if (gateway && !(gateway instanceof Gateway || Number.isInteger(Number(gateway)))) {
throw new Error(
'The optional `gateway` property on method createCommand must be either an ID or a Gateway object'
);
}
getCommandDefinitions(system)
.then(defs => {
const defMatch = defs.find(def => {
return def.commandType === commandTypeStr;
});
if (!defMatch) {
return reject(
new Error(`Could not find command type ${commandTypeStr} in command definitions for system ${system.name}`)
);
}
const parsedFields = JSON.parse(defMatch.fields);
Object.entries(fields).forEach(([fieldName, fieldValue]) => {
const fieldDef = parsedFields.find(({ name }) => name === fieldName);
const typeMatches = fieldDef && typesDoMatch(fieldValue, typeof fieldValue, fieldDef.type);
if (!(fieldDef && typeMatches)) {
const errStr = fieldDef
? `Field ${fieldName} was given value ${fieldValue} which does not match the expected type ${fieldDef.type}`
: `Command ${commandTypeStr} does not have a defined field ${fieldName}`;
reject(new Error(errStr));
}
});
const newCommand = new Command({ command: defMatch.id, system: system.id, fields });
if (gateway) {
newCommand.setGateway(gateway);
}
resolve(newCommand);
})
.catch(err => reject(err));
});
/**
* @param {Satellite} system
* @returns {Promise<CommandDefinition[]>}
*/
const getCommandDefinitions = system => new Promise((resolve, reject) => {
if (!(system instanceof Satellite)) {
throw new Error('Method getCommandDefinitions requires a Satellite argument');
}
const query = `
query GetCommandDefinitions {
system (id: ${system.id}) {
commandDefinitions {
nodes {
id
commandType
fields
displayName
description
tags
}
}
}
}
`.trim();
makeGqlReq({ query })
.then(({ data }) => resolve(data.data.system.commandDefinitions.nodes))
.catch(err => reject(err));
});
/**
* @param {Command} command
* @returns {Promise<Command>}
*/
const executeCommand = command => new Promise((resolve, reject) => {
if (!command instanceof Command) {
reject(new Error(`Method executeCommand requires a Command object`));
}
if (!command.gatewayId) {
reject(new Error('Method executeCommand requires a Command object with a gatewayId set'));
}
const query = `
mutation QueueAndExecute($systemId: ID!, $commandDefinitionId: ID!, $gatewayId: ID!, $fields: Json!) {
queueAndExecuteCommand(input: { systemId: $systemId, commandDefinitionId: $commandDefinitionId, gatewayId: $gatewayId, fields: $fields }) {
command {
id
state
}
}
}
`.trim();
makeGqlReq({ query, variables: command.getVariables() })
.then(({ data }) => {
const { id, state } = data.data.queueAndExecuteCommand.command;
command.setId(id);
command.state = state;
resolve(command);
})
.catch(err => reject(err));
});
/**
* Returns a Promise that will only resolve once the command has been updated to either "completed",
* "failed", or "cancelled" state in Major Tom. Relies on the Major Tom command state, and will
* reject if the command's state is not updated in Major Tom.
* @param {Command} command
* @param {number} [maxWaitTime]
* @returns {Promise<Command>}
*/
const executeAndCompleteCommand = (command, maxWaitTime = 90000) => new Promise((resolve, reject) => {
if (!command instanceof Command) {
reject(new Error(`Method executeCommand requires a Command object`));
}
if (!command.gatewayId) {
reject(new Error('Method executeCommand requires a Command object with a gatewayId set'));
}
const commandId = command.id;
const commandIsQueued = command.state === 'queued';
const queueAndExecuteQuery = `
mutation QueueAndExecute($systemId: ID!, $commandDefinitionId: ID!, $gatewayId: ID!, $fields: Json!) {
queueAndExecuteCommand(input: { systemId: $systemId, commandDefinitionId: $commandDefinitionId, gatewayId: $gatewayId, fields: $fields }) {
command {
id
}
}
}
`.trim();
const executeQuery = `
mutation Queue($commandId: ID!) {
executeCommand(input: { id: $commandId }) {
command {
id
state
}
}
}
`.trim();
const mutationName = commandIsQueued ? 'executeCommand' : 'queueAndExecuteCommand';
const query = commandIsQueued ? executeQuery : queueAndExecuteQuery;
let lastUpdateTime = Date.now();
makeGqlReq({ query, variables: commandIsQueued ? { commandId } : command.getVariables() })
.then(({ data }) => {
const { id, state } = data.data[mutationName].command;
if (!commandId) {
command.setId(id);
}
if (FINAL_STATES.includes(state)) {
return resolve(command.setFinalState(state));
}
const updateQuery = `
query CommandState {
command(id:${command.id}) {
state
}
}
`.trim();
const updateInterval = setInterval(() => {
if (Date.now() - lastUpdateTime > maxWaitTime) {
reject(
new Error(
`Command ${command.id} did not complete within the maximum wait time of ${(maxWaitTime / 1000).toFixed(1)} seconds`
)
);
} else {
makeGqlReq({ query: updateQuery })
.then(({ data }) => {
const { state } = data.data.command;
if (state !== command.state) {
command.state = state;
lastUpdateTime = Date.now();
}
if (FINAL_STATES.includes(state)) {
clearInterval(updateInterval);
return resolve(command.setFinalState(state));
}
})
.catch(err => {
clearInterval(updateInterval);
reject(err)
});
}
}, 200);
})
.catch(err => {
reject(err);
});
});
/**
* @param {object} param0
* @param {string} param0.name
* @param {string|number} param0.id
* @returns {Promise<Gateway>}
*/
const getGateway = ({ name: gatewayName, id }) => new Promise((resolve, reject) => {
if (!(gatewayName || id)) {
reject(new Error('Method getGateway requires either a `name` or `id` property'));
}
const query = `
query GetGateway {
gateway(${id ? `id:${id}` : `name:"${gatewayName}", missionId:${mission}`}) {
id
name
disabledAt
disablingUser {
name
email
}
connected
}
}
`.trim();
makeGqlReq({ query })
.then(({ data }) => {
const gateway = get(data, 'data.gateway');
if (!gateway) {
return reject(
new Error(`Could not find gateway with ${id ? `ID ${id}` : `name ${gatewayName}`}`)
);
}
resolve(new Gateway(gateway, { host, token, mission }));
})
.catch(err => reject(err));
});
/**
* @param {Command} command
* @returns {Promise<Command>}
*/
const queueCommand = command => new Promise((resolve, reject) => {
if (!command instanceof Command) {
reject(new Error(`Method executeCommand requires a Command object`));
}
if (!command.gatewayId) {
reject(new Error('Method executeCommand requires a Command object with a gatewayId set'));
}
const query = `
mutation Queue($systemId: ID!, $commandDefinitionId: ID!, $gatewayId: ID!, $fields: Json!) {
queueCommand(input: { systemId: $systemId, commandDefinitionId: $commandDefinitionId, gatewayId: $gatewayId, fields: $fields }) {
command {
id
state
}
}
}
`.trim();
makeGqlReq({ query, variables: command.getVariables() })
.then(({ data }) => {
const { id, state } = data.data.queueCommand.command;
command.setId(id);
if (state === 'queued') {
command.setIsQueued();
}
resolve(command);
})
.catch(err => reject(err));
});
/**
* Execute an Array of commands, only beginning the next after the first has resolved. Depends
* on the Major Tom command 'status' field. Use the optional second argument object to indicate
* the max time for a command to resolve. Options also may indicate that the sequence should
* continue even if commands do not resolve to a 'completed' state. If 'continuePastFailures' is
* true, then this will always resolve the updated Array of commands. If false (default), the
* Promise will reject with the Array of only the commands that were executed, including the
* command that did not succeed as the last element.
* @param {Command|Command[]} commandsArr
* @param {object} [options]
* @param {number} options.maxWaitTime
* @param {boolean} options.continuePastFailures
* @returns {Promise<Command[]>}
*/
const executeCommandsInSequence = (
commandsArr,
{ maxWaitTime = 90000, continuePastFailures = false } = {}
) => new Promise(async (resolve, reject) => {
const workingCommands = Array.isArray(commandsArr) ? [...commandsArr] : [commandsArr];
const resolvedCommands = [];
let current;
while (workingCommands.length) {
try {
current = workingCommands.shift();
const resolved = await executeAndCompleteCommand(current, maxWaitTime);
resolvedCommands.push(resolved);
if (resolved.finalState !== 'completed' && !continuePastFailures) {
return reject(resolvedCommands);
}
} catch (err) {
current.setFinalState('timed_out');
resolvedCommands.push(current);
if (!continuePastFailures) {
return reject(resolvedCommands);
}
}
}
resolve(resolvedCommands);
});
getMissionId();
const surface = {
getMissionId,
getSatellite,
getLatestMetricValue,
getCommandDefinitions,
createCommand,
executeCommand,
getGateway,
queueCommand,
executeAndCompleteCommand,
executeCommandsInSequence,
};
return surface;
};
module.exports = mts;