Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP]Add redis caching #11

Open
wants to merge 2 commits into
base: ona-custom-changes
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 84 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"dotenv": "^16.4.5",
"fastify": "^4.26.1",
"pg": "^8.11.3",
"query-string": "^7.1.3"
"query-string": "^7.1.3",
"redis": "^4.6.13"
}
}
56 changes: 54 additions & 2 deletions routes/mvt.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// route query
require("dotenv").config()

const { createClient } = require('redis');
const crypto = require('crypto');

const sql = (params, query) => {
return `
WITH mvtgeom2 as (
Expand Down Expand Up @@ -30,7 +33,7 @@ const sql = (params, query) => {
) transformed_geom

-- Add where clause only when filtering by bounds
${params.z == 0 && params.x == 0 && params.y == 0 ? `
${String(params.z) == '0' && String(params.x) == '0' && String(params.y) == '0' ? `
WHERE
ST_Intersects(
${process.env.TABLE_COLUMN},
Expand Down Expand Up @@ -92,14 +95,62 @@ const schema = {
}
}

const initializeRedis = async () => {
const client = createClient();

client.on('error', err => console.log('Redis Client Error', err));

return client.connect();
}

// cache results for at least 2 minutes
const cacheResults = async (params, results) => {
client = await initializeRedis()
client.set(params, results)
}

const getCachedResults = async (cacheKey) => {
client = await initializeRedis()
return await client.get(cacheKey)
}


// Function to merge two objects and generate a hash
function mergeAndHash(params, query) {
const mergedObject = { ...params, ...query };
const jsonString = JSON.stringify(mergedObject);
const hash = crypto.createHash('sha256').update(jsonString).digest('hex');

return hash;
}

function arrayBufferToBase64(buffer) {
return Buffer.from(buffer).toString('base64');
}


// create route
module.exports = function (fastify, opts, next) {
fastify.route({
method: 'GET',
url: '/mvt/:z/:x/:y',
schema: schema,
handler: function (request, reply) {
fastify.pg.connect(onConnect)
// check redis to see if we have cached something already
cacheKey = mergeAndHash(request.params, request.query)
getCachedResults(cacheKey).then((
cacheResult
)=> {
if (cacheResult == null) {
fastify.pg.connect(onConnect)
} else {
reply.header('Content-Type', 'application/x-protobuf').send(Buffer.from(cacheResults, 'base64').buffer)
}
}
).catch((error) => {
console.log(error)
} )


function onConnect(err, client, release) {
if (err) {
Expand All @@ -116,6 +167,7 @@ module.exports = function (fastify, opts, next) {
reply.send(err)
} else {
const mvt = result.rows[0].mvt
cacheResults(cacheKey, arrayBufferToBase64(mvt))
if (mvt.length === 0) {
reply.code(204).send()
}
Expand Down