task-manager.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { Task, Progress, RuntimeContext } from '../../mol-task';
  7. import { RxEventHelper } from '../../mol-util/rx-event-helper';
  8. import { now } from '../../mol-util/now';
  9. import { CreateObservableCtx, ExecuteInContext } from '../../mol-task/execution/observable';
  10. import { arrayRemoveInPlace } from '../../mol-util/array';
  11. export { TaskManager };
  12. class TaskManager {
  13. private ev = RxEventHelper.create();
  14. private id = 0;
  15. private runningTasks = new Set<number>();
  16. private abortRequests = new Map<number, string | undefined>();
  17. private options = new Map<number, { useOverlay: boolean }>();
  18. private currentContext: { ctx: RuntimeContext, refCount: number }[] = [];
  19. readonly events = {
  20. progress: this.ev<TaskManager.ProgressEvent>(),
  21. finished: this.ev<{ id: number }>()
  22. };
  23. private tryGetAbortTaskId(node: Progress.Node): number | undefined {
  24. if (this.abortRequests.has(node.progress.taskId)) return node.progress.taskId;
  25. for (const c of node.children) {
  26. const abort = this.tryGetAbortTaskId(c);
  27. if (abort !== void 0) return abort;
  28. }
  29. return void 0;
  30. }
  31. private track(internalId: number, taskId: number) {
  32. return (progress: Progress) => {
  33. if (progress.canAbort && progress.requestAbort) {
  34. const abortTaskId = this.tryGetAbortTaskId(progress.root);
  35. if (abortTaskId !== void 0) progress.requestAbort(this.abortRequests.get(abortTaskId));
  36. }
  37. const elapsed = now() - progress.root.progress.startedTime;
  38. this.events.progress.next({
  39. id: internalId,
  40. useOverlay: this.options.get(taskId)?.useOverlay,
  41. level: elapsed < 250 ? 'none' : 'background',
  42. progress
  43. });
  44. };
  45. }
  46. async run<T>(task: Task<T>, params?: { createNewContext?: boolean, useOverlay?: boolean }): Promise<T> {
  47. const id = this.id++;
  48. let ctx: TaskManager['currentContext'][0];
  49. if (params?.createNewContext || this.currentContext.length === 0) {
  50. ctx = { ctx: CreateObservableCtx(task, this.track(id, task.id), 100), refCount: 1 };
  51. } else {
  52. ctx = this.currentContext[this.currentContext.length - 1];
  53. ctx.refCount++;
  54. }
  55. try {
  56. this.options.set(task.id, { useOverlay: !!params?.useOverlay });
  57. this.runningTasks.add(task.id);
  58. const ret = await ExecuteInContext(ctx.ctx, task);
  59. return ret;
  60. } finally {
  61. this.options.delete(task.id);
  62. this.runningTasks.delete(task.id);
  63. this.events.finished.next({ id });
  64. this.abortRequests.delete(task.id);
  65. ctx.refCount--;
  66. if (ctx.refCount === 0) arrayRemoveInPlace(this.currentContext, ctx);
  67. }
  68. }
  69. requestAbortAll(reason?: string) {
  70. this.runningTasks.forEach(id => this.abortRequests.set(id, reason));
  71. }
  72. requestAbort(taskIdOrProgress: number | Progress, reason?: string) {
  73. const id = typeof taskIdOrProgress === 'number'
  74. ? taskIdOrProgress
  75. : taskIdOrProgress.root.progress.taskId;
  76. this.abortRequests.set(id, reason);
  77. }
  78. dispose() {
  79. this.ev.dispose();
  80. }
  81. }
  82. namespace TaskManager {
  83. export type ReportLevel = 'none' | 'background'
  84. export interface ProgressEvent {
  85. id: number,
  86. useOverlay?: boolean,
  87. level: ReportLevel,
  88. progress: Progress
  89. }
  90. function delay(time: number): Promise<void> {
  91. return new Promise(res => setTimeout(res, time));
  92. }
  93. export function testTask(N: number) {
  94. return Task.create('Test', async ctx => {
  95. let i = 0;
  96. while (i < N) {
  97. await delay(100 + Math.random() * 200);
  98. if (ctx.shouldUpdate) {
  99. await ctx.update({ message: 'Step ' + i, current: i, max: N, isIndeterminate: false });
  100. }
  101. i++;
  102. }
  103. });
  104. }
  105. }