forked from Schibsted-Tech-Polska/stp.phantom-renderer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
161 lines (134 loc) · 4.82 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
var phridge = require('phridge'),
phantomPage = require('./phantom-page'),
utils = require('./utils'),
http = require('http'),
Q = require('q');
var Server = function(options) {
this.options = options || {};
this.options.port = this.options.port || 3000;
this.logger = options.logger;
this.requests = [];
this.servedPages = 0;
this.isRequestProcessed = false;
};
Server.prototype.start = function() {
this.instance = http.createServer(this.onRequest.bind(this));
this.spawnPhantom();
this.instance.listen(this.options.port, function () {
this.logger.info('Server running on port ' + this.options.port);
}.bind(this));
};
Server.prototype.spawnPhantom = function() {
var deferred = Q.defer();
this.servedPages = 0;
if(this.phantom) {
this.phantom.dispose().then(function () {
this.logger.info("Phantom process terminated");
deferred.resolve();
}.bind(this)).catch(function(error){
this.logger.error("Phantom process dispose error: " + error);
});
this.phantom = null;
}
else {
deferred.resolve();
}
return deferred.promise.then(function() {
return this.spawnPhantomProcess(3);
}.bind(this))
.then(function (phantom) {
this.logger.info('PhantomJS spawned');
return phantom.run(this.options.workerId, function(workerId){
this.workerId = workerId;
}).then(function(){
return phantom.run(phantomPage.setupResourceHandlers);
}).then(function(){
this.phantom = phantom;
}.bind(this));
}.bind(this))
.then(this.tryServePage.bind(this))
.done();
};
Server.prototype.spawnPhantomProcess = function(count) {
this.logger.info('Spawn PhantomJS process');
return phridge.spawn().catch(function(error) {
if(count > 0) {
this.logger.info('Error spawning phantom process - retry - error: ' + error);
return Q.delay(1000).then(this.spawnPhantomProcess.bind(this, count - 1));
}
else {
this.logger.error('Phantom spawn error: ' + error);
process.exit();
}
}.bind(this));
};
Server.prototype.onRequest = function(req, res) {
this.logger.info('New request url: ' + req.url + (typeof req.headers['user-agent'] !== 'undefined' ? ', user agent: ' + req.headers['user-agent'] : ''));
req.escapedFragmentUrl = utils.getEscapedFragmentUrl(req);
if(req.escapedFragmentUrl) {
req.startTime = new Date();
this.requests.push({
req: req,
res: res
});
this.logger.info('Still waiting requests: ' + (this.requests.length - 1));
this.tryServePage();
}
else {
res.writeHead(500);
res.end('Missing _escaped_fragment_ parameter');
}
};
Server.prototype.tryServePage = function() {
if(this.phantom && this.options.pageRequestsBeforeRespawn && this.servedPages && this.servedPages === this.options.pageRequestsBeforeRespawn) {
this.logger.info('Respawn PhantomJS');
this.spawnPhantom();
}
else if(this.phantom && !this.isRequestProcessed && this.requests.length) {
this.servePage();
}
};
Server.prototype.servePage = function() {
var request = this.requests.shift(),
req = request.req,
res = request.res,
params = {
url: this.options.url + req.escapedFragmentUrl,
blacklistedDomains: this.options.blacklistedDomains
};
this.isRequestProcessed = true;
req.startProcessingTime = new Date();
this.logger.info('Serving page: ' +req.url);
this.phantom.run(phantomPage.createWebPage)
.then(function() {
return this.phantom.run(params, function(options) {
this.setOptions(options);
});
}.bind(this))
.then(function() {
return this.phantom.run(phantomPage.openWebPage);
}.bind(this))
.then(function () {
return this.phantom.run(phantomPage.getPageContent);
}.bind(this))
.then(function(content){
this.isRequestProcessed = false;
if(content.indexOf('meta name="' + this.options.page404meta + '"') > -1) {
res.writeHead(404);
}
res.end(content);
this.servedPages += 1;
this.logger.info('Page (' + req.url + ') served in ' + ((new Date() - req.startTime)/1000).toFixed(3) + 's, processed in ' + ((new Date() - req.startProcessingTime)/1000).toFixed(3) + 's');
this.tryServePage();
}.bind(this))
.catch(function (err) {
this.isRequestProcessed = false;
this.servedPages += 1;
this.logger.error('Phantom server error: ' + err.message);
console.log(err.stack);
res.writeHead(500);
res.end('Error 500');
this.tryServePage();
}.bind(this));
};
module.exports = Server;