-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-cached.js
More file actions
218 lines (176 loc) · 5.21 KB
/
server-cached.js
File metadata and controls
218 lines (176 loc) · 5.21 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
/* eslint-disable @typescript-eslint/no-var-requires */
require('dotenv').config()
const express = require('express')
const zlib = require('node:zlib')
const { createClient } = require('redis')
const next = require('next')
require('elastic-apm-node').start({
serverUrl: process.env.NEXT_PUBLIC_APM_SERVER_URL,
serviceName: `FE-node-block-explorer_${process.env.NEXT_PUBLIC_CHAIN_ID}`,
secretToken: 'some_secret_token',
})
const SSR_URLS_CACHE_TIME = {
'/': 60,
'/block/*': 60,
'/tx/*': 60,
'/blocks/*': 60,
'/txs/*': 60,
'/address/*': 60,
'/holdings/*': 60,
'/token/*': 60,
'/charts': 60,
'/charts/*': 60,
}
const JSON_URLS_CACHE_TIME = {
'/index.json': 60,
'/block/*': 60,
'/tx/*': 60,
'/blocks/*': 60,
'/txs/*': 60,
'/address/*': 60,
'/holdings/*': 60,
'/token/*': 60,
'/charts': 60,
'/charts/*': 60,
}
const redisURL = process.env.REDIS_URL
? {
url: process.env.REDIS_URL,
}
: undefined
const chainId = process.env.NEXT_PUBLIC_CHAIN_ID || ''
console.log('chainID:', chainId)
console.log('[ Redis Client] Using Redis URL:', redisURL)
const redis = createClient(redisURL)
let isRedisConnected = false
redis.on('error', (err) => {
if (isRedisConnected) {
console.log('[ Redis Client Error ]', err)
}
if (err?.code === 'ECONNREFUSED') {
isRedisConnected = false
}
})
redis.on('connect', () => {
console.log('[ Redis Client ] Connected')
isRedisConnected = true
})
redis.on('disconnect', () => {
console.log('[ Redis Client ] Disconnected')
isRedisConnected = false
})
const app = next({ dev: false })
const handle = app.getRequestHandler()
const getJsonKey = (req) =>
`props:${req.url.split('/').slice(4).join('/')}:${chainId}`
const getSsrKey = (req) => `page:${req.url}:${chainId}`
const getRedisReady = () => isRedisConnected && redis.isReady
async function jsonCache(req, res, time = 15 * 60 * 1000) {
const isRedisReady = getRedisReady()
const key = getJsonKey(req)
const cache = isRedisReady ? await redis.get(key) : null
res.setHeader('Content-Type', 'application/json')
res.setHeader('X-Content-Source', cache ? 'cache' : 'direct')
res.setHeader('X-Content-Redis', isRedisReady ? 'alive' : 'gone')
if (cache) {
res.setHeader('Content-Encoding', 'gzip')
res.setHeader('X-Cache-Key', key)
const buff = Buffer.from(cache, 'base64')
return res.send(buff)
} else {
if (isRedisReady) {
redis.del(key)
}
}
const rawResEnd = res.end
const rawResWrite = res.write
const data = await new Promise(async (resolve) => {
const chunks = []
res.write = new Proxy(res.write, {
apply(target, thisArg, args) {
const chunk = Buffer.from(args[0])
chunks.push(chunk)
},
})
res.end = async (res) => {
resolve(res || chunks)
}
await app.render(req, res, req.path, {
...req.query,
...req.params,
})
})
res.write = rawResWrite
res.end = rawResEnd
const isChunked = Array.isArray(data)
const compressedData = isChunked
? Buffer.concat(data)
: zlib.gzipSync(Buffer.from(data))
if (isRedisReady && res.statusCode === 200 && compressedData) {
const buff = Buffer.from(compressedData).toString('base64')
if (buff) {
redis.set(key, buff, { EX: time })
}
}
return res.end(compressedData)
}
async function ssrCache(req, res, time = 15 * 60 * 1000) {
const isRedisReady = getRedisReady()
const key = getSsrKey(req)
const cache = isRedisReady ? await redis.get(key) : null
res.setHeader('Content-Type', 'text/html; charset=utf-8')
res.setHeader('Content-Encoding', isRedisReady ? 'br' : 'gzip')
res.setHeader('X-Content-Source', cache ? 'cache' : 'direct')
res.setHeader('X-Content-Redis', isRedisReady ? 'alive' : 'gone')
if (cache) {
res.setHeader('X-Cache-Key', key)
let buff = Buffer.from(cache, 'base64')
return res.send(buff)
} else {
if (isRedisReady) {
redis.del(key)
}
}
const data =
(await app.renderToHTML(req, res, req.path, {
...req.query,
...req.params,
})) + `<!-- cache @ ${new Date().toLocaleString()} -->`
const compressedData = isRedisReady
? zlib.brotliCompressSync(data)
: zlib.gzipSync(data)
if (isRedisReady && res.statusCode === 200 && data) {
const buff = Buffer.from(compressedData).toString('base64')
if (buff) {
redis.set(key, buff, { EX: time })
}
}
return res.send(compressedData)
}
app.prepare().then(async () => {
const server = express()
console.log('[ Redis Client ] Connecting...')
redis.connect()
Object.entries(SSR_URLS_CACHE_TIME).forEach(([url, time]) => {
console.log(
`[ Block Explorer Server ] > Page request "${url}" cache for ${time}s`
)
server.get(url, (req, res) => ssrCache(req, res, time))
})
Object.entries(JSON_URLS_CACHE_TIME).forEach(([url, time]) => {
console.log(
`[ Block Explorer Server ] > Props request "${url}" cache for ${time}s`
)
server.get(`/_next/data/:hash${url}`, (req, res) =>
jsonCache(req, res, time)
)
})
server.get('*', (req, res) => handle(req, res))
server.post('*', (req, res) => handle(req, res))
server.listen(3000, (err) => {
if (err) {
throw err
}
console.log(`[ Block Explorer Server ] > Ready!`)
})
})