Files
sor/Server/src/SOR.Cdn/HttpCdnClient.cs
T
73c3a71194 Feature: ETag-based CDN model cache invalidation
When admin replaces a model/art file via the CDN browser, the S3 ETag is
now captured and stored on CardAsset.ContentETag. The ETag is included in
the content sync DTO (CardAssetDto) so clients receive it on every sync.

Client-side ModelCache now keys its disk cache on sha256(url + "#" + etag)
instead of sha256(url), so updating a file at the same CDN path busts the
disk cache automatically. A _CACHE_VER="v2" sentinel purges old-scheme
.bin files on first launch after the client update.

Changes:
- CdnUploadResult: add string? ETag field
- S3CdnClient: capture ETag from PutObjectAsync response
- CardAsset: add string? ContentETag property
- Migration 20260318000001_AddAssetContentETag: add content_etag text column
- ContentMessages: add string? ContentETag to CardAssetDto
- ContentDtoMapper: map ContentETag in CardAsset → CardAssetDto
- CdnBrowser.razor: UploadFileToKeyAsync returns Task<string?> (ETag);
  ReplaceAsync calls PropagateAssetETagAsync which updates CardAsset rows
  and touches CardDefinition.UpdatedAt to trigger a version bump
- ModelCache.gd: versioned disk key + cache migration + etag parameter on
  load_model() and evict()
- game_screen.gd: pass model_asset.contentETag to load_model / retry chain

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
2026-03-18 09:38:17 -04:00

81 lines
2.6 KiB
C#

namespace SOR.Cdn;
using Amazon.S3;
using Amazon.S3.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
/// <summary>
/// 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).
/// </summary>
public sealed class S3CdnClient : ICdnClient
{
private readonly IAmazonS3 _s3;
private readonly CdnOptions _options;
private readonly ILogger<S3CdnClient> _logger;
public S3CdnClient(IAmazonS3 s3, IOptions<CdnOptions> options, ILogger<S3CdnClient> logger)
{
_s3 = s3;
_options = options.Value;
_logger = logger;
}
public async Task<CdnUploadResult> 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";
var response = 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, response.ETag);
}
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<bool> 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;
}
}
}