fs-caching-server.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. #!/usr/bin/env node
  2. /**
  3. * A caching HTTP server/proxy that stores data on the local filesystem
  4. *
  5. * Author: Dave Eddy <dave@daveeddy.com>
  6. * Date: May 05, 2015
  7. * License: MIT
  8. */
  9. var events = require('events');
  10. var fs = require('fs');
  11. var http = require('http');
  12. var https = require('https');
  13. var path = require('path');
  14. var url = require('url');
  15. var util = require('util');
  16. var accesslog = require('access-log');
  17. var assert = require('assert-plus');
  18. var mime = require('mime');
  19. var mkdirp = require('mkdirp');
  20. var uuid = require('uuid');
  21. var Clone = require('readable-stream-clone');
  22. /*
  23. * default headers to ignore when proxying request (not copied to backend
  24. * server).
  25. */
  26. var NO_PROXY_HEADERS = ['date', 'server', 'host'];
  27. /*
  28. * default methods that will be considered for caching - all others will be
  29. * proxied directly.
  30. */
  31. var CACHE_METHODS = ['GET', 'HEAD'];
  32. // default regex to match for caching.
  33. var REGEX = /\.(png|jpg|jpeg|css|html|js|tar|tgz|tar\.gz)$/;
  34. // safe hasOwnProperty
  35. function hap(o, p) {
  36. return ({}).hasOwnProperty.call(o, p);
  37. }
  38. /*
  39. * FsCachingServer
  40. *
  41. * Create an instance of an FS Caching Server
  42. *
  43. * Aurguments
  44. * opts Object
  45. * opts.host String (Required) Host to bind to. ex: '0.0.0.0',
  46. * '127.0.0.1', etc.
  47. * opts.port Number (Required) Port to bind to. ex: 80, 8080, etc.
  48. * opts.backendUrl String (Required) URL of the backend to proxy
  49. * requests to. ex:
  50. * 'http://1.2.3.4:5678'
  51. * opts.cacheDir String (Required) Directory for the cached items. ex:
  52. * '/tmp/fs-caching-server'
  53. * opts.regex RegExp (Optional) Regex to match to enable caching,
  54. * defaults to REGEX above.
  55. * opts.noProxyHeaders Array (Optional) An array of headers to not proxy to
  56. * the backend, default is [date,
  57. * server, host].
  58. * opts.cacheMethods Array (Optional) An array of methods to proxy,
  59. * default is [GET, HEAD].
  60. *
  61. * Methods
  62. *
  63. * .start()
  64. * - Start the server.
  65. *
  66. * .stop()
  67. * - Stop the server.
  68. *
  69. * .onIdle(cb)
  70. * - Call the callback when the caching server is "idle" (see events below).
  71. *
  72. * Events
  73. *
  74. * 'start'
  75. * - Called when the listener is started.
  76. *
  77. * 'stop'
  78. * - Called when the listener is stopped.
  79. *
  80. * 'access-log'
  81. * - Called per-request with a CLF-formatted apache log style string.
  82. *
  83. * 'log'
  84. * - Called with debug logs from the server - useful for debugging.
  85. *
  86. * 'idle'
  87. * - Called when the server is idle. "idle" does not mean there are not
  88. * pending web requests, but instead means there are no pending filesystem
  89. * actions remaining. This is useful for writing automated tests.
  90. */
  91. function FsCachingServer(opts) {
  92. var self = this;
  93. assert.object(opts, 'opts');
  94. assert.string(opts.host, 'opts.host');
  95. assert.number(opts.port, 'opts.port');
  96. assert.string(opts.backendUrl, 'opts.backendUrl');
  97. assert.string(opts.cacheDir, 'opts.cacheDir');
  98. assert.optionalRegexp(opts.regex, 'opts.regex');
  99. assert.optionalArrayOfString(opts.noProxyHeaders, 'opts.noProxyHeaders');
  100. assert.optionalArrayOfString(opts.cacheMethods, 'opts.cacheMethods');
  101. events.EventEmitter.call(self);
  102. self.host = opts.host;
  103. self.port = opts.port;
  104. self.backendUrl = opts.backendUrl;
  105. self.cacheDir = opts.cacheDir;
  106. self.regex = opts.regex || REGEX;
  107. self.noProxyHeaders = opts.noProxyHeaders || NO_PROXY_HEADERS;
  108. self.cacheMethods = opts.cacheMethods || CACHE_METHODS;
  109. self.server = null;
  110. self.idle = true;
  111. self.backendHttps = !!self.backendUrl.match(/^https:/);
  112. self._opts = opts;
  113. }
  114. util.inherits(FsCachingServer, events.EventEmitter);
  115. /*
  116. * Start the server
  117. *
  118. * emits "listening" when the server starts
  119. */
  120. FsCachingServer.prototype.start = function start() {
  121. var self = this;
  122. assert(!self.server, 'server already exists');
  123. assert(!self.inProgress, 'requests in progress');
  124. self._log('starting server');
  125. self.server = http.createServer(onRequest);
  126. self.server.listen(self.port, self.host, onListen);
  127. self.inProgress = {};
  128. self.idle = true;
  129. function onListen() {
  130. self._log('listening on http://%s:%d', self.host, self.port);
  131. self._log('proxying requests to %s', self.backendUrl);
  132. self._log('caching matches of %s', self.regex);
  133. self._log('caching to %s', self.cacheDir);
  134. self.emit('start');
  135. }
  136. function onRequest(req, res) {
  137. self._onRequest(req, res);
  138. }
  139. };
  140. /*
  141. * Stop the server
  142. *
  143. * emits "stop" when the server stops
  144. */
  145. FsCachingServer.prototype.stop = function stop() {
  146. var self = this;
  147. assert(self.server, 'server does not exist');
  148. self.server.once('close', function () {
  149. self.idle = true;
  150. self.server = null;
  151. self.emit('stop');
  152. });
  153. self.server.close();
  154. };
  155. /*
  156. * A convience method for calling the given 'cb' when the server is idle. The
  157. * callback will be invoked immediately if the server is idle, or will be
  158. * scheduled to run when the server becomes idle.
  159. */
  160. FsCachingServer.prototype.onIdle = function onIdle(cb) {
  161. var self = this;
  162. assert.func(cb, 'cb');
  163. if (self.idle) {
  164. cb();
  165. } else {
  166. self.once('idle', cb);
  167. }
  168. };
  169. /*
  170. * Called internally when a new request is received
  171. */
  172. FsCachingServer.prototype._onRequest = function _onRequest(req, res) {
  173. var self = this;
  174. var _id = uuid.v4();
  175. function log() {
  176. var s = util.format.apply(util, arguments);
  177. self._log('[%s] %s', _id, s);
  178. }
  179. accesslog(req, res, undefined, function (s) {
  180. self.emit('access-log', s);
  181. log(s);
  182. });
  183. log('INCOMING REQUEST - %s %s', req.method, req.url);
  184. // parse the URL and determine the filename
  185. var parsed = url.parse(req.url);
  186. var file;
  187. try {
  188. file = path.posix.normalize(decodeURIComponent(parsed.pathname));
  189. } catch (e) {
  190. log('failed to parse pathname - sending 400 to client -', e.message);
  191. res.statusCode = 400;
  192. res.end();
  193. return;
  194. }
  195. /*
  196. * Any request that isn't in the list of methods to cache, or any request
  197. * to a file that doesn't match the regex, gets proxied directly.
  198. */
  199. if (self.cacheMethods.indexOf(req.method) < 0 || ! self.regex.test(file)) {
  200. proxyRequest();
  201. return;
  202. }
  203. // make the filename relative to the cache dir
  204. file = path.join(self.cacheDir, file);
  205. // check to see if the file exists
  206. fs.stat(file, function (err, stats) {
  207. // directory, give up
  208. if (stats && stats.isDirectory()) {
  209. log('%s is a directory - sending 400 to client', file);
  210. res.statusCode = 400;
  211. res.end();
  212. return;
  213. }
  214. // file exists, stream it locally
  215. if (stats) {
  216. log('%s is a file (cached) - streaming to client', file);
  217. streamFile(file, stats, req, res);
  218. return;
  219. }
  220. // another request is already proxying for this file, we wait
  221. if (hap(self.inProgress, file)) {
  222. log('%s download in progress - response queued', file);
  223. self.inProgress[file].push({
  224. id: _id,
  225. req: req,
  226. res: res,
  227. });
  228. return;
  229. }
  230. /*
  231. * If we are here the file matches the caching requirements based on
  232. * method and regex, and is also not found on the local filesystem.
  233. *
  234. * The final step before caching the request is to ensure it is *not* a
  235. * HEAD requests. HEAD requests should only ever be cached if the data
  236. * was retrieved and cached first by another type of request. In this
  237. * specific case the HEAD request should just be proxied directly.
  238. */
  239. if (req.method === 'HEAD') {
  240. proxyRequest();
  241. return;
  242. }
  243. // error with stat, proxy it
  244. self.inProgress[file] = [];
  245. self.idle = false;
  246. var uristring = self.backendUrl + parsed.path;
  247. var uri = url.parse(uristring);
  248. uri.method = req.method;
  249. uri.headers = {};
  250. Object.keys(req.headers || {}).forEach(function (header) {
  251. if (self.noProxyHeaders.indexOf(header) === -1) {
  252. uri.headers[header] = req.headers[header];
  253. }
  254. });
  255. uri.headers.host = uri.host;
  256. log('proxying %s to %s', uri.method, uristring);
  257. // proxy it
  258. var oreq = self._request(uri, function (ores) {
  259. res.statusCode = ores.statusCode;
  260. Object.keys(ores.headers || {}).forEach(function (header) {
  261. if (self.noProxyHeaders.indexOf(header) === -1) {
  262. res.setHeader(header, ores.headers[header]);
  263. }
  264. });
  265. if (res.statusCode < 200 || res.statusCode >= 300) {
  266. //ores.pipe(res);
  267. log('statusCode %d from backend not in 200 range - proxying ' +
  268. 'back to caller', res.statusCode);
  269. finish({
  270. statusCode: res.statusCode,
  271. });
  272. res.end();
  273. return;
  274. }
  275. mkdirp(path.dirname(file), function (err) {
  276. var tmp = file + '.in-progress';
  277. log('saving local file to %s', tmp);
  278. var ws = fs.createWriteStream(tmp);
  279. ws.once('finish', function () {
  280. fs.rename(tmp, file, function (err) {
  281. if (err) {
  282. log('failed to rename %s to %s', tmp, file);
  283. finish({
  284. statusCode: 500
  285. });
  286. return;
  287. }
  288. // everything worked! proxy all with success
  289. log('renamed %s to %s', tmp, file);
  290. finish({
  291. ores: ores
  292. });
  293. });
  294. });
  295. ws.once('error', function (e) {
  296. log('failed to save local file %s', e.message);
  297. ores.unpipe(ws);
  298. finish({
  299. statusCode: 500,
  300. });
  301. });
  302. var ores_ws = new Clone(ores);
  303. var ores_res = new Clone(ores);
  304. ores_ws.pipe(ws);
  305. ores_res.pipe(res);
  306. });
  307. });
  308. oreq.on('error', function (e) {
  309. log('error with proxy request %s', e.message);
  310. res.statusCode = 500;
  311. res.end();
  312. finish({
  313. statusCode: 500
  314. });
  315. });
  316. oreq.end();
  317. });
  318. /*
  319. * Proxy file directly with no caching
  320. */
  321. function proxyRequest() {
  322. log('request will be proxied with no caching');
  323. var uristring = self.backendUrl + parsed.path;
  324. var uri = url.parse(uristring);
  325. uri.method = req.method;
  326. uri.headers = {};
  327. Object.keys(req.headers || {}).forEach(function (header) {
  328. if (self.noProxyHeaders.indexOf(header) === -1) {
  329. uri.headers[header] = req.headers[header];
  330. }
  331. });
  332. uri.headers.host = uri.host;
  333. var oreq = self._request(uri, function (ores) {
  334. res.statusCode = ores.statusCode;
  335. Object.keys(ores.headers || {}).forEach(function (header) {
  336. if (self.noProxyHeaders.indexOf(header) === -1) {
  337. res.setHeader(header, ores.headers[header]);
  338. }
  339. });
  340. ores.pipe(res);
  341. });
  342. oreq.once('error', function (e) {
  343. res.statusCode = 500;
  344. res.end();
  345. });
  346. req.pipe(oreq);
  347. return;
  348. }
  349. /*
  350. * Process requests that may be blocked on the current file to be cached.
  351. */
  352. function finish(opts) {
  353. assert.object(opts, 'opts');
  354. assert.optionalNumber(opts.statusCode, 'opts.statusCode');
  355. assert.optionalObject(opts.ores, 'opts.ores');
  356. if (hap(opts, 'statusCode')) {
  357. self.inProgress[file].forEach(function (o) {
  358. o.res.statusCode = opts.statusCode;
  359. o.res.end();
  360. });
  361. delete self.inProgress[file];
  362. checkIdle();
  363. return;
  364. }
  365. assert.object(opts.ores, 'opts.ores');
  366. fs.stat(file, function (err, stats) {
  367. if (stats && stats.isDirectory()) {
  368. // directory, give up
  369. self.inProgress[file].forEach(function (o) {
  370. o.res.statusCode = 400;
  371. o.res.end();
  372. });
  373. } else if (stats) {
  374. // file exists, stream it locally
  375. self.inProgress[file].forEach(function (o) {
  376. o.res.statusCode = opts.ores.statusCode;
  377. Object.keys(opts.ores.headers || {}).forEach(function (header) {
  378. if (self.noProxyHeaders.indexOf(header) === -1) {
  379. o.res.setHeader(header, opts.ores.headers[header]);
  380. }
  381. });
  382. streamFile(file, stats, o.req, o.res);
  383. });
  384. } else {
  385. // not found
  386. self.inProgress[file].forEach(function (o) {
  387. o.res.statusCode = 500;
  388. o.res.end();
  389. });
  390. }
  391. delete self.inProgress[file];
  392. checkIdle();
  393. });
  394. }
  395. /*
  396. * Check if the server is idle and emit an event if it is
  397. */
  398. function checkIdle() {
  399. if (Object.keys(self.inProgress).length === 0) {
  400. self.idle = true;
  401. self.emit('idle');
  402. }
  403. }
  404. };
  405. /*
  406. * Emit a "log" event with the given arguments (formatted via util.format)
  407. */
  408. FsCachingServer.prototype._log = function _log() {
  409. var self = this;
  410. var s = util.format.apply(util, arguments);
  411. self.emit('log', s);
  412. };
  413. /*
  414. * Create an outgoing http/https request based on the backend URL
  415. */
  416. FsCachingServer.prototype._request = function _request(uri, cb) {
  417. var self = this;
  418. if (self.backendHttps) {
  419. return https.request(uri, cb);
  420. } else {
  421. return http.request(uri, cb);
  422. }
  423. };
  424. /*
  425. * Given a filename and its stats object (and req and res)
  426. * stream it to the caller.
  427. */
  428. function streamFile(file, stats, req, res) {
  429. var etag = util.format('"%d-%d"', stats.size, stats.mtime.getTime());
  430. res.setHeader('Last-Modified', stats.mtime.toUTCString());
  431. res.setHeader('Content-Type', mime.lookup(file));
  432. res.setHeader('ETag', etag);
  433. if (req.headers['if-none-match'] === etag) {
  434. // etag matched, end the request
  435. res.statusCode = 304;
  436. res.end();
  437. return;
  438. }
  439. res.setHeader('Content-Length', stats.size);
  440. if (req.method === 'HEAD') {
  441. res.end();
  442. return;
  443. }
  444. var rs = fs.createReadStream(file);
  445. rs.pipe(res);
  446. rs.once('error', function (e) {
  447. res.statusCode = e.code === 'ENOENT' ? 404 : 500;
  448. res.end();
  449. });
  450. res.once('close', function () {
  451. rs.destroy();
  452. });
  453. }
  454. /*
  455. * Main method (invoked from CLI)
  456. */
  457. function main() {
  458. var getopt = require('posix-getopt');
  459. var package = require('./package.json');
  460. // command line arguments
  461. var opts = {
  462. host: process.env.FS_CACHE_HOST || '0.0.0.0',
  463. port: process.env.FS_CACHE_PORT,
  464. backendUrl: process.env.FS_CACHE_URL,
  465. cacheDir: process.env.FS_CACHE_DIR || process.cwd(),
  466. regex: process.env.FS_CACHE_REGEX,
  467. };
  468. var debug = !!process.env.FS_CACHE_DEBUG;
  469. if (opts.port) {
  470. var i = parseInt(opts.port, 10);
  471. if (isNaN(i)) {
  472. console.error('FS_CACHE_PORT must be a number, got "%s"', opts.port);
  473. process.exit(1);
  474. }
  475. opts.port = i;
  476. } else {
  477. opts.port = 8080;
  478. }
  479. var usage = [
  480. 'usage: fs-caching-server [options]',
  481. '',
  482. 'options',
  483. ' -c, --cache-dir <dir> [env FS_CACHE_DIR] directory to use for caching data, defaults to CWD',
  484. ' -d, --debug enable debug logging to stderr',
  485. ' -H, --host <host> [env FS_CACHE_HOST] the host on which to listen, defaults to ' + opts.host,
  486. ' -h, --help print this message and exit',
  487. ' -p, --port <port> [env FS_CACHE_PORT] the port on which to listen, defaults to ' + opts.port,
  488. ' -r, --regex <regex> [env FS_CACHE_REGEX] regex to match to cache files, defaults to ' + REGEX,
  489. ' -U, --url <url> [env FS_CACHE_URL] URL to proxy to',
  490. ' -u, --updates check npm for available updates',
  491. ' -v, --version print the version number and exit',
  492. ].join('\n');
  493. var options = [
  494. 'c:(cache-dir)',
  495. 'd(debug)',
  496. 'H:(host)',
  497. 'h(help)',
  498. 'p:(port)',
  499. 'r:(regex)',
  500. 'U:(url)',
  501. 'u(updates)',
  502. 'v(version)'
  503. ].join('');
  504. var parser = new getopt.BasicParser(options, process.argv);
  505. var option;
  506. while ((option = parser.getopt()) !== undefined) {
  507. switch (option.option) {
  508. case 'c': opts.cacheDir = option.optarg; break;
  509. case 'd': debug = true; break;
  510. case 'H': opts.host = option.optarg; break;
  511. case 'h': console.log(usage); process.exit(0); break;
  512. case 'p': opts.port = parseInt(option.optarg, 10); break;
  513. case 'r': opts.regex = option.optarg; break;
  514. case 'U': opts.backendUrl = option.optarg; break;
  515. case 'u': // check for updates
  516. require('latest').checkupdate(package, function (ret, msg) {
  517. console.log(msg);
  518. process.exit(ret);
  519. });
  520. return;
  521. case 'v': console.log(package.version); process.exit(0); break;
  522. default: console.error(usage); process.exit(1);
  523. }
  524. }
  525. if (!opts.backendUrl) {
  526. console.error('url must be specified with `-U <url>` or as FS_CACHE_URL');
  527. process.exit(1);
  528. }
  529. if (opts.regex) {
  530. opts.regex = new RegExp(opts.regex);
  531. }
  532. // remove trailing slash
  533. opts.backendUrl = opts.backendUrl.replace(/\/{0,}$/, '');
  534. var fsCachingServer = new FsCachingServer(opts);
  535. fsCachingServer.on('access-log', console.log);
  536. if (debug) {
  537. fsCachingServer.on('log', console.error);
  538. }
  539. fsCachingServer.start();
  540. }
  541. if (require.main === module) {
  542. main();
  543. } else {
  544. module.exports = FsCachingServer;
  545. module.exports.FsCachingServer = FsCachingServer;
  546. }