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}); final RetryMode mode; final String requestKey; } /// 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)}'; }