carlos / platform Public

fxrate: daily ECB reference rates for the billing figures

New internal/fxrate reads the ECB's daily euro reference rates behind
fxrate.Source (GET, 200 only, 64 KiB cap, refuses a bad date, an empty
set or any rate that is not a positive finite number). The console
stores them as published (units per euro) in billing_eur_rates, and the
billing money pass fetches them at most every 20 h; a failed fetch
stores nothing and the last good set stays in use. eurRates.eurCents
converts minor units to euro cents on read.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev f594ad381f1c71bac86a06a7a21140cda4b3b364 parent 9da7737
11 files changed, +530 −4
  • cmd/console/billing.go +4 −1
  • internal/console/billing.go +4 −0
  • internal/console/billingmoneypass.go +4 −0
  • internal/console/billingpayments_store.go +10 −2
  • internal/console/billingrates.go +133 −0
  • internal/console/billingrates_test.go +140 −0
  • internal/console/jobs_test.go +1 −1
  • internal/console/store_gate.go +1 −0
  • internal/fxrate/fxrate.go +123 −0
  • internal/fxrate/fxrate_test.go +97 −0
  • internal/fxrate/testdata/eurofxref-daily.xml +13 −0
diff --git a/cmd/console/billing.go b/cmd/console/billing.go
index b50186ea2..b2d543d9a 100644
--- a/cmd/console/billing.go
+++ b/cmd/console/billing.go
@@ -7,6 +7,7 @@ import (
"github.com/carlosframework/platform/internal/billing"
"github.com/carlosframework/platform/internal/billingstripe"
"github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/fxrate"
"github.com/carlosframework/platform/internal/plans"
)
@@ -98,5 +99,7 @@ func billingConfig(getenv func(string) string, cat *plans.Catalog) (*console.Bil
if err != nil {
return nil, billingConfigError("CARLOS_STRIPE_SECRET_KEY")
}
- return &console.BillingConfig{LiveMode: live, Book: book, Prices: prices, Provider: provider, HouseCoupon: coupon}, nil
+ return &console.BillingConfig{LiveMode: live, Book: book, Prices: prices, Provider: provider, HouseCoupon: coupon,
+ Rates: fxrate.ECB{URL: fxrate.ECBDailyURL},
+ }, nil
}
diff --git a/internal/console/billing.go b/internal/console/billing.go
index c7f18542b..ddaceae07 100644
--- a/internal/console/billing.go
+++ b/internal/console/billing.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/fxrate"
"github.com/carlosframework/platform/internal/plans"
)
@@ -22,6 +23,9 @@ type BillingConfig struct {
// (CARLOS_STRIPE_HOUSE_COUPON), "" for none. The console copies it into
// CheckoutRequest.Coupon, so it is frozen in the prepared bytes.
HouseCoupon string
+ // Rates is where the daily euro reference rates come from
+ // (billingRatesPass); nil fetches none.
+ Rates fxrate.Source
}
// billingRuntime is a server's billing state. ready is set once the
diff --git a/internal/console/billingmoneypass.go b/internal/console/billingmoneypass.go
index db930de3e..4b6e0574d 100644
--- a/internal/console/billingmoneypass.go
+++ b/internal/console/billingmoneypass.go
@@ -36,6 +36,10 @@ func (s *Server) billingMoneyPass(ctx context.Context, now time.Time) {
log.Printf("console: billing money pass: payments: %v", err)
jobFailed(ctx, fmt.Errorf("billing money pass: payments: %w", err))
}
+ if err := s.billingRatesPass(ctx, now); err != nil {
+ log.Printf("console: billing money pass: euro rates: %v", err)
+ jobFailed(ctx, fmt.Errorf("billing money pass: euro rates: %w", err))
+ }
}
// reconcilePayments records every balance movement from the cursor (less
diff --git a/internal/console/billingpayments_store.go b/internal/console/billingpayments_store.go
index 217fe18de..3bca7f88e 100644
--- a/internal/console/billingpayments_store.go
+++ b/internal/console/billingpayments_store.go
@@ -11,8 +11,9 @@ import (
)
// migrateBillingMoney adds the billing dashboard's money record: one row
-// per provider balance movement, and the reconcile's cursor. Account
-// deletion leaves payment rows alone: they are the money record.
+// per provider balance movement, the reconcile's cursor, and the daily
+// euro reference rates (billingrates.go). Account deletion leaves payment
+// rows alone: they are the money record.
func (s *Store) migrateBillingMoney() error {
_, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS billing_payments (
movement_id TEXT PRIMARY KEY,
@@ -43,6 +44,13 @@ CREATE TABLE IF NOT EXISTS billing_payment_cursor (
id INTEGER PRIMARY KEY CHECK (id = 1),
through INTEGER NOT NULL,
succeeded_at INTEGER NOT NULL DEFAULT 0
+);
+CREATE TABLE IF NOT EXISTS billing_eur_rates (
+ day TEXT NOT NULL,
+ currency TEXT NOT NULL,
+ per_eur REAL NOT NULL,
+ fetched_at INTEGER NOT NULL,
+ PRIMARY KEY (day, currency)
);`)
return err
}
diff --git a/internal/console/billingrates.go b/internal/console/billingrates.go
new file mode 100644
index 000000000..94a53b5a6
--- /dev/null
+++ b/internal/console/billingrates.go
@@ -0,0 +1,133 @@
+package console
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "fmt"
+ "math"
+ "time"
+
+ "github.com/carlosframework/platform/internal/fxrate"
+)
+
+// billingRatesEvery is how old the newest stored euro rates must be before
+// billingRatesPass fetches again. The ECB publishes once a working day.
+const billingRatesEvery = 20 * time.Hour
+
+// eurRates is one stored day's euro reference rates: Day is the
+// publisher's date, FetchedAt the newest time that day's set was fetched,
+// and PerEUR maps a lower-case currency to its units per euro.
+type eurRates struct {
+ Day string
+ FetchedAt time.Time
+ PerEUR map[string]float64
+}
+
+// eurCents converts minor units of currency to euro cents: euros are
+// themselves, another currency is divided by its rate, rounded. Every
+// selling currency has two decimals, so minor units convert to cents
+// directly. False when the currency has no rate.
+func (r eurRates) eurCents(minor int64, currency string) (int64, bool) {
+ if currency == "eur" {
+ return minor, true
+ }
+ rate, ok := r.PerEUR[currency]
+ if !ok || !(rate > 0) || math.IsInf(rate, 0) {
+ return 0, false
+ }
+ return int64(math.Round(float64(minor) / rate)), true
+}
+
+// PutEURRates stores a day's rates, one row per currency; a refetch of the
+// same day overwrites its rates and fetched_at. All rows or none.
+func (s *Store) PutEURRates(r fxrate.Rates, now time.Time) error {
+ if r.Day == "" || len(r.PerEUR) == 0 {
+ return errors.New("euro rates: empty set")
+ }
+ tx, err := s.db.Begin()
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+ for c, v := range r.PerEUR {
+ if _, err := tx.Exec(`INSERT INTO billing_eur_rates (day, currency, per_eur, fetched_at) VALUES (?, ?, ?, ?)
+ ON CONFLICT(day, currency) DO UPDATE SET per_eur = excluded.per_eur, fetched_at = excluded.fetched_at`,
+ r.Day, c, v, now.Unix()); err != nil {
+ return err
+ }
+ }
+ return tx.Commit()
+}
+
+// LatestEURRates is the newest stored day's rates, FetchedAt that day's
+// newest fetched_at. A zero Day means no rates were ever stored.
+func (s *Store) LatestEURRates() (eurRates, error) {
+ var day string
+ err := s.db.QueryRow(`SELECT day FROM billing_eur_rates ORDER BY day DESC LIMIT 1`).Scan(&day)
+ if errors.Is(err, sql.ErrNoRows) {
+ return eurRates{}, nil
+ }
+ if err != nil {
+ return eurRates{}, err
+ }
+ rows, err := s.db.Query(`SELECT currency, per_eur, fetched_at FROM billing_eur_rates WHERE day = ?`, day)
+ if err != nil {
+ return eurRates{}, err
+ }
+ defer rows.Close()
+ out := eurRates{Day: day, PerEUR: map[string]float64{}}
+ var newest int64
+ for rows.Next() {
+ var c string
+ var v float64
+ var at int64
+ if err := rows.Scan(&c, &v, &at); err != nil {
+ return eurRates{}, err
+ }
+ out.PerEUR[c] = v
+ newest = max(newest, at)
+ }
+ if err := rows.Err(); err != nil {
+ return eurRates{}, err
+ }
+ out.FetchedAt = time.Unix(newest, 0).UTC()
+ return out, nil
+}
+
+// eurRatesFetchedAt is the newest fetched_at of any stored row, so a
+// source answering with an older day than the newest stored still waits
+// out billingRatesEvery; false when no rates were ever stored.
+func (s *Store) eurRatesFetchedAt() (time.Time, bool, error) {
+ var last sql.NullInt64
+ if err := s.db.QueryRow(`SELECT MAX(fetched_at) FROM billing_eur_rates`).Scan(&last); err != nil {
+ return time.Time{}, false, err
+ }
+ if !last.Valid {
+ return time.Time{}, false, nil
+ }
+ return time.Unix(last.Int64, 0).UTC(), true, nil
+}
+
+// billingRatesPass fetches the daily euro reference rates when none were
+// fetched within billingRatesEvery. Without a Source it does nothing. A
+// failed fetch stores nothing and returns the error; the last good rates
+// stay in use.
+func (s *Server) billingRatesPass(ctx context.Context, now time.Time) error {
+ src := s.billing.cfg.Rates
+ if src == nil {
+ return nil
+ }
+ last, ok, err := s.store.eurRatesFetchedAt()
+ if err != nil {
+ return err
+ }
+ if ok && now.Sub(last) < billingRatesEvery {
+ return nil
+ }
+ r, err := src.Latest(ctx)
+ if err != nil {
+ return fmt.Errorf("fetching: %w", err)
+ }
+ return s.store.PutEURRates(r, now)
+}
diff --git a/internal/console/billingrates_test.go b/internal/console/billingrates_test.go
new file mode 100644
index 000000000..f4e834e82
--- /dev/null
+++ b/internal/console/billingrates_test.go
@@ -0,0 +1,140 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/fxrate"
+)
+
+// fakeRates is an fxrate.Source counting its calls; err, when set, is
+// every call's answer.
+type fakeRates struct {
+ mu sync.Mutex
+ calls int
+ rates fxrate.Rates
+ err error
+}
+
+func (f *fakeRates) Latest(context.Context) (fxrate.Rates, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.calls++
+ if f.err != nil {
+ return fxrate.Rates{}, f.err
+ }
+ return f.rates, nil
+}
+
+func (f *fakeRates) count() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.calls
+}
+
+func TestEURCents(t *testing.T) {
+ r := eurRates{Day: "2026-11-06", PerEUR: map[string]float64{"usd": 1.12}}
+ if got, ok := r.eurCents(2800, "usd"); !ok || got != 2500 {
+ t.Errorf("eurCents(2800, usd) = %d, %v; want 2500, true", got, ok)
+ }
+ if got, ok := r.eurCents(2400, "eur"); !ok || got != 2400 {
+ t.Errorf("eurCents(2400, eur) = %d, %v; want 2400, true", got, ok)
+ }
+ if got, ok := r.eurCents(2400, "chf"); ok {
+ t.Errorf("eurCents(2400, chf) = %d, true; want false", got)
+ }
+}
+
+func TestRatesPassFetchesDaily(t *testing.T) {
+ bf := newBillingFixture(t)
+ src := &fakeRates{rates: fxrate.Rates{Day: "2026-11-06", PerEUR: map[string]float64{"usd": 1.0823, "gbp": 0.8412}}}
+ bf.srv.billing.cfg.Rates = src
+ ctx := context.Background()
+ now := billingNow
+
+ if err := bf.srv.billingRatesPass(ctx, now); err != nil {
+ t.Fatal(err)
+ }
+ if src.count() != 1 {
+ t.Fatalf("first pass: %d fetches, want 1", src.count())
+ }
+ got, err := bf.st.LatestEURRates()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Day != "2026-11-06" || got.PerEUR["usd"] != 1.0823 || got.PerEUR["gbp"] != 0.8412 || !got.FetchedAt.Equal(now.Truncate(time.Second)) {
+ t.Fatalf("LatestEURRates = %+v", got)
+ }
+
+ if err := bf.srv.billingRatesPass(ctx, now.Add(2*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ if src.count() != 1 {
+ t.Fatalf("pass 2 h later: %d fetches, want 1", src.count())
+ }
+
+ later := now.Add(21 * time.Hour)
+ if err := bf.srv.billingRatesPass(ctx, later); err != nil {
+ t.Fatal(err)
+ }
+ if src.count() != 2 {
+ t.Fatalf("pass 21 h later: %d fetches, want 2", src.count())
+ }
+ // The same ECB day fetched again refreshes FetchedAt.
+ if got, err = bf.st.LatestEURRates(); err != nil || !got.FetchedAt.Equal(later.Truncate(time.Second)) {
+ t.Fatalf("after refetch LatestEURRates = %+v, %v; want FetchedAt %v", got, err, later)
+ }
+}
+
+func TestRatesPassSkipsWithoutSource(t *testing.T) {
+ bf := newBillingFixture(t)
+ if err := bf.srv.billingRatesPass(context.Background(), billingNow); err != nil {
+ t.Fatal(err)
+ }
+ got, err := bf.st.LatestEURRates()
+ if err != nil || got.Day != "" {
+ t.Fatalf("LatestEURRates = %+v, %v; want none", got, err)
+ }
+}
+
+func TestRatesPassKeepsLastGood(t *testing.T) {
+ bf := newBillingFixture(t)
+ if err := bf.st.PutEURRates(fxrate.Rates{Day: "2026-11-05", PerEUR: map[string]float64{"usd": 1.08}}, billingNow.Add(-30*time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ src := &fakeRates{err: errors.New("ecb down")}
+ bf.srv.billing.cfg.Rates = src
+ if err := bf.srv.billingRatesPass(context.Background(), billingNow); err == nil {
+ t.Fatal("billingRatesPass with a failing source: no error")
+ }
+ if src.count() != 1 {
+ t.Fatalf("%d fetches, want 1", src.count())
+ }
+ got, err := bf.st.LatestEURRates()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Day != "2026-11-05" || got.PerEUR["usd"] != 1.08 {
+ t.Fatalf("LatestEURRates = %+v, want the stored 2026-11-05 set", got)
+ }
+}
+
+func TestLatestEURRatesNewestDay(t *testing.T) {
+ st := openTestStore(t)
+ if err := st.PutEURRates(fxrate.Rates{Day: "2026-11-05", PerEUR: map[string]float64{"usd": 1.08, "gbp": 0.84}}, billingNow); err != nil {
+ t.Fatal(err)
+ }
+ if err := st.PutEURRates(fxrate.Rates{Day: "2026-11-06", PerEUR: map[string]float64{"usd": 1.09}}, billingNow.Add(-time.Hour)); err != nil {
+ t.Fatal(err)
+ }
+ got, err := st.LatestEURRates()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Day != "2026-11-06" || len(got.PerEUR) != 1 || got.PerEUR["usd"] != 1.09 {
+ t.Fatalf("LatestEURRates = %+v, want only the 2026-11-06 set", got)
+ }
+}
diff --git a/internal/console/jobs_test.go b/internal/console/jobs_test.go
index 43f73344a..468a0a70a 100644
--- a/internal/console/jobs_test.go
+++ b/internal/console/jobs_test.go
@@ -51,7 +51,7 @@ var jobPassFuncs = map[string][]string{
"StartPlanGracePass": {"planGracePass", "planGraceAccountLocked", "notifyPlanOwners",
"convergeStoreDeny", "dropStaleLapseItem", "resumeStaleCapPause"},
"StartDomainPurchasePass": {"domainPurchasePass", "advancePurchase", "advancePurchaseStep", "advancePurchaseEffects", "reconcileRegisteringPurchase", "purchaseMutation", "purchaseCheckout", "purchaseCheckoutStep", "registerPurchase", "registeredPurchase", "failPurchase", "purchaseAlert", "purchaseOwnerNotice"},
- "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge", "recordChargeMovements"},
+ "StartBillingSyncPass": {"billingSyncPass", "billingDiscoveryPass", "discoverCustomer", "transitionAccountPlan", "billingMoneyPass", "reconcilePayments", "recordCharge", "recordChargeMovements", "billingRatesPass"},
"PublishPlansMarker": {"publishPlansMarkerOnce"},
"StartRunSweep": {"runSweepPass", "sweepExpireQueued", "sweepLostRun", "sweepTerminalRun", "sweepOrphanRuns",
"orphanCandidates", "orphanConfirmed", "orphanRunEnd", "auditRunEnd",
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index b89da653b..68decd137 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -288,6 +288,7 @@ var claimSQLTables = map[string]claimSQLTable{
// The billing dashboard's money record (billingpayments_store.go).
"billing_payments": {NonApp: "money received, refunded or kept as fees, one row per provider balance movement, with the account; names no app"},
"billing_payment_cursor": {NonApp: "how far the payment reconcile has read; names no app"},
+ "billing_eur_rates": {NonApp: "daily euro reference rates; names no app"},
"managed_fleet_delivered_keys": {NonApp: "fleet access key IDs ever delivered to boxes; no app identity"},
diff --git a/internal/fxrate/fxrate.go b/internal/fxrate/fxrate.go
new file mode 100644
index 000000000..ad4eefc02
--- /dev/null
+++ b/internal/fxrate/fxrate.go
@@ -0,0 +1,123 @@
+// Package fxrate reads daily euro reference rates. The console converts
+// the money record's other currencies to euros with them, on read only;
+// the ECB's XML stays in this package, behind Source.
+package fxrate
+
+import (
+ "context"
+ "encoding/xml"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+)
+
+// Rates is one day's set of reference rates.
+type Rates struct {
+ // Day is the publisher's date for the set, "2006-01-02".
+ Day string
+ // PerEUR maps a lower-case currency code to its units per euro.
+ PerEUR map[string]float64
+}
+
+// Source gives the newest published set of rates.
+type Source interface {
+ Latest(ctx context.Context) (Rates, error)
+}
+
+// ECBDailyURL is the European Central Bank's daily reference rates.
+const ECBDailyURL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
+
+// ecbMaxBody is the most of a response Latest reads; the real file is
+// under 2 KiB.
+const ecbMaxBody = 64 << 10
+
+// ecbTimeout is the default client's timeout.
+const ecbTimeout = 20 * time.Second
+
+// ECB reads the European Central Bank's daily reference rates from URL.
+type ECB struct {
+ URL string
+ // Client is the HTTP client; nil is one with a 20 s timeout.
+ Client *http.Client
+}
+
+// ecbEnvelope is the shape of eurofxref-daily.xml: Cube/Cube[@time]/
+// Cube[@currency,@rate]. Element names match in any namespace.
+type ecbEnvelope struct {
+ Days []struct {
+ Time string `xml:"time,attr"`
+ Rates []struct {
+ Currency string `xml:"currency,attr"`
+ Rate string `xml:"rate,attr"`
+ } `xml:"Cube"`
+ } `xml:"Cube>Cube"`
+}
+
+// Latest fetches and parses the daily set. It refuses a status other than
+// 200, a body over 64 KiB, a missing or unparsable date, an empty set, and
+// any rate that is not a positive finite number.
+func (e ECB) Latest(ctx context.Context) (Rates, error) {
+ client := e.Client
+ if client == nil {
+ client = &http.Client{Timeout: ecbTimeout}
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, e.URL, nil)
+ if err != nil {
+ return Rates{}, err
+ }
+ resp, err := client.Do(req)
+ if err != nil {
+ return Rates{}, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return Rates{}, fmt.Errorf("ecb rates: status %d", resp.StatusCode)
+ }
+ body, err := io.ReadAll(io.LimitReader(resp.Body, ecbMaxBody+1))
+ if err != nil {
+ return Rates{}, fmt.Errorf("ecb rates: reading: %w", err)
+ }
+ if len(body) > ecbMaxBody {
+ return Rates{}, fmt.Errorf("ecb rates: body over %d bytes", ecbMaxBody)
+ }
+ return parseECB(body)
+}
+
+func parseECB(body []byte) (Rates, error) {
+ var env ecbEnvelope
+ if err := xml.Unmarshal(body, &env); err != nil {
+ return Rates{}, fmt.Errorf("ecb rates: %w", err)
+ }
+ if len(env.Days) != 1 {
+ return Rates{}, fmt.Errorf("ecb rates: %d dated sets, want 1", len(env.Days))
+ }
+ d := env.Days[0]
+ day, err := time.Parse(time.DateOnly, strings.TrimSpace(d.Time))
+ if err != nil {
+ return Rates{}, fmt.Errorf("ecb rates: date %q: %w", d.Time, err)
+ }
+ if len(d.Rates) == 0 {
+ return Rates{}, errors.New("ecb rates: no rates")
+ }
+ out := Rates{Day: day.Format(time.DateOnly), PerEUR: make(map[string]float64, len(d.Rates))}
+ for _, r := range d.Rates {
+ code := strings.ToLower(strings.TrimSpace(r.Currency))
+ if len(code) != 3 {
+ return Rates{}, fmt.Errorf("ecb rates: currency %q", r.Currency)
+ }
+ v, err := strconv.ParseFloat(strings.TrimSpace(r.Rate), 64)
+ if err != nil || math.IsNaN(v) || math.IsInf(v, 0) || v <= 0 {
+ return Rates{}, fmt.Errorf("ecb rates: %s rate %q is not a positive number", code, r.Rate)
+ }
+ if _, dup := out.PerEUR[code]; dup {
+ return Rates{}, fmt.Errorf("ecb rates: %s listed twice", code)
+ }
+ out.PerEUR[code] = v
+ }
+ return out, nil
+}
diff --git a/internal/fxrate/fxrate_test.go b/internal/fxrate/fxrate_test.go
new file mode 100644
index 000000000..8b5f5926b
--- /dev/null
+++ b/internal/fxrate/fxrate_test.go
@@ -0,0 +1,97 @@
+package fxrate
+
+import (
+ "context"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+)
+
+// serve answers every GET with status and body, on 127.0.0.1 only.
+func serve(t *testing.T, status int, body string) ECB {
+ t.Helper()
+ srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ t.Errorf("method %s, want GET", r.Method)
+ }
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(body))
+ }))
+ ln, err := net.Listen("tcp", "127.0.0.1:0")
+ if err != nil {
+ t.Fatal(err)
+ }
+ srv.Listener.Close()
+ srv.Listener = ln
+ srv.Start()
+ t.Cleanup(srv.Close)
+ return ECB{URL: srv.URL, Client: srv.Client()}
+}
+
+func daily(t *testing.T) string {
+ t.Helper()
+ b, err := os.ReadFile("testdata/eurofxref-daily.xml")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return string(b)
+}
+
+func TestECBParsesDaily(t *testing.T) {
+ r, err := serve(t, http.StatusOK, daily(t)).Latest(context.Background())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if r.Day != "2026-11-06" {
+ t.Errorf("Day = %q, want 2026-11-06", r.Day)
+ }
+ want := map[string]float64{"usd": 1.0823, "gbp": 0.8412}
+ if len(r.PerEUR) != len(want) {
+ t.Errorf("PerEUR = %v, want %v", r.PerEUR, want)
+ }
+ for c, v := range want {
+ if r.PerEUR[c] != v {
+ t.Errorf("PerEUR[%s] = %v, want %v", c, r.PerEUR[c], v)
+ }
+ }
+}
+
+func TestECBRefusesBadRates(t *testing.T) {
+ good := daily(t)
+ withRate := func(rate string) string {
+ return strings.Replace(good, "rate='1.0823'", "rate='"+rate+"'", 1)
+ }
+ noCubes := `<?xml version="1.0" encoding="UTF-8"?>
+<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
+ <Cube><Cube time='2026-11-06'></Cube></Cube>
+</gesmes:Envelope>`
+ big := strings.Replace(good, "<Cube>", "<!--"+strings.Repeat("x", 64<<10)+"--><Cube>", 1)
+ cases := []struct {
+ name string
+ status int
+ body string
+ }{
+ {"zero rate", 200, withRate("0")},
+ {"negative rate", 200, withRate("-1")},
+ {"NaN rate", 200, withRate("NaN")},
+ {"infinite rate", 200, withRate("+Inf")},
+ {"unparsable rate", 200, withRate("abc")},
+ {"no time", 200, strings.Replace(good, " time='2026-11-06'", "", 1)},
+ {"bad time", 200, strings.Replace(good, "2026-11-06", "6 Nov 2026", 1)},
+ {"no cubes", 200, noCubes},
+ {"no currency", 200, strings.Replace(good, "currency='USD' ", "", 1)},
+ {"status 500", 500, good},
+ {"over 64 KiB", 200, big},
+ }
+ for _, c := range cases {
+ t.Run(c.name, func(t *testing.T) {
+ r, err := serve(t, c.status, c.body).Latest(context.Background())
+ if err == nil {
+ t.Fatalf("Latest = %+v, want an error", r)
+ }
+ })
+ }
+}
diff --git a/internal/fxrate/testdata/eurofxref-daily.xml b/internal/fxrate/testdata/eurofxref-daily.xml
new file mode 100644
index 000000000..f13455e6a
--- /dev/null
+++ b/internal/fxrate/testdata/eurofxref-daily.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
+ <gesmes:subject>Reference rates</gesmes:subject>
+ <gesmes:Sender>
+ <gesmes:name>European Central Bank</gesmes:name>
+ </gesmes:Sender>
+ <Cube>
+ <Cube time='2026-11-06'>
+ <Cube currency='USD' rate='1.0823'/>
+ <Cube currency='GBP' rate='0.8412'/>
+ </Cube>
+ </Cube>
+</gesmes:Envelope>