Sort lines by score by default.
[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
11 // Constants.
12 var json_filename = '/srv/analysis.sesse.net/www/analysis.json';
13
14 // The current contents of the file to hand out, and its last modified time.
15 var json_contents = undefined;
16 var json_last_modified = undefined;
17
18 // The list of clients that are waiting for new data to show up,
19 // and their associated timers. Uniquely keyed by request_id
20 // so that we can take them out of the queue if they time out.
21 var sleeping_clients = {};
22 var request_id = 0;
23
24 // List of when clients were last seen, keyed by their unique ID.
25 // Used to show a viewer count to the user.
26 var last_seen_clients = {};
27
28 var reread_file = function(event, filename) {
29         if (filename != path.basename(json_filename)) {
30                 return;
31         }
32         console.log("Rereading " + json_filename);
33         fs.open(json_filename, 'r+', function(err, fd) {
34                 if (err) throw err;
35                 fs.fstat(fd, function(err, st) {
36                         if (err) throw err;
37                         var buffer = new Buffer(1048576);
38                         fs.read(fd, buffer, 0, 1048576, 0, function(err, bytesRead, buffer) {
39                                 if (err) throw err;
40                                 fs.close(fd, function() {
41                                         json_contents = buffer.toString('utf8', 0, bytesRead);
42                                         json_last_modified = st.mtime.getTime();
43                                         possibly_wakeup_clients();
44                                 });
45                         });
46                 });
47         });
48 }
49 var possibly_wakeup_clients = function() {
50         for (var i in sleeping_clients) {
51                 clearTimeout(sleeping_clients[i].timer);
52                 send_json(sleeping_clients[i].response);
53         }
54         sleeping_clients = {};
55 }
56 var send_404 = function(response) {
57         response.writeHead(404, {
58                 'Content-Type': 'text/plain',
59         });
60         response.write('Something went wrong. Sorry.');
61         response.end();
62 }
63 var send_json = function(response) {
64         response.writeHead(200, {
65                 'Content-Type': 'text/json',
66                 'X-Remoteglot-Last-Modified': json_last_modified,
67                 'X-Remoteglot-Num-Viewers': count_viewers(),
68                 'Access-Control-Allow-Origin': 'http://analysis.sesse.net',
69                 'Access-Control-Expose-Headers': 'X-Remoteglot-Last-Modified, X-Remoteglot-Num-Viewers',
70                 'Expires': 'Mon, 01 Jan 1970 00:00:00 UTC',
71         });
72         response.write(json_contents);
73         response.end();
74 }
75 var timeout_client = function(client) {
76         send_json(client.response);
77         delete sleeping_clients[client.request_id];
78 }
79 var count_viewers = function() {
80         var now = (new Date).getTime();
81
82         // Go through and remove old viewers, and count them at the same time.
83         var new_last_seen_clients = {};
84         var num_viewers = 0;
85         for (var unique in last_seen_clients) {
86                 if (now - last_seen_clients[unique] < 60000) {
87                         ++num_viewers;
88                         new_last_seen_clients[unique] = last_seen_clients[unique];
89                 }
90         }
91         last_seen_clients = new_last_seen_clients;
92         return num_viewers;
93 }
94
95 // Set up a watcher to catch changes to the file, then do an initial read
96 // to make sure we have a copy.
97 fs.watch(path.dirname(json_filename), reread_file);
98 reread_file(null, path.basename(json_filename));
99
100 http.createServer(function(request, response) {
101         var u = url.parse(request.url, true);
102         var ims = (u.query)['ims'];
103         var unique = (u.query)['unique'];
104
105         console.log((new Date).getTime()*1e-3 + " " + request.url);
106
107         if (u.pathname !== '/analysis.pl') {
108                 // This is not the request you are looking for.
109                 send_404(response);
110                 return;
111         }
112
113         if (unique) {
114                 last_seen_clients[unique] = (new Date).getTime();
115         }
116
117         // If we already have something newer than what the user has,
118         // just send it out and be done with it.
119         if (json_last_modified !== undefined && (!ims || json_last_modified > ims)) {
120                 send_json(response);
121                 return;
122         }
123
124         // OK, so we need to hang until we have something newer.
125         // Put the user on the wait list; if we don't get anything
126         // in 30 seconds, though, we'll send something anyway.
127         var client = {};
128         client.response = response;
129         client.timer = setTimeout(function() { timeout_client(client); }, 30000);
130         client.request_id = request_id;
131         sleeping_clients[request_id++] = client;
132 }).listen(5000);