forked from nextstrain/nextstrain.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
171 lines (139 loc) · 5.88 KB
/
server.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
/* eslint no-console: off */
const path = require("path");
const sslRedirect = require('heroku-ssl-redirect');
const nakedRedirect = require('express-naked-redirect');
const express = require("express");
const expressStaticGzip = require("express-static-gzip");
const favicon = require('serve-favicon');
const compression = require('compression');
const argparse = require('argparse');
const utils = require("./src/utils");
const { potentialAuspiceRoutes, isRequestBackedByAuspiceDataset } = require('./auspicePaths');
const cors = require('cors');
const {addAsync} = require("@awaitjs/express");
const {NotFound} = require('http-errors');
const production = process.env.NODE_ENV === "production";
const version = utils.getGitHash();
const nextstrainAbout = `
Nextstrain is an open-source project to harness the scientific and public
health potential of pathogen genome data.
This is the server behind nextstrain.org.
See https://github.com/nextstrain/nextstrain.org for more.
`;
const parser = new argparse.ArgumentParser({
version,
addHelp: true,
description: `Nextstrain.org server version ${version}`,
epilog: nextstrainAbout
});
parser.addArgument('--verbose', {action: "storeTrue", help: "verbose server logging"});
const args = parser.parseArgs();
global.verbose = args.verbose;
// Import these after parsing CLI arguments and setting global.verbose so code
// in them can use utils.verbose() at load time.
const auspiceServerHandlers = require("./src/index.js");
const authn = require("./authn");
const redirects = require("./redirects");
/* Path helpers for static assets, to make routes more readable.
*/
const relativePath = (...subpath) =>
path.join(__dirname, ...subpath);
const gatsbyAssetPath = (...subpath) =>
relativePath("static-site", "public", ...subpath);
const auspiceAssetPath = (...subpath) =>
relativePath("auspice-client", ...subpath);
/* BASIC APP SETUP */
// NOTE: order of app.get is first come first serve (https://stackoverflow.com/questions/32603818/order-of-router-precedence-in-express-js)
const app = addAsync(express());
// In production, trust Heroku as a reverse proxy and Express will use request
// metadata from the proxy.
if (production) app.enable("trust proxy");
app.set('port', process.env.PORT || 5000);
app.use(sslRedirect()); // redirect HTTP to HTTPS
app.use(compression()); // send files (e.g. res.json()) using compression (if possible)
app.use(nakedRedirect({reverse: true})); // redirect www.nextstrain.org to nextstrain.org
app.use(favicon(relativePath("favicon.ico")));
app.use('/favicon.png', express.static(relativePath("favicon.png")));
/* Authentication (authn)
*/
authn.setup(app);
/* Redirects.
*/
redirects.setup(app);
/* Static assets.
* Any paths matching resources here will be handled and not fall through to our handlers below.
* E.g. URL `/influenza` gets sent `static-site/public/influenza/index.html`
*/
app.use(express.static(gatsbyAssetPath()));
app.route("/dist/*") // Auspice hardcodes /dist/… in its Webpack config.
.all(expressStaticGzip(auspiceAssetPath(), {maxAge: '30d'}));
/* Charon API used by Auspice.
*/
app.routeAsync("/charon/getAvailable")
.all(cors({origin: 'http://localhost:8000'})) // allow cross-origin from the gatsby dev server
.getAsync(auspiceServerHandlers.getAvailable);
app.routeAsync("/charon/getDataset")
.getAsync(auspiceServerHandlers.getDataset);
app.routeAsync("/charon/getNarrative")
.getAsync(auspiceServerHandlers.getNarrative);
app.routeAsync("/charon/getSourceInfo")
.getAsync(auspiceServerHandlers.getSourceInfo);
app.routeAsync("/charon/*")
.all((req) => {
utils.warn(`(${req.method}) ${req.url} has not been handled / has no handler`);
throw new NotFound();
});
/* Specific routes to be handled by Gatsby client-side routing
*/
app.route([
"/users/:user",
"/groups",
"/groups/:groupName"
]).get((req, res) => res.sendFile(gatsbyAssetPath("index.html")));
/* Routes which are plausibly for auspice, as they have specific path signatures.
* We verify if these are are backed by datasets and hand to auspice if so.
*/
app.route(potentialAuspiceRoutes).get(
isRequestBackedByAuspiceDataset,
sendAuspiceHandler,
sendGatsbyHandler
);
/**
* Finally, we catch all remaining routes and send to Gatsby
*/
app.get("*", sendGatsbyHandler);
const server = app.listen(app.get('port'), () => {
console.log(" -------------------------------------------------------------------------");
console.log(nextstrainAbout);
console.log(` Server listening on port ${server.address().port}`);
console.log(` Accessible at https://nextstrain.org or http://localhost:${server.address().port}`);
console.log(` Server is running in ${production ? 'production' : 'development'} mode`);
console.log("\n -------------------------------------------------------------------------\n\n");
}).on('error', (err) => {
if (err.code === 'EADDRINUSE') {
utils.error(`Port ${app.get('port')} is currently in use by another program.
You must either close that program or specify a different port by setting the shell variable
"$PORT". Note that on MacOS / Linux, "lsof -n -i :${app.get('port')} | grep LISTEN" should
identify the process currently using the port.`);
}
utils.error(`Uncaught error in app.listen(). Code: ${err.code}`);
});
function sendGatsbyHandler(req, res) {
utils.verbose(`Sending Gatsby entrypoint for ${req.originalUrl}`);
return res.sendFile(
gatsbyAssetPath(""),
{},
(err) => {
// callback runs when the transfer is complete or when an error occurs
if (err) res.status(404).sendFile(gatsbyAssetPath("404.html"));
}
);
}
function sendAuspiceHandler(req, res, next) {
if (!req.sendToAuspice) return next(); // see previous middleware
utils.verbose(`Sending Auspice entrypoint for ${req.originalUrl}`);
return res.sendFile(
auspiceAssetPath("dist", "index.html"),
{headers: {"Cache-Control": "no-cache, no-store, must-revalidate"}}
);
}