Files
mtusi2026lab5-fork/scr/Messenger.Api/Services/S3AttachmentStorage.cs
T

89 lines
3.1 KiB
C#

using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;
using System.Net;
using System.Security.Cryptography;
namespace Messenger.Api.Services;
public sealed class S3AttachmentStorage : IAttachmentStorage, IDisposable
{
private readonly AmazonS3Client _client;
private readonly string _bucket;
public S3AttachmentStorage(S3Settings settings)
{
var config = new AmazonS3Config
{
ServiceURL = settings.Endpoint,
ForcePathStyle = true,
AuthenticationRegion = settings.Region,
Timeout = TimeSpan.FromSeconds(15),
MaxErrorRetry = 1
};
var credentials = new BasicAWSCredentials(settings.AccessKey, settings.SecretKey);
_client = new AmazonS3Client(credentials, config);
_bucket = settings.Bucket;
}
public async Task PutAsync(string objectKey, Stream content, string contentType, CancellationToken ct, bool createOnly = false)
{
var request = new PutObjectRequest
{
BucketName = _bucket,
Key = objectKey,
InputStream = content,
ContentType = contentType,
IfNoneMatch = createOnly ? "*" : null,
// Поток принадлежит вызывающему коду, а не SDK.
AutoCloseStream = false
};
try
{
await _client.PutObjectAsync(request, ct);
}
catch (AmazonS3Exception ex) when (createOnly && ex.StatusCode == HttpStatusCode.PreconditionFailed)
{
// Повтор после аварии использует уже записанные байты. Несовпадение закрывает публикацию.
using var existing = new LimitedDownloadStream(content.Length);
await CopyToAsync(objectKey, existing, ct);
content.Position = 0;
var expected = await SHA256.HashDataAsync(content, ct);
var actual = SHA256.HashData(existing.GetBuffer().AsSpan(0, (int)existing.Length));
if (existing.Length != content.Length || !expected.AsSpan().SequenceEqual(actual))
throw new IOException("Existing object differs from the pipeline result");
}
}
public async Task CopyToAsync(string objectKey, Stream destination, CancellationToken ct)
{
var request = new GetObjectRequest
{
BucketName = _bucket,
Key = objectKey
};
using var response = await _client.GetObjectAsync(request, ct);
await response.ResponseStream.CopyToAsync(destination, ct);
}
public async Task DeleteAsync(string objectKey, CancellationToken ct)
{
var request = new DeleteObjectRequest
{
BucketName = _bucket,
Key = objectKey
};
await _client.DeleteObjectAsync(request, ct);
}
public void Dispose() => _client.Dispose();
public async Task CheckAsync(CancellationToken ct) =>
await _client.GetBucketLocationAsync(new GetBucketLocationRequest { BucketName = _bucket }, ct);
}