executor.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict'
  2. const log = require('./logger').create()
  3. class Executor {
  4. constructor (capturedBrowsers, config, emitter) {
  5. this.capturedBrowsers = capturedBrowsers
  6. this.config = config
  7. this.emitter = emitter
  8. this.executionScheduled = false
  9. this.pendingCount = 0
  10. this.runningBrowsers = null
  11. // bind all the events
  12. this.emitter.on('run_complete', () => this.onRunComplete())
  13. this.emitter.on('browser_complete', () => this.onBrowserComplete())
  14. }
  15. schedule () {
  16. const nonReady = []
  17. if (!this.capturedBrowsers.length) {
  18. log.warn('No captured browser, open %s//%s:%s%s', this.config.protocol, this.config.hostname,
  19. this.config.port, this.config.urlRoot)
  20. return false
  21. }
  22. if (this.capturedBrowsers.areAllReady(nonReady)) {
  23. log.debug('All browsers are ready, executing')
  24. log.debug('Captured %s browsers', this.capturedBrowsers.length)
  25. this.executionScheduled = false
  26. this.capturedBrowsers.clearResults()
  27. this.capturedBrowsers.setAllToExecuting()
  28. this.pendingCount = this.capturedBrowsers.length
  29. this.runningBrowsers = this.capturedBrowsers.clone()
  30. this.emitter.emit('run_start', this.runningBrowsers)
  31. this.socketIoSockets.emit('execute', this.config.client)
  32. return true
  33. }
  34. log.info('Delaying execution, these browsers are not ready: ' + nonReady.join(', '))
  35. this.executionScheduled = true
  36. return false
  37. }
  38. onRunComplete () {
  39. if (this.executionScheduled) {
  40. this.schedule()
  41. }
  42. }
  43. onBrowserComplete () {
  44. this.pendingCount--
  45. if (!this.pendingCount) {
  46. // Ensure run_complete is emitted in the next tick
  47. // so it is never emitted before browser_complete
  48. setTimeout(() => {
  49. this.emitter.emit('run_complete', this.runningBrowsers, this.runningBrowsers.getResults())
  50. }, 0)
  51. }
  52. }
  53. }
  54. Executor.factory = function (capturedBrowsers, config, emitter) {
  55. return new Executor(capturedBrowsers, config, emitter)
  56. }
  57. module.exports = Executor