import 'dart:math'; /// The two deliberate retry choices. `resume` is the server's default, so its /// wire field is omitted; `restart` replays the whole pipeline. enum RetryMode { resume, restart; /// The `retry_mode` value to send, or null to let the server resume. String? get wireMode => this == RetryMode.restart ? 'restart' : null; } /// One confirmed retry intent: the chosen mode plus the idempotency key that /// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the /// server can dedupe it; a fresh deliberate intent uses a new key. class RetryIntent { const RetryIntent({ required this.mode, required this.requestKey, this.extraVisits, this.extraStage, }); final RetryMode mode; final String requestKey; /// Extra visits (1-5) to grant on resume; null grants none. final int? extraVisits; /// The stage the extra visits go to; null lets the server grant them to the /// exhausted stage(s). final String? extraStage; /// The `retry_extra_visits` value to send: only on resume, within 1-5. int? get wireExtraVisits { final visits = extraVisits; if (mode != RetryMode.resume || visits == null) return null; return visits >= 1 && visits <= 5 ? visits : null; } /// The `retry_extra_stage` value to send, only alongside extra visits. String? get wireExtraStage { final stage = extraStage?.trim() ?? ''; return wireExtraVisits == null || stage.isEmpty ? null : stage; } } /// The entropy bound for a fresh key. /// /// Written as a literal: on the web a bitwise `1 << 32` wraps to 0, which makes /// `Random.nextInt` reject every retry with a `RangeError`. const _entropyBound = 0x100000000; /// A fresh `request_key` for one retry intent. The server requires one and caps /// it at 128 characters; this stays well inside that bound and unique per call. String newRetryRequestKey(num runId, {DateTime? now, int? random}) { final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch; final entropy = random ?? Random().nextInt(_entropyBound); return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}'; }