1 // node.js version of analysis.pl; hopefully scales a bit better
2 // for this specific kind of task.
5 var http = require('http');
6 var fs = require('fs');
7 var url = require('url');
8 var querystring = require('querystring');
9 var path = require('path');
10 var zlib = require('zlib');
11 var readline = require('readline');
12 var child_process = require('child_process');
13 var delta = require('../www/js/json_delta.js');
14 var hash_lookup = require('./hash-lookup.js');
17 var HISTORY_TO_KEEP = 5;
18 var MINIMUM_VERSION = null;
19 var COUNT_FROM_VARNISH_LOG = true;
22 var json_filename = '/srv/analysis.sesse.net/www/analysis.json';
23 if (process.argv.length >= 3) {
24 json_filename = process.argv[2];
26 var html_filename = '/srv/analysis.sesse.net/www/index.html';
28 // Expected destination filenames.
29 var serve_url = '/analysis.pl';
30 var html_serve_url = '/index-inline.html';
31 var hash_serve_url = '/hash';
32 if (process.argv.length >= 4) {
33 serve_url = process.argv[3];
35 if (process.argv.length >= 5) {
36 hash_serve_url = process.argv[4];
39 // TCP port to listen on.
41 if (process.argv.length >= 6) {
42 port = parseInt(process.argv[5]);
46 var grpc_backends = ["localhost:50051", "localhost:50052"];
47 if (process.argv.length >= 7) {
48 grpc_backends = process.argv[6].split(",");
50 hash_lookup.init(grpc_backends);
52 // If set to 1, we are already processing a JSON update and should not
53 // start a new one. If set to 2, we are _also_ having one in the queue.
56 // The current contents of the file to hand out, and its last modified time.
60 // The last five timestamps, and diffs from them to the latest version.
61 var historic_json = [];
64 // The list of clients that are waiting for new data to show up.
65 // Uniquely keyed by request_id so that we can take them out of
66 // the queue if they close the socket.
67 var sleeping_clients = {};
70 // List of when clients were last seen, keyed by their unique ID.
71 // Used to show a viewer count to the user.
72 var last_seen_clients = {};
74 // The timer used to touch the file every 30 seconds if nobody
75 // else does it for us. This makes sure we don't have clients
76 // hanging indefinitely (which might have them return errors).
77 var touch_timer = undefined;
79 // If we are behind Varnish, we can't count the number of clients
80 // ourselves, so we need to get it from parsing varnishncsa.
81 var viewer_count_override = undefined;
83 var replace_json = function(new_json_contents, mtime) {
84 // Generate the list of diffs from the last five versions.
85 if (json !== undefined) {
86 // If two versions have the same mtime, clients could have either.
87 // Note the fact, so that we never insert it.
88 if (json.last_modified == mtime) {
89 json.invalid_base = true;
91 if (!json.invalid_base) {
92 historic_json.push(json);
93 if (historic_json.length > HISTORY_TO_KEEP) {
94 historic_json.shift();
99 var parsed = JSON.parse(new_json_contents);
101 if (parsed['internal']) {
102 if (parsed['internal']['grpc_backends'] &&
103 hash_lookup.need_reinit(parsed['internal']['grpc_backends'])) {
104 hash_lookup.init(parsed['internal']['grpc_backends']);
106 delete parsed['internal'];
107 new_json_contents = JSON.stringify(parsed);
112 plain: new_json_contents,
115 create_json_historic_diff(new_json, historic_json.slice(0), {}, function(new_diff_json) {
116 // gzip the new version (non-delta), and put it into place.
117 zlib.gzip(new_json_contents, function(err, buffer) {
120 new_json.gzip = buffer;
122 diff_json = new_diff_json;
125 // Finally, wake up any sleeping clients.
126 possibly_wakeup_clients();
131 var create_json_historic_diff = function(new_json, history_left, new_diff_json, cb) {
132 if (history_left.length == 0) {
137 var histobj = history_left.shift();
138 var diff = delta.JSON_delta.diff(histobj.parsed, new_json.parsed);
139 var diff_text = JSON.stringify(diff);
141 // Verify that the delta is correct
142 var base = JSON.parse(histobj.plain);
143 delta.JSON_delta.patch(base, diff);
144 var correct_pv = JSON.stringify(base['pv']);
145 var wrong_pv = JSON.stringify(new_json.parsed['pv']);
146 if (correct_pv !== wrong_pv) {
147 console.log("Patch went wrong:", histobj.plain, new_json.plain);
151 zlib.gzip(diff_text, function(err, buffer) {
153 new_diff_json[histobj.last_modified] = {
157 last_modified: new_json.last_modified,
159 create_json_historic_diff(new_json, history_left, new_diff_json, cb);
163 function read_entire_file(filename, callback) {
164 fs.open(filename, 'r', function(err, fd) {
166 fs.fstat(fd, function(err, st) {
168 var buffer = new Buffer(1048576);
169 fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
171 fs.close(fd, function() {
172 var contents = buffer.toString('utf8', 0, bytesRead);
173 callback(contents, st.mtime.getTime());
180 var reread_file = function(event, filename) {
181 if (filename != path.basename(json_filename)) {
184 if (json_lock >= 2) {
187 if (json_lock == 1) {
188 // Already processing; wait a bit.
190 setTimeout(function() { if (json_lock == 2) json_lock = 1; reread_file(event, filename); }, 100);
195 console.log("Rereading " + json_filename);
196 read_entire_file(json_filename, function(new_json_contents, mtime) {
197 replace_json(new_json_contents, mtime);
199 // The HTML can go async, it's not too hopeless if it's out of date by a few milliseconds
200 read_entire_file(html_filename, function(new_html_contents, html_mtime) {
203 'X-RGNV': count_viewers(), // May be slightly out of date.
205 if (MINIMUM_VERSION) {
206 json_headers['X-RGMV'] = MINIMUM_VERSION;
209 'data': JSON.parse(new_json_contents),
210 'headers': json_headers,
212 delete inline_json['data']['internal'];
214 new_html_contents = new_html_contents.replace(
215 '/*REPLACE:inlinejson*/',
216 'window.inline_json=' + JSON.stringify(inline_json) + ';');
217 zlib.gzip(new_html_contents, function(err, buffer) {
220 plain: new_html_contents,
227 if (touch_timer !== undefined) {
228 clearTimeout(touch_timer);
230 touch_timer = setTimeout(function() {
231 console.log("Touching analysis.json due to no other activity");
232 var now = Date.now() / 1000;
233 fs.utimes(json_filename, now, now, function() {});
236 var possibly_wakeup_clients = function() {
237 var num_viewers = count_viewers();
238 for (var i in sleeping_clients) {
239 mark_recently_seen(sleeping_clients[i].unique);
240 send_json(sleeping_clients[i].response,
241 sleeping_clients[i].ims,
242 sleeping_clients[i].accept_gzip,
245 sleeping_clients = {};
247 var send_404 = function(response) {
248 response.writeHead(404, {
249 'Content-Type': 'text/plain',
251 response.write('Something went wrong. Sorry.');
254 var send_json = function(response, ims, accept_gzip, num_viewers) {
255 var this_json = diff_json[ims] || json;
258 'Content-Type': 'text/json',
259 'X-RGLM': this_json.last_modified,
260 'X-RGNV': num_viewers,
261 'Access-Control-Expose-Headers': 'X-RGLM, X-RGNV, X-RGMV',
262 'Vary': 'Accept-Encoding',
265 if (MINIMUM_VERSION) {
266 headers['X-RGMV'] = MINIMUM_VERSION;
270 headers['Content-Length'] = this_json.gzip.length;
271 headers['Content-Encoding'] = 'gzip';
272 response.writeHead(200, headers);
273 response.write(this_json.gzip);
275 headers['Content-Length'] = this_json.plain.length;
276 response.writeHead(200, headers);
277 response.write(this_json.plain);
281 var send_html = function(response, accept_gzip, num_viewers) {
283 'Content-type': 'text/html; charset=utf-8',
284 'Vary': 'Accept-Encoding',
288 headers['Content-Length'] = html.gzip.length;
289 headers['Content-Encoding'] = 'gzip';
290 response.writeHead(200, headers);
291 response.write(html.gzip);
293 headers['Content-Length'] = html.plain.length;
294 response.writeHead(200, headers);
295 response.write(html.plain);
299 var mark_recently_seen = function(unique) {
301 last_seen_clients[unique] = (new Date).getTime();
304 var count_viewers = function() {
305 if (viewer_count_override !== undefined) {
306 return viewer_count_override;
309 var now = (new Date).getTime();
311 // Go through and remove old viewers, and count them at the same time.
312 var new_last_seen_clients = {};
314 for (var unique in last_seen_clients) {
315 if (now - last_seen_clients[unique] < 5000) {
317 new_last_seen_clients[unique] = last_seen_clients[unique];
321 // Also add sleeping clients that we would otherwise assume timed out.
322 for (var request_id in sleeping_clients) {
323 var unique = sleeping_clients[request_id].unique;
324 if (unique && !(unique in new_last_seen_clients)) {
329 last_seen_clients = new_last_seen_clients;
332 var log = function(str) {
333 console.log("[" + ((new Date).getTime()*1e-3).toFixed(3) + "] " + str);
336 // Set up a watcher to catch changes to the file, then do an initial read
337 // to make sure we have a copy.
338 fs.watch(path.dirname(json_filename), reread_file);
339 reread_file(null, path.basename(json_filename));
341 if (COUNT_FROM_VARNISH_LOG) {
342 // Note: We abuse serve_url as a regex.
343 var varnishncsa = child_process.spawn(
344 'varnishncsa', ['-F', '%{%s}t %U %q tffb=%{Varnish:time_firstbyte}x',
345 '-q', 'ReqURL ~ "^(' + serve_url + '|' + html_serve_url + ')"']);
346 var rl = readline.createInterface({
347 input: varnishncsa.stdout,
348 output: varnishncsa.stdin,
353 rl.on('line', function(line) {
354 var v = line.match(/(\d+) .*\?ims=\d+&unique=(.*) tffb=(.*)/);
357 last_seen: (parseInt(v[1]) + parseFloat(v[3])) * 1e3,
360 log(v[1] + " " + v[2] + " " + v[3]);
362 log("VARNISHNCSA UNPARSEABLE LINE: " + line);
365 setInterval(function() {
366 var mtime = json.last_modified - 1000; // Compensate for subsecond issues.
367 var now = (new Date).getTime();
370 for (var unique in uniques) {
372 var last_seen = uniques[unique].last_seen;
373 if (now - last_seen <= 5000) {
374 // We've seen this user in the last five seconds;
378 if (last_seen >= mtime) {
379 // This user has the latest version;
380 // they are probably just hanging.
383 if (uniques[unique].grace === null) {
384 // They have five seconds after a new JSON has been
385 // provided to get get it, or they're out.
386 // We don't simply use mtime, since we don't want to
387 // reset the grace timer just because a new JSON is
389 uniques[unique].grace = mtime;
391 if (now - uniques[unique].grace > 5000) {
392 log("Timing out " + unique + " (last_seen=" + last_seen + ", now=" + now +
393 ", mtime=" + mtime, ", grace=" + uniques[unique].grace + ")");
394 delete uniques[unique];
399 log(num_viewers + " entries in hash, mtime=" + mtime);
400 viewer_count_override = num_viewers;
404 var server = http.createServer();
405 server.on('request', function(request, response) {
406 var u = url.parse(request.url, true);
407 var ims = (u.query)['ims'];
408 var unique = (u.query)['unique'];
411 if (u.pathname === hash_serve_url) {
412 var fen = (u.query)['fen'];
413 hash_lookup.handle_request(fen, response);
416 if (u.pathname !== serve_url && u.pathname !== html_serve_url) {
417 // This is not the request you are looking for.
422 var accept_encoding = request.headers['accept-encoding'];
423 let accept_gzip = (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/));
425 if (u.pathname === html_serve_url) {
426 send_html(response, accept_gzip, count_viewers());
430 mark_recently_seen(unique);
432 // If we already have something newer than what the user has,
433 // just send it out and be done with it.
434 if (json !== undefined && (!ims || json.last_modified > ims)) {
435 send_json(response, ims, accept_gzip, count_viewers());
439 // OK, so we need to hang until we have something newer.
440 // Put the user on the wait list.
442 client.response = response;
443 client.request_id = request_id;
444 client.accept_gzip = accept_gzip;
445 client.unique = unique;
447 sleeping_clients[request_id++] = client;
449 request.socket.client = client;
451 server.on('connection', function(socket) {
452 socket.on('close', function() {
453 var client = socket.client;
455 mark_recently_seen(client.unique);
456 delete sleeping_clients[client.request_id];