/
VFlov
/
NotificationService_1
Обзор
Документация
Войти
/
VFlov
/
NotificationService_1
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
src/Shared/NotificationService.Shared/Repositories/NotificationRepository.cs
189 строк
6 KB
VFlov
Update
25 дек 2025, 21:02
25 дек 2025, 21:02
cf3965d
Код
Авторство
О чём код?
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using NotificationService.Shared.Data; using NotificationService.Shared.Interfaces; using NotificationService.Shared.Models; namespace NotificationService.Shared.Repositories; /// <summary> /// Репозиторий для работы с уведомлениями /// </summary> public class NotificationRepository : INotificationRepository { private readonly NotificationDbContext _context; private readonly ILogger<NotificationRepository> _logger; public NotificationRepository(NotificationDbContext context, ILogger<NotificationRepository> logger) { _context = context ?? throw new ArgumentNullException(nameof(context)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<NotificationRecord> CreateAsync(NotificationRecord record, CancellationToken cancellationToken = default) { if (record == null) { throw new ArgumentNullException(nameof(record)); } try { _logger.LogDebug("Creating notification record - Id: {Id}, Type: {Type}", record.Id, record.Type); _context.Notifications.Add(record); var changes = await _context.SaveChangesAsync(cancellationToken); _logger.LogInformation( "Created notification record - Id: {Id}, Type: {Type}, Status: {Status}", record.Id, record.Type, record.Status); return record; } catch (DbUpdateException ex) { _logger.LogError(ex, "Database error creating notification record - Id: {Id}", record.Id); throw; } catch (Exception ex) { _logger.LogError(ex, "Error creating notification record - Id: {Id}", record.Id); throw; } } public async Task<NotificationRecord?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default) { if (id == Guid.Empty) { throw new ArgumentException("Invalid notification ID", nameof(id)); } try { _logger.LogDebug("Retrieving notification record - Id: {Id}", id); var record = await _context.Notifications .AsNoTracking() .FirstOrDefaultAsync(n => n.Id == id, cancellationToken); if (record == null) { _logger.LogDebug("Notification record not found - Id: {Id}", id); } return record; } catch (Exception ex) { _logger.LogError(ex, "Error getting notification - Id: {Id}", id); throw; } } public async Task UpdateAsync(NotificationRecord record, CancellationToken cancellationToken = default) { if (record == null) { throw new ArgumentNullException(nameof(record)); } try { _logger.LogDebug( "Updating notification record - Id: {Id}, Status: {Status}", record.Id, record.Status); record.UpdatedAt = DateTime.UtcNow; _context.Notifications.Update(record); var changes = await _context.SaveChangesAsync(cancellationToken); _logger.LogInformation( "Updated notification record - Id: {Id}, Status: {Status}, RetryCount: {RetryCount}", record.Id, record.Status, record.RetryCount); } catch (DbUpdateConcurrencyException ex) { _logger.LogError(ex, "Concurrency error updating notification - Id: {Id}", record.Id); throw; } catch (DbUpdateException ex) { _logger.LogError(ex, "Database error updating notification - Id: {Id}", record.Id); throw; } catch (Exception ex) { _logger.LogError(ex, "Error updating notification - Id: {Id}", record.Id); throw; } } public async Task<IEnumerable<NotificationRecord>> GetByStatusAsync(NotificationStatus status, CancellationToken cancellationToken = default) { try { _logger.LogDebug("Retrieving notifications by status: {Status}", status); var records = await _context.Notifications .AsNoTracking() .Where(n => n.Status == status) .OrderByDescending(n => n.CreatedAt) .Take(100) .ToListAsync(cancellationToken); _logger.LogDebug( "Retrieved {Count} notifications with status: {Status}", records.Count, status); return records; } catch (Exception ex) { _logger.LogError(ex, "Error getting notifications by status: {Status}", status); throw; } } public async Task<IEnumerable<NotificationRecord>> GetFailedForRetryAsync(CancellationToken cancellationToken = default) { try { var cutoffTime = DateTime.UtcNow.AddMinutes(-5); // Retry after 5 minutes _logger.LogDebug( "Retrieving failed notifications for retry - Cutoff time: {CutoffTime}", cutoffTime); var records = await _context.Notifications .AsNoTracking() .Where(n => n.Status == NotificationStatus.Failed && n.RetryCount < 3 && n.UpdatedAt < cutoffTime) .OrderBy(n => n.UpdatedAt) .Take(50) .ToListAsync(cancellationToken); _logger.LogInformation( "Retrieved {Count} failed notifications for retry", records.Count); return records; } catch (Exception ex) { _logger.LogError(ex, "Error getting failed notifications for retry"); throw; } } }