]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server/middlewares/cache.ts
Handle concurrent requests in cache middleware
[github/Chocobozzz/PeerTube.git] / server / middlewares / cache.ts
1 import * as express from 'express'
2 import * as AsyncLock from 'async-lock'
3 import { Redis } from '../lib/redis'
4 import { logger } from '../helpers/logger'
5
6 const lock = new AsyncLock({ timeout: 5000 })
7
8 function cacheRoute (lifetime: number) {
9 return async function (req: express.Request, res: express.Response, next: express.NextFunction) {
10 const redisKey = Redis.Instance.buildCachedRouteKey(req)
11
12 await lock.acquire(redisKey, async (done) => {
13 const cached = await Redis.Instance.getCachedRoute(req)
14
15 // Not cached
16 if (!cached) {
17 logger.debug('Not cached result for route %s.', req.originalUrl)
18
19 const sendSave = res.send.bind(res)
20
21 res.send = (body) => {
22 if (res.statusCode >= 200 && res.statusCode < 400) {
23 const contentType = res.getHeader('content-type').toString()
24 Redis.Instance.setCachedRoute(req, body, lifetime, contentType, res.statusCode)
25 .then(() => done())
26 .catch(err => {
27 logger.error('Cannot cache route.', { err })
28 return done(err)
29 })
30 }
31
32 return sendSave(body)
33 }
34
35 return next()
36 }
37
38 if (cached.contentType) res.contentType(cached.contentType)
39
40 if (cached.statusCode) {
41 const statusCode = parseInt(cached.statusCode, 10)
42 if (!isNaN(statusCode)) res.status(statusCode)
43 }
44
45 logger.debug('Use cached result for %s.', req.originalUrl)
46 res.send(cached.body).end()
47
48 return done()
49 })
50 }
51 }
52
53 // ---------------------------------------------------------------------------
54
55 export {
56 cacheRoute
57 }