-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathCleanupAzureBlobStorageSnippetsCommandHandler.cs
More file actions
56 lines (49 loc) · 2.36 KB
/
CleanupAzureBlobStorageSnippetsCommandHandler.cs
File metadata and controls
56 lines (49 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using Azure.Storage.Blobs.Models;
using ByteSync.ServerCommon.Business.Settings;
using ByteSync.ServerCommon.Interfaces.Services;
using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace ByteSync.ServerCommon.Commands.Storage;
public class CleanupAzureBlobStorageSnippetsCommandHandler : IRequestHandler<CleanupAzureBlobStorageSnippetsRequest, int>
{
private readonly IBlobStorageContainerService _blobStorageContainerService;
private readonly ILogger<CleanupAzureBlobStorageSnippetsCommandHandler> _logger;
private readonly AzureBlobStorageSettings _blobStorageSettings;
public CleanupAzureBlobStorageSnippetsCommandHandler(
IBlobStorageContainerService blobStorageContainerService,
IOptions<AzureBlobStorageSettings> blobStorageSettings,
ILogger<CleanupAzureBlobStorageSnippetsCommandHandler> logger)
{
_blobStorageContainerService = blobStorageContainerService;
_blobStorageSettings = blobStorageSettings.Value;
_logger = logger;
}
public async Task<int> Handle(CleanupAzureBlobStorageSnippetsRequest request, CancellationToken cancellationToken)
{
if (_blobStorageSettings.RetentionDurationInDays < 1)
{
_logger.LogWarning("RetentionDurationInDays is less than 1, no element deleted");
return 0;
}
var container = await _blobStorageContainerService.BuildBlobContainerClient();
if (!await container.ExistsAsync(cancellationToken))
{
_logger.LogWarning("...Container not found, no element deleted");
return 0;
}
var deletedBlobsCount = 0;
var blobs = container.GetBlobsAsync();
await foreach (var blobItem in blobs.WithCancellation(cancellationToken))
{
if (blobItem.Properties.CreatedOn != null &&
blobItem.Properties.CreatedOn <= DateTimeOffset.UtcNow.AddDays(-_blobStorageSettings.RetentionDurationInDays))
{
_logger.LogInformation("Deleting Obsolete blob {BlobName} (CreatedOn:{CreatedOn})", blobItem.Name, blobItem.Properties.CreatedOn);
await container.DeleteBlobAsync(blobItem.Name, DeleteSnapshotsOption.IncludeSnapshots, cancellationToken: cancellationToken);
deletedBlobsCount += 1;
}
}
return deletedBlobsCount;
}
}