|
| 1 | +import crypto from 'node:crypto'; |
| 2 | +import https from 'node:https'; |
| 3 | + |
| 4 | +import axios from 'axios'; |
| 5 | + |
| 6 | +import { platformBuildingBlocksSchemasUrl } from 'consts/urls'; |
| 7 | +import logger from 'utils/logger'; |
| 8 | +import { appsUrlBuilder } from 'utils/urls-builder'; |
| 9 | + |
| 10 | +type PbbSchemaEntry = { |
| 11 | + name?: string; |
| 12 | + status?: string; |
| 13 | +}; |
| 14 | + |
| 15 | +const TWO_HOURS_IN_MS = 1000 * 60 * 60 * 2; |
| 16 | +const FETCH_TIMEOUT_IN_MS = 5000; |
| 17 | + |
| 18 | +class PbbSchemaManager { |
| 19 | + private activeTypeNames: string[] = []; |
| 20 | + private lastFetchedAt?: number; |
| 21 | + private fetchPromise?: Promise<void>; |
| 22 | + |
| 23 | + public async initialize(): Promise<void> { |
| 24 | + if (this.fetchPromise) { |
| 25 | + return this.fetchPromise; |
| 26 | + } |
| 27 | + |
| 28 | + if (this.isInitialized()) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + this.fetchPromise = this.fetchSchemas(); |
| 33 | + try { |
| 34 | + await this.fetchPromise; |
| 35 | + } finally { |
| 36 | + this.fetchPromise = undefined; |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public getActiveTypeNames(): string[] { |
| 41 | + return [...this.activeTypeNames]; |
| 42 | + } |
| 43 | + |
| 44 | + public isInitialized(): boolean { |
| 45 | + return ( |
| 46 | + this.activeTypeNames.length > 0 && |
| 47 | + this.lastFetchedAt !== undefined && |
| 48 | + this.lastFetchedAt + TWO_HOURS_IN_MS > Date.now() |
| 49 | + ); |
| 50 | + } |
| 51 | + |
| 52 | + private async fetchSchemas(): Promise<void> { |
| 53 | + try { |
| 54 | + const url = appsUrlBuilder(platformBuildingBlocksSchemasUrl()); |
| 55 | + const httpsAgent = new https.Agent({ |
| 56 | + secureOptions: crypto.constants.SSL_OP_LEGACY_SERVER_CONNECT, |
| 57 | + rejectUnauthorized: false, |
| 58 | + }); |
| 59 | + |
| 60 | + const response = await axios.get<PbbSchemaEntry[]>(url, { |
| 61 | + timeout: FETCH_TIMEOUT_IN_MS, |
| 62 | + headers: { Accept: 'application/json' }, |
| 63 | + httpsAgent, |
| 64 | + }); |
| 65 | + |
| 66 | + const schemas = Array.isArray(response.data) ? response.data : []; |
| 67 | + this.activeTypeNames = schemas |
| 68 | + .filter(schema => schema.status === 'ACTIVE' && typeof schema.name === 'string' && schema.name.length > 0) |
| 69 | + .map(schema => schema.name as string); |
| 70 | + this.lastFetchedAt = Date.now(); |
| 71 | + } catch (error) { |
| 72 | + logger.debug(error, 'pbb-schema-manager'); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | + |
| 77 | +export const pbbSchemaManager = new PbbSchemaManager(); |
0 commit comments