Solve timeouts by touching analysis.json.
[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
12 // Constants.
13 var json_filename = '/srv/analysis.sesse.net/www/analysis.json';
14
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;
19
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 = {};
24 var request_id = 0;
25
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 = {};
29
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;
34
35 var reread_file = function(event, filename) {
36         if (filename != path.basename(json_filename)) {
37                 return;
38         }
39         console.log("Rereading " + json_filename);
40         fs.open(json_filename, 'r+', function(err, fd) {
41                 if (err) throw err;
42                 fs.fstat(fd, function(err, st) {
43                         if (err) throw err;
44                         var buffer = new Buffer(1048576);
45                         fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
46                                 if (err) throw err;
47                                 fs.close(fd, function() {
48                                         var new_json_contents = buffer.toString('utf8', 0, bytesRead);
49                                         zlib.gzip(new_json_contents, function(err, buffer) {
50                                                 if (err) throw err;
51                                                 json_contents = new_json_contents;
52                                                 json_contents_gz = buffer;
53                                                 json_last_modified = st.mtime.getTime();
54                                                 possibly_wakeup_clients();
55                                         });
56                                 });
57                         });
58                 });
59         });
60
61         if (touch_timer !== undefined) {
62                 clearTimeout(touch_timer);
63         }
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);
68         }, 30000);
69 }
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,
76                           num_viewers);
77         }
78         sleeping_clients = {};
79 }
80 var send_404 = function(response) {
81         response.writeHead(404, {
82                 'Content-Type': 'text/plain',
83         });
84         response.write('Something went wrong. Sorry.');
85         response.end();
86 }
87 var send_json = function(response, accept_gzip, num_viewers) {
88         var headers = {
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',
95         };
96
97         if (accept_gzip) {
98                 headers['Content-Encoding'] = 'gzip';
99                 response.writeHead(200, headers);
100                 response.write(json_contents_gz);
101         } else {
102                 response.writeHead(200, headers);
103                 response.write(json_contents);
104         }
105         response.end();
106 }
107 var mark_recently_seen = function(unique) {
108         if (unique) {
109                 last_seen_clients[unique] = (new Date).getTime();
110         }
111 }
112 var count_viewers = function() {
113         var now = (new Date).getTime();
114
115         // Go through and remove old viewers, and count them at the same time.
116         var new_last_seen_clients = {};
117         var num_viewers = 0;
118         for (var unique in last_seen_clients) {
119                 if (now - last_seen_clients[unique] < 5000) {
120                         ++num_viewers;
121                         new_last_seen_clients[unique] = last_seen_clients[unique];
122                 }
123         }
124
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)) {
129                         ++num_viewers;
130                 }
131         }
132
133         last_seen_clients = new_last_seen_clients;
134         return num_viewers;
135 }
136
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));
141
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'];
147
148         console.log((new Date).getTime()*1e-3 + " " + request.url);
149
150         if (u.pathname !== '/analysis.pl') {
151                 // This is not the request you are looking for.
152                 send_404(response);
153                 return;
154         }
155
156         mark_recently_seen(unique);
157
158         var accept_encoding = request.headers['accept-encoding'];
159         var accept_gzip;
160         if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
161                 accept_gzip = true;
162         } else {
163                 accept_gzip = false;
164         }
165
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());
170                 return;
171         }
172
173         // OK, so we need to hang until we have something newer.
174         // Put the user on the wait list.
175         var client = {};
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;
181
182         request.socket.client = client;
183 });
184 server.on('connection', function(socket) {
185         socket.on('close', function() {
186                 var client = socket.client;
187                 if (client) {
188                         mark_recently_seen(client.unique);
189                         delete sleeping_clients[client.request_id];
190                 }
191         });
192 });
193 server.listen(5000);