Skip to content

Commit

Permalink
feat(staticMaps): Add concurrency and caching to speed up static maps
Browse files Browse the repository at this point in the history
NB: Caching will not be noticable in dev, because currently npm start
and npm run dev will turn off http caching, but have tested this works
when http caching is enabled.
  • Loading branch information
gmaclennan authored and okdistribute committed Sep 14, 2020
1 parent 8c40a4f commit 69dc324
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions src/background/maps.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,35 @@ const { default: PQ } = require('p-queue')
const config = require('../../config')
const logger = require('../logger')

const queue = new PQ({ concurrency: 1 })
const CONCURRENCY = 4
const queue = new PQ({ concurency: CONCURRENCY })

const accessToken = config.MAPBOX_ACCESS_TOKEN
const style = 'mapbox://styles/mapbox/outdoors-v10'

const getMapboxInstance = (() => {
let cur = 0
let instances
// TODO: Should we remove and cleanup these instances after a timeout? To
// avoid ongoing memory usage?
return () => {
if (!instances) {
instances = new Array(CONCURRENCY)
.fill(null)
.map(() => new HiddenMapbox({ accessToken, style }))
}
cur = (cur + 1) % CONCURRENCY
return instances[cur]
}
})()

var router = Router()
let mapbox

router.addRoute('/map/:lon/:lat/:zoom/:width/:height/x:pixelRatio.png', function (req, res, params) {
const { lon, lat, zoom, width, height, pixelRatio } = params
if (!mapbox) mapbox = new HiddenMapbox({accessToken, style})

const promise = queue.add(() => {
const mapbox = getMapboxInstance()
return mapbox.getMapImage({
center: {lon, lat},
zoom: parseInt(zoom),
Expand All @@ -36,6 +52,8 @@ router.addRoute('/map/:lon/:lat/:zoom/:width/:height/x:pixelRatio.png', function
promise
.then((blob) => {
res.setHeader('Content-Type', 'image/png')
// Cache static maps in the browser for 15 minutes
res.setHeader('Cache-Control', 'public, max-age=900')
blob.arrayBuffer()
.then((buf) => {
res.end(Buffer.from(buf))
Expand Down

0 comments on commit 69dc324

Please sign in to comment.