observable.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import Task from '../task'
  7. import RuntimeContext from './runtime-context'
  8. import Progress from './progress'
  9. import now from '../util/now'
  10. function defaultProgress(rootTaskId: number, task: Task<any>): Task.Progress {
  11. return {
  12. rootTaskId,
  13. taskId: task.id,
  14. taskName: task.name,
  15. message: 'Running...',
  16. elapsedMs: { real: 0, cpu: 0 },
  17. canAbort: true,
  18. isIndeterminate: true,
  19. current: 0,
  20. max: 0
  21. };
  22. }
  23. class ProgressInfo {
  24. taskId: number;
  25. elapsedMs: { real: number, cpu: number };
  26. tree: Progress.Node;
  27. tryAbort?: (reason?: string) => void;
  28. snapshot(): Progress {
  29. return 0 as any;
  30. }
  31. }
  32. class ObservableExecutor {
  33. progressInfo: ProgressInfo;
  34. async run<T>(task: Task<T>): Promise<T> {
  35. const ctx = new ObservableRuntimeContext(task.id, task, 0);
  36. if (!task.__onAbort) return task.__f(ctx);
  37. try {
  38. return await task.__f(ctx);
  39. } catch (e) {
  40. if (Task.isAborted(e)) task.__onAbort();
  41. throw e;
  42. }
  43. }
  44. constructor(observer: Progress.Observer, updateRateMs: number) {
  45. }
  46. }
  47. class ObservableRuntimeContext implements RuntimeContext {
  48. elapsedCpuMs: number;
  49. lastScheduledTime: number;
  50. started: number;
  51. taskId: number;
  52. taskName: string;
  53. progress: Task.Progress;
  54. updateRateMs: number;
  55. get requiresUpdate(): boolean {
  56. return now() - this.started > this.updateRateMs;
  57. }
  58. update(progress: Partial<RuntimeContext.ProgressUpdate>): Promise<void> {
  59. return 0 as any;
  60. }
  61. runChild<T>(progress: Partial<RuntimeContext.ProgressUpdate>, task: Task<T>): Promise<T> {
  62. return 0 as any;
  63. }
  64. constructor(parentId: number, task: Task<any>, updateRateMs: number) {
  65. this.started = now();
  66. this.lastScheduledTime = this.started;
  67. this.taskId = task.id;
  68. this.taskName = task.name;
  69. this.progress = defaultProgress(parentId, task);
  70. this.updateRateMs = updateRateMs;
  71. }
  72. }
  73. function ExecuteObservable<T>(task: Task<T>, observer: Progress.Observer, updateRateMs = 250) {
  74. return new ObservableExecutor(observer, updateRateMs).run(task);
  75. }
  76. namespace ExecuteObservable {
  77. export let PRINT_ERRORS_TO_CONSOLE = false;
  78. }
  79. export default ExecuteObservable