|
1 | | -import { Injectable } from '@nestjs/common'; |
| 1 | +import { BadRequestException, Injectable, OnApplicationBootstrap } from '@nestjs/common'; |
2 | 2 | import { PackageJson } from 'types-package-json'; |
3 | 3 | import { ModuleRef } from '@nestjs/core'; |
4 | 4 | import { readFileSync } from 'fs'; |
5 | 5 | import { AbstractService } from '~/_common/abstracts/abstract.service'; |
6 | 6 | import { pick } from 'radash'; |
| 7 | +import { HttpService } from '@nestjs/axios'; |
| 8 | +import { LRUCache } from 'lru-cache'; |
| 9 | +import { catchError, firstValueFrom } from 'rxjs'; |
| 10 | +import { Cron, CronExpression } from '@nestjs/schedule'; |
| 11 | + |
| 12 | +export enum ProjectsList { |
| 13 | + SESAME_ORCHESTRATOR = 'sesame-orchestrator', |
| 14 | + SESAME_DAEMON = 'sesame-daemon', |
| 15 | + SESAME_APP_MANAGER = 'sesame-app-manager', |
| 16 | +} |
| 17 | + |
| 18 | +export interface GithubAuthor { |
| 19 | + login: string; |
| 20 | + id: number; |
| 21 | + node_id: string; |
| 22 | + avatar_url: string; |
| 23 | + gravatar_id: string; |
| 24 | + url: string; |
| 25 | + html_url: string; |
| 26 | + followers_url: string; |
| 27 | + following_url: string; |
| 28 | + gists_url: string; |
| 29 | + starred_url: string; |
| 30 | + subscriptions_url: string; |
| 31 | + organizations_url: string; |
| 32 | + repos_url: string; |
| 33 | + events_url: string; |
| 34 | + received_events_url: string; |
| 35 | + type: string; |
| 36 | + user_view_type: string; |
| 37 | + site_admin: boolean; |
| 38 | +} |
| 39 | + |
| 40 | +export interface GithubAsset { |
| 41 | + [key: string]: any; |
| 42 | +} |
| 43 | + |
| 44 | +export interface GithubUpdate { |
| 45 | + url: string; |
| 46 | + assets_url: string; |
| 47 | + upload_url: string; |
| 48 | + html_url: string; |
| 49 | + id: number; |
| 50 | + author: GithubAuthor; |
| 51 | + node_id: string; |
| 52 | + tag_name: string; |
| 53 | + target_commitish: string; |
| 54 | + name: string; |
| 55 | + draft: boolean; |
| 56 | + prerelease: boolean; |
| 57 | + created_at: string; |
| 58 | + published_at: string; |
| 59 | + assets: GithubAsset[]; |
| 60 | + tarball_url: string; |
| 61 | + zipball_url: string; |
| 62 | + body: string; |
| 63 | +} |
7 | 64 |
|
8 | 65 | @Injectable() |
9 | | -export class AppService extends AbstractService { |
| 66 | +export class AppService extends AbstractService implements OnApplicationBootstrap { |
| 67 | + protected storage = new LRUCache({ |
| 68 | + ttl: 1_000 * 60 * 60 * 6, // 6 hours |
| 69 | + ttlAutopurge: true, |
| 70 | + }); |
| 71 | + |
10 | 72 | protected package: Partial<PackageJson>; |
11 | 73 |
|
12 | | - public constructor(protected moduleRef: ModuleRef) { |
| 74 | + public constructor( |
| 75 | + protected moduleRef: ModuleRef, |
| 76 | + private readonly httpService: HttpService, |
| 77 | + ) { |
13 | 78 | super({ moduleRef }); |
14 | 79 | this.package = JSON.parse(readFileSync('package.json', 'utf-8')); |
15 | 80 | } |
16 | 81 |
|
| 82 | + /** |
| 83 | + * On application bootstrap, this method is called to initialize the service. |
| 84 | + * It logs the start of the bootstrap process and fetches the latest releases for each project |
| 85 | + * in the ProjectsList enum. |
| 86 | + * It uses the fetchGithubRelease method to get the latest releases from GitHub. |
| 87 | + * |
| 88 | + * @returns {Promise<void>} A promise that resolves when the bootstrap process is complete. |
| 89 | + */ |
| 90 | + public async onApplicationBootstrap(): Promise<void> { |
| 91 | + this.logger.debug('Application service bootstrap starting...'); |
| 92 | + |
| 93 | + for (const project of Object.values(ProjectsList)) { |
| 94 | + this.logger.verbose(`Checking for updates for project: ${project}`); |
| 95 | + |
| 96 | + await this.fetchGithubRelease(project); |
| 97 | + } |
| 98 | + |
| 99 | + this.logger.log('Application service bootstrap completed.'); |
| 100 | + } |
| 101 | + |
| 102 | + /** |
| 103 | + * Cron job to fetch the latest releases of projects every 6 hours. |
| 104 | + * This method logs the start and end of the job, and fetches updates for each project in the ProjectsList. |
| 105 | + * It uses the fetchGithubRelease method to get the latest releases from GitHub. |
| 106 | + * The job is scheduled using the CronExpression.EVERY_6_HOURS expression. |
| 107 | + * |
| 108 | + * @Cron(CronExpression.EVERY_6_HOURS) |
| 109 | + * @returns {Promise<void>} |
| 110 | + * @memberof AppService |
| 111 | + */ |
| 112 | + @Cron(CronExpression.EVERY_6_HOURS) |
| 113 | + public async handleCron(): Promise<void> { |
| 114 | + this.logger.debug('Cron job started.'); |
| 115 | + |
| 116 | + for (const project of Object.values(ProjectsList)) { |
| 117 | + this.logger.verbose(`Checking for updates for project: ${project}`); |
| 118 | + |
| 119 | + await this.fetchGithubRelease(project); |
| 120 | + } |
| 121 | + |
| 122 | + this.logger.debug('Cron job completed.'); |
| 123 | + } |
| 124 | + |
| 125 | + /** |
| 126 | + * Returns basic information about the application, such as name and version. |
| 127 | + * |
| 128 | + * @returns {Partial<PackageJson>} Returns basic information about the application, such as name and version. |
| 129 | + */ |
17 | 130 | public getInfo(): Partial<PackageJson> { |
18 | 131 | return pick(this.package, ['name', 'version']); |
19 | 132 | } |
| 133 | + |
| 134 | + /** |
| 135 | + * Fetches the latest release information for a specified project from GitHub. |
| 136 | + * |
| 137 | + * @param project The project name to fetch updates for. |
| 138 | + * @returns {Promise<GithubUpdate>} A promise that resolves to the latest release information for the specified project. |
| 139 | + */ |
| 140 | + public getProjectUpdate(project: ProjectsList): GithubUpdate { |
| 141 | + if (!Object.values(ProjectsList).includes(project)) { |
| 142 | + throw new BadRequestException(`Invalid project: ${project}`); |
| 143 | + } |
| 144 | + |
| 145 | + if (this.storage.has(project)) { |
| 146 | + this.logger.debug(`Fetching ${project} tags from cache`); |
| 147 | + |
| 148 | + return this.storage.get(project) as GithubUpdate; |
| 149 | + } |
| 150 | + |
| 151 | + return null; // Return null if the project is not cached |
| 152 | + } |
| 153 | + |
| 154 | + /** |
| 155 | + * Fetches the latest release information for a specified project from GitHub. |
| 156 | + * |
| 157 | + * @param project The project name to fetch updates for. |
| 158 | + * @returns {Promise<GithubUpdate>} A promise that resolves to the latest release information for the specified project. |
| 159 | + */ |
| 160 | + private async fetchGithubRelease(project: ProjectsList, retry = 0): Promise<any> { |
| 161 | + if (this.storage.has(project)) { |
| 162 | + this.logger.debug(`Fetching ${project} tags from cache`); |
| 163 | + |
| 164 | + return this.storage.get(project) as GithubUpdate; |
| 165 | + } |
| 166 | + |
| 167 | + this.logger.debug(`Fetching ${project} tags from GitHub API`); |
| 168 | + |
| 169 | + try { |
| 170 | + const { data } = await firstValueFrom( |
| 171 | + this.httpService.get<GithubUpdate>(`https://api.github.com/repos/Libertech-FR/${project}/releasesppp/latest`).pipe( |
| 172 | + catchError((error) => { |
| 173 | + this.logger.error(`Error fetching release for ${project}: ${error.message}`); |
| 174 | + throw error; |
| 175 | + }) |
| 176 | + ) |
| 177 | + ); |
| 178 | + this.storage.set(project, data); |
| 179 | + return data; |
| 180 | + } catch (error) { |
| 181 | + if (retry >= 3) { |
| 182 | + this.logger.fatal(`Failed to fetch release for ${project} after multiple retries: ${error.message}`); |
| 183 | + |
| 184 | + return null; // Return null or handle as needed |
| 185 | + } |
| 186 | + |
| 187 | + setTimeout(() => { |
| 188 | + this.logger.verbose(`Retrying to fetch ${project} release after error: ${error.message}`); |
| 189 | + return this.fetchGithubRelease(project, retry + 1); |
| 190 | + }, 1_000 * 60); // Retry after 60 seconds |
| 191 | + } |
| 192 | + } |
20 | 193 | } |
0 commit comments