runsQueue.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. var Q = require('q');
  2. var debug = require('debug')('ylt:runsQueue');
  3. function RunsQueue() {
  4. 'use strict';
  5. var queue = [];
  6. var lastTestTimestamp = 0;
  7. this.push = function(runId) {
  8. var deferred = Q.defer();
  9. var startingPosition = queue.length;
  10. debug('Adding run %s to the queue, position is %d', runId, startingPosition);
  11. if (startingPosition === 0) {
  12. // The queue is empty, let's run immediatly
  13. queue.push({
  14. runId: runId
  15. });
  16. lastTestTimestamp = Date.now();
  17. deferred.resolve();
  18. } else {
  19. queue.push({
  20. runId: runId,
  21. positionChangedCallback: function(position) {
  22. deferred.notify(position);
  23. },
  24. itIsTimeCallback: function() {
  25. lastTestTimestamp = Date.now();
  26. deferred.resolve();
  27. }
  28. });
  29. }
  30. var promise = deferred.promise;
  31. promise.startingPosition = startingPosition;
  32. return promise;
  33. };
  34. this.getPosition = function(runId) {
  35. // Position 0 means it's a work in progress (a run is removed AFTER it is finished, not before)
  36. var position = -1;
  37. queue.some(function(run, index) {
  38. if (run.runId === runId) {
  39. position = index;
  40. return true;
  41. }
  42. return false;
  43. });
  44. return position;
  45. };
  46. this.remove = function(runId) {
  47. var position = this.getPosition(runId);
  48. if (position >= 0) {
  49. queue.splice(position, 1);
  50. }
  51. // Update other runs' positions
  52. queue.forEach(function(run, index) {
  53. if (index === 0 && run.itIsTimeCallback) {
  54. run.itIsTimeCallback();
  55. } else if (index > 0 && run.positionChangedCallback) {
  56. run.positionChangedCallback(index);
  57. }
  58. });
  59. };
  60. this.length = function() {
  61. return queue.length;
  62. };
  63. // Returns the number of seconds since the last test was launched
  64. this.timeSinceLastTestStarted = function() {
  65. return Math.round((Date.now() - lastTestTimestamp) / 1000);
  66. };
  67. }
  68. module.exports = RunsQueue;