| 1 | import { Inject, Injectable, Logger } from '@nestjs/common' |
| 2 | import { Cron } from '@nestjs/schedule' |
| 3 | import { WithLoggerContext } from '@yikart/common' |
| 4 | import { Redlock } from '@yikart/redlock' |
| 5 | import { isCallbackEnabled, isQueueEnabled } from '../assets.config' |
| 6 | import { AssetsService } from '../assets.service' |
| 7 | import { R2EventsService } from '../r2-events.service' |
| 8 | import { ASSETS_HTTP_OPTIONS, AssetsHttpModuleOptions, AssetsRedlockKey } from './assets-http.options' |
| 9 | |
| 10 | @Injectable() |
| 11 | export class AssetsHttpScheduler { |
| 12 | private readonly logger = new Logger(AssetsHttpScheduler.name) |
| 13 | private readonly queueEnabled: boolean |
| 14 | private readonly callbackEnabled: boolean |
| 15 | |
| 16 | constructor( |
| 17 | private readonly assetsService: AssetsService, |
| 18 | private readonly r2EventsService: R2EventsService, |
| 19 | @Inject(ASSETS_HTTP_OPTIONS) options: AssetsHttpModuleOptions, |
| 20 | ) { |
| 21 | this.queueEnabled = isQueueEnabled(options.assetsConfig) |
| 22 | this.callbackEnabled = isCallbackEnabled(options.assetsConfig) |
| 23 | } |
| 24 | |
| 25 | @Cron('*/5 * * * * *') |
| 26 | @Redlock(AssetsRedlockKey.AssetsR2EventsProcess, 4, { throwOnFailure: false }) |
| 27 | @WithLoggerContext() |
| 28 | async processAssetConfirmation() { |
| 29 | if (this.queueEnabled) { |
| 30 | const result = await this.r2EventsService.processMessages() |
| 31 | if (result.processed > 0 || result.failed > 0) { |
| 32 | this.logger.log(`R2 events: processed=${result.processed}, failed=${result.failed}`) |
| 33 | } |
| 34 | } |
| 35 | else if (!this.callbackEnabled) { |
| 36 | const result = await this.assetsService.processQuickPollPendingAssets(50) |
| 37 | if (result.confirmed > 0) { |
| 38 | this.logger.log(`Quick poll: confirmed=${result.confirmed}`) |
| 39 | } |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | @Cron('0 */5 * * * *') |
| 44 | @Redlock(AssetsRedlockKey.AssetsPendingCheck, 60, { throwOnFailure: false }) |
| 45 | @WithLoggerContext() |
| 46 | async processPendingAssets() { |
| 47 | const result = await this.assetsService.processPendingAssets(120, 100) |
| 48 | if (result.confirmed > 0 || result.failed > 0) { |
| 49 | this.logger.log(`Pending assets: confirmed=${result.confirmed}, failed=${result.failed}`) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | @Cron('0 0 * * * *') |
| 54 | @Redlock(AssetsRedlockKey.AssetsExpiredCleanup, 60, { throwOnFailure: false }) |
| 55 | @WithLoggerContext() |
| 56 | async cleanupExpiredAssets() { |
| 57 | const result = await this.assetsService.cleanupExpiredPendingAssets(24 * 60 * 60) |
| 58 | if (result.affectedCount > 0) { |
| 59 | this.logger.log(`Expired assets cleanup: ${result.affectedCount}`) |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 |