runsQueue.js 2.3 KB

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