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