@@ -3,10 +3,12 @@ const noop = require('lodash/noop');
33const ChromeRemote = require ( 'chrome-remote-interface' ) ;
44const { encode } = require ( '64' ) ;
55const { Launcher } = require ( 'chrome-launcher' ) ;
6+ const { HttpStatusError } = require ( 'common-errors' ) ;
67
78const debug = require ( 'debug' ) ( 'ms-printer:chrome' ) ;
89
910const _SIGINT = 'SIGINT' ;
11+ const kStatusCheckHTML = '<html><head><title>status</title></head><body></body></html>' ;
1012
1113class Chrome {
1214 /**
@@ -30,7 +32,7 @@ class Chrome {
3032 constructor ( opts = { } ) {
3133 const {
3234 logger,
33- timeout = 10000 ,
35+ timeout = 7500 ,
3436 ...restOpts
3537 } = opts ;
3638
@@ -40,7 +42,7 @@ class Chrome {
4042 // settings
4143 this . settings = Object . assign ( {
4244 logLevel : 'info' ,
43- port : 9222 ,
45+ port : 0 , // generates random port
4446 chromeFlags : [
4547 '--window-size=1024,768' ,
4648 '--disable-gpu' ,
@@ -85,13 +87,42 @@ class Chrome {
8587 * @returns {Promise<null> }
8688 */
8789 async kill ( ) {
90+ const { launcher } = this ;
91+
8892 // kill chrome instance if has been launched
89- if ( this . launcher ) {
90- await this . launcher . kill ( ) ;
93+ if ( launcher ) {
94+ this . launcher = null ;
95+ await launcher . kill ( ) ;
9196 }
97+ }
9298
93- this . launcher = null ;
94- return null ;
99+ async status ( attempt = 0 ) {
100+ this . log . debug ( 'evaluating chrome health' ) ;
101+
102+ if ( this . launcher == null ) {
103+ throw new HttpStatusError ( 502 , 'chrome not started' ) ;
104+ }
105+
106+ try {
107+ await this . printToPdf ( kStatusCheckHTML ) ;
108+ return true ;
109+ } catch ( e ) {
110+ this . log . warn ( { err : e } , 'failed chrome status check' ) ;
111+ if ( attempt > 0 ) {
112+ throw new HttpStatusError ( 504 , `failed to open tab: ${ e . message } ` ) ;
113+ }
114+ }
115+
116+ try {
117+ this . log . warn ( 'restarting chrome due to a healthcheck error' ) ;
118+ await Promise . all ( [ this . kill ( ) , this . init ( ) ] ) ;
119+ } catch ( e ) {
120+ this . log . fatal ( { err : e } , 'failed to restart chrome' ) ;
121+ throw new HttpStatusError ( 500 , 'failed to restart chrome' ) ;
122+ }
123+
124+ // do a second attempt after restart
125+ return this . status ( 1 ) ;
95126 }
96127
97128 /**
0 commit comments