executor.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. this.emitter.on('run_complete', () => this.onRunComplete())
  12. this.emitter.on('browser_complete', () => this.onBrowserComplete())
  13. }
  14. schedule () {
  15. if (this.capturedBrowsers.length === 0) {
  16. log.warn(`No captured browser, open ${this.config.protocol}//${this.config.hostname}:${this.config.port}${this.config.urlRoot}`)
  17. return false
  18. } else if (this.capturedBrowsers.areAllReady()) {
  19. log.debug('All browsers are ready, executing')
  20. log.debug(`Captured ${this.capturedBrowsers.length} browsers`)
  21. this.executionScheduled = false
  22. this.capturedBrowsers.clearResults()
  23. this.pendingCount = this.capturedBrowsers.length
  24. this.runningBrowsers = this.capturedBrowsers.clone()
  25. this.emitter.emit('run_start', this.runningBrowsers)
  26. this.socketIoSockets.emit('execute', this.config.client)
  27. return true
  28. } else {
  29. log.info('Delaying execution, these browsers are not ready: ' + this.capturedBrowsers.getNonReady().join(', '))
  30. this.executionScheduled = true
  31. return false
  32. }
  33. }
  34. onRunComplete () {
  35. if (this.executionScheduled) {
  36. this.schedule()
  37. }
  38. }
  39. onBrowserComplete () {
  40. this.pendingCount--
  41. if (!this.pendingCount) {
  42. // Ensure run_complete is emitted in the next tick
  43. // so it is never emitted before browser_complete
  44. setTimeout(() => {
  45. this.emitter.emit('run_complete', this.runningBrowsers, this.runningBrowsers.getResults())
  46. })
  47. }
  48. }
  49. }
  50. Executor.factory = function (capturedBrowsers, config, emitter) {
  51. return new Executor(capturedBrowsers, config, emitter)
  52. }
  53. module.exports = Executor