using AttendanceHub.Sync.Domain;
namespace AttendanceHub.Sync.Upload;
///
/// Local outbox upload state machine (durable in SQLite).
/// PENDING -> SENDING -> SENT | RETRY -> SENDING ...
/// Permanent failures -> DLQ (never silently deleted).
///
public enum OutboxUploadState
{
Pending = 0,
Sending = 1,
Sent = 2,
Retry = 3,
Dlq = 4,
PermanentFailure = 5
}
public enum RecordOutcome
{
AcceptedNew = 0,
AlreadyExists = 1,
RejectedInvalid = 2,
RejectedPermanent = 3,
RetryableError = 4
}
public static class RecordOutcomeExtensions
{
public static bool IsTerminalSuccess(this RecordOutcome o)
=> o is RecordOutcome.AcceptedNew or RecordOutcome.AlreadyExists;
public static bool IsRetryable(this RecordOutcome o)
=> o is RecordOutcome.RetryableError;
}
public sealed record UploadRecord(
long LocalId,
PunchIdentity Identity,
string PayloadJson);
public sealed record RecordAck(
PunchIdentity Identity,
RecordOutcome Outcome,
string? Reason,
string? ServerReceiptId,
DateTimeOffset? ProcessedAt);
public sealed record BatchAck(
string BatchId,
DateTimeOffset ReceivedAt,
IReadOnlyList Records)
{
public IEnumerable Successes => Records.Where(r => r.Outcome.IsTerminalSuccess());
public IEnumerable Retries => Records.Where(r => r.Outcome.IsRetryable());
public IEnumerable Permanent => Records.Where(r =>
r.Outcome is RecordOutcome.RejectedPermanent or RecordOutcome.RejectedInvalid);
}
public enum FailureClass
{
RetryableTransport = 0,
RetryableHttp = 1,
RetryableThrottle = 2,
PermanentValidation = 3,
PermanentAuth = 4,
PermanentBusiness = 5,
Unknown = 6
}
public sealed record UploadHttpResult(
bool TransportOk,
int StatusCode,
BatchAck? Ack,
FailureClass FailureClass,
string? Error);
public sealed record RetryPolicy(
int MaxAttempts = 12,
TimeSpan BaseDelay = default,
TimeSpan MaxDelay = default,
TimeSpan SendingLease = default)
{
public static RetryPolicy Default { get; } = new()
{
MaxAttempts = 12,
BaseDelay = TimeSpan.FromSeconds(2),
MaxDelay = TimeSpan.FromMinutes(10),
SendingLease = TimeSpan.FromMinutes(5)
};
public TimeSpan ComputeDelay(int attempt, Random? rng = null)
{
var baseDelay = BaseDelay == default ? TimeSpan.FromSeconds(2) : BaseDelay;
var maxDelay = MaxDelay == default ? TimeSpan.FromMinutes(10) : MaxDelay;
var exp = Math.Min(maxDelay.TotalMilliseconds, baseDelay.TotalMilliseconds * Math.Pow(2, Math.Max(0, attempt - 1)));
var jitter = (rng ?? Random.Shared).NextDouble() * 0.3 * exp;
return TimeSpan.FromMilliseconds(exp + jitter);
}
}