|
| 1 | +using Microsoft.Extensions.Logging; |
| 2 | +using Moonglade.Data; |
| 3 | +using System.Collections.Concurrent; |
| 4 | + |
| 5 | +namespace Moonglade.Core.PostFeature; |
| 6 | + |
| 7 | +public record AddRequestCountCommand(Guid PostId) : IRequest<int>; |
| 8 | + |
| 9 | +public class AddRequestCountCommandHandler( |
| 10 | + MoongladeRepository<PostViewEntity> postViewRepo, |
| 11 | + ILogger<AddRequestCountCommandHandler> logger) : IRequestHandler<AddRequestCountCommand, int> |
| 12 | +{ |
| 13 | + // Ugly code to prevent race condition, which will make Moonglade a single instance application, shit |
| 14 | + private static readonly ConcurrentDictionary<Guid, SemaphoreSlim> _locks = new(); |
| 15 | + |
| 16 | + public async Task<int> Handle(AddRequestCountCommand request, CancellationToken cancellationToken) |
| 17 | + { |
| 18 | + var postLock = _locks.GetOrAdd(request.PostId, _ => new SemaphoreSlim(1, 1)); |
| 19 | + await postLock.WaitAsync(cancellationToken); |
| 20 | + |
| 21 | + try |
| 22 | + { |
| 23 | + var entity = await postViewRepo.GetByIdAsync(request.PostId, cancellationToken); |
| 24 | + if (entity is null) |
| 25 | + { |
| 26 | + entity = new PostViewEntity |
| 27 | + { |
| 28 | + PostId = request.PostId, |
| 29 | + RequestCount = 1, |
| 30 | + BeginTimeUtc = DateTime.UtcNow |
| 31 | + }; |
| 32 | + |
| 33 | + await postViewRepo.AddAsync(entity, cancellationToken); |
| 34 | + |
| 35 | + logger.LogInformation("New request added for {PostId}", request.PostId); |
| 36 | + return 1; |
| 37 | + } |
| 38 | + |
| 39 | + entity.RequestCount++; |
| 40 | + await postViewRepo.UpdateAsync(entity, cancellationToken); |
| 41 | + |
| 42 | + logger.LogInformation("Request count updated for {PostId}, {RequestCount}", request.PostId, entity.RequestCount); |
| 43 | + |
| 44 | + return entity.RequestCount; |
| 45 | + } |
| 46 | + catch (Exception ex) |
| 47 | + { |
| 48 | + // Not fatal error, eat it and do not block application from running |
| 49 | + logger.LogError(ex, "Failed to add request count for {PostId}", request.PostId); |
| 50 | + return -1; |
| 51 | + } |
| 52 | + finally |
| 53 | + { |
| 54 | + postLock.Release(); |
| 55 | + |
| 56 | + if (postLock.CurrentCount == 1) |
| 57 | + { |
| 58 | + _locks.TryRemove(request.PostId, out _); |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments