]> git.sesse.net Git - remoteglot/blob - www/serve-analysis.js
e45e34f3d3e781e07506bc0f861233e0102569f8
[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 delta = require('./js/json_delta.js');
12
13 // Constants.
14 var JSON_FILENAME = '/srv/analysis.sesse.net/www/analysis.json';
15 var HISTORY_TO_KEEP = 5;
16 var MINIMUM_VERSION = 2015062104;
17
18 // If set to 1, we are already processing a JSON update and should not
19 // start a new one. If set to 2, we are _also_ having one in the queue.
20 var json_lock = 0;
21
22 // The current contents of the file to hand out, and its last modified time.
23 var json = undefined;
24
25 // The last five timestamps, and diffs from them to the latest version.
26 var historic_json = [];
27 var diff_json = {};
28
29 // The list of clients that are waiting for new data to show up.
30 // Uniquely keyed by request_id so that we can take them out of
31 // the queue if they close the socket.
32 var sleeping_clients = {};
33 var request_id = 0;
34
35 // List of when clients were last seen, keyed by their unique ID.
36 // Used to show a viewer count to the user.
37 var last_seen_clients = {};
38
39 // The timer used to touch the file every 30 seconds if nobody
40 // else does it for us. This makes sure we don't have clients
41 // hanging indefinitely (which might have them return errors).
42 var touch_timer = undefined;
43
44 // If we are behind Varnish, we can't count the number of clients
45 // ourselves, so some external log-tailing daemon needs to tell us.
46 var viewer_count_override = undefined;
47
48 var replace_json = function(new_json_contents, mtime) {
49         // Generate the list of diffs from the last five versions.
50         if (json !== undefined) {
51                 // If two versions have the same mtime, clients could have either.
52                 // Note the fact, so that we never insert it.
53                 if (json.last_modified == mtime) {
54                         json.invalid_base = true;
55                 }
56                 if (!json.invalid_base) {
57                         historic_json.push(json);
58                         if (historic_json.length > HISTORY_TO_KEEP) {
59                                 historic_json.shift();
60                         }
61                 }
62         }
63
64         var new_json = {
65                 parsed: JSON.parse(new_json_contents),
66                 plain: new_json_contents,
67                 last_modified: mtime
68         };
69         create_json_historic_diff(new_json, historic_json.slice(0), {}, function(new_diff_json) {
70                 // gzip the new version (non-delta), and put it into place.
71                 zlib.gzip(new_json_contents, function(err, buffer) {
72                         if (err) throw err;
73
74                         new_json.gzip = buffer;
75                         json = new_json;
76                         diff_json = new_diff_json;
77                         json_lock = 0;
78
79                         // Finally, wake up any sleeping clients.
80                         possibly_wakeup_clients();
81                 });
82         });
83 }
84
85 var create_json_historic_diff = function(new_json, history_left, new_diff_json, cb) {
86         if (history_left.length == 0) {
87                 cb(new_diff_json);
88                 return;
89         }
90
91         var histobj = history_left.shift();
92         var diff = delta.JSON_delta.diff(histobj.parsed, new_json.parsed);
93         var diff_text = JSON.stringify(diff);
94         zlib.gzip(diff_text, function(err, buffer) {
95                 if (err) throw err;
96                 new_diff_json[histobj.last_modified] = {
97                         parsed: diff,
98                         plain: diff_text,
99                         gzip: buffer,
100                         last_modified: new_json.last_modified,
101                 };
102                 create_json_historic_diff(new_json, history_left, new_diff_json, cb);
103         });
104 }
105
106 var reread_file = function(event, filename) {
107         if (filename != path.basename(JSON_FILENAME)) {
108                 return;
109         }
110         if (json_lock >= 2) {
111                 return;
112         }
113         if (json_lock == 1) {
114                 // Already processing; wait a bit.
115                 json_lock = 2;
116                 setTimeout(function() { json_lock = 1; reread_file(event, filename); }, 100);
117                 return;
118         }
119         json_lock = 1;
120
121         console.log("Rereading " + JSON_FILENAME);
122         fs.open(JSON_FILENAME, 'r+', function(err, fd) {
123                 if (err) throw err;
124                 fs.fstat(fd, function(err, st) {
125                         if (err) throw err;
126                         var buffer = new Buffer(1048576);
127                         fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
128                                 if (err) throw err;
129                                 fs.close(fd, function() {
130                                         var new_json_contents = buffer.toString('utf8', 0, bytesRead);
131                                         replace_json(new_json_contents, st.mtime.getTime());
132                                 });
133                         });
134                 });
135         });
136
137         if (touch_timer !== undefined) {
138                 clearTimeout(touch_timer);
139         }
140         touch_timer = setTimeout(function() {
141                 console.log("Touching analysis.json due to no other activity");
142                 var now = Date.now() / 1000;
143                 fs.utimes(JSON_FILENAME, now, now);
144         }, 30000);
145 }
146 var possibly_wakeup_clients = function() {
147         var num_viewers = count_viewers();
148         for (var i in sleeping_clients) {
149                 mark_recently_seen(sleeping_clients[i].unique);
150                 send_json(sleeping_clients[i].response,
151                           sleeping_clients[i].ims,
152                           sleeping_clients[i].accept_gzip,
153                           num_viewers);
154         }
155         sleeping_clients = {};
156 }
157 var send_404 = function(response) {
158         response.writeHead(404, {
159                 'Content-Type': 'text/plain',
160         });
161         response.write('Something went wrong. Sorry.');
162         response.end();
163 }
164 var handle_viewer_override = function(request, u, response) {
165         // Only accept requests from localhost.
166         var peer = request.socket.localAddress;
167         if ((peer != '127.0.0.1' && peer != '::1') || request.headers['x-forwarded-for']) {
168                 console.log("Refusing viewer override from " + peer);
169                 send_404(response);
170         } else {
171                 viewer_count_override = (u.query)['num'];
172                 response.writeHead(200, {
173                         'Content-Type': 'text/plain',
174                 });
175                 response.write('OK.');
176                 response.end();
177         }
178 }
179 var send_json = function(response, ims, accept_gzip, num_viewers) {
180         var this_json = diff_json[ims] || json;
181
182         var headers = {
183                 'Content-Type': 'text/json',
184                 'X-RGLM': this_json.last_modified,
185                 'X-RGNV': num_viewers,
186                 'Access-Control-Expose-Headers': 'X-RGLM, X-RGNV, X-RGMV',
187                 'Vary': 'Accept-Encoding',
188         };
189
190         if (MINIMUM_VERSION) {
191                 headers['X-RGMV'] = MINIMUM_VERSION;
192         }
193
194         if (accept_gzip) {
195                 headers['Content-Length'] = this_json.gzip.length;
196                 headers['Content-Encoding'] = 'gzip';
197                 response.writeHead(200, headers);
198                 response.write(this_json.gzip);
199         } else {
200                 headers['Content-Length'] = this_json.plain.length;
201                 response.writeHead(200, headers);
202                 response.write(this_json.plain);
203         }
204         response.end();
205 }
206 var mark_recently_seen = function(unique) {
207         if (unique) {
208                 last_seen_clients[unique] = (new Date).getTime();
209         }
210 }
211 var count_viewers = function() {
212         if (viewer_count_override !== undefined) {
213                 return viewer_count_override;
214         }
215
216         var now = (new Date).getTime();
217
218         // Go through and remove old viewers, and count them at the same time.
219         var new_last_seen_clients = {};
220         var num_viewers = 0;
221         for (var unique in last_seen_clients) {
222                 if (now - last_seen_clients[unique] < 5000) {
223                         ++num_viewers;
224                         new_last_seen_clients[unique] = last_seen_clients[unique];
225                 }
226         }
227
228         // Also add sleeping clients that we would otherwise assume timed out.
229         for (var request_id in sleeping_clients) {
230                 var unique = sleeping_clients[request_id].unique;
231                 if (unique && !(unique in new_last_seen_clients)) {
232                         ++num_viewers;
233                 }
234         }
235
236         last_seen_clients = new_last_seen_clients;
237         return num_viewers;
238 }
239
240 // Set up a watcher to catch changes to the file, then do an initial read
241 // to make sure we have a copy.
242 fs.watch(path.dirname(JSON_FILENAME), reread_file);
243 reread_file(null, path.basename(JSON_FILENAME));
244
245 var server = http.createServer();
246 server.on('request', function(request, response) {
247         var u = url.parse(request.url, true);
248         var ims = (u.query)['ims'];
249         var unique = (u.query)['unique'];
250
251         console.log(((new Date).getTime()*1e-3).toFixed(3) + " " + request.url);
252         if (u.pathname === '/override-num-viewers') {
253                 handle_viewer_override(request, u, response);
254                 return;
255         }
256         if (u.pathname !== '/analysis.pl') {
257                 // This is not the request you are looking for.
258                 send_404(response);
259                 return;
260         }
261
262         mark_recently_seen(unique);
263
264         var accept_encoding = request.headers['accept-encoding'];
265         var accept_gzip;
266         if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
267                 accept_gzip = true;
268         } else {
269                 accept_gzip = false;
270         }
271
272         // If we already have something newer than what the user has,
273         // just send it out and be done with it.
274         if (json !== undefined && (!ims || json.last_modified > ims)) {
275                 send_json(response, ims, accept_gzip, count_viewers());
276                 return;
277         }
278
279         // OK, so we need to hang until we have something newer.
280         // Put the user on the wait list.
281         var client = {};
282         client.response = response;
283         client.request_id = request_id;
284         client.accept_gzip = accept_gzip;
285         client.unique = unique;
286         client.ims = ims;
287         sleeping_clients[request_id++] = client;
288
289         request.socket.client = client;
290 });
291 server.on('connection', function(socket) {
292         socket.on('close', function() {
293                 var client = socket.client;
294                 if (client) {
295                         mark_recently_seen(client.unique);
296                         delete sleeping_clients[client.request_id];
297                 }
298         });
299 });
300 server.listen(5000);