]> git.sesse.net Git - remoteglot/blob - www/serve-analysis.js
Clean up the minification stuff a bit; still not really in use.
[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 // 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;
38
39 var reread_file = function(event, filename) {
40         if (filename != path.basename(json_filename)) {
41                 return;
42         }
43         console.log("Rereading " + json_filename);
44         fs.open(json_filename, 'r+', function(err, fd) {
45                 if (err) throw err;
46                 fs.fstat(fd, function(err, st) {
47                         if (err) throw err;
48                         var buffer = new Buffer(1048576);
49                         fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
50                                 if (err) throw err;
51                                 fs.close(fd, function() {
52                                         var new_json_contents = buffer.toString('utf8', 0, bytesRead);
53                                         zlib.gzip(new_json_contents, function(err, buffer) {
54                                                 if (err) throw err;
55                                                 json_contents = new_json_contents;
56                                                 json_contents_gz = buffer;
57                                                 json_last_modified = st.mtime.getTime();
58                                                 possibly_wakeup_clients();
59                                         });
60                                 });
61                         });
62                 });
63         });
64
65         if (touch_timer !== undefined) {
66                 clearTimeout(touch_timer);
67         }
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);
72         }, 30000);
73 }
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,
80                           num_viewers);
81         }
82         sleeping_clients = {};
83 }
84 var send_404 = function(response) {
85         response.writeHead(404, {
86                 'Content-Type': 'text/plain',
87         });
88         response.write('Something went wrong. Sorry.');
89         response.end();
90 }
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);
96                 send_404(response);
97         } else {
98                 viewer_count_override = (u.query)['num'];
99                 response.writeHead(200, {
100                         'Content-Type': 'text/plain',
101                 });
102                 response.write('OK.');
103                 response.end();
104         }
105 }
106 var send_json = function(response, accept_gzip, num_viewers) {
107         var headers = {
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',
114         };
115
116         if (accept_gzip) {
117                 headers['Content-Encoding'] = 'gzip';
118                 response.writeHead(200, headers);
119                 response.write(json_contents_gz);
120         } else {
121                 response.writeHead(200, headers);
122                 response.write(json_contents);
123         }
124         response.end();
125 }
126 var mark_recently_seen = function(unique) {
127         if (unique) {
128                 last_seen_clients[unique] = (new Date).getTime();
129         }
130 }
131 var count_viewers = function() {
132         if (viewer_count_override !== undefined) {
133                 return viewer_count_override;
134         }
135
136         var now = (new Date).getTime();
137
138         // Go through and remove old viewers, and count them at the same time.
139         var new_last_seen_clients = {};
140         var num_viewers = 0;
141         for (var unique in last_seen_clients) {
142                 if (now - last_seen_clients[unique] < 5000) {
143                         ++num_viewers;
144                         new_last_seen_clients[unique] = last_seen_clients[unique];
145                 }
146         }
147
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)) {
152                         ++num_viewers;
153                 }
154         }
155
156         last_seen_clients = new_last_seen_clients;
157         return num_viewers;
158 }
159
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));
164
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'];
170
171         console.log((new Date).getTime()*1e-3 + " " + request.url);
172         if (u.pathname === '/override-num-viewers') {
173                 handle_viewer_override(request, u, response);
174                 return;
175         }
176         if (u.pathname !== '/analysis.pl') {
177                 // This is not the request you are looking for.
178                 send_404(response);
179                 return;
180         }
181
182         mark_recently_seen(unique);
183
184         var accept_encoding = request.headers['accept-encoding'];
185         var accept_gzip;
186         if (accept_encoding !== undefined && accept_encoding.match(/\bgzip\b/)) {
187                 accept_gzip = true;
188         } else {
189                 accept_gzip = false;
190         }
191
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());
196                 return;
197         }
198
199         // OK, so we need to hang until we have something newer.
200         // Put the user on the wait list.
201         var client = {};
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;
207
208         request.socket.client = client;
209 });
210 server.on('connection', function(socket) {
211         socket.on('close', function() {
212                 var client = socket.client;
213                 if (client) {
214                         mark_recently_seen(client.unique);
215                         delete sleeping_clients[client.request_id];
216                 }
217         });
218 });
219 server.listen(5000);