summaryrefslogtreecommitdiffstats
path: root/src/pybind/mgr/dashboard/frontend/src/app/shared/services/task-wrapper.service.ts
blob: 721e1edcdc2692cf6ad0bd7454e80622d0a5dc14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { Injectable } from '@angular/core';

import { Observable, Subscriber } from 'rxjs';

import { NotificationType } from '../enum/notification-type.enum';
import { CdNotificationConfig } from '../models/cd-notification';
import { ExecutingTask } from '../models/executing-task';
import { FinishedTask } from '../models/finished-task';
import { NotificationService } from './notification.service';
import { SummaryService } from './summary.service';
import { TaskManagerService } from './task-manager.service';
import { TaskMessageService } from './task-message.service';

@Injectable({
  providedIn: 'root'
})
export class TaskWrapperService {
  constructor(
    private notificationService: NotificationService,
    private summaryService: SummaryService,
    private taskMessageService: TaskMessageService,
    private taskManagerService: TaskManagerService
  ) {}

  wrapTaskAroundCall({ task, call }: { task: FinishedTask; call: Observable<any> }) {
    return new Observable((observer: Subscriber<any>) => {
      call.subscribe(
        (resp) => {
          if (resp.status === 202) {
            this._handleExecutingTasks(task);
          } else {
            this.summaryService.refresh();
            task.success = true;
            this.notificationService.notifyTask(task);
          }
        },
        (resp) => {
          task.success = false;
          task.exception = resp.error;
          observer.error(resp);
        },
        () => {
          observer.complete();
        }
      );
    });
  }

  _handleExecutingTasks(task: FinishedTask) {
    const notification = new CdNotificationConfig(
      NotificationType.info,
      this.taskMessageService.getRunningTitle(task)
    );
    notification.isFinishedTask = true;
    this.notificationService.show(notification);

    const executingTask = new ExecutingTask(task.name, task.metadata);
    this.summaryService.addRunningTask(executingTask);

    this.taskManagerService.subscribe(
      executingTask.name,
      executingTask.metadata,
      (asyncTask: FinishedTask) => {
        this.notificationService.notifyTask(asyncTask);
      }
    );
  }
}