|
1 | 1 | import { BadRequestException, HttpStatus, Injectable, RequestTimeoutException } from '@nestjs/common'; |
2 | 2 | import { ModuleRef } from '@nestjs/core'; |
3 | | -import { Job } from 'bullmq'; |
| 3 | +import { Types } from 'mongoose'; |
4 | 4 | import { AbstractQueueProcessor } from '~/_common/abstracts/abstract.queue.processor'; |
| 5 | +import { IdentityState } from '~/management/identities/_enums/states.enum'; |
| 6 | +import { Identities } from '~/management/identities/_schemas/identities.schema'; |
| 7 | +import { IdentitiesService } from '~/management/identities/identities.service'; |
| 8 | +import { JobState } from '../jobs/_enums/state.enum'; |
| 9 | +import { Jobs } from '../jobs/_schemas/jobs.schema'; |
| 10 | +import { JobsService } from '../jobs/jobs.service'; |
| 11 | +import { TasksService } from '../tasks/tasks.service'; |
5 | 12 | import { ActionType } from './_enum/action-type.enum'; |
6 | 13 | import { ExecuteJobOptions } from './_interfaces/execute-job-options.interface'; |
7 | 14 |
|
8 | 15 | const DEFAULT_SYNC_TIMEOUT = 30_000; |
9 | 16 |
|
10 | 17 | @Injectable() |
11 | 18 | export class BackendsService extends AbstractQueueProcessor { |
12 | | - public constructor(protected moduleRef: ModuleRef) { |
| 19 | + public constructor( |
| 20 | + protected moduleRef: ModuleRef, |
| 21 | + protected identitiesService: IdentitiesService, |
| 22 | + protected jobsService: JobsService, |
| 23 | + protected tasksService: TasksService, |
| 24 | + ) { |
13 | 25 | super({ moduleRef }); |
14 | 26 | } |
15 | 27 |
|
| 28 | + public async onModuleInit() { |
| 29 | + await super.onModuleInit(); |
| 30 | + |
| 31 | + //TODO: resync failed + completed |
| 32 | + const jobsCompleted = await this._queue.getCompleted(); |
| 33 | + for (const job of jobsCompleted) { |
| 34 | + const isSyncedJob = await this.jobsService.model.findOneAndUpdate<Jobs>( |
| 35 | + { jobId: job.id, state: { $ne: JobState.COMPLETED } }, |
| 36 | + { |
| 37 | + $set: { |
| 38 | + state: JobState.COMPLETED, |
| 39 | + finishedAt: new Date(), |
| 40 | + result: job.returnvalue, |
| 41 | + }, |
| 42 | + }, |
| 43 | + { new: true }, |
| 44 | + ); |
| 45 | + if (isSyncedJob) { |
| 46 | + this.logger.warn(`Job already completed, syncing... [${job.id}::COMPLETED]`); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + this.queueEvents.on('waiting', (payload) => this.logger.debug(`Job is now waiting... [${payload.jobId}]`)); |
| 51 | + this.queueEvents.on('active', async (payload) => { |
| 52 | + this.logger.debug(`Job is now active... [${payload.jobId}]`); |
| 53 | + await this.jobsService.model.findOneAndUpdate<Jobs>( |
| 54 | + { jobId: payload.jobId, state: { $ne: JobState.COMPLETED } }, |
| 55 | + { |
| 56 | + $set: { |
| 57 | + state: JobState.IN_PROGRESS, |
| 58 | + processedAt: new Date(), |
| 59 | + }, |
| 60 | + }, |
| 61 | + { new: true }, |
| 62 | + ); |
| 63 | + }); |
| 64 | + |
| 65 | + this.queueEvents.on('failed', async (payload) => { |
| 66 | + this.logger.debug(`Job failed ! [${payload.jobId}]`); |
| 67 | + await this.jobsService.model.findOneAndUpdate<Jobs>( |
| 68 | + { jobId: payload.jobId, state: { $ne: JobState.COMPLETED } }, |
| 69 | + { |
| 70 | + $set: { |
| 71 | + state: JobState.FAILED, |
| 72 | + finishedAt: new Date(), |
| 73 | + result: payload.failedReason, |
| 74 | + }, |
| 75 | + }, |
| 76 | + { new: true }, |
| 77 | + ); |
| 78 | + }); |
| 79 | + |
| 80 | + this.queueEvents.on('completed', async (payload) => { |
| 81 | + await this.jobsService.model.findOneAndUpdate<Jobs>( |
| 82 | + { jobId: payload.jobId, state: { $ne: JobState.COMPLETED } }, |
| 83 | + { |
| 84 | + $set: { |
| 85 | + state: JobState.COMPLETED, |
| 86 | + finishedAt: new Date(), |
| 87 | + result: payload.returnvalue, |
| 88 | + }, |
| 89 | + }, |
| 90 | + { upsert: true }, |
| 91 | + ); |
| 92 | + this.logger.log(`Job completed... Syncing [${payload.jobId}]`); |
| 93 | + }); |
| 94 | + } |
| 95 | + |
| 96 | + public async syncIdentities(payload: string[], options?: ExecuteJobOptions): Promise<any> { |
| 97 | + const identities: { |
| 98 | + action: ActionType; |
| 99 | + identity: Identities; |
| 100 | + }[] = []; |
| 101 | + |
| 102 | + for (const key of payload) { |
| 103 | + const identity = await this.identitiesService.findById<Identities>(key); |
| 104 | + if (identity.state !== IdentityState.TO_SYNC) { |
| 105 | + throw new BadRequestException({ |
| 106 | + status: HttpStatus.BAD_REQUEST, |
| 107 | + message: `Identity ${key} is not in state TO_SYNC`, |
| 108 | + identity, |
| 109 | + }); |
| 110 | + } |
| 111 | + identities.push({ |
| 112 | + action: ActionType.IDENTITY_UPDATE, |
| 113 | + identity, |
| 114 | + }); |
| 115 | + } |
| 116 | + |
| 117 | + const result = {}; |
| 118 | + for (const identity of identities) { |
| 119 | + const [executedJob] = await this.executeJob(identity.action, identity.identity._id, { identity }, options); |
| 120 | + result[identity.identity._id] = executedJob; |
| 121 | + } |
| 122 | + return result; |
| 123 | + } |
| 124 | + |
16 | 125 | public async executeJob( |
17 | 126 | actionType: ActionType, |
| 127 | + concernedTo: Types.ObjectId, |
18 | 128 | // eslint-disable-next-line @typescript-eslint/no-unused-vars |
19 | 129 | payload?: Record<string | number, any>, |
20 | 130 | options?: ExecuteJobOptions, |
21 | | - ): Promise<[Job, any]> { |
22 | | - const job = await this.queue.add(actionType, payload, options?.job); |
| 131 | + ): Promise<[Jobs, any]> { |
| 132 | + const job = await this.queue.add( |
| 133 | + actionType, |
| 134 | + { |
| 135 | + concernedTo, |
| 136 | + payload, |
| 137 | + }, |
| 138 | + options?.job, |
| 139 | + ); |
| 140 | + const optionals = {}; |
| 141 | + if (!options?.async) { |
| 142 | + optionals['processedAt'] = new Date(); |
| 143 | + optionals['state'] = JobState.IN_PROGRESS; |
| 144 | + } |
| 145 | + const jobStore = await this.jobsService.create<Jobs>({ |
| 146 | + jobId: job.id, |
| 147 | + action: actionType, |
| 148 | + params: payload, |
| 149 | + concernedTo: concernedTo, |
| 150 | + comment: options?.comment, |
| 151 | + state: JobState.CREATED, |
| 152 | + ...optionals, |
| 153 | + }); |
23 | 154 | if (!options?.async) { |
24 | 155 | let error: Error; |
25 | 156 | try { |
26 | 157 | const response = await job.waitUntilFinished(this.queueEvents, options.syncTimeout || DEFAULT_SYNC_TIMEOUT); |
27 | | - return [job, response]; |
| 158 | + const jobStoreUpdated = await this.jobsService.update<Jobs>(jobStore._id, { |
| 159 | + $set: { |
| 160 | + state: JobState.COMPLETED, |
| 161 | + processedAt: new Date(), |
| 162 | + finishedAt: new Date(), |
| 163 | + result: response, |
| 164 | + }, |
| 165 | + }); |
| 166 | + return [jobStoreUpdated as unknown as Jobs, response]; |
28 | 167 | } catch (err) { |
29 | 168 | error = err; |
30 | 169 | } |
| 170 | + const jobFailed = await this.jobsService.update<Jobs>(jobStore._id, { |
| 171 | + $set: { |
| 172 | + state: JobState.FAILED, |
| 173 | + finishedAt: new Date(), |
| 174 | + result: error, |
| 175 | + }, |
| 176 | + }); |
31 | 177 | if (options?.timeoutDiscard !== false) { |
32 | 178 | job.discard(); |
33 | 179 | throw new BadRequestException({ |
34 | 180 | status: HttpStatus.BAD_REQUEST, |
35 | 181 | message: `Sync job ${job.id} failed to finish in time`, |
36 | 182 | error, |
37 | | - job, |
| 183 | + job: jobFailed as unknown as Jobs, |
38 | 184 | }); |
39 | 185 | } |
40 | 186 | throw new RequestTimeoutException({ |
41 | 187 | status: HttpStatus.REQUEST_TIMEOUT, |
42 | 188 | message: `Job now continue to run in background ${job.id}, timeout wait until finish reached`, |
43 | 189 | error, |
44 | | - job, |
| 190 | + job: jobFailed as unknown as Jobs, |
45 | 191 | }); |
46 | 192 | } |
47 | | - return [job, null]; |
| 193 | + return [jobStore.toObject(), null]; |
48 | 194 | } |
49 | 195 | } |
0 commit comments