]> git.sesse.net Git - remoteglot-book/blob - www/serve-analysis.js
5778dc921c99ced8bb8c82a64250f9e4d513ca5e
[remoteglot-book] / 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         for (var i in sleeping_clients) {
58                 clearTimeout(sleeping_clients[i].timer);
59                 mark_recently_seen(sleeping_clients[request_id].unique);
60                 send_json(sleeping_clients[i].response, sleeping_clients[i].accept_gzip);
61         }
62         sleeping_clients = {};
63 }
64 var send_404 = function(response) {
65         response.writeHead(404, {
66                 'Content-Type': 'text/plain',
67         });
68         response.write('Something went wrong. Sorry.');
69         response.end();
70 }
71 var send_json = function(response, accept_gzip) {
72         var headers = {
73                 'Content-Type': 'text/json',
74                 'X-Remoteglot-Last-Modified': json_last_modified,
75                 'X-Remoteglot-Num-Viewers': count_viewers(),
76                 'Access-Control-Allow-Origin': 'http://analysis.sesse.net',
77                 'Access-Control-Expose-Headers': 'X-Remoteglot-Last-Modified, X-Remoteglot-Num-Viewers',
78                 'Expires': 'Mon, 01 Jan 1970 00:00:00 UTC',
79         };
80
81         if (accept_gzip) {
82                 headers['Content-Encoding'] = 'gzip';
83                 response.writeHead(200, headers);
84                 response.write(json_contents_gz);
85         } else {
86                 response.writeHead(200, headers);
87                 response.write(json_contents);
88         }
89         response.end();
90 }
91 var timeout_client = function(client) {
92         mark_recently_seen(client.unique);
93         send_json(client.response, client.accept_gzip);
94         delete sleeping_clients[client.request_id];
95 }
96 var mark_recently_seen = function(unique) {
97         if (unique) {
98                 last_seen_clients[unique] = (new Date).getTime();
99         }
100 }
101 var count_viewers = function() {
102         var now = (new Date).getTime();
103
104         // Go through and remove old viewers, and count them at the same time.
105         var new_last_seen_clients = {};
106         var num_viewers = 0;
107         for (var unique in last_seen_clients) {
108                 if (now - last_seen_clients[unique] < 5000) {
109                         ++num_viewers;
110                         new_last_seen_clients[unique] = last_seen_clients[unique];
111                 }
112         }
113
114         // Also add sleeping clients that we would otherwise assume timed out.
115         for (var request_id in sleeping_clients) {
116                 var unique = sleeping_clients[request_id].unique;
117                 if (unique && !(unique in new_last_seen_clients)) {
118                         ++num_viewers;
119                 }
120         }
121
122         last_seen_clients = new_last_seen_clients;
123         return num_viewers;
124 }
125
126 // Set up a watcher to catch changes to the file, then do an initial read
127 // to make sure we have a copy.
128 fs.watch(path.dirname(json_filename), reread_file);
129 reread_file(null, path.basename(json_filename));
130
131 http.createServer(function(request, response) {
132         var u = url.parse(request.url, true);
133         var ims = (u.query)['ims'];
134         var unique = (u.query)['unique'];
135
136         console.log((new Date).getTime()*1e-3 + " " + request.url);
137
138         if (u.pathname !== '/analysis.pl') {
139                 // This is not the request you are looking for.
140                 send_404(response);
141                 return;
142         }
143
144         mark_recently_seen(unique);
145
146         var accept_encoding = request.headers['accept-encoding'];
147         var accept_gzip;
148         if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
149                 accept_gzip = true;
150         } else {
151                 accept_gzip = false;
152         }
153
154         // If we already have something newer than what the user has,
155         // just send it out and be done with it.
156         if (json_last_modified !== undefined && (!ims || json_last_modified > ims)) {
157                 send_json(response, accept_gzip);
158                 return;
159         }
160
161         // OK, so we need to hang until we have something newer.
162         // Put the user on the wait list; if we don't get anything
163         // in 30 seconds, though, we'll send something anyway.
164         var client = {};
165         client.response = response;
166         client.timer = setTimeout(function() { timeout_client(client); }, 30000);
167         client.request_id = request_id;
168         client.accept_gzip = accept_gzip;
169         client.unique = unique;
170         sleeping_clients[request_id++] = client;
171 }).listen(5000);