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 delta = require('./js/json_delta.js');
14 var JSON_FILENAME = '/srv/analysis.sesse.net/www/analysis.json';
15 var HISTORY_TO_KEEP = 5;
16 var MINIMUM_VERSION = null;
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.
22 // The current contents of the file to hand out, and its last modified time.
25 // The last five timestamps, and diffs from them to the latest version.
26 var historic_json = [];
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 = {};
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 = {};
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;
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;
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;
56 if (!json.invalid_base) {
57 historic_json.push(json);
58 if (historic_json.length > HISTORY_TO_KEEP) {
59 historic_json.shift();
65 parsed: JSON.parse(new_json_contents),
66 plain: new_json_contents,
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) {
74 new_json.gzip = buffer;
76 diff_json = new_diff_json;
79 // Finally, wake up any sleeping clients.
80 possibly_wakeup_clients();
85 var create_json_historic_diff = function(new_json, history_left, new_diff_json, cb) {
86 if (history_left.length == 0) {
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) {
96 new_diff_json[histobj.last_modified] = {
100 last_modified: new_json.last_modified,
102 create_json_historic_diff(new_json, history_left, new_diff_json, cb);
106 var reread_file = function(event, filename) {
107 if (filename != path.basename(JSON_FILENAME)) {
110 if (json_lock >= 2) {
113 if (json_lock == 1) {
114 // Already processing; wait a bit.
116 setTimeout(function() { json_lock = 1; reread_file(event, filename); }, 100);
121 console.log("Rereading " + JSON_FILENAME);
122 fs.open(JSON_FILENAME, 'r+', function(err, fd) {
124 fs.fstat(fd, function(err, st) {
126 var buffer = new Buffer(1048576);
127 fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
129 fs.close(fd, function() {
130 var new_json_contents = buffer.toString('utf8', 0, bytesRead);
131 replace_json(new_json_contents, st.mtime.getTime());
137 if (touch_timer !== undefined) {
138 clearTimeout(touch_timer);
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);
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,
155 sleeping_clients = {};
157 var send_404 = function(response) {
158 response.writeHead(404, {
159 'Content-Type': 'text/plain',
161 response.write('Something went wrong. Sorry.');
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);
171 viewer_count_override = (u.query)['num'];
172 response.writeHead(200, {
173 'Content-Type': 'text/plain',
175 response.write('OK.');
179 var send_json = function(response, ims, accept_gzip, num_viewers) {
180 var this_json = diff_json[ims] || json;
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',
187 'Vary': 'Accept-Encoding',
190 if (MINIMUM_VERSION) {
191 headers['X-RGMV'] = MINIMUM_VERSION;
195 headers['Content-Length'] = this_json.gzip.length;
196 headers['Content-Encoding'] = 'gzip';
197 response.writeHead(200, headers);
198 response.write(this_json.gzip);
200 headers['Content-Length'] = this_json.plain.length;
201 response.writeHead(200, headers);
202 response.write(this_json.plain);
206 var mark_recently_seen = function(unique) {
208 last_seen_clients[unique] = (new Date).getTime();
211 var count_viewers = function() {
212 if (viewer_count_override !== undefined) {
213 return viewer_count_override;
216 var now = (new Date).getTime();
218 // Go through and remove old viewers, and count them at the same time.
219 var new_last_seen_clients = {};
221 for (var unique in last_seen_clients) {
222 if (now - last_seen_clients[unique] < 5000) {
224 new_last_seen_clients[unique] = last_seen_clients[unique];
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)) {
236 last_seen_clients = new_last_seen_clients;
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));
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'];
251 console.log((new Date).getTime()*1e-3 + " " + request.url);
252 if (u.pathname === '/override-num-viewers') {
253 handle_viewer_override(request, u, response);
256 if (u.pathname !== '/analysis.pl') {
257 // This is not the request you are looking for.
262 mark_recently_seen(unique);
264 var accept_encoding = request.headers['accept-encoding'];
266 if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
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());
279 // OK, so we need to hang until we have something newer.
280 // Put the user on the wait list.
282 client.response = response;
283 client.request_id = request_id;
284 client.accept_gzip = accept_gzip;
285 client.unique = unique;
287 sleeping_clients[request_id++] = client;
289 request.socket.client = client;
291 server.on('connection', function(socket) {
292 socket.on('close', function() {
293 var client = socket.client;
295 mark_recently_seen(client.unique);
296 delete sleeping_clients[client.request_id];