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

Added ratelimit headers to v2 API #169

Closed
wants to merge 1 commit into from
Closed
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
28 changes: 25 additions & 3 deletions platform/api/controllers/api/v2/PistonController.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const axios = require('axios');
const moment = require('moment')
const Redis = require('ioredis');

module.exports = {
Expand Down Expand Up @@ -32,9 +32,15 @@ module.exports = {

const ip = req.headers['x-real-ip'];
const authorization = req.headers['authorization'];
let rate_limit_reset = '0';
let rate_limit_remaining = 'Infinity';
let rate_limit_limit = 'Infinity'

if (!sails.config.piston.unlimited_keys.includes(authorization)) {
const redis = new Redis(6379, 'redis');
const time_limit = 200;
rate_limit_remaining = '0';
rate_limit_limit = '1';

let entry = await redis.get(`piston-${req.ip}`);

Expand All @@ -43,11 +49,17 @@ module.exports = {

return res
.status(429)
.set({
'x-ratelimit-limit': rate_limit_limit,
'x-ratelimit-reset': entry,
'x-ratelimit-remaining': rate_limit_remaining
})
.send({
message: 'Requests limited to 1 per 200ms'
message: `Requests limited to 1 per ${time_limit} ms`
});
} else {
await redis.set(`piston-${req.ip}`, 0, 'px', 200);
rate_limit_reset = (moment().value_of() + time_limit).to_string();
await redis.set(`piston-${req.ip}`, rate_limit_reset, 'px', time_limit);
}

redis.disconnect();
Expand All @@ -64,6 +76,12 @@ module.exports = {
};
}

let headers = {
'x-ratelimit-limit': rate_limit_limit,
'x-ratelimit-reset': rate_limit_reset,
'x-ratelimit-remaining': rate_limit_remaining
};

try {
let result = await piston
.execute(
Expand All @@ -81,22 +99,26 @@ module.exports = {

return res
.status(200)
.set(headers)
.send({
language: result.language,
version: result.version,
run: result.run,
compile: result.compile
});

} catch(e) {
if (e.status_code === 400) {
return res
.status(400)
.set(headers)
.send({
message: e.message
});
} else {
return res
.status(500)
.set(headers)
.send({
message: 'Execution problem: ' + e.message
});
Expand Down