-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.js
104 lines (81 loc) · 2.34 KB
/
webserver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
var union = require('union');
var director = require('director');
var RingBuffer = require('./ringbuffer');
var ringBuffers = require('./ringbuffers');
var CompositeRingBuffer = require('./session');
var uuid = require('node-uuid');
module.exports.createServer= function(options) {
return new LogplexWebServer(options);
};
function LogplexWebServer(options) {
var self = this;
self.start = function() {
var router = new director.http.Router();
self.webServer = union.createServer({
before: [
function (req, res) {
var found = router.dispatch(req, res);
if (!found) {
res.emit('next');
}
}
]
});
setupRoutes(router);
self.webServer.listen(options.port);
};
self.stop = function() {
self.webServer.close();
};
}
var sessions = [];
function setupRoutes(router) {
router.post("/sessions", function () {
var body = this.req.body;
var id = uuid.v4();
console.dir(body);
var session = new CompositeRingBuffer(body);
sessions[id] = session;
this.res.write(JSON.stringify({ id: id }));
this.res.end();
});
// TODO: handle no tail, length and ps/source filtering
router.get("/sessions/:sessionId", { stream: true }, function (sessionId) {
var req = this.req, res = this.res;
var session = sessions[sessionId];
res.writeHead(200, { 'Content-Type': 'text/plain' });
var snapshot = session.getAll();
var formatItem = function(item) {
var tsDate = new Date();
tsDate.setTime(item.ts);
return tsDate.toISOString() + ' ' + item.channel + '[' + item.source + ']: ' + item.msg;
};
snapshot.forEach(function(item) {
if(item) res.write(formatItem(item));
});
var produce = true;
res.on('pause', function() {
produce = false;
});
res.on('resume', function() {
produce = true;
});
var writeAdded = function(item) {
if(produce) {
res.write(formatItem(item));
}
};
res.response.socket.on('end', function() {
produce = false;
session.removeListener('added', writeAdded);
console.log('Client disconnected');
});
session.on('added', writeAdded);
res.on('close', function() {
console.log('ended');
});
res.on('end', function() {
console.log('ended');
});
});
}