Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1 +1,10 @@
module.exports = require('./lib');
const server = require('./lib');
/**
* We are starting the server here now, since SDK consumers (if any) used to receive
* an already listening server instance in the past, and we changed that in server.js.
*
* So starting it here will keep the API backwards compatible.
*/
server.start();

module.exports = server;
6 changes: 5 additions & 1 deletion lib/browsers/chrome.js
Original file line number Diff line number Diff line change
Expand Up @@ -366,6 +366,8 @@ chrome.loadUrlThenWaitForPageLoadEvent = function(tab, url) {
return new Promise((resolve, reject) => {
tab.prerender.url = url;

let pageLoadTimer;

var finished = false;
const {
Page,
Expand Down Expand Up @@ -413,7 +415,7 @@ chrome.loadUrlThenWaitForPageLoadEvent = function(tab, url) {
});
};

setTimeout(() => {
pageLoadTimer = setTimeout(() => {
if (!finished) {
finished = true;
util.log('page timed out', tab.prerender.url);
Expand Down Expand Up @@ -452,6 +454,8 @@ chrome.loadUrlThenWaitForPageLoadEvent = function(tab, url) {
tab.prerender.statusCode = 504;
finished = true;
reject();
}).finally(() => {
clearTimeout(pageLoadTimer);
});
});
};
Expand Down
23 changes: 2 additions & 21 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,12 @@
const fs = require('fs');
const path = require('path');
const http = require('http');
const util = require('./util');
const basename = path.basename;
const server = require('./server');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const compression = require('compression');

exports = module.exports = (options = {}) => {
const parsedOptions = Object.assign({}, {
port: options.port || process.env.PORT || 3000
}, options)
const basename = path.basename;

exports = module.exports = (options = {}) => {
server.init(options);
server.onRequest = server.onRequest.bind(server);

app.disable('x-powered-by');
app.use(compression());

app.get('*', server.onRequest);

//dont check content-type and just always try to parse body as json
app.post('*', bodyParser.json({ type: () => true }), server.onRequest);

app.listen(parsedOptions, () => util.log(`Prerender server accepting requests on port ${parsedOptions.port}`))

return server;
};
Expand Down
81 changes: 65 additions & 16 deletions lib/server.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
const bodyParser = require('body-parser');
const compression = require('compression');
const express = require('express');
const util = require('./util.js');
const zlib = require('zlib');
const validUrl = require('valid-url');
Expand Down Expand Up @@ -25,7 +28,7 @@ const server = exports = module.exports = {};


server.init = function(options) {
this.plugins = this.plugins || [];
this.plugins = [];
this.options = options || {};

this.options.waitAfterLastRequest = this.options.waitAfterLastRequest || WAIT_AFTER_LAST_REQUEST;
Expand All @@ -37,9 +40,36 @@ server.init = function(options) {
this.options.pdfOptions = this.options.pdfOptions || {
printBackground: true
};
this.isBrowserClosing = false;

process.on('SIGINT', () => {
this.stop().then(() => {
util.log('Prerender stopped');
});
});

this.expressOptions = {
...options,
port: this.options.port || process.env.PORT || 3000
};

this.browser = require('./browsers/chrome');

this.onRequest = this.onRequest.bind(this);

this.app = express();
this.app.disable('x-powered-by');
this.app.use(compression());

this.app.on('error', (error) => {
console.log('Error', error);
});

this.app.get('*', this.onRequest);

//dont check content-type and just always try to parse body as json
this.app.post('*', bodyParser.json({ type: () => true }), this.onRequest);

return this;
};

Expand All @@ -48,23 +78,36 @@ server.init = function(options) {
server.start = function() {
util.log('Starting Prerender');
this.isBrowserConnected = false;
this.startPrerender().then(() => {

process.on('SIGINT', () => {
this.killBrowser();
setTimeout(() => {
util.log('Stopping Prerender');
process.exit();
}, 500);
return new Promise((resolve, reject) => {
this.appServerReference = this.app.listen(this.expressOptions, () => {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do like this better for being able to start/stop for tests, but since the lib/index.js used to call app.listen and then server.start() would actually start the Chrome server, does that make this a breaking change requiring a major version bump? I'd argue no one would actually include lib/index.js without calling server.start() since that would have been useless, but just a thought.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a very good point, thanks! Actually we can still keep it backwards compatible, if i'm not mistaken. The lib/index.js is not an entry point of the app, so it may be good as is now. However the ./index.js is a de-facto entry point, where I added the server.start() invocation now. And the server.js still does what we need, if I didn't mess it up :)

What do you think?

util.log(`Prerender server is running on port ${this.expressOptions.port}`);

server.address = util.getServerAddress(this.appServerReference.address());

this.startPrerender().then(() => {
util.log('Prerender started');
resolve();
}, () => {
this.stop().then(resolve, reject);
});
});

}).catch(() => {
if(process.exit) {
process.exit();
}
});
};

server.stop = function() {
return new Promise(resolve => {
util.log('Stopping Prerender');

this.killBrowser();

this.appServerReference && this.appServerReference.close(() => {
// We give Chrome a bit more time to actually stop
setTimeout(resolve, 2000);
})
});
}



server.startPrerender = function() {
Expand Down Expand Up @@ -139,7 +182,11 @@ server.listenForBrowserClose = function() {
return process.exit();
}

this.startPrerender();
this.startPrerender().then(() => {
util.log('Prerender restarted');
}, () => {
this.killBrowser();
});
});
};

Expand Down Expand Up @@ -186,7 +233,7 @@ server.use = function(plugin) {


server.onRequest = function(req, res) {

let safetyLoadTimer;
req.prerender = util.getOptions(req);
req.prerender.start = new Date();
req.prerender.responseSent = false;
Expand All @@ -212,7 +259,7 @@ server.onRequest = function(req, res) {
req.prerender.browserRequestIsInFlight = true;

//if there is a case where a page hangs, this will at least let us restart chrome
setTimeout(() => {
safetyLoadTimer = setTimeout(() => {
if (!req.prerender.responseSent) {
util.log('response not sent for', req.prerender.url);
req.prerender.browserRequestIsInFlight = false;
Expand Down Expand Up @@ -270,6 +317,8 @@ server.onRequest = function(req, res) {
}).catch((err) => {
if (err) util.log(err);
this.finish(req, res);
}).finally(() => {
clearTimeout(safetyLoadTimer);
});
};

Expand Down
11 changes: 10 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,13 @@ util.log = function() {
}

console.log.apply(console.log, [new Date().toISOString()].concat(Array.prototype.slice.call(arguments, 0)));
};
};

/**
* Constructs a server address from the return object of the node net.Server#address() API.
*/
util.getServerAddress = function(serverAddressInfo) {
const { address, family, port } = serverAddressInfo;

return `http://${family === 'IPv6' ? `[${address}]` : address}:${port}`;
}
Loading