namespace SOR.Cdn;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
///
/// S3-compatible CDN client backed by Ceph RadosGW.
///
/// Uploads objects with public-read ACL; the public URL is built as:
/// {PublicBaseUrl}/{folder}/{fileName}
///
/// Requires ForcePathStyle=true for Ceph (virtual-hosted bucket style is not supported
/// without explicit DNS configuration).
///
public sealed class S3CdnClient : ICdnClient
{
private readonly IAmazonS3 _s3;
private readonly CdnOptions _options;
private readonly ILogger _logger;
public S3CdnClient(IAmazonS3 s3, IOptions options, ILogger logger)
{
_s3 = s3;
_options = options.Value;
_logger = logger;
}
public async Task UploadAsync(
string folder,
string fileName,
string contentType,
Stream data,
CancellationToken ct = default)
{
var key = $"{folder.Trim('/')}/{fileName}";
try
{
var request = new PutObjectRequest
{
BucketName = _options.BucketName,
Key = key,
InputStream = data,
ContentType = contentType,
CannedACL = S3CannedACL.PublicRead,
DisableDefaultChecksumValidation = true,
};
// Immutable URLs: each upload gets a unique timestamped key, so browsers
// and CDN edges can cache aggressively without ever serving stale bytes.
request.Headers["Cache-Control"] = "public, max-age=31536000, immutable";
await _s3.PutObjectAsync(request, ct);
var publicUrl = $"{_options.PublicBaseUrl.TrimEnd('/')}/{key}";
_logger.LogInformation("CDN upload succeeded: {Url}", publicUrl);
return new CdnUploadResult(true, key, publicUrl, null);
}
catch (Exception ex)
{
_logger.LogError(ex, "CDN upload failed for {Folder}/{FileName}", folder, fileName);
return new CdnUploadResult(false, null, null, ex.Message);
}
}
public async Task DeleteAsync(string path, CancellationToken ct = default)
{
try
{
await _s3.DeleteObjectAsync(_options.BucketName, path, ct);
return true;
}
catch (Exception ex)
{
_logger.LogError(ex, "CDN delete failed for path {Path}", path);
return false;
}
}
}