-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathappClass.tsx
258 lines (228 loc) · 8.62 KB
/
appClass.tsx
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
import { simpleGit } from "simple-git"
import express, { NextFunction } from "express"
// eslint-disable-next-line @typescript-eslint/no-require-imports
require("express-async-errors") // todo: why the require?
import cookieParser from "cookie-parser"
import http from "http"
import Bugsnag from "@bugsnag/js"
import BugsnagPluginExpress from "@bugsnag/plugin-express"
import {
BAKED_BASE_URL,
BUGSNAG_NODE_API_KEY,
ENV_IS_STAGING,
} from "../settings/serverSettings.js"
import * as db from "../db/db.js"
import { IndexPage } from "./IndexPage.js"
import {
authCloudflareSSOMiddleware,
tailscaleAuthMiddleware,
authMiddleware,
} from "./authentication.js"
import { apiRouter } from "./apiRouter.js"
import { testPageRouter } from "./testPageRouter.js"
import { adminRouter } from "./adminRouter.js"
import { renderToHtmlPage } from "../serverUtils/serverUtil.js"
import { publicApiRouter } from "./publicApiRouter.js"
import { mockSiteRouter } from "./mockSiteRouter.js"
import { GdocsContentSource } from "@ourworldindata/utils"
import OwidGdocPage from "../site/gdocs/OwidGdocPage.js"
import { getAndLoadGdocById } from "../db/model/Gdoc/GdocFactory.js"
interface OwidAdminAppOptions {
gitCmsDir: string
isDev: boolean
isTest?: boolean
quiet?: boolean
}
export class OwidAdminApp {
constructor(options: OwidAdminAppOptions) {
this.options = options
}
app = express()
private options: OwidAdminAppOptions
private async getGitCmsBranchName() {
const git = simpleGit({
baseDir: this.options.gitCmsDir,
binary: "git",
maxConcurrentProcesses: 1,
})
const branches = await git.branchLocal()
const gitCmsBranchName = await branches.current
return gitCmsBranchName
}
private gitCmsBranchName = ""
server?: http.Server
async stopListening() {
if (!this.server) return
this.server.close()
}
async startListening(adminServerPort: number, adminServerHost: string) {
this.gitCmsBranchName = await this.getGitCmsBranchName()
let bugsnagMiddleware
const { app } = this
if (BUGSNAG_NODE_API_KEY) {
Bugsnag.start({
apiKey: BUGSNAG_NODE_API_KEY,
context: "admin-server",
plugins: [BugsnagPluginExpress],
autoTrackSessions: false,
})
bugsnagMiddleware = Bugsnag.getPlugin("express")
// From the docs: "this must be the first piece of middleware in the
// stack. It can only capture errors in downstream middleware"
if (bugsnagMiddleware) app.use(bugsnagMiddleware.requestHandler)
}
// since the server is running behind a reverse proxy (nginx), we need to "trust"
// the X-Forwarded-For header in order to get the real request IP
// https://expressjs.com/en/guide/behind-proxies.html
app.set("trust proxy", true)
// Parse cookies https://github.com/expressjs/cookie-parser
app.use(cookieParser())
app.use(express.urlencoded({ extended: true, limit: "50mb" }))
if (ENV_IS_STAGING) {
// Try to log in with tailscale if we're in staging
app.use(tailscaleAuthMiddleware)
} else {
// In production use Cloudflare
app.use("/admin/login", authCloudflareSSOMiddleware)
}
// Require authentication (only for /admin requests)
app.use(authMiddleware)
app.use("/assets", express.static("dist/assets"))
app.use("/fonts", express.static("public/fonts"))
app.use("/assets-admin", express.static("dist/assets-admin"))
app.use("/api", publicApiRouter.router)
app.use("/admin/api", apiRouter.router)
app.use("/admin/test", testPageRouter)
app.use("/admin/storybook", express.static(".storybook/build"))
app.use("/admin", adminRouter)
// Default route: single page admin app
app.get("/admin/*", async (req, res) => {
res.send(
renderToHtmlPage(
<IndexPage
username={res.locals.user.fullName}
isSuperuser={res.locals.user.isSuperuser}
gitCmsBranchName={this.gitCmsBranchName}
/>
)
)
})
// Public preview of a Gdoc document
app.get("/gdocs/:id/preview", async (req, res) => {
try {
await db.knexReadonlyTransaction(async (knex) => {
const gdoc = await getAndLoadGdocById(
knex,
req.params.id,
GdocsContentSource.Gdocs
)
res.set("X-Robots-Tag", "noindex")
res.send(
renderToHtmlPage(
<OwidGdocPage
baseUrl={BAKED_BASE_URL}
gdoc={gdoc}
debug
isPreviewing
/>
)
)
})
} catch (error) {
console.error("Error fetching gdoc preview", error)
res.status(500).json({
error: { message: String(error), status: 500 },
})
}
})
// From the docs: "this handles any errors that Express catches. This
// needs to go before other error handlers. BugSnag will call the `next`
// error handler if it exists.
if (bugsnagMiddleware) app.use(bugsnagMiddleware.errorHandler)
if (this.options.isDev) {
if (!this.options.isTest) {
// https://vitejs.dev/guide/ssr
const { createServer } = await import("vite")
const vite = await createServer({
configFile: "vite.config-site.mts",
css: { devSourcemap: true },
server: { middlewareMode: true },
appType: "custom",
base: "/",
})
app.use(vite.middlewares)
}
// todo (DB): we probably always want to have this
app.use("/", mockSiteRouter)
}
// Give full error messages, including in production
app.use(this.errorHandler)
await this.connectToDatabases()
this.server = await this.listenPromise(
app,
adminServerPort,
adminServerHost
)
this.server.timeout = 5 * 60 * 1000 // Increase server timeout for long-running uploads
if (!this.options.quiet)
console.log(
`owid-admin server started on http://${adminServerHost}:${adminServerPort}`
)
}
// Server.listen does not seem to have an async/await form yet.
// https://github.com/expressjs/express/pull/3675
// https://github.com/nodejs/node/issues/21482
private listenPromise(
app: express.Express,
adminServerPort: number,
adminServerHost: string
): Promise<http.Server> {
return new Promise((resolve) => {
const server = app.listen(adminServerPort, adminServerHost, () => {
resolve(server)
})
})
}
errorHandler = async (
err: any,
req: express.Request,
res: express.Response,
// keep `next` because Express only passes errors to handlers with 4 parameters.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
next: NextFunction
) => {
if (!res.headersSent) {
res.status(err.status || 500)
res.send({
error: {
message: err.stack || err,
status: err.status || 500,
},
})
} else {
res.write(
JSON.stringify({
error: {
message: err.stack || err,
status: err.status || 500,
},
})
)
res.end()
}
}
connectToDatabases = async () => {
try {
const _ = db.knexInstance()
} catch (error) {
// grapher database is in fact required, but we will not fail now in case it
// comes online later
if (!this.options.quiet) {
console.error(error)
console.warn(
"Could not connect to grapher database. Continuing without DB..."
)
}
}
}
}