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 var reread_file = function(event, filename) {
36 if (filename != path.basename(json_filename)) {
39 console.log("Rereading " + json_filename);
40 fs.open(json_filename, 'r+', function(err, fd) {
42 fs.fstat(fd, function(err, st) {
44 var buffer = new Buffer(1048576);
45 fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
47 fs.close(fd, function() {
48 var new_json_contents = buffer.toString('utf8', 0, bytesRead);
49 zlib.gzip(new_json_contents, function(err, buffer) {
51 json_contents = new_json_contents;
52 json_contents_gz = buffer;
53 json_last_modified = st.mtime.getTime();
54 possibly_wakeup_clients();
61 if (touch_timer !== undefined) {
62 clearTimeout(touch_timer);
64 touch_timer = setTimeout(function() {
65 console.log("Touching analysis.json due to no other activity");
66 var now = Date.now() / 1000;
67 fs.utimes(json_filename, now, now);
70 var possibly_wakeup_clients = function() {
71 var num_viewers = count_viewers();
72 for (var i in sleeping_clients) {
73 mark_recently_seen(sleeping_clients[i].unique);
74 send_json(sleeping_clients[i].response,
75 sleeping_clients[i].accept_gzip,
78 sleeping_clients = {};
80 var send_404 = function(response) {
81 response.writeHead(404, {
82 'Content-Type': 'text/plain',
84 response.write('Something went wrong. Sorry.');
87 var send_json = function(response, accept_gzip, num_viewers) {
89 'Content-Type': 'text/json',
90 'X-Remoteglot-Last-Modified': json_last_modified,
91 'X-Remoteglot-Num-Viewers': num_viewers,
92 'Access-Control-Allow-Origin': 'http://analysis.sesse.net',
93 'Access-Control-Expose-Headers': 'X-Remoteglot-Last-Modified, X-Remoteglot-Num-Viewers',
94 'Expires': 'Mon, 01 Jan 1970 00:00:00 UTC',
98 headers['Content-Encoding'] = 'gzip';
99 response.writeHead(200, headers);
100 response.write(json_contents_gz);
102 response.writeHead(200, headers);
103 response.write(json_contents);
107 var mark_recently_seen = function(unique) {
109 last_seen_clients[unique] = (new Date).getTime();
112 var count_viewers = function() {
113 var now = (new Date).getTime();
115 // Go through and remove old viewers, and count them at the same time.
116 var new_last_seen_clients = {};
118 for (var unique in last_seen_clients) {
119 if (now - last_seen_clients[unique] < 5000) {
121 new_last_seen_clients[unique] = last_seen_clients[unique];
125 // Also add sleeping clients that we would otherwise assume timed out.
126 for (var request_id in sleeping_clients) {
127 var unique = sleeping_clients[request_id].unique;
128 if (unique && !(unique in new_last_seen_clients)) {
133 last_seen_clients = new_last_seen_clients;
137 // Set up a watcher to catch changes to the file, then do an initial read
138 // to make sure we have a copy.
139 fs.watch(path.dirname(json_filename), reread_file);
140 reread_file(null, path.basename(json_filename));
142 var server = http.createServer();
143 server.on('request', function(request, response) {
144 var u = url.parse(request.url, true);
145 var ims = (u.query)['ims'];
146 var unique = (u.query)['unique'];
148 console.log((new Date).getTime()*1e-3 + " " + request.url);
150 if (u.pathname !== '/analysis.pl') {
151 // This is not the request you are looking for.
156 mark_recently_seen(unique);
158 var accept_encoding = request.headers['accept-encoding'];
160 if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
166 // If we already have something newer than what the user has,
167 // just send it out and be done with it.
168 if (json_last_modified !== undefined && (!ims || json_last_modified > ims)) {
169 send_json(response, accept_gzip, count_viewers());
173 // OK, so we need to hang until we have something newer.
174 // Put the user on the wait list.
176 client.response = response;
177 client.request_id = request_id;
178 client.accept_gzip = accept_gzip;
179 client.unique = unique;
180 sleeping_clients[request_id++] = client;
182 request.socket.client = client;
184 server.on('connection', function(socket) {
185 socket.on('close', function() {
186 var client = socket.client;
188 mark_recently_seen(client.unique);
189 delete sleeping_clients[client.request_id];