]> git.sesse.net Git - remoteglot/blob - server/serve-analysis.js
Verify that JSON_delta does not have any strangeness.
[remoteglot] / server / serve-analysis.js
1 // node.js version of analysis.pl; hopefully scales a bit better
2 // for this specific kind of task.
3
4 // Modules.
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');
15
16 // Constants.
17 var HISTORY_TO_KEEP = 5;
18 var MINIMUM_VERSION = null;
19 var COUNT_FROM_VARNISH_LOG = true;
20
21 // Filename to serve.
22 var json_filename = '/srv/analysis.sesse.net/www/analysis.json';
23 if (process.argv.length >= 3) {
24         json_filename = process.argv[2];
25 }
26
27 // Expected destination filenames.
28 var serve_url = '/analysis.pl';
29 var hash_serve_url = '/hash';
30 if (process.argv.length >= 4) {
31         serve_url = process.argv[3];
32 }
33 if (process.argv.length >= 5) {
34         hash_serve_url = process.argv[4];
35 }
36
37 // TCP port to listen on.
38 var port = 5000;
39 if (process.argv.length >= 6) {
40         port = parseInt(process.argv[5]);
41 }
42
43 // gRPC backends.
44 var grpc_backends = ["localhost:50051", "localhost:50052"];
45 if (process.argv.length >= 7) {
46         grpc_backends = process.argv[6].split(",");
47 }
48 hash_lookup.init(grpc_backends);
49
50 // If set to 1, we are already processing a JSON update and should not
51 // start a new one. If set to 2, we are _also_ having one in the queue.
52 var json_lock = 0;
53
54 // The current contents of the file to hand out, and its last modified time.
55 var json = undefined;
56
57 // The last five timestamps, and diffs from them to the latest version.
58 var historic_json = [];
59 var diff_json = {};
60
61 // The list of clients that are waiting for new data to show up.
62 // Uniquely keyed by request_id so that we can take them out of
63 // the queue if they close the socket.
64 var sleeping_clients = {};
65 var request_id = 0;
66
67 // List of when clients were last seen, keyed by their unique ID.
68 // Used to show a viewer count to the user.
69 var last_seen_clients = {};
70
71 // The timer used to touch the file every 30 seconds if nobody
72 // else does it for us. This makes sure we don't have clients
73 // hanging indefinitely (which might have them return errors).
74 var touch_timer = undefined;
75
76 // If we are behind Varnish, we can't count the number of clients
77 // ourselves, so we need to get it from parsing varnishncsa.
78 var viewer_count_override = undefined;
79
80 var replace_json = function(new_json_contents, mtime) {
81         // Generate the list of diffs from the last five versions.
82         if (json !== undefined) {
83                 // If two versions have the same mtime, clients could have either.
84                 // Note the fact, so that we never insert it.
85                 if (json.last_modified == mtime) {
86                         json.invalid_base = true;
87                 }
88                 if (!json.invalid_base) {
89                         historic_json.push(json);
90                         if (historic_json.length > HISTORY_TO_KEEP) {
91                                 historic_json.shift();
92                         }
93                 }
94         }
95
96         var parsed = JSON.parse(new_json_contents);
97
98         if (parsed['internal']) {
99                 if (parsed['internal']['grpc_backends'] &&
100                     hash_lookup.need_reinit(parsed['internal']['grpc_backends'])) {
101                         hash_lookup.init(parsed['internal']['grpc_backends']);
102                 }
103                 delete parsed['internal'];
104                 new_json_contents = JSON.stringify(parsed);
105         }
106
107         var new_json = {
108                 parsed: parsed,
109                 plain: new_json_contents,
110                 last_modified: mtime
111         };
112         create_json_historic_diff(new_json, historic_json.slice(0), {}, function(new_diff_json) {
113                 // gzip the new version (non-delta), and put it into place.
114                 zlib.gzip(new_json_contents, function(err, buffer) {
115                         if (err) throw err;
116
117                         new_json.gzip = buffer;
118                         json = new_json;
119                         diff_json = new_diff_json;
120                         json_lock = 0;
121
122                         // Finally, wake up any sleeping clients.
123                         possibly_wakeup_clients();
124                 });
125         });
126 }
127
128 var create_json_historic_diff = function(new_json, history_left, new_diff_json, cb) {
129         if (history_left.length == 0) {
130                 cb(new_diff_json);
131                 return;
132         }
133
134         var histobj = history_left.shift();
135         var diff = delta.JSON_delta.diff(histobj.parsed, new_json.parsed);
136         var diff_text = JSON.stringify(diff);
137
138         // Verify that the delta is correct
139         var base = JSON.parse(histobj.plain);
140         delta.JSON_delta.patch(base, diff);
141         var correct_pv = JSON.stringify(base['pv']);
142         var wrong_pv = JSON.stringify(new_json.parsed['pv']);
143         if (correct_pv !== wrong_pv) {
144                 console.log("Patch went wrong:", histobj.plain, new_json.plain);
145                 exit();
146         }
147
148         zlib.gzip(diff_text, function(err, buffer) {
149                 if (err) throw err;
150                 new_diff_json[histobj.last_modified] = {
151                         parsed: diff,
152                         plain: diff_text,
153                         gzip: buffer,
154                         last_modified: new_json.last_modified,
155                 };
156                 create_json_historic_diff(new_json, history_left, new_diff_json, cb);
157         });
158 }
159
160 var reread_file = function(event, filename) {
161         if (filename != path.basename(json_filename)) {
162                 return;
163         }
164         if (json_lock >= 2) {
165                 return;
166         }
167         if (json_lock == 1) {
168                 // Already processing; wait a bit.
169                 json_lock = 2;
170                 setTimeout(function() { if (json_lock == 2) json_lock = 1; reread_file(event, filename); }, 100);
171                 return;
172         }
173         json_lock = 1;
174
175         console.log("Rereading " + json_filename);
176         fs.open(json_filename, 'r', function(err, fd) {
177                 if (err) throw err;
178                 fs.fstat(fd, function(err, st) {
179                         if (err) throw err;
180                         var buffer = new Buffer(1048576);
181                         fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
182                                 if (err) throw err;
183                                 fs.close(fd, function() {
184                                         var new_json_contents = buffer.toString('utf8', 0, bytesRead);
185                                         replace_json(new_json_contents, st.mtime.getTime());
186                                 });
187                         });
188                 });
189         });
190
191         if (touch_timer !== undefined) {
192                 clearTimeout(touch_timer);
193         }
194         touch_timer = setTimeout(function() {
195                 console.log("Touching analysis.json due to no other activity");
196                 var now = Date.now() / 1000;
197                 fs.utimes(json_filename, now, now, function() {});
198         }, 30000);
199 }
200 var possibly_wakeup_clients = function() {
201         var num_viewers = count_viewers();
202         for (var i in sleeping_clients) {
203                 mark_recently_seen(sleeping_clients[i].unique);
204                 send_json(sleeping_clients[i].response,
205                           sleeping_clients[i].ims,
206                           sleeping_clients[i].accept_gzip,
207                           num_viewers);
208         }
209         sleeping_clients = {};
210 }
211 var send_404 = function(response) {
212         response.writeHead(404, {
213                 'Content-Type': 'text/plain',
214         });
215         response.write('Something went wrong. Sorry.');
216         response.end();
217 }
218 var send_json = function(response, ims, accept_gzip, num_viewers) {
219         var this_json = diff_json[ims] || json;
220
221         var headers = {
222                 'Content-Type': 'text/json',
223                 'X-RGLM': this_json.last_modified,
224                 'X-RGNV': num_viewers,
225                 'Access-Control-Expose-Headers': 'X-RGLM, X-RGNV, X-RGMV',
226                 'Vary': 'Accept-Encoding',
227         };
228
229         if (MINIMUM_VERSION) {
230                 headers['X-RGMV'] = MINIMUM_VERSION;
231         }
232
233         if (accept_gzip) {
234                 headers['Content-Length'] = this_json.gzip.length;
235                 headers['Content-Encoding'] = 'gzip';
236                 response.writeHead(200, headers);
237                 response.write(this_json.gzip);
238         } else {
239                 headers['Content-Length'] = this_json.plain.length;
240                 response.writeHead(200, headers);
241                 response.write(this_json.plain);
242         }
243         response.end();
244 }
245 var mark_recently_seen = function(unique) {
246         if (unique) {
247                 last_seen_clients[unique] = (new Date).getTime();
248         }
249 }
250 var count_viewers = function() {
251         if (viewer_count_override !== undefined) {
252                 return viewer_count_override;
253         }
254
255         var now = (new Date).getTime();
256
257         // Go through and remove old viewers, and count them at the same time.
258         var new_last_seen_clients = {};
259         var num_viewers = 0;
260         for (var unique in last_seen_clients) {
261                 if (now - last_seen_clients[unique] < 5000) {
262                         ++num_viewers;
263                         new_last_seen_clients[unique] = last_seen_clients[unique];
264                 }
265         }
266
267         // Also add sleeping clients that we would otherwise assume timed out.
268         for (var request_id in sleeping_clients) {
269                 var unique = sleeping_clients[request_id].unique;
270                 if (unique && !(unique in new_last_seen_clients)) {
271                         ++num_viewers;
272                 }
273         }
274
275         last_seen_clients = new_last_seen_clients;
276         return num_viewers;
277 }
278 var log = function(str) {
279         console.log("[" + ((new Date).getTime()*1e-3).toFixed(3) + "] " + str);
280 }
281
282 // Set up a watcher to catch changes to the file, then do an initial read
283 // to make sure we have a copy.
284 fs.watch(path.dirname(json_filename), reread_file);
285 reread_file(null, path.basename(json_filename));
286
287 if (COUNT_FROM_VARNISH_LOG) {
288         // Note: We abuse serve_url as a regex.
289         var varnishncsa = child_process.spawn(
290                 'varnishncsa', ['-F', '%{%s}t %U %q tffb=%{Varnish:time_firstbyte}x',
291                 '-q', 'ReqURL ~ "^' + serve_url + '"']);
292         var rl = readline.createInterface({
293                 input: varnishncsa.stdout,
294                 output: varnishncsa.stdin,
295                 terminal: false
296         });
297
298         var uniques = [];
299         rl.on('line', function(line) {
300                 var v = line.match(/(\d+) .*\?ims=\d+&unique=(.*) tffb=(.*)/);
301                 if (v) {
302                         uniques[v[2]] = {
303                                 last_seen: (parseInt(v[1]) + parseFloat(v[3])) * 1e3,
304                                 grace: null,
305                         };
306                         log(v[1] + " " + v[2] + " " + v[3]);
307                 } else {
308                         log("VARNISHNCSA UNPARSEABLE LINE: " + line);
309                 }
310         });
311         setInterval(function() {
312                 var mtime = json.last_modified - 1000;  // Compensate for subsecond issues.
313                 var now = (new Date).getTime();
314                 var num_viewers = 0;
315
316                 for (var unique in uniques) {
317                         ++num_viewers;
318                         var last_seen = uniques[unique].last_seen;
319                         if (now - last_seen <= 5000) {
320                                 // We've seen this user in the last five seconds;
321                                 // it's okay.
322                                 continue;
323                         }
324                         if (last_seen >= mtime) {
325                                 // This user has the latest version;
326                                 // they are probably just hanging.
327                                 continue;
328                         }
329                         if (uniques[unique].grace === null) {
330                                 // They have five seconds after a new JSON has been
331                                 // provided to get get it, or they're out.
332                                 // We don't simply use mtime, since we don't want to
333                                 // reset the grace timer just because a new JSON is
334                                 // published.
335                                 uniques[unique].grace = mtime;
336                         }
337                         if (now - uniques[unique].grace > 5000) {
338                                 log("Timing out " + unique + " (last_seen=" + last_seen + ", now=" + now +
339                                         ", mtime=" + mtime, ", grace=" + uniques[unique].grace + ")");
340                                 delete uniques[unique];
341                                 --num_viewers;
342                         }
343                 }
344
345                 log(num_viewers + " entries in hash, mtime=" + mtime);
346                 viewer_count_override = num_viewers;
347         }, 1000);
348 }
349
350 var server = http.createServer();
351 server.on('request', function(request, response) {
352         var u = url.parse(request.url, true);
353         var ims = (u.query)['ims'];
354         var unique = (u.query)['unique'];
355
356         log(request.url);
357         if (u.pathname === hash_serve_url) {
358                 var fen = (u.query)['fen'];
359                 hash_lookup.handle_request(fen, response);
360                 return;
361         }
362         if (u.pathname !== serve_url) {
363                 // This is not the request you are looking for.
364                 send_404(response);
365                 return;
366         }
367
368         mark_recently_seen(unique);
369
370         var accept_encoding = request.headers['accept-encoding'];
371         var accept_gzip;
372         if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
373                 accept_gzip = true;
374         } else {
375                 accept_gzip = false;
376         }
377
378         // If we already have something newer than what the user has,
379         // just send it out and be done with it.
380         if (json !== undefined && (!ims || json.last_modified > ims)) {
381                 send_json(response, ims, accept_gzip, count_viewers());
382                 return;
383         }
384
385         // OK, so we need to hang until we have something newer.
386         // Put the user on the wait list.
387         var client = {};
388         client.response = response;
389         client.request_id = request_id;
390         client.accept_gzip = accept_gzip;
391         client.unique = unique;
392         client.ims = ims;
393         sleeping_clients[request_id++] = client;
394
395         request.socket.client = client;
396 });
397 server.on('connection', function(socket) {
398         socket.on('close', function() {
399                 var client = socket.client;
400                 if (client) {
401                         mark_recently_seen(client.unique);
402                         delete sleeping_clients[client.request_id];
403                 }
404         });
405 });
406
407 server.listen(port);