diff --git a/app.js b/app.js index 177c7dc6..9f296f3d 100755 --- a/app.js +++ b/app.js @@ -33,6 +33,7 @@ var nopt = require('nopt'), temp = require('temp'), path = require('path'), async = require('async'), + LRU = require('lru-cache'), fs = require('fs'); var opts = nopt({ @@ -52,6 +53,13 @@ var port = props.get('gcc-explorer', 'port', 10240); var compilers = []; var compilersByExe = {}; +var cache = LRU({ + max: props.get('gcc-explorer', 'cacheMb') * 1024 * 1024, + length: function(n) { return n.length; } +}); +var cacheHits = 0; +var cacheMisses = 0; + var compileQueue = async.queue(function(task, callback) { console.log("Compiling, queue size " + compileQueue.length()); task.task(callback); @@ -89,6 +97,10 @@ function checkSource(source) { return null; } +function cacheStats() { + console.log("Cache stats: " + cacheHits + " hits, " + cacheMisses + " misses"); +} + function compile(req, res) { var source = req.body.source; var compiler = req.body.compiler; @@ -109,6 +121,17 @@ function compile(req, res) { if (sourceErr) { return res.end(JSON.stringify({code: -1, stderr: sourceErr})); } + + var key = compiler + " | " + source; + var cached = cache.get(key); + if (cached) { + cacheHits++; + cacheStats(); + res.end(cached); + return; + } + cacheMisses++; + var compileTask = function(taskFinished) { temp.mkdir('gcc-explorer-compiler', function(err, dirPath) { if (err) { @@ -153,11 +176,14 @@ function compile(req, res) { data = ''; } - res.end(JSON.stringify({ + var result = JSON.stringify({ stdout: stdout, stderr: stderr, asm: data, - code: code })); + code: code }); + cache.set(key, result); + cacheStats(); + res.end(result); fs.unlink(outputFilename, function() { fs.unlink(inputFilename, function() { fs.rmdir(dirPath); }); diff --git a/etc/config/gcc-explorer.defaults.properties b/etc/config/gcc-explorer.defaults.properties index cb027a01..34512226 100644 --- a/etc/config/gcc-explorer.defaults.properties +++ b/etc/config/gcc-explorer.defaults.properties @@ -4,3 +4,4 @@ compileTimeoutMs=1000 compilers=/usr/bin/g++-4.4:/usr/bin/g++-4.5:/usr/bin/g++-4.6:/usr/bin/g++-4.7:/usr/bin/clang++ compileFilename=example.cpp postProcess=c++filt +cacheMb=200 diff --git a/package.json b/package.json index 35d7ab72..4b371c68 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,8 @@ "async": "0.1.x", "nopt": "1.0.x", "temp": "0.4.x", - "ffi": "1.0.x" + "ffi": "1.0.x", + "lru-cache": "2.2.x" }, "devDependencies": { "supervisor": "0.3.1"