using Application.Abstractions.Data; using Application.Helpers; using Domain.Entities.Stocks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SharedKernel; namespace Infrastructure.StockData; /// /// 채권지수 일별시세 수집 — KRX OpenAPI (idx/bon_dd_trd, AUTH_KEY 헤더). /// 응답 shape(총수익·순가격·재투자·시장가격 지수 + 듀레이션·컨벡시티·YTM)이 주식/파생 지수와 달라 IndexPriceSyncService 와 분리한다. /// 기본 18:35 KST 실행(지수 수집 18:30 뒤). 공용 KrxBackfill 로 최근 BackfillYears(기본 3)년치를 endDate(직전 영업일)부터 /// 과거로 훑으며 미적재일만 채운다. quota 보호를 위해 1회 실행당 BackfillMaxPerRun(기본 60)일까지만 fetch → /// 여러 날에 걸쳐 3년치를 메우고 이후엔 최신만 유지한다. 각 날짜는 1개 엔드포인트를 수집해 BondIndexDailyPrice upsert /// (UQ = GroupName+TradeDate). ApiKey 미설정 시 로그만 남기고 skip (다른 KRX 배치와 동일 정책). /// internal sealed class BondIndexPriceSyncService( IServiceScopeFactory scopeFactory, IHttpClientFactory httpClientFactory, IOptions settings, ILogger logger ) : DailyScheduledService(logger) { private const string EndpointPath = "/svc/apis/idx/bon_dd_trd"; protected override string JobName => "BondIndexPriceSync"; protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.BondIndexSyncTime, new TimeOnly(18, 35)); protected override int MaxRetryCount => 2; protected override TimeSpan RetryDelay => TimeSpan.FromHours(2); protected override async Task RunOnceAsync(DateOnly todayKst, CancellationToken ct) { var cfg = settings.Value.KRXCoKr; if (string.IsNullOrWhiteSpace(cfg.ApiKey)) { Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName); return true; } using var scope = scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName); var endDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct); var years = cfg.BackfillYears > 0 ? cfg.BackfillYears : 3; var startDate = todayKst.AddYears(-years); // 백필 창 전체의 휴장일을 한 번에 로드 (KrxBackfill 은 주말은 자동 제외, 휴장일만 필요) var holidays = (await db.MarketHoliday.AsNoTracking() .Where(c => c.Date >= startDate && c.Date <= endDate) .Select(c => c.Date) .ToListAsync(ct)).ToHashSet(); var maxPerRun = cfg.BackfillMaxPerRun > 0 ? cfg.BackfillMaxPerRun : 60; var fetched = await KrxBackfill.RunAsync( existsForDate: (day, token) => db.BondIndexDailyPrice.AsNoTracking().AnyAsync(c => c.TradeDate == day, token), fetchAndUpsertForDate: (day, token) => FetchAndUpsertAsync(db, client, cfg.BaseUrl, cfg.ApiKey, day, token), startDate: startDate, endDate: endDate, holidays: holidays, maxPerRun: maxPerRun, delayMs: 300, ct: ct); Logger.LogInformation("[{Job}] 완료 — 창=[{Start}~{End}], 이번 실행 fetch={Fetched}일 (maxPerRun={Max})", JobName, startDate, endDate, fetched, maxPerRun); // fetch 가 0 이어도(이미 최신까지 적재됨) 정상 완료 — 재시도 불필요 return true; } /// 한 날짜에 대해 채권지수 엔드포인트를 수집하고 BondIndexDailyPrice upsert. private async Task FetchAndUpsertAsync(IAppDbContext db, HttpClient client, string baseUrl, string apiKey, DateOnly day, CancellationToken ct) { var url = $"{baseUrl.TrimEnd('/')}{EndpointPath}?basDd={day:yyyyMMdd}"; var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, apiKey, Logger, ct); var rows = KrxBondIndexParser.ParseBondIndexPrices(json); Logger.LogInformation("[{Job}] basDd={Day} rows={Rows}", JobName, day, rows.Count); if (rows.Count == 0) { Logger.LogInformation("[{Job}] basDd={Day} 채권지수 미반영 (0건)", JobName, day); return; } var existing = await db.BondIndexDailyPrice.Where(c => c.TradeDate == day).ToListAsync(ct); var existingByKey = existing.ToDictionary(c => c.GroupName); var inserted = 0; var updated = 0; foreach (var row in rows) { if (existingByKey.TryGetValue(row.GroupName, out var price)) { price.Update(row.TotalEarningIndex, row.TotalEarningChange, row.NetPriceIndex, row.NetPriceChange, row.ZeroReinvestIndex, row.ZeroReinvestChange, row.CallReinvestIndex, row.CallReinvestChange, row.MarketPriceIndex, row.MarketPriceChange, row.AvgDuration, row.AvgConvexity, row.AvgYield); updated++; } else { var created = BondIndexDailyPrice.Create(row.GroupName, row.TradeDate, row.TotalEarningIndex, row.TotalEarningChange, row.NetPriceIndex, row.NetPriceChange, row.ZeroReinvestIndex, row.ZeroReinvestChange, row.CallReinvestIndex, row.CallReinvestChange, row.MarketPriceIndex, row.MarketPriceChange, row.AvgDuration, row.AvgConvexity, row.AvgYield); await db.BondIndexDailyPrice.AddAsync(created, ct); existingByKey[row.GroupName] = created; inserted++; } } await db.SaveChangesAsync(ct); Logger.LogInformation("[{Job}] basDd={Day} 적재 — rows={Rows}, inserted={Inserted}, updated={Updated}", JobName, day, rows.Count, inserted, updated); } }