showEngine method

  1. @protected
Future<AdShowResult> showEngine({
  1. OnUserEarnedReward? onReward,
  2. Future<bool> confirm()?,
})

The full show engine, shared by every format. onReward is forwarded to the handle for the rewarded formats (their public show(onReward:) overrides call this); the base show never passes one.

confirm, when supplied, runs AFTER every policy check has passed and WHILE the coordinator claim is held, immediately before the ad is dispatched — the rewarded interstitial presents its mandatory intro there (4.0 audit). Ordering is the point, twice over: (a) every consent/cap/pacing refusal happens BEFORE the user is promised an ad, so accepting the intro can no longer end in "no ad, no reward"; (b) the claim spans the intro, so a warm-return app-open cannot stack over it. Returning false (the user skipped; report the reason yourself before returning) or throwing rolls everything back to a warm AdLoaded.

Completes when the dispatched ad CLOSES, or at once when the show is refused or fails (6.0); an ad the SDK never presents completes after presentationTimeout.

Implementation

@protected
Future<AdShowResult> showEngine({
  OnUserEarnedReward? onReward,
  Future<bool> Function()? confirm,
}) async {
  if (_disposed) return const AdShowResult.blocked(AdBlockReason.notReady);
  if (_state.value is AdShowing) {
    return const AdShowResult.blocked(AdBlockReason.otherAdShowing);
  }
  final handle = _handle;
  if (handle == null || !isReady) {
    unawaited(load()); // warm one up for the next natural break
    return _refused(AdBlockReason.notReady);
  }
  if (isExpired) {
    // Stale inventory (the proactive timer did not fire — e.g. the app was
    // suspended past the ad's maximum age): discard, keep a fresh one warm,
    // show nothing. Showing it risks a failed display, or one that does
    // not count.
    noteBlocked(AdBlockReason.expired);
    discardCurrentAd();
    return const AdShowResult.blocked(AdBlockReason.expired);
  }

  // Atomically check-and-claim the coordinator BEFORE any await — see
  // FullScreenAdCoordinator.tryEnter doc. An await-separated check (via
  // AdGate.canShow, which reads the coordinator too) lets two
  // independently-gated controllers — e.g. interstitial + app open —
  // both observe "nothing is showing" in the same turn and both
  // proceed, so this bypasses gate.canShow's coordinator check and does
  // its own atomic one instead. gate.canLoad + caps.canShow cover the
  // remaining (consent/enabled/frequency-cap) checks.
  if (!_coordinator.tryEnter()) {
    return _refused(AdBlockReason.otherAdShowing);
  }
  _enteredCoordinator = true;
  // Set Showing synchronously, in the same turn as the coordinator
  // claim above, so a concurrent show() call on THIS controller also
  // sees it immediately and bails.
  _state.value = const AdShowing();

  // Inside the try below every rollback is AWAITED: a bare
  // `return rejectAndRollBack();` hands back its Future, so a throw from the
  // rollback itself would skip the catch and leave the slot at AdShowing
  // with the claim flag set (5.3.1; Dart 3.13 flags it as
  // unawaited_return_in_try_block). The catch then runs the rollback again,
  // which is safe: the state write is a no-op the second time, and exit()
  // runs again only if the first call threw (the flag is cleared after it).
  Future<AdShowResult> rejectAndRollBack(AdBlockReason reason) async {
    _exitCoordinator();
    if (_disposed) return AdShowResult.blocked(reason);
    if (isExpired) {
      // The ad aged out while this show held the slot (a long rewarded
      // intro): drop and reload in the same turn as the claim release —
      // never back to AdLoaded first (ADR-075).
      discardCurrentAd();
    } else {
      _state.value = const AdLoaded();
      // The expiry timer may have fired (and done nothing) during AdShowing.
      _scheduleExpiry();
    }
    return AdShowResult.blocked(reason);
  }

  // A warm ad that must not be shown at all (stale consent, or expired) is
  // dropped and reloaded in the same turn as the claim release — never
  // rolled back to AdLoaded first (5.3.1). That rollback notified `state`
  // listeners a microtask before the discard: a listener's show() claimed
  // the doomed handle in between, the discard then dropped it from under
  // that show and started a load, and that show's own discard started a
  // second one, leaking a handle (ADR-075).
  AdShowResult releaseAndDiscard(AdBlockReason reason) {
    _exitCoordinator();
    discardCurrentAd();
    return AdShowResult.blocked(reason);
  }

  // The graph was disposed while this show awaited a check: dispose()
  // already rolled everything back.
  const disposedMidShow = AdShowResult.blocked(AdBlockReason.notReady);

  // These preconditions run AFTER the coordinator has been claimed and
  // AdShowing written (both must be synchronous — ADR-024), so any throw in
  // here MUST roll both back. A corrupt shared_preferences backend makes
  // `_caps.canShow` throw a PlatformException, and the plugin's
  // `canRequestAds()` can throw too; before this guard such a throw escaped
  // show() with the coordinator still claimed, permanently blocking EVERY
  // full-screen format (interstitial, rewarded, rewarded-interstitial and
  // app-open) for the rest of the session. Review finding #1 fixed only the
  // symmetric hole around `handle.show()`; this is the other half.
  try {
    // The CHEAP show checks, not loadBlockReason: a warm handle proves the
    // config gate and consent settle already passed at load time, and this
    // runs while holding the coordinator claim — awaiting a network-bound
    // consent re-attempt here would freeze every full-screen format behind
    // it (2026-07 audit). canRequestAds() is still read live, so a consent
    // withdrawal between load and show is still respected.
    final blocked = await _gate.showBlockReason(slot);
    if (blocked != null) {
      noteBlocked(blocked);
      return await rejectAndRollBack(blocked);
    }
    if (_disposed) return disposedMidShow;
    if (!await _caps.canShow(slot)) {
      noteBlocked(AdBlockReason.frequencyCapped);
      return await rejectAndRollBack(AdBlockReason.frequencyCapped);
    }
    if (_disposed) return disposedMidShow;
    if (!canShowExtra()) {
      noteBlocked(AdBlockReason.userActionPacing);
      return await rejectAndRollBack(AdBlockReason.userActionPacing);
    }
    // The confirm hook (the rewarded-interstitial intro) runs LAST, with
    // every policy check already passed and the claim held. It is
    // user-facing and unbounded — the state is AdShowing throughout, so
    // the expiry timer cannot discard the handle mid-intro and re-entrant
    // show() calls bail on the AdShowing guard.
    if (confirm != null && !await confirm()) {
      return await rejectAndRollBack(AdBlockReason.introSkipped);
    }
    // The confirm hook can outlive the graph (the user backgrounds the
    // app on the intro and the screen is popped): dispose() already
    // released the claim and dropped the handle — do not show.
    if (_disposed) return disposedMidShow;
    // RE-VALIDATE after the unbounded confirm hook (4.1 audit). The checks
    // above ran BEFORE the intro, which the user may sit on for minutes:
    // Remove-Ads can be bought and the warm ad can age past maxAdAge in
    // that window. Re-run the cheap live checks (no network/config join —
    // showBlockReason is the same subset the show path already trusts) and
    // re-check expiry; a stale or no-longer-permitted ad is rolled back
    // rather than shown. internalError is a transient hiccup — proceed
    // (mirrors recheckGate), never waste an accepted intro on a blip.
    if (confirm != null) {
      final after = await _gate.showBlockReason(slot);
      if (_disposed) return disposedMidShow;
      if (after != null && after != AdBlockReason.internalError) {
        noteBlocked(after);
        return await rejectAndRollBack(after);
      }
      if (isExpired) {
        noteBlocked(AdBlockReason.expired);
        return releaseAndDiscard(AdBlockReason.expired);
      }
    }
  } catch (_) {
    // Degrade to "don't show", never to "wedged forever".
    return rejectAndRollBack(AdBlockReason.internalError);
  }
  // FINAL synchronous dispatch boundary (5.2.1). Every check above ran BEFORE
  // one or more awaits (showBlockReason, caps.canShow, and — for the rewarded
  // interstitial — the unbounded intro). A disableAds() or consent mutation
  // that landed during those awaits is deliberately ignored by _recheckAll
  // while AdShowing, and the warm ad can age past maxAdAge during a slow
  // cap-store hydration — so the previously-captured handle could otherwise be
  // dispatched despite being revoked or stale. Re-verify only the cheap
  // SYNCHRONOUS facts that can have gone stale (no network/consent flow, no
  // async cap recompute), in the same turn as handle.show() below.
  if (_disposed) return disposedMidShow;
  if (!_gate.isEnabled) {
    // Ads disabled mid-show: do not dispatch, and do not leave it warm under
    // adsDisabled (mirrors recheckGate, which could not touch AdShowing).
    noteBlocked(AdBlockReason.adsDisabled);
    _exitCoordinator();
    _timer?.cancel();
    _dropHandle();
    if (!_disposed) _state.value = const AdBlocked(AdBlockReason.adsDisabled);
    _scheduleGateRecheck();
    return const AdShowResult.blocked(AdBlockReason.adsDisabled);
  }
  if (_loadedGeneration != _gate.consentGeneration) {
    // Consent mutated mid-show: the warm ad carries stale consent.
    // Release the claim, then drop + reload through the fresh gate.
    return releaseAndDiscard(AdBlockReason.notReady);
  }
  if (isExpired) {
    // Aged past maxAdAge mid-show (e.g. a slow cap hydration crossed expiry):
    // discard rather than show a stale ad that may fail or not count.
    noteBlocked(AdBlockReason.expired);
    return releaseAndDiscard(AdBlockReason.expired);
  }

  // Dispatching. The attempt is in place BEFORE handle.show() so content
  // events that arrive while the dispatch is still awaited are not lost.
  final attempt = _ShowAttempt();
  _attempt = attempt;
  attempt.timer = Timer(presentationTimeout, () {
    if (!identical(_attempt, attempt) || attempt.showedOnScreen) return;
    _finishShow(
      (_) => const AdShowResult.failed(
        AdFlowError(
          AdFlowErrorKind.timeout,
          'The ad was dispatched, but the SDK did not put it on screen.',
        ),
      ),
    );
  });
  // A reward is granted at most once per ad, even if the SDK misfires —
  // and the app's grant callback is isolated, so an app bug inside it
  // cannot corrupt the show flow or become an unhandled platform-callback
  // error (4.0 audit). The reward is also kept for the show's result.
  var granted = false;
  void onRewardOnce(RewardEarned reward) {
    if (granted) return;
    granted = true;
    attempt.reward = reward;
    if (onReward != null) {
      guardedCallback(() => onReward(reward), debugName: 'onReward');
    }
  }

  // Not awaited before returning: the result is bounded by
  // [presentationTimeout] and [dispose] even if the platform call never
  // replies.
  unawaited(_dispatch(handle, attempt, onRewardOnce));
  return attempt.completer.future;
}