// apps/box-app-api/src/feature/ads/ad.service.ts import { Injectable, Logger } from '@nestjs/common'; import { RedisService } from '@box/db/redis/redis.service'; import { MongoPrismaService } from '@box/db/prisma/mongo-prisma.service'; import { CacheKeys } from '@box/common/cache/cache-keys'; import { AdDto } from './dto/ad.dto'; import { AdListResponseDto, AdItemDto } from './dto'; import { AdType } from '@box/common/ads/ad-types'; interface AdPoolEntry { id: string; weight: number; } // This should match what mgnt-side rebuildSingleAdCache stores. // We only care about a subset for now. interface CachedAd { id: string; channelId?: string; adsModuleId?: string; advertiser?: string; title?: string; adsContent?: string | null; adsCoverImg?: string | null; adsUrl?: string | null; adType?: string | null; // startDt?: bigint; // expiryDt?: bigint; // seq?: number; // status?: number; // createAt?: bigint; // updateAt?: bigint; } export interface GetAdForPlacementParams { scene: string; // e.g. 'home' | 'detail' | 'player' | 'global' slot: string; // e.g. 'top' | 'carousel' | 'popup' | 'preroll' | ... adType: string; // e.g. 'BANNER' | 'CAROUSEL' | 'POPUP_IMAGE' | ... maxTries?: number; // optional, default 3 } /** * Handles ad selection for app clients using prebuilt Redis pools. * Reads the ad pool for a given (scene, slot, adType), picks a candidate, * and maps the cached payload back into the public AdDto shape. */ @Injectable() export class AdService { private readonly logger = new Logger(AdService.name); constructor( private readonly redis: RedisService, private readonly mongoPrisma: MongoPrismaService, ) {} /** * Core method for app-api: * Given a (scene, slot, adType), try to pick one ad from the prebuilt pool * and return its details as AdDto. Returns null if no suitable ad is found. */ async getAdForPlacement( params: GetAdForPlacementParams, ): Promise { const { scene, slot, adType } = params; const maxTries = params.maxTries ?? 3; const poolKey = CacheKeys.appAdPoolByType(adType); const pool = await this.readPoolWithDiagnostics(poolKey, { scene, slot, adType, }); if (!pool) { return null; } // Limit attempts so we don't loop too much if some ad entries are stale. const attempts = Math.min(maxTries, pool.length); // We'll try up to `attempts` random entries from the pool. const usedIndexes = new Set(); for (let i = 0; i < attempts; i++) { const idx = this.pickRandomIndex(pool.length, usedIndexes); if (idx === -1) break; usedIndexes.add(idx); const entry = pool[idx]; const adKey = CacheKeys.appAdById(entry.id); const cachedAd = (await this.redis.getJson(adKey)) ?? null; if (!cachedAd) { this.logger.debug( `getAdForPlacement: missing per-ad cache for adId=${entry.id}, key=${adKey}, poolKey=${poolKey}`, ); continue; } const dto = this.mapCachedAdToDto(cachedAd, adType); return dto; } // All attempts failed to find a valid cached ad this.logger.debug( `getAdForPlacement: no usable ad found after ${attempts} attempt(s) for scene=${scene}, slot=${slot}, adType=${adType}, poolKey=${poolKey}`, ); return null; } /** * Fetch and parse a pool entry list, while emitting useful diagnostics when * the pool is missing/empty or contains malformed JSON. Keeps API behavior * unchanged (returns null when the pool is not usable). */ private async readPoolWithDiagnostics( poolKey: string, placement: Pick, ): Promise { const raw = await this.redis.get(poolKey); if (raw === null) { this.logger.warn( `Ad pool cache miss for scene=${placement.scene}, slot=${placement.slot}, adType=${placement.adType}, key=${poolKey}. Cache may be cold; ensure cache-sync rebuilt pools.`, ); return null; } let parsed: unknown; try { parsed = JSON.parse(raw); } catch (err) { const message = err instanceof Error ? err.message : JSON.stringify(err ?? 'Unknown'); this.logger.error( `Failed to parse ad pool JSON for key=${poolKey}: ${message}`, ); return null; } if (!Array.isArray(parsed) || parsed.length === 0) { this.logger.warn( `Ad pool empty or invalid shape for scene=${placement.scene}, slot=${placement.slot}, adType=${placement.adType}, key=${poolKey}`, ); return null; } return parsed as AdPoolEntry[]; } /** * Pick a random index in [0, length-1] that is not in usedIndexes. * Returns -1 if all indexes are already used. */ private pickRandomIndex(length: number, usedIndexes: Set): number { if (usedIndexes.size >= length) return -1; // Simple approach: try a few times to find an unused index. // Since length is small in most pools, this is fine. for (let attempts = 0; attempts < 5; attempts++) { const idx = Math.floor(Math.random() * length); if (!usedIndexes.has(idx)) { return idx; } } // Fallback: linear scan for the first unused index for (let i = 0; i < length; i++) { if (!usedIndexes.has(i)) return i; } return -1; } /** * Map cached ad (as stored by mgnt-api) to the AdDto exposed to frontend. */ private mapCachedAdToDto(cachedAd: CachedAd, fallbackAdType: string): AdDto { return { id: cachedAd.id, adType: cachedAd.adType ?? fallbackAdType, title: cachedAd.title ?? '', advertiser: cachedAd.advertiser ?? '', content: cachedAd.adsContent ?? undefined, coverImg: cachedAd.adsCoverImg ?? undefined, targetUrl: cachedAd.adsUrl ?? undefined, }; } /** * Get paginated list of ads by type from Redis pool. * Reads the prebuilt ad pool from Redis, applies pagination, and fetches full ad details. * * Flow: * 1. Get total count from pool * 2. Compute start/stop indices for LRANGE * 3. Fetch poolEntries (AdPoolEntry array as JSON) * 4. Query MongoDB to fetch full ad details for the entries * 5. Reorder results to match Redis pool order * 6. Map to AdItemDto and return response */ async listAdsByType( adType: string, page: number, size: number, ): Promise { const poolKey = CacheKeys.appAdPoolByType(adType); // Step 1: Get the entire pool from Redis // Note: The key should be a STRING (JSON), but might be a LIST from old implementation let poolEntries: AdPoolEntry[] = []; try { // First, try to get as JSON (STRING type) const jsonData = await this.redis.getJson(poolKey); if (jsonData && Array.isArray(jsonData)) { poolEntries = jsonData; } else { // If getJson failed or returned null, the key might not exist this.logger.warn( `Ad pool cache miss or invalid for adType=${adType}, key=${poolKey}`, ); } } catch (err) { // If WRONGTYPE error, the key is stored as a different Redis type (likely from old code) // Delete the incompatible key so it can be rebuilt properly if (err instanceof Error && err.message?.includes('WRONGTYPE')) { this.logger.warn( `Ad pool key ${poolKey} has wrong type, deleting incompatible key`, ); try { await this.redis.del(poolKey); this.logger.log( `Deleted incompatible ad pool key ${poolKey}. It will be rebuilt on next cache warmup.`, ); } catch (delErr) { this.logger.error( `Failed to delete incompatible key ${poolKey}`, delErr instanceof Error ? delErr.stack : String(delErr), ); } } else { this.logger.error( `Failed to read ad pool for adType=${adType}, key=${poolKey}`, err instanceof Error ? err.stack : String(err), ); } } if (!Array.isArray(poolEntries) || poolEntries.length === 0) { this.logger.debug( `Ad pool empty or invalid for adType=${adType}, key=${poolKey}`, ); return { page, size, total: 0, adType: adType as AdType, items: [], }; } const total = poolEntries.length; // Step 2: Compute pagination indices const start = (page - 1) * size; const stop = start + size - 1; // Check if page is out of range if (start >= total) { this.logger.debug( `Page out of range: page=${page}, size=${size}, total=${total}`, ); return { page, size, total, adType: adType as AdType, items: [], }; } // Step 3: Slice the pool entries for this page const pagedEntries = poolEntries.slice(start, stop + 1); const adIds = pagedEntries.map((entry) => entry.id); // Step 4: Query MongoDB for full ad details let ads: Awaited>; try { const now = BigInt(Date.now()); ads = await this.mongoPrisma.ads.findMany({ where: { id: { in: adIds }, status: 1, startDt: { lte: now }, OR: [{ expiryDt: BigInt(0) }, { expiryDt: { gte: now } }], }, }); } catch (err) { this.logger.error( `Failed to query ads from MongoDB for adIds=${adIds.join(',')}`, err instanceof Error ? err.stack : String(err), ); return { page, size, total, adType: adType as AdType, items: [], }; } // Step 5: Create a map of ads by ID for fast lookup const adMap = new Map(ads.map((ad) => [ad.id, ad])); // Step 6: Reorder results to match the pool order and map to AdItemDto const items: AdItemDto[] = []; for (const entry of pagedEntries) { const ad = adMap.get(entry.id); if (!ad) { this.logger.debug( `Ad not found in MongoDB for adId=${entry.id} from pool`, ); continue; } items.push({ id: ad.id, advertiser: ad.advertiser ?? '', title: ad.title ?? '', adsContent: ad.adsContent ?? null, adsCoverImg: ad.adsCoverImg ?? null, adsUrl: ad.adsUrl ?? null, startDt: ad.startDt.toString(), expiryDt: ad.expiryDt.toString(), seq: ad.seq ?? 0, }); } return { page, size, total, adType: adType as AdType, items, }; } /** * Get an ad by ID and validate it's enabled and within date range. * Returns the ad with its relationships (channel, adsModule) loaded. * Returns null if ad is not found, disabled, or outside date range. */ async getAdByIdValidated(adsId: string): Promise<{ id: string; channelId: string; adsModuleId: string; adType: string; adsUrl: string | null; advertiser: string; title: string; } | null> { const now = BigInt(Date.now()); try { const ad = await this.mongoPrisma.ads.findUnique({ where: { id: adsId }, include: { channel: { select: { id: true } }, adsModule: { select: { id: true, adType: true } }, }, }); if (!ad) { this.logger.debug(`Ad not found: adsId=${adsId}`); return null; } // Validate status (1 = enabled) if (ad.status !== 1) { this.logger.debug(`Ad is disabled: adsId=${adsId}`); return null; } // Validate date range if (ad.startDt > now) { this.logger.debug(`Ad not started yet: adsId=${adsId}`); return null; } // If expiryDt is 0, it means no expiry; otherwise check if expired if (ad.expiryDt !== BigInt(0) && ad.expiryDt < now) { this.logger.debug(`Ad expired: adsId=${adsId}`); return null; } return { id: ad.id, channelId: ad.channelId, adsModuleId: ad.adsModuleId, adType: ad.adsModule.adType, adsUrl: ad.adsUrl, advertiser: ad.advertiser, title: ad.title, }; } catch (err) { this.logger.error( `Error fetching ad by ID: adsId=${adsId}`, err instanceof Error ? err.stack : String(err), ); return null; } } }