carlos / platform Public

transfer card: keep polling after the hour; say when it stops

Final-review fix F9.

- A live transfer's card polls every 5 s for ten minutes, every minute
  to the hour, then every 5 minutes while the page is visible; a page
  seen again after the hour polls at once.
- Five failed polls in a row, or a lapsed session (sent to sign in, or
  401/403), stop it with a visible notice and a link to reload the card.
- Tested by running the rendered script in node against a fake page
  (testdata/transfer_card_poll.mjs), as the buy card's poll test does.
- The Checkout-expiry test ticks past the wall-clock expiry stamp.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 04592c85307bb821ec825e0a74e3cb4d6d0fd1ad parent 9e91da5
6 files changed, +237 −8
  • internal/console/appdomainbuy.go +5 −0
  • internal/console/domaintransfer_bounded_test.go +4 −1
  • internal/console/domaintransfer_copy.go +5 −0
  • internal/console/templates/domain_buy.html +38 −7
  • internal/console/testdata/transfer_card_poll.mjs +123 −0
  • internal/console/transfercard_poll_test.go +62 −0
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go
index 39c5320ec..54d23e527 100644
--- a/internal/console/appdomainbuy.go
+++ b/internal/console/appdomainbuy.go
@@ -272,6 +272,10 @@ type transferCardView struct {
Poll bool
Live map[string]transferLiveStage
PollError string
+ // Stale is the notice the script shows when it stops polling (errors in
+ // a row, or a lapsed session), with Reload, a link to this card.
+ Stale string
+ Reload transferLink
}
type transferChip struct{ Class, Label string }
@@ -414,6 +418,7 @@ func transferCard(acct *Account, p *DomainPurchase, now time.Time) transferCardV
}
v.Poll = purchaseLive(p.State)
if v.Poll {
+ v.Stale, v.Reload = c.StaleNote, transferLink{Href: domainPurchaseURL(acct.Sqid, p.ID), Label: c.Reload}
v.Live = transferLiveStages(p.Domain)
}
return v
diff --git a/internal/console/domaintransfer_bounded_test.go b/internal/console/domaintransfer_bounded_test.go
index d721c6028..0a0228e71 100644
--- a/internal/console/domaintransfer_bounded_test.go
+++ b/internal/console/domaintransfer_bounded_test.go
@@ -360,7 +360,10 @@ func TestTransferCheckoutExpiryOnTheProvidersWord(t *testing.T) {
tf := newTransferFixture(t)
p := tf.start(t)
tf.fake.SetProviderClock(tf.now.Add(-20 * time.Minute)) // the provider is behind
- tf.tick(time.Hour) // the console's expiry; the provider's is 20 minutes off
+ // Past the console's expiry (the start stamps it from the wall
+ // clock, a moment after the fixture's); the provider's is 20
+ // minutes off.
+ tf.tick(time.Hour + time.Minute)
switch mode {
case "pays in the gap":
tf.authorise(t, p)
diff --git a/internal/console/domaintransfer_copy.go b/internal/console/domaintransfer_copy.go
index 185a78583..c5cedf577 100644
--- a/internal/console/domaintransfer_copy.go
+++ b/internal/console/domaintransfer_copy.go
@@ -92,7 +92,12 @@ var transferCardCopy = struct {
// A refusal while the card hold is still being released; arrived but
// not yet paid for; refunded another way than to the card.
StatusReleasing, ReleasingNote, ArrivedLede, RefundedOutsideNote string
+ // The card stopped checking on the move, and its link to reload it.
+ StaleNote, Reload string
}{
+ // Drafts for the Luna pass (final review fixes, F9).
+ StaleNote: "This page has stopped updating. The move carries on.",
+ Reload: "Reload the page",
StatusReleasing: "Releasing your card hold",
ReleasingNote: "Nothing was charged. We’re releasing the hold on your card. The domain stays where it was, and its DNS and email didn’t change.",
ArrivedLede: "The transfer for {domain} was accepted. We’re taking the payment now, and this page will update when it’s done. Its DNS and email didn’t change.",
diff --git a/internal/console/templates/domain_buy.html b/internal/console/templates/domain_buy.html
index c9a2aac5e..2e1532c5c 100644
--- a/internal/console/templates/domain_buy.html
+++ b/internal/console/templates/domain_buy.html
@@ -132,7 +132,10 @@
done, or a failure shown as a state beside what happened to the money.
The script polls a live transfer's status, moves between the stepped
stages in place, and reloads for any other change, which the server
- draws. Called with the page. */}}
+ draws. It polls every 5 s for ten minutes, then every minute to the
+ hour, then every 5 minutes while the page is visible. When it stops
+ (five errors in a row, or a lapsed session) it says so, with a link
+ to reload. Called with the page. */}}
{{define "transfer_card"}}{{$b := .DomainBuy}}{{$t := $b.Transfer}}
<div class="pagehead">
<p class="eyebrow">{{$t.Eyebrow}}</p>
@@ -151,6 +154,7 @@
</ol>
<p id="purchase-note" class="small" {{if not $t.Note}}hidden{{end}}>{{$t.Note}}</p>
<p id="purchase-error" class="purchase-error" hidden></p>
+ {{if $t.Poll}}<p id="purchase-stale" class="purchase-error" role="status" hidden>{{$t.Stale}} <a id="purchase-reload" href="{{$t.Reload.Href}}">{{$t.Reload.Label}}</a></p>{{end}}
</div>
<div class="done-actions">
{{if and $b.CheckoutURL (eq $b.Purchase.State "awaiting_payment")}}<a id="purchase-continue" class="btn" href="{{$b.CheckoutURL}}">{{.DomainBuyCopy.continuePayment}}</a>{{end}}
@@ -165,8 +169,9 @@
const title = document.getElementById('purchase-title'), lede = document.getElementById('purchase-lede');
const note = document.getElementById('purchase-note'), error = document.getElementById('purchase-error');
const steps = document.getElementById('purchase-steps'), status = document.getElementById('purchase-status');
- const started = Date.now();
- let stage = {{$t.Stage}};
+ const stale = document.getElementById('purchase-stale');
+ const started = Date.now(), fastFor = 600000, hour = 3600000, slowEvery = 300000, maxFailures = 5;
+ let stage = {{$t.Stage}}, failures = 0, timer = 0, busy = false, stopped = false;
// show draws a stepped stage in place. Its steps are always four.
function show(s) {
title.textContent = s.Title;
@@ -182,27 +187,53 @@
});
if (status.textContent !== s.Status) status.textContent = s.Status;
}
+ // slow: past the first hour, when polling waits for the page to be seen.
+ function slow() { return Date.now() - started >= hour; }
+ // stop ends polling for good, saying so.
+ function stop() {
+ stopped = true;
+ clearTimeout(timer);
+ timer = 0;
+ error.hidden = true;
+ stale.hidden = false;
+ }
+ function schedule() {
+ const elapsed = Date.now() - started;
+ const delay = elapsed < fastFor ? 5000 : elapsed < hour ? Math.min(60000, hour - elapsed) : slowEvery;
+ timer = setTimeout(poll, delay);
+ }
async function poll() {
+ timer = 0;
+ if (stopped || busy) return;
+ if (slow() && document.visibilityState === 'hidden') return; // resumed when seen
+ busy = true;
try {
const response = await fetch(endpoint, {credentials: 'same-origin', cache: 'no-store'});
+ // Sent to sign in: the session lapsed, so no poll can succeed.
+ if (response.redirected || response.status === 401 || response.status === 403) { busy = false; stop(); return; }
if (!response.ok) throw new Error();
const purchase = await response.json();
if (purchase.kind !== 'transfer' || typeof purchase.stage !== 'string') throw new Error();
+ failures = 0;
error.hidden = true;
if (purchase.stage !== stage) {
const drawn = Object.prototype.hasOwnProperty.call(live, stage) && steps.querySelectorAll('li').length === 4;
- if (!drawn || !Object.prototype.hasOwnProperty.call(live, purchase.stage)) { location.reload(); return; }
+ if (!drawn || !Object.prototype.hasOwnProperty.call(live, purchase.stage)) { busy = false; location.reload(); return; }
stage = purchase.stage;
show(live[stage]);
}
} catch (_) {
+ failures++;
+ if (failures >= maxFailures) { busy = false; stop(); return; }
error.textContent = pollError;
error.hidden = false;
}
- const elapsed = Date.now() - started;
- if (elapsed >= 3600000) return;
- setTimeout(poll, Math.min(elapsed < 600000 ? 5000 : 60000, 3600000 - elapsed));
+ busy = false;
+ schedule();
}
+ document.addEventListener('visibilitychange', function () {
+ if (!stopped && !timer && !busy && slow() && document.visibilityState === 'visible') poll();
+ });
poll();
})();
</script>{{end}}
diff --git a/internal/console/testdata/transfer_card_poll.mjs b/internal/console/testdata/transfer_card_poll.mjs
new file mode 100644
index 000000000..63fc70bb9
--- /dev/null
+++ b/internal/console/testdata/transfer_card_poll.mjs
@@ -0,0 +1,123 @@
+// The transfer card's polling script (templates/domain_buy.html), run in a
+// fake page: a controlled clock, timers, fetch and visibility. Argument 1
+// is the rendered script's path.
+import assert from 'node:assert/strict';
+import {readFile} from 'node:fs/promises';
+import vm from 'node:vm';
+
+const source = await readFile(process.argv[2], 'utf8');
+const hour = 3600000;
+
+function page() {
+ let now = 1_800_000_000_000;
+ const timers = [], listeners = {};
+ const el = () => ({textContent: '', hidden: true, dataset: {}, setAttribute() {}, removeAttribute() {}});
+ const nodes = {};
+ for (const id of ['purchase-title', 'purchase-lede', 'purchase-note', 'purchase-error', 'purchase-status', 'purchase-stale']) nodes[id] = el();
+ const rows = [0, 1, 2, 3].map(() => ({dataset: {}, setAttribute() {}, removeAttribute() {}, querySelector: () => el()}));
+ nodes['purchase-steps'] = {...el(), querySelectorAll: () => rows};
+ const p = {
+ nodes, timers, fetches: 0, reloads: 0,
+ answer: () => ({ok: true, status: 200, redirected: false, json: async () => ({kind: 'transfer', stage: 'waiting'})}),
+ document: {
+ visibilityState: 'visible',
+ getElementById: id => nodes[id] ?? null,
+ addEventListener(type, fn) { (listeners[type] ??= []).push(fn); },
+ },
+ elapsed: () => now - start,
+ async settle() { for (let i = 0; i < 5; i++) await new Promise(r => setImmediate(r)); },
+ // fire runs the next timer, after its delay, then lets the poll finish.
+ async fire() {
+ const t = timers.shift();
+ assert(t, 'no timer pending');
+ now += t.delay;
+ t.fn();
+ await p.settle();
+ return t.delay;
+ },
+ async show(state) {
+ p.document.visibilityState = state;
+ for (const fn of listeners.visibilitychange ?? []) fn();
+ await p.settle();
+ },
+ };
+ const start = now;
+ vm.runInNewContext(source, {
+ document: p.document,
+ location: {reload() { p.reloads++; }},
+ Date: class extends Date { static now() { return now; } },
+ setTimeout(fn, delay) { timers.push({fn, delay}); return timers.length; },
+ clearTimeout() { timers.length = 0; },
+ fetch: async () => { p.fetches++; return p.answer(); },
+ });
+ return p;
+}
+
+// The cadence: 5 s for ten minutes, then a minute to the hour (the last
+// wait landing on it), then every 5 minutes.
+{
+ const p = page();
+ await p.settle();
+ assert.equal(p.fetches, 1);
+ const delays = [];
+ while (p.elapsed() < hour) delays.push(await p.fire());
+ assert.equal(p.elapsed(), hour, 'the fast polls end on the hour');
+ assert(delays.slice(0, 120).every(d => d === 5000), 'every 5 s at first');
+ assert(delays.slice(120).every(d => d === 60000), 'then every minute');
+ for (let i = 0; i < 3; i++) assert.equal(await p.fire(), 300000, 'every 5 minutes after the hour');
+ assert.equal(p.nodes['purchase-stale'].hidden, true);
+
+ // Past the hour, a hidden page is not polled; seen again, it is, at once.
+ await p.show('hidden');
+ const before = p.fetches;
+ await p.fire();
+ assert.equal(p.fetches, before, 'polled while hidden');
+ assert.equal(p.timers.length, 0, 'a timer kept while hidden');
+ await p.show('visible');
+ assert.equal(p.fetches, before + 1, 'not polled when seen again');
+ assert.equal(p.timers[0].delay, 300000);
+ await p.show('visible'); // a second event does not poll twice
+ assert.equal(p.fetches, before + 1);
+}
+
+// In the first hour a hidden page is still polled, as before.
+{
+ const p = page();
+ await p.settle();
+ await p.show('hidden');
+ await p.fire();
+ assert.equal(p.fetches, 2);
+}
+
+// Five errors in a row stop it, saying so; one error alone does not.
+{
+ const p = page();
+ await p.settle();
+ p.answer = () => ({ok: false, status: 503, redirected: false});
+ await p.fire();
+ assert.equal(p.nodes['purchase-error'].hidden, false);
+ assert.equal(p.nodes['purchase-stale'].hidden, true);
+ p.answer = () => ({ok: true, status: 200, redirected: false, json: async () => ({kind: 'transfer', stage: 'waiting'})});
+ await p.fire();
+ assert.equal(p.nodes['purchase-error'].hidden, true);
+ p.answer = () => { throw new Error('offline'); };
+ for (let i = 0; i < 4; i++) await p.fire();
+ assert.equal(p.nodes['purchase-stale'].hidden, true, 'stopped before five in a row');
+ await p.fire();
+ assert.equal(p.nodes['purchase-stale'].hidden, false, 'no stale notice after five errors');
+ assert.equal(p.nodes['purchase-error'].hidden, true);
+ assert.equal(p.timers.length, 0, 'still polling after it stopped');
+ await p.show('visible');
+ assert.equal(p.timers.length, 0);
+}
+
+// A lapsed session (sent to sign in) stops it at once.
+for (const lapsed of [{ok: true, status: 200, redirected: true, json: async () => ({})}, {ok: false, status: 401, redirected: false}]) {
+ const p = page();
+ await p.settle();
+ p.answer = () => lapsed;
+ await p.fire();
+ assert.equal(p.nodes['purchase-stale'].hidden, false, 'no stale notice on a lapsed session');
+ assert.equal(p.timers.length, 0);
+}
+console.log('transfer card: cadence to the hour and after, visibility, stopping and its notice passed');
diff --git a/internal/console/transfercard_poll_test.go b/internal/console/transfercard_poll_test.go
new file mode 100644
index 000000000..4b661c7c4
--- /dev/null
+++ b/internal/console/transfercard_poll_test.go
@@ -0,0 +1,62 @@
+package console
+
+import (
+ "net/http"
+
+ "golang.org/x/net/html"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func hasAttr(n *html.Node, key string) bool {
+ for _, a := range n.Attr {
+ if a.Key == key {
+ return true
+ }
+ }
+ return false
+}
+
+// TestTransferCardPollingScript runs the live transfer card's own script,
+// as rendered, in node against a fake page (testdata/transfer_card_poll.mjs):
+// it polls every 5 s, then every minute to the hour, then every 5 minutes
+// while the page is visible, and when it stops (five errors in a row, or a
+// lapsed session) it shows the stale notice with its reload link.
+func TestTransferCardPollingScript(t *testing.T) {
+ node, err := exec.LookPath("node")
+ if err != nil {
+ t.Skip("no installed node for the card script")
+ }
+ tf := newTransferFixture(t)
+ c, _ := tf.ownerBrowser(t)
+ p := transferCardPurchase(t, tf, PurchaseTransferPending, func(p *DomainPurchase) {
+ p.Facts.Registrar, p.Facts.Payment = rPending, pCaptured
+ })
+ status, _, body := get(t, c, tf.ts.URL+domainPurchaseURL(tf.acct.Sqid, p.ID))
+ if status != http.StatusOK {
+ t.Fatalf("card: %d", status)
+ }
+ stale := purchaseElement(t, body, "purchase-stale")
+ reload := purchaseElement(t, body, "purchase-reload")
+ if text := purchaseText(stale); !strings.Contains(text, transferCardCopy.StaleNote) || !strings.Contains(text, transferCardCopy.Reload) ||
+ purchaseAttr(reload, "href") != domainPurchaseURL(tf.acct.Sqid, p.ID) || !hasAttr(stale, "hidden") {
+ t.Fatalf("stale notice: %q, reload %q", text, purchaseAttr(reload, "href"))
+ }
+ _, rest, ok := strings.Cut(body, "<script>\n(function () {\n const endpoint")
+ script, _, ok2 := strings.Cut(rest, "</script>")
+ if !ok || !ok2 {
+ t.Fatal("no card script")
+ }
+ path := filepath.Join(t.TempDir(), "card.js")
+ if err := os.WriteFile(path, []byte("(function () {\n const endpoint"+script), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ out, err := exec.Command(node, "testdata/transfer_card_poll.mjs", path).CombinedOutput()
+ if err != nil {
+ t.Fatalf("%v\n%s", err, out)
+ }
+ t.Log(strings.TrimSpace(string(out)))
+}