From 2472f865adc8cb69cc79bfef74f690b47d14cb5e Mon Sep 17 00:00:00 2001 From: dahyeon Date: Sun, 26 Apr 2026 01:22:38 -0700 Subject: [PATCH] . --- apps/api/package.json | 1 + .../modules/global/garnet/garnet.constants.ts | 1 + .../modules/global/garnet/garnet.module.ts | 57 +++ .../modules/global/garnet/garnet.service.ts | 90 ++++ apps/api/src/modules/global/global.module.ts | 7 +- .../modules/riot/riot-ddragon.controller.ts | 19 + .../src/modules/riot/riot-ddragon.service.ts | 132 ++++++ apps/api/src/modules/riot/riot.module.ts | 6 +- apps/web/src/api/hooks.ts | 17 + apps/web/src/api/types.ts | 8 + apps/web/src/pages/AuctionPage.tsx | 30 +- apps/web/src/pages/MatchDetailPage.tsx | 6 +- garnet.ts | 389 ++++++++++++++++++ pnpm-lock.yaml | 80 ++++ 14 files changed, 825 insertions(+), 18 deletions(-) create mode 100644 apps/api/src/modules/global/garnet/garnet.constants.ts create mode 100644 apps/api/src/modules/global/garnet/garnet.module.ts create mode 100644 apps/api/src/modules/global/garnet/garnet.service.ts create mode 100644 apps/api/src/modules/riot/riot-ddragon.controller.ts create mode 100644 apps/api/src/modules/riot/riot-ddragon.service.ts create mode 100644 garnet.ts diff --git a/apps/api/package.json b/apps/api/package.json index a5a271ab..a45ff898 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -37,6 +37,7 @@ "jose": "^6.2.2", "mongoose": "^9.4.1", "nats": "^2.29.3", + "redis": "^5.12.1", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", "socket.io": "^4.8.3", diff --git a/apps/api/src/modules/global/garnet/garnet.constants.ts b/apps/api/src/modules/global/garnet/garnet.constants.ts new file mode 100644 index 00000000..842616cb --- /dev/null +++ b/apps/api/src/modules/global/garnet/garnet.constants.ts @@ -0,0 +1 @@ +export const GARNET_CLIENT = Symbol('GARNET_CLIENT'); diff --git a/apps/api/src/modules/global/garnet/garnet.module.ts b/apps/api/src/modules/global/garnet/garnet.module.ts new file mode 100644 index 00000000..8bc9ec66 --- /dev/null +++ b/apps/api/src/modules/global/garnet/garnet.module.ts @@ -0,0 +1,57 @@ +import { Logger, Module } from '@nestjs/common'; +import { createClient } from 'redis'; +import { SecretModule } from '../secret/secret.module'; +import { SecretService } from '../secret/secret.service'; +import { GARNET_CLIENT } from './garnet.constants'; +import { GarnetService, type GarnetRedisClient } from './garnet.service'; + +function normalizeGarnetUrl(endpoint: string): string { + const trimmed = endpoint.trim(); + if (!trimmed) { + throw new Error('GARNET_ENDPOINT cannot be empty'); + } + if (/^redis(s)?:\/\//iu.test(trimmed)) { + return trimmed; + } + return `redis://${trimmed}`; +} + +@Module({ + imports: [SecretModule], + providers: [ + { + provide: GARNET_CLIENT, + inject: [SecretService], + useFactory: async ( + secretService: SecretService, + ): Promise => { + await secretService.ready(); + + const [endpoint, username, password] = await Promise.all([ + secretService.get('GARNET_ENDPOINT'), + secretService.get('GARNET_USERID'), + secretService.get('GARNET_PASSWORD'), + ]); + + const logger = new Logger('GarnetClient'); + const client = createClient({ + url: normalizeGarnetUrl(endpoint), + username, + password, + }); + + client.on('error', (error) => { + logger.error(`Garnet client error: ${error?.message ?? error}`); + }); + + await client.connect(); + logger.log('Garnet connected'); + + return client; + }, + }, + GarnetService, + ], + exports: [GarnetService, GARNET_CLIENT], +}) +export class GarnetModule {} diff --git a/apps/api/src/modules/global/garnet/garnet.service.ts b/apps/api/src/modules/global/garnet/garnet.service.ts new file mode 100644 index 00000000..5abffe85 --- /dev/null +++ b/apps/api/src/modules/global/garnet/garnet.service.ts @@ -0,0 +1,90 @@ +import { + Inject, + Injectable, + Logger, + OnModuleDestroy, +} from '@nestjs/common'; +import type { createClient } from 'redis'; +import { GARNET_CLIENT } from './garnet.constants'; + +export type GarnetRedisClient = ReturnType; + +@Injectable() +export class GarnetService implements OnModuleDestroy { + private readonly logger = new Logger(GarnetService.name); + + constructor( + @Inject(GARNET_CLIENT) private readonly client: GarnetRedisClient, + ) {} + + async onModuleDestroy() { + try { + await this.client.quit(); + } catch { + this.client.destroy(); + } + } + + public raw(): GarnetRedisClient { + return this.client; + } + + public async getJson(key: string): Promise { + const raw = await this.client.get(key); + if (!raw) return null; + try { + return JSON.parse(raw) as T; + } catch (err) { + this.logger.warn( + `Failed to JSON.parse cached value for key="${key}": ${ + (err as Error)?.message ?? err + }`, + ); + return null; + } + } + + public async setJson( + key: string, + value: unknown, + ttlSeconds?: number, + ): Promise { + const serialized = JSON.stringify(value); + if (ttlSeconds && ttlSeconds > 0) { + await this.client.set(key, serialized, { EX: ttlSeconds }); + return; + } + await this.client.set(key, serialized); + } + + public async getString(key: string): Promise { + return this.client.get(key); + } + + public async setString( + key: string, + value: string, + ttlSeconds?: number, + ): Promise { + if (ttlSeconds && ttlSeconds > 0) { + await this.client.set(key, value, { EX: ttlSeconds }); + return; + } + await this.client.set(key, value); + } + + public async setStringIfAbsent( + key: string, + value: string, + ttlSeconds?: number, + ): Promise { + const options: { EX?: number; NX: true } = { NX: true }; + if (ttlSeconds && ttlSeconds > 0) options.EX = ttlSeconds; + const result = await this.client.set(key, value, options); + return result === 'OK'; + } + + public async delete(key: string): Promise { + return this.client.del(key); + } +} diff --git a/apps/api/src/modules/global/global.module.ts b/apps/api/src/modules/global/global.module.ts index 4cccb788..ba3ea479 100644 --- a/apps/api/src/modules/global/global.module.ts +++ b/apps/api/src/modules/global/global.module.ts @@ -1,14 +1,13 @@ import { Module, Global } from '@nestjs/common'; import { SecretModule } from './secret/secret.module'; -// import { DatabaseModule } from './database/database.module'; import { NatsModule } from './nats/nats.module'; import { DatabaseModule } from './database/database.module'; -// import { DatabaseModule } from './database/database.module'; +import { GarnetModule } from './garnet/garnet.module'; @Global() @Module({ - imports: [SecretModule, NatsModule, DatabaseModule], + imports: [SecretModule, NatsModule, DatabaseModule, GarnetModule], providers: [], - exports: [SecretModule, NatsModule, DatabaseModule], + exports: [SecretModule, NatsModule, DatabaseModule, GarnetModule], }) export class GlobalModule {} diff --git a/apps/api/src/modules/riot/riot-ddragon.controller.ts b/apps/api/src/modules/riot/riot-ddragon.controller.ts new file mode 100644 index 00000000..4dbd58a0 --- /dev/null +++ b/apps/api/src/modules/riot/riot-ddragon.controller.ts @@ -0,0 +1,19 @@ +import { Controller, Get, Query } from '@nestjs/common'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { + RiotDdragonService, + type DdragonManifest, +} from './riot-ddragon.service'; + +@Controller('riot/ddragon') +export class RiotDdragonController { + constructor(private readonly ddragonService: RiotDdragonService) {} + + @Get('manifest') + @AllowPublicAccess() + public async getManifest( + @Query('locale') locale?: string, + ): Promise { + return this.ddragonService.getManifest(locale ?? 'ko_KR'); + } +} diff --git a/apps/api/src/modules/riot/riot-ddragon.service.ts b/apps/api/src/modules/riot/riot-ddragon.service.ts new file mode 100644 index 00000000..d10fce21 --- /dev/null +++ b/apps/api/src/modules/riot/riot-ddragon.service.ts @@ -0,0 +1,132 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { GarnetService } from '../global/garnet/garnet.service'; + +const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com'; +const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`; +const DEFAULT_LOCALE = 'ko_KR'; +const CACHE_TTL_SECONDS = 24 * 60 * 60; +const FETCH_TIMEOUT_MS = 10_000; + +export interface DdragonManifest { + version: string; + cdn: string; + locale: string; + champions: Record; + fetchedAt: string; +} + +interface ChampionDataEntry { + key: string; + id: string; +} + +interface ChampionDataResponse { + data: Record; +} + +@Injectable() +export class RiotDdragonService { + private readonly logger = new Logger(RiotDdragonService.name); + private inflight = new Map>(); + + constructor(private readonly garnetService: GarnetService) {} + + public async getManifest(locale: string = DEFAULT_LOCALE): Promise { + const normalizedLocale = normalizeLocale(locale); + const cacheKey = manifestCacheKey(normalizedLocale); + + const cached = await this.garnetService.getJson(cacheKey); + if (cached) return cached; + + const pending = this.inflight.get(cacheKey); + if (pending) return pending; + + const promise = this.buildManifest(normalizedLocale) + .then(async (manifest) => { + await this.garnetService.setJson(cacheKey, manifest, CACHE_TTL_SECONDS); + return manifest; + }) + .finally(() => { + this.inflight.delete(cacheKey); + }); + + this.inflight.set(cacheKey, promise); + return promise; + } + + private async buildManifest(locale: string): Promise { + const version = await this.fetchLatestVersion(); + const champions = await this.fetchChampionMap(version, locale); + return { + version, + cdn: DDRAGON_CDN, + locale, + champions, + fetchedAt: new Date().toISOString(), + }; + } + + private async fetchLatestVersion(): Promise { + const versions = await this.fetchJson(`${DDRAGON_BASE}/api/versions.json`); + if (!Array.isArray(versions) || typeof versions[0] !== 'string') { + throw new Error('ddragon versions.json response is malformed.'); + } + return versions[0]; + } + + private async fetchChampionMap( + version: string, + locale: string, + ): Promise> { + const url = `${DDRAGON_CDN}/${version}/data/${locale}/champion.json`; + const payload = await this.fetchJson(url); + if (!payload || typeof payload !== 'object' || !payload.data) { + throw new Error(`ddragon champion.json response is malformed (${url}).`); + } + + const map: Record = {}; + for (const entry of Object.values(payload.data)) { + if (entry?.key && entry.id) { + map[entry.key] = entry.id; + } + } + return map; + } + + private async fetchJson(url: string): Promise { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + try { + const response = await fetch(url, { + method: 'GET', + headers: { Accept: 'application/json' }, + signal: controller.signal, + }); + if (!response.ok) { + throw new Error( + `ddragon request failed (${response.status}): ${url}`, + ); + } + return (await response.json()) as T; + } catch (err) { + this.logger.error( + `ddragon fetch error for ${url}: ${(err as Error)?.message ?? err}`, + ); + throw err; + } finally { + clearTimeout(timeout); + } + } +} + +function normalizeLocale(locale: string): string { + const trimmed = locale.trim(); + if (!/^[a-zA-Z]{2}_[a-zA-Z]{2}$/.test(trimmed)) { + return DEFAULT_LOCALE; + } + return `${trimmed.slice(0, 2).toLowerCase()}_${trimmed.slice(3).toUpperCase()}`; +} + +function manifestCacheKey(locale: string): string { + return `ddragon:manifest:${locale}`; +} diff --git a/apps/api/src/modules/riot/riot.module.ts b/apps/api/src/modules/riot/riot.module.ts index 076f6133..95b00de7 100644 --- a/apps/api/src/modules/riot/riot.module.ts +++ b/apps/api/src/modules/riot/riot.module.ts @@ -4,6 +4,8 @@ import { RiotAccountEnrichmentService } from './riot-account-enrichment.service' import { RiotAccountService } from './riot-account.service'; import { RiotChampionMasteryService } from './riot-champion-mastery.service'; import { RiotClientService } from './riot.client.service'; +import { RiotDdragonController } from './riot-ddragon.controller'; +import { RiotDdragonService } from './riot-ddragon.service'; import { RiotLeagueService } from './riot-league.service'; import { RiotMatchService } from './riot-match.service'; import { RiotSummonerService } from './riot-summoner.service'; @@ -11,7 +13,7 @@ import { RiotWebhookController } from './riot-webhook.controller'; @Module({ imports: [SecretModule], - controllers: [RiotWebhookController], + controllers: [RiotWebhookController, RiotDdragonController], providers: [ RiotClientService, RiotAccountService, @@ -20,6 +22,7 @@ import { RiotWebhookController } from './riot-webhook.controller'; RiotLeagueService, RiotChampionMasteryService, RiotAccountEnrichmentService, + RiotDdragonService, ], exports: [ RiotClientService, @@ -29,6 +32,7 @@ import { RiotWebhookController } from './riot-webhook.controller'; RiotLeagueService, RiotChampionMasteryService, RiotAccountEnrichmentService, + RiotDdragonService, ], }) export class RiotModule {} diff --git a/apps/web/src/api/hooks.ts b/apps/web/src/api/hooks.ts index 92ddeabe..22bc1f82 100644 --- a/apps/web/src/api/hooks.ts +++ b/apps/web/src/api/hooks.ts @@ -5,11 +5,14 @@ import type { ApiAuction, ApiCommunity, ApiMatch, + DdragonManifest, MatchStatus, MatchesResponse, MeResponse, } from './types'; +const DDRAGON_MANIFEST_STALE_MS = 24 * 60 * 60 * 1000; + interface MatchesQueryOptions { status?: MatchStatus; limit?: number; @@ -74,6 +77,20 @@ export function useAuction( }); } +export function useDdragonManifest(locale = 'ko_KR') { + return useQuery({ + queryKey: ['ddragon-manifest', locale], + queryFn: () => + apiFetch( + `/riot/ddragon/manifest?locale=${encodeURIComponent(locale)}`, + ), + staleTime: DDRAGON_MANIFEST_STALE_MS, + gcTime: DDRAGON_MANIFEST_STALE_MS, + refetchOnMount: false, + refetchOnReconnect: false, + }); +} + export function useMe() { const authUserId = useAuthUserId(); diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 77a92613..58b84bb6 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -220,3 +220,11 @@ export interface MeResponse { export interface MatchesResponse { matches: ApiMatch[]; } + +export interface DdragonManifest { + version: string; + cdn: string; + locale: string; + champions: Record; + fetchedAt: string; +} diff --git a/apps/web/src/pages/AuctionPage.tsx b/apps/web/src/pages/AuctionPage.tsx index 32602629..7ed563a1 100644 --- a/apps/web/src/pages/AuctionPage.tsx +++ b/apps/web/src/pages/AuctionPage.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from 'react'; import { Link, useParams } from 'react-router'; -import { useAuction, useMatch, useMe } from '../api/hooks'; +import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks'; import { formatTierLabel, getTierColorToken, @@ -14,6 +14,7 @@ import { useDevCaptainSide, } from '../config'; import { ApiError } from '../lib/api'; +import { championIconUrl, profileIconUrl } from '../lib/ddragon'; import { positionIcon, positionLabel } from '../lib/league'; import type { Position } from '../api/types'; @@ -53,6 +54,7 @@ function TeamPanel({ isActive: boolean; isLeft: boolean; }) { + const { data: ddragon } = useDdragonManifest(); const borderColor = team.side === 'blue' ? 'border-blue-500/25' : 'border-red-500/25'; const accentBar = team.side === 'blue' ? 'bg-blue-500' : 'bg-red-500'; @@ -92,7 +94,7 @@ function TeamPanel({
@@ -190,15 +193,19 @@ function PlayerSpotlight({
{player.masteries.length > 0 ? ( - player.masteries.map((mastery) => ( + player.masteries.map((mastery) => { + const iconUrl = championIconUrl(ddragon, mastery.championId); + return (
- {mastery.championName} + {iconUrl ? ( + {mastery.championName} + ) : null}
@@ -209,7 +216,8 @@ function PlayerSpotlight({
- )) + ); + }) ) : (
숙련도 데이터가 없습니다. diff --git a/apps/web/src/pages/MatchDetailPage.tsx b/apps/web/src/pages/MatchDetailPage.tsx index cd456d5a..58b35be1 100644 --- a/apps/web/src/pages/MatchDetailPage.tsx +++ b/apps/web/src/pages/MatchDetailPage.tsx @@ -1,7 +1,7 @@ import { useEffect, useState } from 'react'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { Link, useNavigate, useParams } from 'react-router'; -import { useAuction, useMatch, useMe } from '../api/hooks'; +import { useAuction, useDdragonManifest, useMatch, useMe } from '../api/hooks'; import { buildDefaultPreferredPositions, formatTierLabel, @@ -13,6 +13,7 @@ import { } from '../api/mappers'; import { DEFAULT_COMMUNITY_ID, useAuthUserId } from '../config'; import { apiFetch, ApiError } from '../lib/api'; +import { profileIconUrl } from '../lib/ddragon'; import { positionIcon, positionLabel } from '../lib/league'; import type { Position } from '../api/types'; @@ -92,6 +93,7 @@ function ParticipantRow({ index: number; assignedPos?: Position; }) { + const { data: ddragon } = useDdragonManifest(); return ( @@ -101,7 +103,7 @@ function ParticipantRow({
; + +export interface StreamEntry { + deliveriesCounter?: number | undefined; + id: string; + message: Record; + millisElapsedFromDelivery?: number | undefined; +} + +export interface StreamReadResult { + messages: StreamEntry[]; + name: string; +} + +export interface StreamPendingEntry { + consumer: string; + deliveriesCounter: number; + id: string; + millisecondsSinceLastDelivery: number; +} + +interface RawStreamMessage { + deliveriesCounter?: number | undefined; + id: string; + message: unknown; + millisElapsedFromDelivery?: number | undefined; +} + +interface RawStreamReadResult { + messages: RawStreamMessage[]; + name: string; +} + +function normalizeGarnetUrl(endpoint: string): string { + const trimmed = endpoint.trim(); + if (!trimmed) { + throw new Error("GARNET_ENDPOINT cannot be empty"); + } + + if (/^redis(s)?:\/\//iu.test(trimmed)) { + return trimmed; + } + + return `redis://${trimmed}`; +} + +function normalizeStreamFields(fields: unknown): Record { + if (fields instanceof Map) { + return Object.fromEntries( + [...fields.entries()].map(([key, value]) => [String(key), String(value)]), + ); + } + + if (typeof fields === "object" && fields !== null) { + return Object.fromEntries( + Object.entries(fields as Record).map(([key, value]) => [ + key, + String(value), + ]), + ); + } + + return {}; +} + +export class GarnetClient { + private client: GarnetRedisClient | null = null; + private readonly logger = getLogger(); + + private getClient(): GarnetRedisClient { + if (!this.client) { + throw new Error("Garnet client not connected"); + } + + return this.client; + } + + async connect(): Promise { + const endpoint = getSecret("GARNET_ENDPOINT"); + const username = getSecret("GARNET_USERID"); + const password = getSecret("GARNET_PASSWORD"); + + if (!endpoint || !username || !password) { + throw new Error("Missing Garnet credentials in secrets"); + } + + const client = createClient({ + password, + url: normalizeGarnetUrl(endpoint), + username, + }); + + client.on("error", (error) => { + this.logger.error({ err: error }, "[Garnet] Client error"); + }); + + await client.connect(); + this.client = client; + + this.logger.info("✓ Garnet connected"); + } + + async getJson(key: string): Promise { + const rawValue = await this.getClient().get(key); + if (!rawValue) { + return null; + } + + return JSON.parse(rawValue) as T; + } + + async setJson( + key: string, + value: unknown, + ttlSeconds?: number, + ): Promise { + const serialized = JSON.stringify(value); + const client = this.getClient(); + + if (ttlSeconds && ttlSeconds > 0) { + await client.set(key, serialized, { EX: ttlSeconds }); + return; + } + + await client.set(key, serialized); + } + + async getString(key: string): Promise { + return this.getClient().get(key); + } + + async setString( + key: string, + value: string, + ttlSeconds?: number, + ): Promise { + const client = this.getClient(); + + if (ttlSeconds && ttlSeconds > 0) { + await client.set(key, value, { EX: ttlSeconds }); + return; + } + + await client.set(key, value); + } + + async setStringIfAbsent( + key: string, + value: string, + ttlSeconds?: number, + ): Promise { + const client = this.getClient(); + const setOptions: { + EX?: number; + NX: true; + } = { + NX: true, + }; + if (ttlSeconds && ttlSeconds > 0) { + setOptions.EX = ttlSeconds; + } + const result = await client.set(key, value, { + ...setOptions, + }); + return result === "OK"; + } + + async delete(key: string): Promise { + return this.getClient().del(key); + } + + async getHash(key: string): Promise> { + return this.getClient().hGetAll(key); + } + + async setHash(key: string, fields: Record): Promise { + await this.getClient().hSet(key, fields); + } + + async appendStream( + key: string, + fields: Record, + options?: { maxLen?: number | undefined }, + ): Promise { + const trimOptions = + options?.maxLen && options.maxLen > 0 + ? { + TRIM: { + strategy: "MAXLEN" as const, + strategyModifier: "~" as const, + threshold: options.maxLen, + }, + } + : undefined; + + return this.getClient().xAdd(key, "*", fields, trimOptions); + } + + async createConsumerGroup( + key: string, + group: string, + startId = "$", + ): Promise { + await this.getClient().xGroupCreate(key, group, startId, { + MKSTREAM: true, + }); + } + + async readGroup( + key: string, + group: string, + consumer: string, + startId: string, + options?: { + blockMs?: number | undefined; + count?: number | undefined; + }, + ): Promise { + const readOptions: { + BLOCK?: number; + COUNT?: number; + } = {}; + if (options?.blockMs !== undefined) { + readOptions.BLOCK = options.blockMs; + } + if (options?.count !== undefined) { + readOptions.COUNT = options.count; + } + + const reply = await this.getClient().xReadGroup( + group, + consumer, + { + key, + id: startId, + }, + readOptions, + ); + + if (!reply) { + return null; + } + + return (reply as RawStreamReadResult[]).map((stream) => ({ + name: String(stream.name), + messages: stream.messages.map((message) => ({ + deliveriesCounter: + typeof message.deliveriesCounter === "number" + ? message.deliveriesCounter + : undefined, + id: String(message.id), + message: normalizeStreamFields(message.message), + millisElapsedFromDelivery: + typeof message.millisElapsedFromDelivery === "number" + ? message.millisElapsedFromDelivery + : undefined, + })), + })); + } + + async acknowledgeStream( + key: string, + group: string, + ids: string | string[], + ): Promise { + return this.getClient().xAck(key, group, ids); + } + + async getPendingStreamRange( + key: string, + group: string, + count: number, + options?: { + consumer?: string | undefined; + idleMs?: number | undefined; + start?: string | undefined; + end?: string | undefined; + }, + ): Promise { + const pendingOptions: { + IDLE?: number; + consumer?: string; + } = {}; + if (options?.idleMs !== undefined) { + pendingOptions.IDLE = options.idleMs; + } + if (options?.consumer !== undefined) { + pendingOptions.consumer = options.consumer; + } + + const reply = await this.getClient().xPendingRange( + key, + group, + options?.start ?? "-", + options?.end ?? "+", + count, + pendingOptions, + ); + + return reply.map((entry) => ({ + consumer: String(entry.consumer), + deliveriesCounter: entry.deliveriesCounter, + id: String(entry.id), + millisecondsSinceLastDelivery: entry.millisecondsSinceLastDelivery, + })); + } + + async claimPendingStream( + key: string, + group: string, + consumer: string, + minIdleTimeMs: number, + ids: string | string[], + options?: { + retryCount?: number | undefined; + }, + ): Promise { + const claimOptions: { + RETRYCOUNT?: number; + } = {}; + if (options?.retryCount !== undefined) { + claimOptions.RETRYCOUNT = options.retryCount; + } + + const claimed = await this.getClient().xClaim( + key, + group, + consumer, + minIdleTimeMs, + ids, + claimOptions, + ); + + return claimed.flatMap((message) => { + if (!message) { + return []; + } + + return [ + { + deliveriesCounter: + typeof message.deliveriesCounter === "number" + ? message.deliveriesCounter + : undefined, + id: String(message.id), + message: normalizeStreamFields(message.message), + millisElapsedFromDelivery: + typeof message.millisElapsedFromDelivery === "number" + ? message.millisElapsedFromDelivery + : undefined, + }, + ]; + }); + } + + async scanKeys(pattern: string): Promise { + const keys: string[] = []; + + for await (const batch of this.getClient().scanIterator({ + COUNT: 100, + MATCH: pattern, + })) { + for (const key of batch) { + keys.push(String(key)); + } + } + + return keys; + } + + async close(): Promise { + if (!this.client) { + return; + } + + const client = this.client; + this.client = null; + + try { + await client.quit(); + } catch { + client.destroy(); + } + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b2218e9f..472ebb7c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -50,6 +50,9 @@ importers: nats: specifier: ^2.29.3 version: 2.29.3 + redis: + specifier: ^5.12.1 + version: 5.12.1 reflect-metadata: specifier: ^0.2.2 version: 0.2.2 @@ -1395,6 +1398,42 @@ packages: '@poppinss/exception@1.2.3': resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==} + '@redis/bloom@5.12.1': + resolution: {integrity: sha512-PUUfv+ms7jgPSBVoo/DN4AkPHj4D5TZSd6SbJX7egzBplkYUcKmHRE8RKia7UtZ8bSQbLguLvxVO+asKtQfZWA==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@redis/client': ^5.12.1 + + '@redis/client@5.12.1': + resolution: {integrity: sha512-7aPGWeqA3uFm43o19umzdl16CEjK/JQGtSXVPevplTaOU3VJA/rseBC1QvYUz9lLDIMBimc4SW/zrW4S89BaCA==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@node-rs/xxhash': ^1.1.0 + '@opentelemetry/api': '>=1 <2' + peerDependenciesMeta: + '@node-rs/xxhash': + optional: true + '@opentelemetry/api': + optional: true + + '@redis/json@5.12.1': + resolution: {integrity: sha512-eOze75esLve4vfqDel7aMX08CNaiLLQS2fV8mpRN9NxPe1rVR4vQyYiW/OgtGUysF6QOr9ANhfxABKNOJfXdKg==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@redis/client': ^5.12.1 + + '@redis/search@5.12.1': + resolution: {integrity: sha512-ItlxbxC9cKI6IU1TLWoczwJCRb6TdmkEpWv05UrPawqaAnWGRu3rcIqsc5vN483T2fSociuyV1UkWIL5I4//2w==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@redis/client': ^5.12.1 + + '@redis/time-series@5.12.1': + resolution: {integrity: sha512-c6JL6E3EcZJuNqKFz+KM+l9l5mpcQiKvTwgA3blt5glWJ8hjDk0yeHN3beE/MpqYIQ8UEX44ItQzgkE/gCBELQ==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@redis/client': ^5.12.1 + '@rolldown/binding-android-arm64@1.0.0-rc.15': resolution: {integrity: sha512-YYe6aWruPZDtHNpwu7+qAHEMbQ/yRl6atqb/AhznLTnD3UY99Q1jE7ihLSahNWkF4EqRPVC4SiR4O0UkLK02tA==} engines: {node: ^20.19.0 || >=22.12.0} @@ -2431,6 +2470,10 @@ packages: resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==} engines: {node: '>=0.8'} + cluster-key-slot@1.1.2: + resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==} + engines: {node: '>=0.10.0'} + co@4.6.0: resolution: {integrity: sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==} engines: {iojs: '>= 1.0.0', node: '>= 0.12.0'} @@ -3838,6 +3881,10 @@ packages: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} + redis@5.12.1: + resolution: {integrity: sha512-LDsoVvb/CpoV9EN3FXvgvSHNJWuCIzl9MiO3ppOevuGLpSGJhwfQjpEwfFJcQvNSddHADDdZaWx0HnmMxRXG7g==} + engines: {node: '>= 18.19.0'} + reflect-metadata@0.2.2: resolution: {integrity: sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==} @@ -6044,6 +6091,26 @@ snapshots: '@poppinss/exception@1.2.3': {} + '@redis/bloom@5.12.1(@redis/client@5.12.1)': + dependencies: + '@redis/client': 5.12.1 + + '@redis/client@5.12.1': + dependencies: + cluster-key-slot: 1.1.2 + + '@redis/json@5.12.1(@redis/client@5.12.1)': + dependencies: + '@redis/client': 5.12.1 + + '@redis/search@5.12.1(@redis/client@5.12.1)': + dependencies: + '@redis/client': 5.12.1 + + '@redis/time-series@5.12.1(@redis/client@5.12.1)': + dependencies: + '@redis/client': 5.12.1 + '@rolldown/binding-android-arm64@1.0.0-rc.15': optional: true @@ -7242,6 +7309,8 @@ snapshots: clone@1.0.4: {} + cluster-key-slot@1.1.2: {} + co@4.6.0: {} collect-v8-coverage@1.0.3: {} @@ -8768,6 +8837,17 @@ snapshots: readdirp@4.1.2: {} + redis@5.12.1: + dependencies: + '@redis/bloom': 5.12.1(@redis/client@5.12.1) + '@redis/client': 5.12.1 + '@redis/json': 5.12.1(@redis/client@5.12.1) + '@redis/search': 5.12.1(@redis/client@5.12.1) + '@redis/time-series': 5.12.1(@redis/client@5.12.1) + transitivePeerDependencies: + - '@node-rs/xxhash' + - '@opentelemetry/api' + reflect-metadata@0.2.2: {} require-directory@2.1.1: {}