forked from dtinth/automatron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
123 lines (109 loc) · 2.75 KB
/
app.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
'use strict'
const express = require('express')
const app = express()
const dotenv = require('dotenv')
const bucketName = `${process.env.GOOGLE_CLOUD_PROJECT}.appspot.com`
const { Storage } = require('@google-cloud/storage')
const gcs = new Storage()
const startupTime = Date.now()
const { VError } = require('verror')
let _cache
// TODO: Move to actual storage
let _storedData = {}
function cached(key, fn) {
return function() {
if (_cache[key]) return _cache[key].value
_cache[key] = { value: fn.apply(this, arguments) }
return _cache[key].value
}
}
const getSecrets = cached('secret', async () => {
try {
// via http://gunargessner.com/gcloud-env-vars/
const [contents] = await gcs
.bucket(bucketName)
.file('secrets.env')
.download()
const secrets = dotenv.parse(contents)
console.log('Secrets loaded with keys', Object.keys(secrets))
return secrets
} catch (error) {
throw new VError(error, 'getSecrets() failed')
}
})
const getAutomatron = cached('automatron', async () => {
const [contents] = await gcs
.bucket(bucketName)
.file('automatron.js')
.download()
const m = { exports: {} }
const code = contents.toString()
new Function('require', 'exports', 'module', code)(require, m.exports, m)
console.log('Code loaded:', contents, 'bytes')
return m.exports
})
function reload() {
_cache = {}
getSecrets()
getAutomatron()
}
reload()
async function webtaskWrapperMiddleware(req, res, next) {
try {
req.webtaskContext = {
secrets: await getSecrets(),
storage: {
get: cb => cb(null, _storedData),
set: (value, cb) => {
_storedData = JSON.parse(JSON.stringify(value))
cb()
}
},
reload
}
} catch (error) {
return next(error)
}
next()
}
app.get('/_ah/warmup', async (req, res, next) => {
try {
console.log('Warmup starting...')
await Promise.all([getSecrets(), getAutomatron()])
console.log('Warmup finished!')
} catch (error) {
return next(error)
}
res.send({ ok: true })
})
app.use('/automatron', webtaskWrapperMiddleware, async function(
req,
res,
next
) {
try {
const automatron = await getAutomatron()
automatron(req, res)
} catch (error) {
next(error)
}
})
app.get('/', (req, res) => {
res.status(200).send('Hello, world!')
})
app.get('/info', async (req, res) => {
res.status(200).json({
uptime: Date.now() - startupTime,
bucketName,
secretKeys: await getSecrets()
.then(s => Object.keys(s))
.catch(e => `Error: ${e}`)
})
})
if (module === require.main) {
const server = app.listen(process.env.PORT || 8080, () => {
const port = server.address().port
console.log(`App listening on port ${port}`)
})
}
module.exports = app