DatasetExecutionService.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. 'use strict';
  2. /**
  3. * Licensed Materials - Property of IBM
  4. * IBM Cognos Products: BI
  5. * (C) Copyright IBM Corp. 2016, 2020
  6. * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
  7. */
  8. define(['../../lib/@waca/core-client/js/core-client/ui/core/Events', '../../lib/@waca/core-client/js/core-client/nls/StringResources', '../../lib/@waca/core-client/js/core-client/ui/ProgressToast', '../../lib/@waca/core-client/js/core-client/utils/Deferred', 'underscore'], function (Events, StringResources, ProgressToast, Deferred, _) {
  9. 'use strict';
  10. var CONTENT_TYPE = 'application/vnd.ibm.bi.platform.execution+json; charset=UTF-8';
  11. var APPLICATION_JSON = 'application/json';
  12. var DatasetExecutionService = Events.extend({
  13. init: function init() {
  14. DatasetExecutionService.inherited('init', this, arguments);
  15. this._backgroundExecutions = {};
  16. // We want to ping a lot at the start and then slow down if the dataset take a long time
  17. this._pingTimeouts = [300, 600, 1000, 1500, 2000, 4000, 6000, 10000];
  18. this._defaultOptions = {
  19. showToastWhenDone: true
  20. };
  21. },
  22. /**
  23. Will execute a dataset in the background. If the dataset is already running,
  24. then it will be canceled before the new run is triggered.
  25. @param options.id {string} - store ID of the dataset to run
  26. @param options.name {stirng} - the name of the data set to execute. Will be shown in the toast
  27. @param options.showToastWhenDone {boolean} - default is true, set to false if you don't want a toast to be displayed when the dataset is done running
  28. @param options.glassContext {object} - the glassContext object
  29. @param options.isRefresh {boolean} - default false. Set to true if doing a refresh from the context menu
  30. **/
  31. execute: function execute(options) {
  32. var _this = this;
  33. _.defaults(options, this._defaultOptions);
  34. this._initLogger(options.glassContext);
  35. // If we're already running the dataset then cancel it before we start another run
  36. if (this.isExecuting(options.id)) {
  37. this.cancel(options, false);
  38. }
  39. var timestamp = Date.now();
  40. options.timestamp = timestamp;
  41. this._backgroundExecutions[options.id] = {
  42. 'status': 'executing',
  43. 'timestamp': timestamp,
  44. 'isRefresh': options.isRefresh
  45. };
  46. if (options.showToastWhenDone) {
  47. this._createProgressToast(options);
  48. }
  49. var data = JSON.stringify({
  50. 'options': {
  51. 'delivery': {
  52. 'save': {
  53. 'notify': false
  54. }
  55. }
  56. }
  57. });
  58. return Promise.resolve().then(function () {
  59. return options.glassContext.services.ajax.post('v1/datasets/' + options.id + '/executions', {
  60. 'headers': {
  61. 'Content-Type': CONTENT_TYPE,
  62. 'Accept': APPLICATION_JSON
  63. },
  64. 'datatype': 'json',
  65. 'data': data
  66. }).then(function (result, status, xhr) {
  67. this._backgroundExecutions[options.id].executionURL = xhr.getResponseHeader('location');
  68. this._backgroundExecutions[options.id].eventID = result.eventID;
  69. this._pingForStatus(options);
  70. }.bind(_this), function (error) {
  71. _this._rejectDeferredObjects(options, 'failed');
  72. throw new Error('Execution failed: ' + error.message);
  73. });
  74. });
  75. },
  76. _initLogger: function _initLogger(glassContext) {
  77. var _this2 = this;
  78. if (!this.logger && glassContext) {
  79. glassContext.getSvc('.Logger').then(function (logger) {
  80. return _this2.logger = logger;
  81. });
  82. }
  83. },
  84. /**
  85. Will create the progress toast to show the user that the data set is being loaded
  86. **/
  87. _createProgressToast: function _createProgressToast(options) {
  88. var progressToast = new ProgressToast();
  89. progressToast.show(this._getToastMessage(options));
  90. progressToast.indefinite(this._getToastMessage(options));
  91. progressToast.onCancel(function (options) {
  92. this.cancel(options, true);
  93. }.bind(this, options));
  94. progressToast.onHide(function (options) {
  95. this._hideProgressToast(options.id);
  96. }.bind(this, options));
  97. this._backgroundExecutions[options.id].progressToast = progressToast;
  98. },
  99. /**
  100. Hide the progress toast
  101. **/
  102. _hideProgressToast: function _hideProgressToast(id) {
  103. var execution = this._backgroundExecutions[id];
  104. if (execution && execution.progressToast) {
  105. execution.progressToast.remove(0);
  106. execution.progressToast = null;
  107. }
  108. },
  109. _showErrorToast: function _showErrorToast(options, errorMessage) {
  110. var execution = this._backgroundExecutions[options.id];
  111. if (options.showToastWhenDone) {
  112. if (execution && execution.progressToast) {
  113. // We don't want the error progress toast to get cleaned up, so null it out here
  114. // so our cleanup code doesn't know to hide it. Sneaky sneaky.
  115. var progressToast = execution.progressToast;
  116. execution.progressToast = null;
  117. progressToast.fail(this._getToastMessage(options, errorMessage));
  118. progressToast.hideButton('cancel');
  119. } else {
  120. options.glassContext.appController.showToast(this._getToastMessage(options), {
  121. 'type': 'error'
  122. });
  123. }
  124. }
  125. },
  126. _showCancelledRefreshToast: function _showCancelledRefreshToast(options) {
  127. options.glassContext.appController.showToast(this._getToastMessage(options), {
  128. 'type': 'info'
  129. });
  130. },
  131. /**
  132. Will query the server for the status of the execution every once in a while until the status of the execution is complete|failed. This method
  133. will query a lot at the begining and slow down the longer the dataset is executing.
  134. @param options.id {string} - store ID of the dataset to run
  135. @param options.type {string} - type of the object being executed
  136. @param options.showToastWhenDone {boolean} - default is true, set to false if you don't want a toast to be displayed when the dataset is done running
  137. @param options.glassContext {object} - the glassContext object
  138. **/
  139. _pingForStatus: function _pingForStatus(options) {
  140. var execution = this._backgroundExecutions[options.id];
  141. // If the timestamp in the options doesn't match the timestamp on the execution object then another execution for the same dataset
  142. // has started and the one we're currently pinging for has been cancelled.
  143. if (!execution || options.timestamp !== execution.timestamp || !execution.executionURL || execution.status === 'cancelled') {
  144. return;
  145. } else if (execution.status === 'failed') {
  146. this._rejectDeferredObjects(options, 'failed');
  147. this._cleanupAfterExecutionFinished(options.id);
  148. return;
  149. } else if (!this.isExecuting(options.id)) {
  150. this._processExecutionStatus(execution.status, options);
  151. return;
  152. }
  153. options.glassContext.services.ajax.get(execution.executionURL, {
  154. 'headers': {
  155. 'Content-Type': CONTENT_TYPE,
  156. 'Accept': APPLICATION_JSON
  157. },
  158. 'datatype': 'json'
  159. }).then(function (response) {
  160. execution.status = response.status;
  161. this._processExecutionStatus(execution.status, options);
  162. }.bind(this), function () {
  163. // The ping failed, not much we can do
  164. this._rejectDeferredObjects(options, 'statusPingFailed');
  165. });
  166. },
  167. /**
  168. Deal with the status of the execution
  169. **/
  170. _processExecutionStatus: function _processExecutionStatus(status, options) {
  171. var _this3 = this;
  172. var execution = this._backgroundExecutions[options.id];
  173. switch (status) {
  174. case 'complete':
  175. case 'succeeded':
  176. // We could get a status of complete back for a cancelled execution. Double check here to make sure we didn't cancel anything
  177. if (execution.status === 'cancelled') {
  178. this._rejectDeferredObjects(options, 'cancelled');
  179. } else {
  180. this._resolveDefferedObjects(options.id);
  181. if (options.showToastWhenDone) {
  182. options.glassContext.appController.showToast(this._getToastMessage(options));
  183. }
  184. this.trigger('loadComplete', { id: options.id });
  185. }
  186. this._cleanupAfterExecutionFinished(options.id);
  187. break;
  188. case 'cancelled':
  189. this._rejectDeferredObjects(options, 'cancelled');
  190. this._cleanupAfterExecutionFinished(options.id);
  191. break;
  192. case 'failed':
  193. this._getErrorMessage(options).then(function (errorMessage) {
  194. _this3._rejectDeferredObjects(options, 'failed', errorMessage);
  195. _this3._cleanupAfterExecutionFinished(options.id);
  196. });
  197. break;
  198. case 'executing':
  199. case 'pending':
  200. var pingTimeoutIndex = options.pingTimeoutIndex || 0;
  201. pingTimeoutIndex += 1;
  202. if (pingTimeoutIndex >= this._pingTimeouts.length) {
  203. pingTimeoutIndex = this._pingTimeouts.length - 1;
  204. }
  205. options.pingTimeoutIndex = pingTimeoutIndex;
  206. setTimeout(function () {
  207. this._pingForStatus(options);
  208. }.bind(this), this._pingTimeouts[pingTimeoutIndex]);
  209. break;
  210. default:
  211. this._cleanupAfterExecutionFinished(options.id);
  212. console.debug('Unknown status returned by ' + execution.executionURL + '. Status of: ' + status);
  213. }
  214. },
  215. /**
  216. Will reject all deferred objects associated to a running dataset. This will let the callers know that
  217. something went wrong - request got cancelled or a fault happened.
  218. **/
  219. _rejectDeferredObjects: function _rejectDeferredObjects(options, status, errorMessage) {
  220. var execution = this._backgroundExecutions[options.id];
  221. if (!execution) {
  222. return;
  223. }
  224. execution.status = status;
  225. if (status === 'failed') {
  226. this._showErrorToast(options, errorMessage);
  227. }
  228. // Reject any deferred objects that were waiting until the request was complete
  229. if (execution.deferredObjects) {
  230. execution.deferredObjects.forEach(function (deferred) {
  231. deferred.reject({
  232. 'status': status
  233. });
  234. });
  235. }
  236. },
  237. _logError: function _logError() {
  238. if (this.logger) {
  239. var _logger;
  240. (_logger = this.logger).error.apply(_logger, arguments);
  241. }
  242. },
  243. _getErrorMessage: function _getErrorMessage(options) {
  244. var _this4 = this;
  245. return this._getItemLastHistoryEntry(options).catch(function (error) {
  246. return _this4._logError('Error trying to read history of asset ' + options.id, error);
  247. }).then(function (historyEntry) {
  248. return historyEntry && _this4._getHistoryEntryDetailMessage(options, historyEntry);
  249. }).catch(function (error) {
  250. return _this4._logError('Error trying to read history details of asset ' + options.id, error);
  251. });
  252. },
  253. _getItemLastHistoryEntry: function _getItemLastHistoryEntry(options) {
  254. return options.glassContext.services.ajax.get('v1/objects/' + options.id + '/items?types=history').then(function (result) {
  255. return result && result.data && _.max(result.data, function (_ref) {
  256. var modificationTime = _ref.modificationTime;
  257. return Date.parse(modificationTime);
  258. });
  259. });
  260. },
  261. _getHistoryEntryDetailMessage: function _getHistoryEntryDetailMessage(options, historyEntry) {
  262. var historyDetailsUrl = historyEntry._meta && historyEntry._meta.links && historyEntry._meta.links.details && historyEntry._meta.links.details.url;
  263. return historyDetailsUrl && options.glassContext.services.ajax.get(historyDetailsUrl).then(function (result) {
  264. //Get first (only?) message, assume it contains the error message of interest
  265. var message = result && result.data && result.data.messages && result.data.messages.length && result.data.messages[0];
  266. return message && message.detail;
  267. });
  268. },
  269. /**
  270. Will resolve all deferred objects associated to a running dataset.
  271. **/
  272. _resolveDefferedObjects: function _resolveDefferedObjects(id) {
  273. var execution = this._backgroundExecutions[id];
  274. // Reject any deferred objects that were waiting until the request was complete
  275. if (execution.deferredObjects) {
  276. execution.deferredObjects.forEach(function (deferred) {
  277. deferred.resolve();
  278. });
  279. }
  280. },
  281. _cleanupAfterExecutionFinished: function _cleanupAfterExecutionFinished(id) {
  282. this._hideProgressToast(id);
  283. this._backgroundExecutions[id] = {
  284. 'status': this._backgroundExecutions[id].status
  285. };
  286. },
  287. /**
  288. Cancels a currently running dataset. There's no reason to wait for the cancel to finish, so this method will simply return right after it sends the request.
  289. @param options.id {string} - store ID of the dataset to run
  290. @param options.glassContext {object} - the glassContext object
  291. @param showCancelToast {boolean} - default true, should we show a toast after the cancel
  292. **/
  293. cancel: function cancel(options, showCancelToast) {
  294. this._hideProgressToast(options.id);
  295. var execution = this._backgroundExecutions[options.id];
  296. if (!execution || !this.isExecuting(options.id)) {
  297. return;
  298. }
  299. execution.status = 'cancelled';
  300. if (showCancelToast !== false) {
  301. this._showCancelledRefreshToast(options);
  302. }
  303. // Reject all deferred object waiting for the completion since we're being asked to cancel
  304. this._rejectDeferredObjects(options, 'cancelled');
  305. if (execution.executionURL) {
  306. options.glassContext.services.ajax['delete'](execution.executionURL, {
  307. 'headers': {
  308. 'Content-Type': CONTENT_TYPE,
  309. 'Accept': APPLICATION_JSON
  310. },
  311. 'datatype': 'json'
  312. });
  313. }
  314. },
  315. /**
  316. * @param id {string} - store ID of the dataset
  317. *
  318. * @returns {promise}
  319. * - will be resolved when the dataset specified by options.id is complete.
  320. * - will be rejected if the dataset execution fails or gets canceled. The reason returns will be an object
  321. * reason.status {string} : the status of request (fault | cancelled)
  322. * reason.msg {string}: In the case of a fault, the error message
  323. **/
  324. whenComplete: function whenComplete(id) {
  325. var deferred = new Deferred();
  326. var status = this.getStatus(id);
  327. var execution = this._backgroundExecutions[id];
  328. // If the dataset is already done then resolve the promise right away
  329. if (!execution || status === 'complete') {
  330. deferred.resolve();
  331. } else if (status === 'failed' || status === 'cancelled') {
  332. // The dataset already failed, reject the promise
  333. deferred.reject({
  334. 'status': status
  335. });
  336. } else {
  337. if (!execution.deferredObjects) {
  338. execution.deferredObjects = [];
  339. }
  340. execution.deferredObjects.push(deferred);
  341. }
  342. return deferred.promise;
  343. },
  344. /**
  345. Will return the last known status for the id provided
  346. @param id {string} - store ID of the dataset
  347. @return {string} - complete | pending | executing | failed | null (if id isn't found)
  348. **/
  349. getStatus: function getStatus(id) {
  350. return this._backgroundExecutions[id] ? this._backgroundExecutions[id].status : null;
  351. },
  352. /**
  353. The UI doesn't distinguish between pending and executing, so treat both of them as 'executing'
  354. **/
  355. isExecuting: function isExecuting(id) {
  356. var status = this.getStatus(id);
  357. return status === 'pending' || status === 'executing';
  358. },
  359. _getToastMessage: function _getToastMessage(options, errorMessage) {
  360. var execution = this._backgroundExecutions[options.id];
  361. if (!execution) {
  362. return '';
  363. }
  364. var stringId = '';
  365. if (execution.isRefresh) {
  366. switch (execution.status) {
  367. case 'executing':
  368. case 'pending':
  369. stringId = 'datasetRefreshing';
  370. break;
  371. case 'complete':
  372. case 'succeeded':
  373. stringId = 'datasetFinishedRefreshing';
  374. break;
  375. case 'failed':
  376. stringId = 'datasetRefreshFailed';
  377. break;
  378. case 'cancelled':
  379. stringId = 'datasetRefreshCancelled';
  380. break;
  381. }
  382. } else {
  383. switch (execution.status) {
  384. case 'executing':
  385. case 'pending':
  386. stringId = 'datasetLoading';
  387. break;
  388. case 'complete':
  389. case 'succeeded':
  390. stringId = 'datasetFinishedLoading';
  391. break;
  392. case 'failed':
  393. stringId = 'datasetLoadingFailed';
  394. break;
  395. case 'cancelled':
  396. stringId = 'datasetLoadingCancelled';
  397. break;
  398. }
  399. }
  400. return [StringResources.get(stringId, {
  401. 'name': options.name
  402. }), errorMessage].filter(function (string) {
  403. return !!string;
  404. }).join('\n');
  405. }
  406. });
  407. return DatasetExecutionService;
  408. });
  409. //# sourceMappingURL=DatasetExecutionService.js.map