// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
using System.Security.Cryptography;
namespace Admin.NET.Core.Service;
///
/// APP 下载票据缓存后端。
///
public interface IAppDownloadTicketCache
{
AppDownloadTicketRecord? Get(string key);
bool Set(string key, AppDownloadTicketRecord value, TimeSpan ttl);
int Remove(string key);
IDisposable? AcquireLock(string key);
}
///
/// 使用系统统一缓存及其分布式锁实现票据存储。
/// Redis 模式下锁跨实例生效;内存缓存模式下锁仅在单进程内生效。
///
public sealed class SysCacheAppDownloadTicketCache : IAppDownloadTicketCache, ISingleton
{
private readonly SysCacheService _cache;
public SysCacheAppDownloadTicketCache(SysCacheService cache)
{
_cache = cache;
}
public AppDownloadTicketRecord? Get(string key) => _cache.Get(key);
public bool Set(string key, AppDownloadTicketRecord value, TimeSpan ttl) => _cache.Set(key, value, ttl);
public int Remove(string key) => _cache.Remove(key);
public IDisposable? AcquireLock(string key) =>
_cache.BeginCacheLock($"lock:{key}", msTimeout: 3000, msExpire: 15000, throwOnFailure: false);
}
public interface IAppDownloadTicketStore
{
AppDownloadTicketIssue Create(AppDownloadTicketRecord record, TimeSpan ttl);
AppDownloadTicketRecord? Get(string token, DateTimeOffset now);
AppDownloadTicketConsumeResult Consume(string token, DateTimeOffset now);
}
///
/// 高熵、短时、一次性 APP 下载票据。
///
public sealed class AppDownloadTicketStore : IAppDownloadTicketStore, ITransient
{
private const string CachePrefix = "app_download_ticket:";
private readonly IAppDownloadTicketCache _cache;
public AppDownloadTicketStore(IAppDownloadTicketCache cache)
{
_cache = cache;
}
public AppDownloadTicketIssue Create(AppDownloadTicketRecord record, TimeSpan ttl)
{
ArgumentNullException.ThrowIfNull(record);
if (ttl <= TimeSpan.Zero) throw new ArgumentOutOfRangeException(nameof(ttl));
if (record.UserId <= 0 || record.TenantId <= 0 || record.FileId <= 0 || record.VersionCode <= 0)
throw new ArgumentException("票据必须绑定有效的用户、租户、文件和版本。", nameof(record));
record.ExpiresAt = DateTimeOffset.UtcNow.Add(ttl);
for (var attempt = 0; attempt < 3; attempt++)
{
var token = Base64UrlEncode(RandomNumberGenerator.GetBytes(32));
var key = CacheKey(token);
using var ticketLock = _cache.AcquireLock(key);
if (ticketLock == null || _cache.Get(key) != null) continue;
if (_cache.Set(key, record, ttl))
return new AppDownloadTicketIssue(token, record.ExpiresAt);
}
throw Oops.Oh("创建 APP 下载票据失败,请稍后重试");
}
public AppDownloadTicketRecord? Get(string token, DateTimeOffset now)
{
if (!IsValidToken(token)) return null;
var record = _cache.Get(CacheKey(token));
if (record == null) return null;
if (record.ExpiresAt <= now)
{
_cache.Remove(CacheKey(token));
return null;
}
return record;
}
public AppDownloadTicketConsumeResult Consume(string token, DateTimeOffset now)
{
if (!IsValidToken(token)) return AppDownloadTicketConsumeResult.NotFound;
var key = CacheKey(token);
using var ticketLock = _cache.AcquireLock(key);
if (ticketLock == null) return AppDownloadTicketConsumeResult.Busy;
var record = _cache.Get(key);
if (record == null) return AppDownloadTicketConsumeResult.NotFound;
// 无论是否刚过期都删除,保证过期票据不能重新出现。
_cache.Remove(key);
return record.ExpiresAt <= now
? AppDownloadTicketConsumeResult.Expired
: new AppDownloadTicketConsumeResult(AppDownloadTicketConsumeStatus.Consumed, record);
}
private static bool IsValidToken(string? token) =>
!string.IsNullOrWhiteSpace(token) &&
token.Length == 43 &&
token.All(c => char.IsAsciiLetterOrDigit(c) || c is '-' or '_');
private static string CacheKey(string token)
{
// 缓存键和锁键不保存 bearer token 明文,降低运维查询泄露风险。
var digest = Convert.ToHexString(SHA256.HashData(Encoding.ASCII.GetBytes(token))).ToLowerInvariant();
return CachePrefix + digest;
}
private static string Base64UrlEncode(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
}
public sealed class AppDownloadTicketRecord
{
public long UserId { get; set; }
public long TenantId { get; set; }
public long FileId { get; set; }
public int VersionCode { get; set; }
public string VersionName { get; set; } = string.Empty;
public string Sha256 { get; set; } = string.Empty;
public DateTimeOffset ExpiresAt { get; set; }
}
public sealed record AppDownloadTicketIssue(string Token, DateTimeOffset ExpiresAt);
public enum AppDownloadTicketConsumeStatus
{
Consumed,
NotFound,
Expired,
Busy
}
public sealed record AppDownloadTicketConsumeResult(
AppDownloadTicketConsumeStatus Status,
AppDownloadTicketRecord? Record = null)
{
public static readonly AppDownloadTicketConsumeResult NotFound = new(AppDownloadTicketConsumeStatus.NotFound);
public static readonly AppDownloadTicketConsumeResult Expired = new(AppDownloadTicketConsumeStatus.Expired);
public static readonly AppDownloadTicketConsumeResult Busy = new(AppDownloadTicketConsumeStatus.Busy);
}