-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadcIO.js
More file actions
437 lines (365 loc) · 13.1 KB
/
adcIO.js
File metadata and controls
437 lines (365 loc) · 13.1 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
'use strict';
//
// adcIO.js
// Functions for the AIRR Data Commons
//
// VDJServer Analysis Portal
// VDJ API Service
// https://vdjserver.org
//
// Copyright (C) 2021 The University of Texas Southwestern Medical Center
//
// Author: Scott Christley <scott.christley@utsouthwestern.edu>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
//
var adcIO = {};
module.exports = adcIO;
// Server environment config
//var config = require('../config/config');
// Tapis
var tapisSettings = require('vdj-tapis-js/tapisSettings');
var tapisIO = tapisSettings.get_default_tapis();
var config = tapisSettings.config;
// Processing
var webhookIO = require('./webhookIO');
// Node Libraries
var _ = require('underscore');
var csv = require('csv-parser');
var fs = require('fs');
const zlib = require('zlib');
const axios = require('axios');
// check if valid JSON
var isJSON = function(data) {
var isValid = false;
try {
var parsedData = JSON.parse(data);
if (parsedData && typeof parsedData === 'object' && parsedData !== null) {
isValid = true;
}
}
catch (e) { isValid = false; }
return isValid;
}
//
// Generic send request
//
adcIO.sendRequest = function(requestSettings, postData) {
return new Promise(function(resolve, reject) {
var request = require('https').request(requestSettings, function(response) {
var output = '';
response.on('data', function(chunk) {
output += chunk;
});
response.on('end', function() {
var responseObject;
//console.log(output);
if (output && isJSON(output)) {
responseObject = JSON.parse(output);
}
else {
reject(new Error('ADC repository response is not json. Raw output: ' + output));
}
//console.log(responseObject);
if (responseObject) {
resolve(responseObject);
}
else {
reject(new Error('ADC repository response is empty: ' + JSON.stringify(responseObject)));
}
});
});
request.on('error', function(error) {
reject(new Error('ADC repository connection error, ' + error));
});
if (postData) {
// Request body parameters
request.write(postData);
}
request.end();
});
};
// Get the set of default ADC repositories
// TODO: is this the same as system set?
adcIO.defaultADCRepositories = function() {
}
// Get status of an ADC ASYNC query
adcIO.asyncQueryStatus = async function(repository, query_id) {
var msg = null;
// we assume the passed in repository is an object entry
if (! repository) return Promise.reject('missing repository parameter');
if (! repository['async_host']) return Promise.reject('repository entry missing async_host');
if (! repository['async_base_url']) return Promise.reject('repository entry missing async_base_url');
if (! query_id) return Promise.reject('missing query_id parameter');
var requestSettings = {
host: repository['async_host'],
method: 'GET',
path: repository['async_base_url'] + '/status/' + query_id,
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json'
}
};
console.log(requestSettings);
var data = await adcIO.sendRequest(requestSettings, null)
.catch(function(error) {
msg = 'VDJ-API ERROR: adcIO.asyncQueryStatus, adcIO.sendRequest error ' + error;
});
if (msg) {
console.error(msg);
webhookIO.postToSlack(msg);
return Promise.reject(new Error(msg));
}
return Promise.resolve(data);
}
// Query rearrangements from an ADC repository with ASYNC API
adcIO.asyncGetRearrangements = async function(repository, repertoire_id, notification) {
var msg = null;
// we assume the passed in repository is an object entry
if (! repository) return Promise.reject('missing repository entry');
if (! repertoire_id) return Promise.reject('missing repertoire_id entry');
if (! repository['async_host']) return Promise.reject('repository entry missing async_host');
if (! repository['async_base_url']) return Promise.reject('repository entry missing async_base_url');
// query rearrangements for a repertoire
var postData = {
"filters": {
"op": "=",
"content": {
"field": "repertoire_id",
"value": repertoire_id
}
},
"format":"tsv"
};
if (notification) postData["notification"] = notification;
postData = JSON.stringify(postData);
var requestSettings = {
host: repository['async_host'],
method: 'POST',
path: repository['async_base_url'] + '/rearrangement',
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
console.log(requestSettings);
var data = await adcIO.sendRequest(requestSettings, postData)
.catch(function(error) {
msg = 'VDJ-API ERROR: adcIO.asyncGetRearrangements, adcIO.sendRequest error ' + error;
});
if (msg) {
console.error(msg);
webhookIO.postToSlack(msg);
return Promise.reject(new Error(msg));
}
return Promise.resolve(data);
}
// Query rearrangements from an ADC repository with standard synchronous ADC API and write response to file
// This assumes iReceptor turnkey behavior which dumps the whole database
// This assumes direct access to Corral for writing the output file
adcIO.downloadRearrangements = async function(repository, repertoire_id, filepath) {
var msg = null;
var context = 'adcIO.downloadRearrangements';
// we assume the passed in repository is an object entry
if (! repository) return Promise.reject('missing repository entry');
if (! repertoire_id) return Promise.reject('missing repertoire_id entry');
// download progress
var progress_size = 10000000;
var progress_count = 0;
var axiosProgressFunction = function(axiosProgressEvent) {
var progress_limit = progress_size * progress_count;
if (axiosProgressEvent.loaded > progress_limit) {
progress_count += 1;
config.log.info(context, 'Downloaded ' + axiosProgressEvent.loaded + ' bytes of data so far.');
}
};
// query rearrangements for a repertoire
var postData = {
"filters": {
"op": "=",
"content": {
"field": "repertoire_id",
"value": repertoire_id
}
},
"format":"tsv"
};
postData = JSON.stringify(postData);
var url = 'https://' + repository['server_host'] + repository['base_url'] + '/rearrangement';
var requestSettings = {
url: url,
method: 'POST',
data: postData,
headers: {
'Content-Type': 'application/json',
},
// axios settings for streaming
responseType: 'stream',
maxRedirects: 0, // avoid buffering the entire stream
onDownloadProgress: axiosProgressFunction
};
console.log(requestSettings);
// we do our own request so we can stream
config.log.info(context, 'Requesting download to file: ' + filepath + ' for repository: ' + repository['repository_id'] + ' for repertoire_id: ' + repertoire_id);
const writer = fs.createWriteStream(filepath);
return axios(requestSettings)
.then(function (response) {
return new Promise((resolve, reject) => {
response.data.pipe(writer);
let error = null;
writer.on('error', err => {
error = err;
writer.close();
reject(err);
});
writer.on('close', () => {
config.log.info(context, 'Download complete to file: ' + filepath + ' for repository: ' + repository['repository_id'] + ' for repertoire_id: ' + repertoire_id);
if (!error) {
resolve(true);
}
});
});
});
}
// Query the repertoires from an ADC repository with optional study_id
adcIO.getRepertoires = async function(repository, study_id) {
var msg = null;
// we assume the passed in repository is an object entry
if (! repository) return Promise.resolve(null);
if (! repository['server_host']) return Promise.reject('repository entry missing server_host');
if (! repository['base_url']) return Promise.reject('repository entry missing base_url');
// query on study_id
var postData = {
"filters": {
"op": "=",
"content": {
"field": "study.study_id",
"value": study_id
}
}
};
postData = JSON.stringify(postData);
var requestSettings = {
host: repository['server_host'],
method: 'POST',
path: repository['base_url'] + '/repertoire',
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
console.log(requestSettings);
var data = await adcIO.sendRequest(requestSettings, postData)
.catch(function(error) {
msg = 'VDJ-API ERROR: adcIO.getRepertoires, adcIO.sendRequest error ' + error;
});
if (msg) {
console.error(msg);
webhookIO.postToSlack(msg);
return Promise.reject(new Error(msg));
}
return Promise.resolve(data);
}
// Query the studies from an ADC repository
adcIO.getStudies = async function(repository) {
var msg = null;
// we assume the passed in repository is an object entry
if (! repository) return Promise.resolve(null);
if (! repository['server_host']) return Promise.reject('repository entry missing server_host');
if (! repository['base_url']) return Promise.reject('repository entry missing base_url');
// do a facets query
var postData = {
facets: 'study.study_id',
};
postData = JSON.stringify(postData);
var requestSettings = {
host: repository['server_host'],
method: 'POST',
path: repository['base_url'] + '/repertoire',
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
console.log(requestSettings);
var data = await adcIO.sendRequest(requestSettings, postData)
.catch(function(error) {
msg = 'VDJ-API ERROR: adcIO.getStudies, adcIO.sendRequest error ' + error;
});
if (msg) {
console.error(msg);
webhookIO.postToSlack(msg);
return Promise.reject(new Error(msg));
}
return Promise.resolve(data['Facet']);
}
//
// Functions for the ADC download cache
//
adcIO.getCachedStudy = function(study_id) {
}
adcIO.getCachedRepertoiresForStudy = function(study_id) {
}
// 1. iterate
adcIO.createCacheEntries = function() {
}
// send a notification
adcIO.sendNotification = function(notification, data) {
// pull out host and path from URL
// TODO: handle http/https
var fields = notification['url'].split('://');
fields = fields[1].split('/');
var host = fields[0];
fields = notification['url'].split(host);
var path = fields[1];
var postData = null;
var method = 'GET';
if (data) {
// put data in request params
if (notification["method"] == 'GET') {
method = 'GET';
// check if URL already has some request params
var mark;
if (path.indexOf('?') >= 0) mark = '&';
else mark = '?';
var keys = Object.keys(data);
for (var p = 0; p < keys.length; ++p) {
path += mark;
path += keys[p] + '=' + encodeURIComponent(data[keys[p]]);
mark = '&';
}
} else {
method = 'POST';
postData = JSON.stringify(data);
}
}
var requestSettings = {
host: host,
method: method,
path: path,
rejectUnauthorized: false,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
};
if (postData) {
requestSettings['headers']['Content-Length'] = Buffer.byteLength(postData);
}
console.log(requestSettings);
return adcIO.sendRequest(requestSettings, postData);
};