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');
13 var json_filename = '/srv/analysis.sesse.net/www/analysis.json';
15 // The current contents of the file to hand out, and its last modified time.
16 var json_contents = undefined;
17 var json_contents_gz = undefined;
18 var json_last_modified = undefined;
20 // The list of clients that are waiting for new data to show up.
21 // Uniquely keyed by request_id so that we can take them out of
22 // the queue if they close the socket.
23 var sleeping_clients = {};
26 // List of when clients were last seen, keyed by their unique ID.
27 // Used to show a viewer count to the user.
28 var last_seen_clients = {};
30 // The timer used to touch the file every 30 seconds if nobody
31 // else does it for us. This makes sure we don't have clients
32 // hanging indefinitely (which might have them return errors).
33 var touch_timer = undefined;
35 // If we are behind Varnish, we can't count the number of clients
36 // ourselves, so some external log-tailing daemon needs to tell us.
37 var viewer_count_override = undefined;
39 var reread_file = function(event, filename) {
40 if (filename != path.basename(json_filename)) {
43 console.log("Rereading " + json_filename);
44 fs.open(json_filename, 'r+', function(err, fd) {
46 fs.fstat(fd, function(err, st) {
48 var buffer = new Buffer(1048576);
49 fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
51 fs.close(fd, function() {
52 var new_json_contents = buffer.toString('utf8', 0, bytesRead);
53 zlib.gzip(new_json_contents, function(err, buffer) {
55 json_contents = new_json_contents;
56 json_contents_gz = buffer;
57 json_last_modified = st.mtime.getTime();
58 possibly_wakeup_clients();
65 if (touch_timer !== undefined) {
66 clearTimeout(touch_timer);
68 touch_timer = setTimeout(function() {
69 console.log("Touching analysis.json due to no other activity");
70 var now = Date.now() / 1000;
71 fs.utimes(json_filename, now, now);
74 var possibly_wakeup_clients = function() {
75 var num_viewers = count_viewers();
76 for (var i in sleeping_clients) {
77 mark_recently_seen(sleeping_clients[i].unique);
78 send_json(sleeping_clients[i].response,
79 sleeping_clients[i].accept_gzip,
82 sleeping_clients = {};
84 var send_404 = function(response) {
85 response.writeHead(404, {
86 'Content-Type': 'text/plain',
88 response.write('Something went wrong. Sorry.');
91 var handle_viewer_override = function(request, u, response) {
92 // Only accept requests from localhost.
93 var peer = request.socket.localAddress;
94 if ((peer != '127.0.0.1' && peer != '::1') || request.headers['x-forwarded-for']) {
95 console.log("Refusing viewer override from " + peer);
98 viewer_count_override = (u.query)['num'];
99 response.writeHead(200, {
100 'Content-Type': 'text/plain',
102 response.write('OK.');
106 var send_json = function(response, accept_gzip, num_viewers) {
108 'Content-Type': 'text/json',
109 'X-Remoteglot-Last-Modified': json_last_modified,
110 'X-Remoteglot-Num-Viewers': num_viewers,
111 'Access-Control-Expose-Headers': 'X-Remoteglot-Last-Modified, X-Remoteglot-Num-Viewers',
112 'Expires': 'Mon, 01 Jan 1970 00:00:00 UTC',
113 'Vary': 'Accept-Encoding',
117 headers['Content-Encoding'] = 'gzip';
118 response.writeHead(200, headers);
119 response.write(json_contents_gz);
121 response.writeHead(200, headers);
122 response.write(json_contents);
126 var mark_recently_seen = function(unique) {
128 last_seen_clients[unique] = (new Date).getTime();
131 var count_viewers = function() {
132 if (viewer_count_override !== undefined) {
133 return viewer_count_override;
136 var now = (new Date).getTime();
138 // Go through and remove old viewers, and count them at the same time.
139 var new_last_seen_clients = {};
141 for (var unique in last_seen_clients) {
142 if (now - last_seen_clients[unique] < 5000) {
144 new_last_seen_clients[unique] = last_seen_clients[unique];
148 // Also add sleeping clients that we would otherwise assume timed out.
149 for (var request_id in sleeping_clients) {
150 var unique = sleeping_clients[request_id].unique;
151 if (unique && !(unique in new_last_seen_clients)) {
156 last_seen_clients = new_last_seen_clients;
160 // Set up a watcher to catch changes to the file, then do an initial read
161 // to make sure we have a copy.
162 fs.watch(path.dirname(json_filename), reread_file);
163 reread_file(null, path.basename(json_filename));
165 var server = http.createServer();
166 server.on('request', function(request, response) {
167 var u = url.parse(request.url, true);
168 var ims = (u.query)['ims'];
169 var unique = (u.query)['unique'];
171 console.log((new Date).getTime()*1e-3 + " " + request.url);
172 if (u.pathname === '/override-num-viewers') {
173 handle_viewer_override(request, u, response);
176 if (u.pathname !== '/analysis.pl') {
177 // This is not the request you are looking for.
182 mark_recently_seen(unique);
184 var accept_encoding = request.headers['accept-encoding'];
186 if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
192 // If we already have something newer than what the user has,
193 // just send it out and be done with it.
194 if (json_last_modified !== undefined && (!ims || json_last_modified > ims)) {
195 send_json(response, accept_gzip, count_viewers());
199 // OK, so we need to hang until we have something newer.
200 // Put the user on the wait list.
202 client.response = response;
203 client.request_id = request_id;
204 client.accept_gzip = accept_gzip;
205 client.unique = unique;
206 sleeping_clients[request_id++] = client;
208 request.socket.client = client;
210 server.on('connection', function(socket) {
211 socket.on('close', function() {
212 var client = socket.client;
214 mark_recently_seen(client.unique);
215 delete sleeping_clients[client.request_id];