using System.Text; using System.Text.Json; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SaasMediaWorker.Configuration; namespace SaasMediaWorker.Services; /// /// NestJS Core API'ye bildirim gönderen HttpClient servisi. /// Worker işlem tamamlandığında veya hata oluştuğunda API'yi bilgilendirir. /// public class ApiNotificationService { private readonly HttpClient _httpClient; private readonly ILogger _logger; private readonly ApiSettings _settings; public ApiNotificationService( HttpClient httpClient, ILogger logger, IOptions settings) { _httpClient = httpClient; _logger = logger; _settings = settings.Value; _httpClient.BaseAddress = new Uri(_settings.CoreApiBaseUrl); _httpClient.Timeout = TimeSpan.FromSeconds(30); } /// /// Render tamamlandığında NestJS API'sine bildirim gönderir. /// public async Task NotifyCompletionAsync( string projectId, string renderJobId, string finalVideoUrl, long processingTimeMs) { var payload = new { projectId, renderJobId, status = "COMPLETED", finalVideoUrl, processingTimeMs, workerHostname = Environment.MachineName, completedAt = DateTime.UtcNow.ToString("O") }; await SendNotification("/internal/worker/callback", payload); _logger.LogInformation( "✅ API'ye tamamlanma bildirimi gönderildi — Project: {ProjectId}", projectId); } /// /// Render başarısız olduğunda NestJS API'sine hata bildirimi gönderir. /// public async Task NotifyFailureAsync( string projectId, string renderJobId, string errorMessage, int attemptNumber) { var payload = new { projectId, renderJobId, status = "FAILED", errorMessage, attemptNumber, workerHostname = Environment.MachineName, failedAt = DateTime.UtcNow.ToString("O") }; await SendNotification("/internal/worker/callback", payload); _logger.LogWarning( "API'ye hata bildirimi gönderildi — Project: {ProjectId}, Hata: {Error}", projectId, errorMessage); } private async Task SendNotification(string endpoint, object payload) { try { var content = new StringContent( JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json"); var response = await _httpClient.PostAsync(endpoint, content); if (!response.IsSuccessStatusCode) { _logger.LogWarning( "API bildirim yanıtı başarısız: {StatusCode}", response.StatusCode); } } catch (Exception ex) { // Bildirim hatası render sonucunu etkilememeli _logger.LogWarning(ex, "API bildirim gönderilemedi — endpoint: {Endpoint}", endpoint); } } }