From eb5bd53ff0b6dc01e247fce9af01d0ed97d8c9ba Mon Sep 17 00:00:00 2001 From: Vojta Jina Date: Tue, 5 Aug 2014 13:19:47 -0700 Subject: [PATCH] fix(web-server): cache static files MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Files in `karma/static/*` were always read from file system. These files typically don’t change (except when developing Karma itself) and so it makes sense to cache them in memory. Especially `./static/context.html`, which is read for every test run. The main reason for this change is that when using native events (non-polling), watching can easily hit the EMFILE limit and then this `fs.readFile()` can be super delayed. This was easily reproducible problem in AngularJS test suite. --- lib/middleware/common.js | 8 ++++++++ test/unit/middleware/karma.spec.coffee | 5 +++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/lib/middleware/common.js b/lib/middleware/common.js index 6376dface..979efafee 100644 --- a/lib/middleware/common.js +++ b/lib/middleware/common.js @@ -26,6 +26,8 @@ var serve404 = function(response, path) { var createServeFile = function(fs, directory) { + var cache = Object.create(null); + return function(filepath, response, transform, content) { var responseData; @@ -33,6 +35,10 @@ var createServeFile = function(fs, directory) { filepath = directory + filepath; } + if (!content && cache[filepath]) { + content = cache[filepath]; + } + // serve from cache if (content) { response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain')); @@ -51,6 +57,8 @@ var createServeFile = function(fs, directory) { return serve404(response, filepath); } + cache[filepath] = data.toString(); + response.setHeader('Content-Type', mime.lookup(filepath, 'text/plain')); // call custom transform fn to transform the data diff --git a/test/unit/middleware/karma.spec.coffee b/test/unit/middleware/karma.spec.coffee index d806e7130..dbb58c59f 100644 --- a/test/unit/middleware/karma.spec.coffee +++ b/test/unit/middleware/karma.spec.coffee @@ -21,16 +21,17 @@ describe 'middleware.karma', -> 'debug.html': mocks.fs.file(0, 'DEBUG\n%SCRIPTS%\n%X_UA_COMPATIBLE%') 'karma.js': mocks.fs.file(0, 'root: %KARMA_URL_ROOT%, v: %KARMA_VERSION%') - serveFile = require('../../../lib/middleware/common').createServeFile fsMock, '/karma/static' + createServeFile = require('../../../lib/middleware/common').createServeFile createKarmaMiddleware = require('../../../lib/middleware/karma').create - handler = filesDeferred = nextSpy = response = null + handler = serveFile = filesDeferred = nextSpy = response = null beforeEach -> clientConfig = foo: 'bar' nextSpy = sinon.spy() response = new HttpResponseMock filesDeferred = q.defer() + serveFile = createServeFile fsMock, '/karma/static' handler = createKarmaMiddleware filesDeferred.promise, serveFile, '/base/path', '/__karma__/', clientConfig