fix(backend): resolve TR json serialization, news concurrency and asset index locks

This commit is contained in:
2026-08-16 16:57:34 +02:00
parent d8ba28a810
commit aaef272f4e
5 changed files with 81 additions and 41 deletions
+15 -7
View File
@@ -36,6 +36,8 @@ public class AssetsIndexService : IAssetsIndexService
private readonly IAssetsDbService _assetsDbService;
private static readonly HttpClient _httpClient = new();
private static readonly SemaphoreSlim _fileLock = new(1, 1);
public AssetsIndexService(IFinlyticLogger<AssetsIndexService> finlyticLogger, IAssetsDbService assetsDbService)
{
_finlyticLogger = finlyticLogger;
@@ -70,10 +72,19 @@ public class AssetsIndexService : IAssetsIndexService
Directory.CreateDirectory(directoryPath);
}
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096,
useAsync: true))
await _fileLock.WaitAsync(cancellationToken);
try
{
await JsonSerializer.SerializeAsync(fileStream, indexAssets, cancellationToken: cancellationToken);
var tempFilePath = Path.Combine(directoryPath, $"index_{Guid.NewGuid():N}.tmp");
using (var fileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite, 4096, useAsync: true))
{
await JsonSerializer.SerializeAsync(fileStream, indexAssets, cancellationToken: cancellationToken);
}
File.Move(tempFilePath, filePath, overwrite: true);
}
finally
{
_fileLock.Release();
}
await _finlyticLogger.LogInfoAsync(SettingKeys.AssetsChannel, "[AssetsIndexService] Successfully recreated asset index file with {Count} entries pointing to local logos at {Path}",
@@ -81,18 +92,15 @@ public class AssetsIndexService : IAssetsIndexService
}
catch (IOException ex)
{
await _finlyticLogger.LogErrorAsync(SettingKeys.AssetsChannel, ex, "[AssetsIndexService] Disk I/O error occurred while writing the asset index file.");
throw;
await _finlyticLogger.LogWarningAsync(SettingKeys.AssetsChannel, ex, "[AssetsIndexService] Concurrent file access while writing asset index file. Skipping cycle.");
}
catch (JsonException ex)
{
await _finlyticLogger.LogErrorAsync(SettingKeys.AssetsChannel, ex, "[AssetsIndexService] Failed to serialize the asset index data to JSON.");
throw;
}
catch (Exception ex)
{
await _finlyticLogger.LogErrorAsync(SettingKeys.AssetsChannel, ex, "[AssetsIndexService] An unexpected error occurred while recreating the asset index file.");
throw;
}
}