]> git.sesse.net Git - remoteglot/blob - www/serve-analysis.js
4f0d2f010376df9748333a58a985c0fbbf1bcd21
[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 // and their associated timers. Uniquely keyed by request_id
22 // so that we can take them out of the queue if they time out.
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 var reread_file = function(event, filename) {
31         if (filename != path.basename(json_filename)) {
32                 return;
33         }
34         console.log("Rereading " + json_filename);
35         fs.open(json_filename, 'r+', function(err, fd) {
36                 if (err) throw err;
37                 fs.fstat(fd, function(err, st) {
38                         if (err) throw err;
39                         var buffer = new Buffer(1048576);
40                         fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
41                                 if (err) throw err;
42                                 fs.close(fd, function() {
43                                         var new_json_contents = buffer.toString('utf8', 0, bytesRead);
44                                         zlib.gzip(new_json_contents, function(err, buffer) {
45                                                 if (err) throw err;
46                                                 json_contents = new_json_contents;
47                                                 json_contents_gz = buffer;
48                                                 json_last_modified = st.mtime.getTime();
49                                                 possibly_wakeup_clients();
50                                         });
51                                 });
52                         });
53                 });
54         });
55 }
56 var possibly_wakeup_clients = function() {
57         var num_viewers = count_viewers();
58         for (var i in sleeping_clients) {
59                 clearTimeout(sleeping_clients[i].timer);
60                 mark_recently_seen(sleeping_clients[i].unique);
61                 send_json(sleeping_clients[i].response,
62                           sleeping_clients[i].accept_gzip,
63                           num_viewers);
64         }
65         sleeping_clients = {};
66 }
67 var send_404 = function(response) {
68         response.writeHead(404, {
69                 'Content-Type': 'text/plain',
70         });
71         response.write('Something went wrong. Sorry.');
72         response.end();
73 }
74 var send_json = function(response, accept_gzip, num_viewers) {
75         var headers = {
76                 'Content-Type': 'text/json',
77                 'X-Remoteglot-Last-Modified': json_last_modified,
78                 'X-Remoteglot-Num-Viewers': num_viewers,
79                 'Access-Control-Allow-Origin': 'http://analysis.sesse.net',
80                 'Access-Control-Expose-Headers': 'X-Remoteglot-Last-Modified, X-Remoteglot-Num-Viewers',
81                 'Expires': 'Mon, 01 Jan 1970 00:00:00 UTC',
82         };
83
84         if (accept_gzip) {
85                 headers['Content-Encoding'] = 'gzip';
86                 response.writeHead(200, headers);
87                 response.write(json_contents_gz);
88         } else {
89                 response.writeHead(200, headers);
90                 response.write(json_contents);
91         }
92         response.end();
93 }
94 var timeout_client = function(client) {
95         mark_recently_seen(client.unique);
96         send_json(client.response, client.accept_gzip, count_viewers());
97         delete sleeping_clients[client.request_id];
98 }
99 var mark_recently_seen = function(unique) {
100         if (unique) {
101                 last_seen_clients[unique] = (new Date).getTime();
102         }
103 }
104 var count_viewers = function() {
105         var now = (new Date).getTime();
106
107         // Go through and remove old viewers, and count them at the same time.
108         var new_last_seen_clients = {};
109         var num_viewers = 0;
110         for (var unique in last_seen_clients) {
111                 if (now - last_seen_clients[unique] < 5000) {
112                         ++num_viewers;
113                         new_last_seen_clients[unique] = last_seen_clients[unique];
114                 }
115         }
116
117         // Also add sleeping clients that we would otherwise assume timed out.
118         for (var request_id in sleeping_clients) {
119                 var unique = sleeping_clients[request_id].unique;
120                 if (unique && !(unique in new_last_seen_clients)) {
121                         ++num_viewers;
122                 }
123         }
124
125         last_seen_clients = new_last_seen_clients;
126         return num_viewers;
127 }
128
129 // Set up a watcher to catch changes to the file, then do an initial read
130 // to make sure we have a copy.
131 fs.watch(path.dirname(json_filename), reread_file);
132 reread_file(null, path.basename(json_filename));
133
134 var server = http.createServer();
135 server.on('request', function(request, response) {
136         var u = url.parse(request.url, true);
137         var ims = (u.query)['ims'];
138         var unique = (u.query)['unique'];
139
140         console.log((new Date).getTime()*1e-3 + " " + request.url);
141
142         if (u.pathname !== '/analysis.pl') {
143                 // This is not the request you are looking for.
144                 send_404(response);
145                 return;
146         }
147
148         mark_recently_seen(unique);
149
150         var accept_encoding = request.headers['accept-encoding'];
151         var accept_gzip;
152         if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
153                 accept_gzip = true;
154         } else {
155                 accept_gzip = false;
156         }
157
158         // If we already have something newer than what the user has,
159         // just send it out and be done with it.
160         if (json_last_modified !== undefined && (!ims || json_last_modified > ims)) {
161                 send_json(response, accept_gzip, count_viewers());
162                 return;
163         }
164
165         // OK, so we need to hang until we have something newer.
166         // Put the user on the wait list; if we don't get anything
167         // in 30 seconds, though, we'll send something anyway.
168         var client = {};
169         client.response = response;
170         client.timer = setTimeout(function() { timeout_client(client); }, 30000);
171         client.request_id = request_id;
172         client.accept_gzip = accept_gzip;
173         client.unique = unique;
174         sleeping_clients[request_id++] = client;
175
176         request.socket.client = client;
177 });
178 server.on('connection', function(socket) {
179         socket.on('close', function() {
180                 var client = socket.client;
181                 if (client) {
182                         mark_recently_seen(client.unique);
183                         delete sleeping_clients[client.request_id];
184                 }
185         });
186 });
187 server.listen(5000);