task.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /**
  2. * A long-running task, which periodically pings the server for its task status
  3. */
  4. define(
  5. function( require ) {
  6. "use strict";
  7. var Marionette = require( "marionette" ),
  8. Backbone = require( "backbone" ),
  9. _ = require( "underscore" ),
  10. fui = require( "app/fui" ),
  11. sprintf = require( "sprintf" );
  12. /* Constants */
  13. var MS = 1000;
  14. var MAX_DELAY = 10 * MS;
  15. /**
  16. * This model represents a long running task process
  17. */
  18. var Task = function( ds, operationType, taskDescription ) {
  19. this.taskDescription = taskDescription;
  20. this.ds = ds;
  21. this.operationType = operationType;
  22. this.delay = 500;
  23. _.bindAll( this, "checkTaskStatus", "onCurrentTaskStatusFail", "onCurrentTaskStatus" );
  24. this.checkTaskStatus();
  25. };
  26. _.extend( Task.prototype, {
  27. /** Return the unique ID (on this server) of the task */
  28. taskId: function() {
  29. return this.taskDescription.taskId;
  30. },
  31. /** Return the URL for the task's API */
  32. taskURL: function() {
  33. return sprintf( "%s/$/tasks/%s", this.ds.baseURL(), this.taskId() );
  34. },
  35. /** Test the current status of the task */
  36. checkTaskStatus: function() {
  37. $.getJSON( this.taskURL() )
  38. .done( this.onCurrentTaskStatus )
  39. .fail( this.onCurrentTaskStatusFail )
  40. },
  41. /** Successful result from checking the task */
  42. onCurrentTaskStatus: function( taskDescription ) {
  43. this.taskDescription = taskDescription;
  44. var status = {
  45. task: this,
  46. dsId: this.ds.name(),
  47. finished: this.taskFinished()
  48. };
  49. fui.vent.trigger( "task.status", status );
  50. this.queueTaskStatusCheck();
  51. },
  52. /** Failed to check the task */
  53. onCurrentTaskStatusFail: function( jqxhr, msg, err ) {
  54. var status = {
  55. task: this,
  56. dsId: this.ds.name(),
  57. errorMessage: err || msg
  58. };
  59. fui.vent.trigger( "task.failed", status );
  60. },
  61. /** Re-queue the status check if the task is not yet complete */
  62. queueTaskStatusCheck: function() {
  63. if (!this.taskFinished()) {
  64. _.delay( this.checkTaskStatus, this.statusDelay() );
  65. }
  66. },
  67. /** Return the completion time if the task has been fid, otherwise null */
  68. taskFinished: function() {
  69. return this.taskDescription.finished;
  70. },
  71. /** Return the delay in ms until the next status check is due. */
  72. statusDelay: function() {
  73. var t = this.delay;
  74. if (t < MAX_DELAY) {
  75. this.delay = t * 2;
  76. }
  77. return t;
  78. }
  79. } );
  80. return Task;
  81. }
  82. );