waitingQueueSocket.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Socket.io handler
  3. */
  4. var fs = require('fs');
  5. var waitingQueueSocket = function(socket, testQueue) {
  6. socket.on('waiting', function(testId) {
  7. console.log('User waiting for test id ' + testId);
  8. sendTestStatus(testId);
  9. testQueue.on('testComplete', function(id) {
  10. if (testId === id) {
  11. socket.emit('complete');
  12. console.log('Sending complete event to test id ' + testId);
  13. }
  14. });
  15. testQueue.on('testFailed', function(id) {
  16. if (testId === id) {
  17. socket.emit('failed');
  18. console.log('Sending failed event to test id ' + testId);
  19. }
  20. });
  21. testQueue.on('queueMoving', function() {
  22. var positionInQueue = testQueue.indexOf(testId);
  23. if (positionInQueue >= 0) {
  24. socket.emit('position', positionInQueue);
  25. console.log('Sending position to test id ' + testId);
  26. }
  27. });
  28. });
  29. // Finds the status of a test and send it to the client
  30. function sendTestStatus(testId) {
  31. // Check task position in queue
  32. var positionInQueue = testQueue.indexOf(testId);
  33. if (positionInQueue >= 0) {
  34. socket.emit('position', positionInQueue);
  35. } else {
  36. // Find in results files
  37. var exists = fs.exists('results/' + testId + '/results.json', function(exists) {
  38. if (exists) {
  39. // TODO : find a way to make sure the file is completely written
  40. setTimeout(function() {
  41. socket.emit('complete');
  42. }, 4000);
  43. } else {
  44. socket.emit('404');
  45. }
  46. });
  47. }
  48. }
  49. };
  50. module.exports = waitingQueueSocket;