-
Notifications
You must be signed in to change notification settings - Fork 26
/
server.mjs
2060 lines (1821 loc) · 63 KB
/
server.mjs
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint no-console: 'off' */
/* eslint strict:0 */
/* eslint no-param-reassign: 'off' */
"use strict";
import "./config-server.mjs";
import { config } from "./config-global.mjs";
import assert from "assert";
import { spawn } from "child_process";
import express from "express";
import bodyParser from "body-parser";
import multer from "multer";
import { v1 as uuid } from "uuid";
import fs from "fs-extra";
import path from "path";
import pathIsInside from "path-is-inside";
import rl from "readline";
import compression from "compression";
import { server as WebSocketServer } from "websocket";
import dotenv from "dotenv";
import dirname from "es-dirname";
import { readFileSync, writeFile } from "fs";
import {
parseRegion,
convertRegionToRangeRegion,
stringifyRangeRegion,
stringifyRegion,
isValidURL,
readsExist,
} from "./common.mjs";
import { Readable } from "stream";
import { finished } from "stream/promises";
import sanitize from "sanitize-filename";
import { createHash } from "node:crypto";
import cron from "node-cron";
import { RWLock, combine } from "readers-writer-lock";
if (process.env.NODE_ENV !== "production") {
// Load any .env file config
dotenv.config();
}
const VG_PATH = config.vgPath;
const MOUNTED_DATA_PATH = config.dataPath;
const INTERNAL_DATA_PATH = config.internalDataPath;
// THis is where we will store uploaded files
const UPLOAD_DATA_PATH = "uploads/";
// This is where we will store per-request generated files
const SCRATCH_DATA_PATH = "tmp/";
// This is where data downloaded from URLs is cached.
// This directory will be recursively removed!
const DOWNLOAD_DATA_PATH = config.tempDirPath;
const SERVER_PORT = process.env.SERVER_PORT || config.serverPort || 3000;
const SERVER_BIND_ADDRESS = config.serverBindAddress || undefined;
// This holds a collection of all the absolute path root directories that the
// server is allowed to access on behalf of users.
const ALLOWED_DATA_DIRECTORIES = [
MOUNTED_DATA_PATH,
INTERNAL_DATA_PATH,
UPLOAD_DATA_PATH,
SCRATCH_DATA_PATH,
DOWNLOAD_DATA_PATH,
].map((p) => path.resolve(p));
const GRAPH_EXTENSIONS = [".xg", ".vg", ".pg", ".hg", ".gbz"];
const HAPLOTYPE_EXTENSIONS = [".gbwt", ".gbz"];
const fileTypes = {
GRAPH: "graph",
HAPLOTYPE: "haplotype",
READ: "read",
BED: "bed",
};
const lockMap = new Map();
const lockTypes = {
READ_LOCK: "read_lock",
WRITE_LOCK: "write_lock",
};
// In memory storage of fetched file eTags
// Used to check if the file has been updated and we need to fetch again
// Stores urls mapped to the eTag from the most recently recieved request
const ETagMap = new Map();
// Make sure that the scratch directory exists at startup, so multiple requests
// can't fight over its creation.
fs.mkdirSync(SCRATCH_DATA_PATH, { recursive: true });
if (typeof setImmediate === "undefined") {
// On newer Jest/React tests, setImmediate is removed from the environment,
// because browsers don't have it. See
// <https://github.com/facebook/jest/pull/11222>.
// We still get to use stuff like the Node filesystem APIs, but weirdly not
// this builtin. To make Express work, we need to have the builtin. So we
// put it back.
// TODO: Work out a way to run end-to-end tests in the project, with the
// frontend and backend both running, but without loading the backend into
// a jsdom JS environment.
// TODO: Resesign the frontend components so that network access and server
// responses can be easily faked.
const timers = require("timers");
window.setImmediate = timers.setImmediate;
window.clearImmediate = timers.clearImmediate;
}
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, UPLOAD_DATA_PATH);
},
filename: function (req, file, cb) {
let ext = file.originalname.substring(
file.originalname.lastIndexOf("."),
file.originalname.length
);
// TODO: This can collide and can also be guessed by other users.
cb(null, Date.now() + ext);
},
});
var limits = {
files: 1, // allow only 1 file per request
fileSize: 1024 * 1024 * 5, // 5 MB (max file size)
};
var upload = multer({ storage, limits });
// deletes expired files given a directory, recursively calls itself for nested directories
// expired files are files not accessed for a certain amount of time
// TODO: find a more reliable way to detect file accessed time than stat.atime?
// atime requires correct environment configurations
function deleteExpiredFiles(directoryPath) {
console.log("deleting expired files in ", directoryPath);
const currentTime = new Date().getTime();
if (!fs.existsSync(directoryPath)) {
return;
}
const files = fs.readdirSync(directoryPath);
files.forEach((file) => {
const filePath = path.join(directoryPath, file);
if (fs.statSync(filePath).isFile()) {
// check to see if file needs to be deleted
const lastAccessedTime = fs.statSync(filePath).atime;
if (currentTime - lastAccessedTime >= config.fileExpirationTime) {
if (file !== ".gitignore" && file !== "directory.lock") {
fs.unlinkSync(filePath);
console.log("Deleting file: ", filePath);
}
}
} else if (fs.statSync(filePath).isDirectory()) {
// call deleteExpiredFiles on the nested directory
deleteExpiredFiles(filePath);
// if the nested directory is empty after deleting expired files, remove it
if (fs.readdirSync(filePath).length === 0) {
fs.rmdirSync(filePath);
console.log("Deleting directory: ", filePath);
}
}
});
}
// takes in an async function, locks the direcotry for the duration of the function
async function lockDirectory(directoryPath, lockType, func) {
console.log("Acquiring", lockType, "for", directoryPath);
// look into lockMap to see if there is a lock assigned to the directory
let lock = lockMap.get(directoryPath);
// if there are no locks, create a new lock and store it in the lock directionary
if (!lock) {
lock = new RWLock();
lockMap.set(directoryPath, lock);
}
if (lockType == lockTypes.READ_LOCK) {
// lock is released when func returns
return lock.read(func);
} else if (lockType == lockTypes.WRITE_LOCK) {
return lock.write(func);
} else {
console.log("Not a valid lock type:", lockType);
return 1;
}
}
// expects an array of directory paths, attemping to acquire all directory locks
// all uses of this function requires the array of directoryPaths to be in the same order
// e.g locking [DOWNLOAD_DATA_PATH, UPLOAD_DATA_PATH] should always lock DOWNLOAD_DATA_PATH first to prevent deadlock
async function lockDirectories(directoryPaths, lockType, func) {
// input is unexpected
if (!directoryPaths || directoryPaths.length === 0) {
return;
}
// last lock to acquire, ready to proceed
if (directoryPaths.length === 1) {
return lockDirectory(directoryPaths[0], lockType, func);
}
// attempt to acquire a lock for the next directory, and call lockDirectories on the remaining directories
const currDirectory = directoryPaths.pop();
return lockDirectory(currDirectory, lockType, async function () {
return lockDirectories(directoryPaths, lockType, func);
});
}
// runs every hour
// deletes any files in the download directory past the set fileExpirationTime set in config
cron.schedule("0 * * * *", async () => {
console.log("cron scheduled check");
// attempt to acquire a write lock for each on the directory before attemping to delete files
for (const dir of [DOWNLOAD_DATA_PATH, UPLOAD_DATA_PATH]) {
try {
await lockDirectory(dir, lockTypes.WRITE_LOCK, async function () {
deleteExpiredFiles(dir);
});
} catch (e) {
console.error("Error checking for expired files in " + dir + ":", e);
}
}
});
const app = express();
// Configure global server settings
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(
bodyParser.urlencoded({
// to support URL-encoded bodies
extended: true,
})
);
app.use(compression());
// Serve the frontend
app.use(express.static("./build"));
// Make another Express object to keep all the API calls on a sensible path
// that can be proxied around if needed.
const api = express();
app.use("/api/v0", api);
// Open up CORS.
// TODO: can we avoid this?
// required for local usage with the Docker container (access docker container from outside)
api.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
// Store files uploaded from trackFilePicker via multer
api.post("/trackFileSubmission", upload.single("trackFile"), (req, res) => {
console.log("/trackFileSubmission");
console.log(req.file);
if (req.body.fileType === fileTypes["READ"]) {
indexGamSorted(req, res);
} else {
res.json({ path: path.relative(".", req.file.path) });
}
});
function indexGamSorted(req, res) {
const prefix = req.file.path.substring(0, req.file.path.lastIndexOf("."));
const sortedGamFile = fs.createWriteStream(prefix + ".sorted.gam", {
encoding: "binary",
});
const vgIndexChild = spawn(`${VG_PATH}vg`, [
"gamsort",
"-i",
prefix + ".sorted.gam.gai",
req.file.path,
]);
vgIndexChild.stderr.on("data", (data) => {
console.log(`err data: ${data}`);
});
vgIndexChild.stdout.on("data", function (data) {
sortedGamFile.write(data);
});
vgIndexChild.on("close", () => {
sortedGamFile.end();
res.json({ path: path.relative(".", prefix + ".sorted.gam") });
});
}
// Checks if a file has one of the extensions provided
function endsWithExtensions(file, extensions) {
for (const extension of extensions) {
if (file.endsWith(extension)) {
return true;
}
}
return false;
}
// INPUT: (track {files: }, string)
// OUTPUT: string
// returns the file name of the specified type in that track
// returns falsy value if file type is not found
function getFileFromType(track, type) {
if (track.trackType === type) {
return track.trackFile;
}
return "none";
}
// Given a collection of tracks (each of which may have a files array with
// items with a type and a name), generate the filenames for the first file of
// the given type for each track with such a file.
//
// This is a fancy ES6 generator.
function* eachFileOfType(tracks, type) {
for (const key in tracks) {
const file = getFileFromType(tracks[key], type);
if (file && file !== "none") {
yield file;
}
}
}
// Get the first files of the given type from all the given tracks.
function getFilesOfType(tracks, type) {
let results = [];
for (const file of eachFileOfType(tracks, type)) {
results.push(file);
}
return results;
}
// Get the first file from the first track with a file of the given type, or
// undefined if no such track exists.
function getFirstFileOfType(tracks, type) {
for (const file of eachFileOfType(tracks, type)) {
return file;
}
return undefined;
}
// Returns an array of the first gam file of every track with a gam file
function getGams(tracks) {
return getFilesOfType(tracks, fileTypes.READ);
}
// To bridge Express next(err) error handling and async function error
// handling, we have this adapter. It takes Express's next and an async
// function and calls next with any error raised when the async function is
// initially called *or* when its promise is awaited.
async function captureErrors(next, callback) {
try {
await callback();
} catch (e) {
next(e);
}
}
api.post("/getChunkedData", (req, res, next) => {
// We would like this to be an async function, but then Express error
// handling doesn't work, because it doesn't detect returned promise
// rejections until Express 5. We have to pass an error to next() or else
// throw synchronously.
captureErrors(next, async () => {
// put readlock on necessary directories while processing chunked data
return lockDirectories(
[DOWNLOAD_DATA_PATH, UPLOAD_DATA_PATH],
lockTypes.READ_LOCK,
async function () {
return getChunkedData(req, res, next);
}
);
});
});
/*
graph = {
node: [
{
sequence: "AGCT"
id: "1"
},
{
sequence: "AGCTAG"
id: "2"
}
],
edge: [],
path: []
}
removing sequence would result in
graph = {
node: [
{
id: "1"
},
{
id: "2"
}
],
edge: [],
path: []
}
*/
// read a graph object and remove "sequence" fields in place
function removeNodeSequencesInPlace(graph){
console.log("graph:", graph)
if (!graph.node){
return;
}
graph.node.forEach(function(node) {
node.sequence = "";
})
}
// Handle a chunked data (tube map view) request. Returns a promise. On error,
// either the promise rejects *or* next() is called with an error, or both.
// TODO: This is a terrible mixed design for error handling; we need to either
// rewrite the flow of talking to vg in terms of async/await or abandon
// async/await altogether in order to get out of it.
async function getChunkedData(req, res, next) {
console.time("request-duration");
console.log("http POST getChunkedData received");
console.log(`region = ${req.body.region}`);
console.log(`tracks = ${JSON.stringify(req.body.tracks)}`);
// This will have a conitg, start, end, or a contig, start, distance
let parsedRegion;
try {
parsedRegion = parseRegion(req.body.region);
} catch (e) {
// Whatever went wrong in the parsing, it makes the request bad.
throw new BadRequestError(
"Wrong query: " + e.message + " See ? button above."
);
}
// There's a chance this request was sent before the proper tracks were fetched
// This can happen when the bed file is a url and track names need to be downloaded
// Check if there are tracks specified by the bedFile
if (req.body.bedFile && req.body.bedFile !== "none") {
const chunk = await getChunkName(req.body.bedFile, parsedRegion);
const fetchedTracks = await getChunkTracks(req.body.bedFile, chunk);
// We're always replacing the given tracks if we were able to find tracks from the bed file
if (fetchedTracks) {
// Color Settings are retained from the initial request
// if newly fetched tracks have matching file names
// Store current colors and file names
const fileToColor = new Map();
for (const key of Object.keys(req.body.tracks)) {
const track = req.body.tracks[key];
fileToColor.set(track["trackFile"], track["trackColorSettings"]);
}
// Replace new track colors if there's a matching file name
for (const track of fetchedTracks) {
if (fileToColor.has(track["trackFile"])) {
track["trackColorSettings"] = fileToColor.get(track["trackFile"]);
}
}
// Convert fetchedTracks into an object format the server expects
let fetchedTracksObject = fetchedTracks.reduce(
(accumulator, obj, index) => {
accumulator[index] = obj;
return accumulator;
},
{}
);
console.log(
"Using new fetched tracks",
JSON.stringify(fetchedTracksObject)
);
req.body.tracks = fetchedTracksObject;
}
}
// Assign each request a UUID. v1 UUIDs can be very similar for similar
// timestamps on the same node, but are still guaranteed to be unique within
// a given nodejs process.
req.uuid = uuid();
// Make a temp directory for vg output files for this request
req.chunkDir = path.join(SCRATCH_DATA_PATH, `tmp-${req.uuid}`);
fs.mkdirSync(req.chunkDir);
// This request owns the directory, so clean it up when the request finishes.
req.rmChunk = true;
// We always have an graph file
const graphFile = getFirstFileOfType(req.body.tracks, fileTypes.GRAPH);
// We sometimes have a GBWT with haplotypes that override any in the graph file
const gbwtFile = getFirstFileOfType(req.body.tracks, fileTypes.HAPLOTYPE);
// We sometimes have a BED file with regions to look at
const bedFile = req.body.bedFile;
let gamFiles = getGams(req.body.tracks);
console.log("graphFile ", graphFile);
console.log("gbwtFile ", gbwtFile);
console.log("bedFile ", bedFile);
console.log("gamFiles ", gamFiles);
req.withGam = true;
if (!gamFiles || !gamFiles.length) {
req.withGam = false;
console.log("no gam index provided.");
}
req.withGbwt = true;
if (!gbwtFile || gbwtFile === "none") {
req.withGbwt = false;
console.log("no gbwt file provided.");
}
req.withBed = true;
if (!bedFile || bedFile === "none") {
req.withBed = false;
console.log("no BED file provided.");
}
// client is going to send simplify = true if they want to simplify view
req.simplify = false;
if (req.body.simplify) {
if (readsExist(req.body.tracks)) {
throw new BadRequestError("Simplify cannot be used on read tracks.");
}
req.simplify = true;
}
// client is going to send removeSequences = true if they don't want sequences of nodes to be displayed
req.removeSequences = false;
if (req.body.removeSequences) {
if (readsExist(req.body.tracks)) {
throw new BadRequestError("Can't remove node sequences if read tracks exist.");
}
req.removeSequences = true;
}
// check the bed file if this region has been pre-fetched
let chunkPath = "";
if (req.withBed) {
// We need to parse the BED file we have been referred to so we can look up
// the pre-parsed chunk.
chunkPath = await getChunkPath(bedFile, parsedRegion);
}
// We only want to have one downstream callback chain out of here, and we
// want to make sure it can only start after there's no possibility that we
// concurrently reject.
let sentResponse = false;
// We always need a range-version of the region, to fill in req.region, to
// generate the region part of the response with the range.
let rangeRegion = convertRegionToRangeRegion(parsedRegion);
if (chunkPath === "") {
// call 'vg chunk' to generate graph
let vgChunkParams = ["chunk"];
// double-check that the file has a valid graph extension and is allowed
if (!endsWithExtensions(graphFile, GRAPH_EXTENSIONS)) {
throw new BadRequestError(
"Graph file does not end in valid extension: " + graphFile
);
}
if (!isAllowedPath(graphFile)) {
throw new BadRequestError("Graph file path not allowed: " + graphFile);
}
// TODO: Use same variable for check and command line?
// Maybe check using file types in the future
// See if we need to ignore haplotypes in gbz graph file
if (req.withGbwt) {
//either push gbz with graph and haplotype or push seperate graph and gbwt file
if (
graphFile.endsWith(".gbz") &&
gbwtFile.endsWith(".gbz") &&
graphFile === gbwtFile
) {
// use gbz haplotype
vgChunkParams.push("-x", graphFile);
} else if (!graphFile.endsWith(".gbz") && gbwtFile.endsWith(".gbz")) {
throw new BadRequestError("Cannot use gbz as haplotype alone.");
} else {
// ignoring haplotype from graph file and using haplotype from gbwt file
vgChunkParams.push("--no-embedded-haplotypes", "-x", graphFile);
// double-check that the file is a .gbwt and allowed
if (!endsWithExtensions(gbwtFile, HAPLOTYPE_EXTENSIONS)) {
throw new BadRequestError(
"GBWT file doesn't end in .gbwt or .gbz: " + gbwtFile
);
}
if (!isAllowedPath(gbwtFile)) {
throw new BadRequestError("GBWT file path not allowed: " + gbwtFile);
}
// Use a GBWT haplotype database
vgChunkParams.push("--gbwt-name", gbwtFile);
}
} else {
// push graph file
if (graphFile.endsWith(".gbz")) {
vgChunkParams.push("-x", graphFile, "--no-embedded-haplotypes");
} else {
vgChunkParams.push("-x", graphFile);
}
}
// push all gam files
for (const gamFile of gamFiles) {
if (!gamFile.endsWith(".gam")) {
throw new BadRequestError("GAM file doesn't end in .gam: " + gamFile);
}
if (!isAllowedPath(gamFile)) {
throw new BadRequestError("GAM file path not allowed: " + gamFile);
}
// Use a GAM index
console.log("pushing gam file", gamFile);
vgChunkParams.push("-a", gamFile, "-g");
}
// to seach by node ID use "node" for the sequence name, e.g. 'node:1-10'
if (parsedRegion.contig === "node") {
if (parsedRegion.distance !== undefined) {
// Start and distance of node IDs, so send that idiomatically.
vgChunkParams.push(
"-r",
parsedRegion.start,
"-c",
parsedRegion.distance
);
} else {
// Start and end of node IDs
vgChunkParams.push(
"-r",
"".concat(parsedRegion.start, ":", parsedRegion.end),
"-c",
20
);
}
} else {
// Ask for the whole region by start - end range.
vgChunkParams.push("-c", "20", "-p", stringifyRangeRegion(rangeRegion));
}
vgChunkParams.push(
"-T",
"-b",
`${req.chunkDir}/chunk`,
"-E",
`${req.chunkDir}/regions.tsv`
);
console.log(`vg ${vgChunkParams.join(" ")}`);
console.time("vg chunk");
const vgChunkCall = spawn(`${VG_PATH}vg`, vgChunkParams);
// vg simplify for gam files
let vgSimplifyCall = null;
if (req.simplify) {
vgSimplifyCall = spawn(`${VG_PATH}vg`, ["simplify", "-"]);
console.log("Spawning vg simplify call");
}
const vgViewCall = spawn(`${VG_PATH}vg`, ["view", "-j", "-"]);
let graphAsString = "";
req.error = Buffer.alloc(0);
vgChunkCall.on("error", function (err) {
console.log(
"Error executing " +
VG_PATH +
"vg " +
vgChunkParams.join(" ") +
": " +
err
);
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg chunk failed"));
}
return;
});
vgChunkCall.stderr.on("data", (data) => {
console.log(`vg chunk err data: ${data}`);
req.error += data;
});
vgChunkCall.stdout.on("data", function (data) {
if (req.simplify) {
vgSimplifyCall.stdin.write(data);
} else {
vgViewCall.stdin.write(data);
}
});
vgChunkCall.on("close", (code) => {
console.log(`vg chunk exited with code ${code}`);
if (req.simplify) {
vgSimplifyCall.stdin.end();
} else {
vgViewCall.stdin.end();
}
if (code !== 0) {
console.log("Error from " + VG_PATH + "vg " + vgChunkParams.join(" "));
// Execution failed
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg chunk failed"));
}
}
});
// vg simplify
if (req.simplify) {
vgSimplifyCall.on("error", function (err) {
console.log(
"Error executing " + VG_PATH + "vg " + "simplify " + "- " + ": " + err
);
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg simplify failed"));
}
return;
});
vgSimplifyCall.stderr.on("data", (data) => {
console.log(`vg simplify err data: ${data}`);
req.error += data;
});
vgSimplifyCall.stdout.on("data", function (data) {
vgViewCall.stdin.write(data);
});
vgSimplifyCall.on("close", (code) => {
console.log(`vg simplify exited with code ${code}`);
vgViewCall.stdin.end();
if (code !== 0) {
console.log("Error from " + VG_PATH + "vg " + "simplify - ");
// Execution failed
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg simplify failed"));
}
}
});
}
// vg view
vgViewCall.on("error", function (err) {
console.log('Error executing "vg view": ' + err);
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg view failed"));
}
return;
});
vgViewCall.stderr.on("data", (data) => {
console.log(`vg view err data: ${data}`);
});
vgViewCall.stdout.on("data", function (data) {
graphAsString += data.toString();
});
vgViewCall.on("close", (code) => {
console.log(`vg view exited with code ${code}`);
console.timeEnd("vg chunk");
if (code !== 0) {
// Execution failed
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg view failed"));
}
return;
}
if (graphAsString === "") {
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg view produced empty graph"));
}
return;
}
req.graph = JSON.parse(graphAsString);
if (req.removeSequences){
removeNodeSequencesInPlace(req.graph)
}
req.region = [rangeRegion.start, rangeRegion.end];
// vg chunk always puts the path we reference on first automatically
if (!sentResponse) {
sentResponse = true;
processAnnotationFile(req, res, next);
}
});
} else {
// chunk has already been pre-fetched and is saved in chunkPath
req.chunkDir = chunkPath;
// We're using a shared directory for this request, so leave it in place
// when the request finishes.
req.rmChunk = false;
let filename = `${req.chunkDir}/chunk.vg`;
// vg simplify for bed files
let vgSimplifyCall = null;
let vgViewArguments = ["view", "-j"];
if (req.simplify) {
vgSimplifyCall = spawn(`${VG_PATH}vg`, ["simplify", filename]);
vgViewArguments.push("-");
console.log("Spawning vg simplify call");
} else {
vgViewArguments.push(filename);
}
let vgViewCall = spawn(`${VG_PATH}vg`, vgViewArguments);
let graphAsString = "";
req.error = Buffer.alloc(0);
// vg simplify
if (req.simplify) {
vgSimplifyCall.on("error", function (err) {
console.log(
"Error executing " +
VG_PATH +
"vg " +
"simplify " +
filename +
": " +
err
);
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg simplify failed"));
}
return;
});
vgSimplifyCall.stderr.on("data", (data) => {
console.log(`vg simplify err data: ${data}`);
req.error += data;
});
vgSimplifyCall.stdout.on("data", function (data) {
vgViewCall.stdin.write(data);
});
vgSimplifyCall.on("close", (code) => {
console.log(`vg simplify exited with code ${code}`);
vgViewCall.stdin.end();
if (code !== 0) {
console.log("Error from " + VG_PATH + "vg " + "simplify " + filename);
// Execution failed
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg simplify failed"));
}
}
});
}
vgViewCall.on("error", function (err) {
console.log('Error executing "vg view": ' + err);
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg view failed"));
}
return;
});
vgViewCall.stderr.on("data", (data) => {
console.log(`vg view err data: ${data}`);
});
vgViewCall.stdout.on("data", function (data) {
graphAsString += data.toString();
});
vgViewCall.on("close", (code) => {
console.log(`vg view exited with code ${code}`);
if (code !== 0) {
// Execution failed
if (!sentResponse) {
sentResponse = true;
return next(new VgExecutionError("vg view failed"));
}
return;
}
if (graphAsString === "") {
if (!sentResponse) {
sentResponse = true;
return next(
new VgExecutionError("vg view produced empty graph failed")
);
}
return;
}
req.graph = JSON.parse(graphAsString);
if (req.removeSequences){
removeNodeSequencesInPlace(req.graph)
}
req.region = [rangeRegion.start, rangeRegion.end];
// We might not have the path we are referencing on appearing first.
if (parsedRegion.contig !== "node") {
// Make sure that path 0 is the path we actually asked about
let refPaths = [];
let otherPaths = [];
for (let path of req.graph.path) {
if (path.name === parsedRegion.contig) {
// This is the path we asked about, so it goes first
refPaths.push(path);
} else {
// Then we put each other path
otherPaths.push(path);
}
}
req.graph.path = refPaths.concat(otherPaths);
}
if (!sentResponse) {
sentResponse = true;
processAnnotationFile(req, res, next);
}
});
}
}
// We can throw this error to trigger our error handling code instead of
// Express's default. It covers input validation failures, and vaguely-expected
// server-side errors we want to report in a controlled way (because they could
// be caused by bad user input to vg).
class TubeMapError extends Error {
constructor(message) {
super(message);
}
}
// We can throw this error to make Express respond with a bad request error
// message. We should throw it whenever we detect that user input is
// unacceptable.
class BadRequestError extends TubeMapError {
constructor(message) {
super(message);
this.status = 400;
}
}
// We can throw this error to make Express respond with an internal server
// error message
class InternalServerError extends TubeMapError {
constructor(message) {
super(message);
this.status = 500;
}
}
// We can throw this error to make Express respond with an internal server
// error message about vg.
class VgExecutionError extends InternalServerError {
constructor(message) {
super(message);
}
}
// We can use this middleware to ensure that errors we synchronously throw or
// next(err) will be sent along to the user. It does *not* happen on API
// endpoint promise rejections until Express 5.
function returnErrorMiddleware(err, req, res, next) {
// Clean up the temp directory for the request, if any
cleanUpChunkIfOwned(req, res);
// Because we take err, Express makes sure err is always set.
if (res.headersSent) {
// We can't send a nice message. Try the next middleware, if any.
return next(err);
}
// We have an error we want to send back to the user.
const result = { error: "" };
if (!(err instanceof TubeMapError)) {
// Unexpected error: we do not have a custom message for this error
result.error += "Something about this request has caused a server error: ";
}
if (err.message) {
// We have an error message to pass along.
result.error += err.message;
}