forked from sdjcw/leanengine-sniper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
98 lines (74 loc) · 2.57 KB
/
server.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
'use strict';
var basicAuth = require('basic-auth');
var express = require('express');
var Redis = require('ioredis');
var http = require('http');
var _ = require('underscore');
var utils = require('./public/utils');
module.exports = function(AV, options) {
var Storage = AV.Object.extend(options.className);
var router = new express.Router();
var authenticate = function(req, res, next) {
var credentials = basicAuth(req);
if (credentials && credentials.name == AV.applicationId && credentials.pass == AV.masterKey) {
next();
} else {
res.header('WWW-Authenticate', 'Basic');
res.status(401).json({
code: 401, error: "Unauthorized."
});
}
};
router.use('/__lcSniper', authenticate, express.static(__dirname + '/public'));
router.get('/__lcSniper/logs.json', authenticate, function (req, res) {
var query = new AV.Query(Storage);
var from = new Date(req.query.logsFrom);
var to = new Date(req.query.logsTo);
if (isNaN(from.valueOf()))
from = new Date(Date.now() - 24 * 3600 * 1000);
query.greaterThan('createdAt', from);
if (!isNaN(to.valueOf()))
query.lessThan('createdAt', to);
query.descending('createdAt').limit(1000).find().then(function(data) {
res.json(data);
});
});
router.get('/__lcSniper/realtime.json', authenticate, function(req, res) {
if (!options.redis) {
return res.send('Need Redis, see the README.md of leanengine-sniper');
}
try {
var subscriber = new Redis(options.redis);
var pushQueue = [];
var intervalId = setInterval(function() {
var log = utils.mergeBuckets(pushQueue.map(function(instanceBucket) {
return {instances: [instanceBucket]};
}), true);
log.createdAt = new Date();
pushQueue = [];
res.write('id: ' + _.uniqueId() + '\n');
res.write('data: ' + JSON.stringify(log) + '\n\n');
}, options.realtimeCycle);
subscriber.subscribe('__lcSniper:realtime', function(err) {
if (err) console.log(err);
});
subscriber.on('message', function(channel, message) {
pushQueue.push(JSON.parse(message));
});
req.socket.setTimeout(3600000);
req.on('close', function() {
subscriber.quit();
clearInterval(intervalId);
});
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.write('\n');
} catch (err) {
console.error(err.stack ? err.stack : err);
}
});
return router;
};