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