Add alerts, currency conversion and notifications.
Items fire when a page is available from an accepted seller at or below max_price, converted with the ECB's daily rates when the page uses another currency. A per-item cooldown, kept in the state file, holds back repeat alerts unless the price drops. Alerts go to Discord, ntfy and JSON webhooks with retries, and to the desktop; 'dibs notify test' sends a sample.
This commit is contained in:
1 parent
2175c0e5aa
commit
8f0eda5d4d
16 files changed
+1409
-15
No files matched your search
@@ -0,0 +1,266 @@
|
||||
// Package fx converts prices between currencies with the ECB's daily
|
||||
// reference rates.
|
||||
package fx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RatesURL is the ECB's feed of the latest reference rates. It needs no API
|
||||
// key and changes once per working day, around 16:00 CET.
|
||||
const RatesURL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
|
||||
|
||||
const (
|
||||
// Rates fetched more than refreshAfter ago are refreshed in the
|
||||
// background while still in use.
|
||||
refreshAfter = 6 * time.Hour
|
||||
// MaxAge is how long rates stay usable without a successful refresh.
|
||||
MaxAge = 72 * time.Hour
|
||||
// retryAfter spaces out refreshes after one fails.
|
||||
retryAfter = 15 * time.Minute
|
||||
fetchTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
// Rates are the ECB reference rates of one day.
|
||||
type Rates struct {
|
||||
// Date is the ECB's publication day, as YYYY-MM-DD.
|
||||
Date string `json:"date"`
|
||||
// Fetched is when the rates were last downloaded, even if the ECB had
|
||||
// not published newer ones.
|
||||
Fetched time.Time `json:"fetched"`
|
||||
// PerEUR is how much of each currency one euro buys.
|
||||
PerEUR map[string]float64 `json:"per_eur"`
|
||||
}
|
||||
|
||||
// Convert converts amount from one currency to another, through the euro.
|
||||
func (r *Rates) Convert(amount float64, from, to string) (float64, error) {
|
||||
if from == to { return amount, nil }
|
||||
|
||||
f, err := r.perEUR(from)
|
||||
if err != nil { return 0, err }
|
||||
|
||||
t, err := r.perEUR(to)
|
||||
if err != nil { return 0, err }
|
||||
|
||||
return amount / f * t, nil
|
||||
}
|
||||
|
||||
func (r *Rates) perEUR(currency string) (float64, error) {
|
||||
if currency == "EUR" { return 1, nil }
|
||||
|
||||
if rate, ok := r.PerEUR[currency]; ok && rate > 0 { return rate, nil }
|
||||
|
||||
return 0, fmt.Errorf("the ECB publishes no rate for %s", currency)
|
||||
}
|
||||
|
||||
// Store keeps the rates between runs and shares them with other dibs
|
||||
// processes.
|
||||
type Store interface {
|
||||
Lock() func()
|
||||
LoadRates() (*Rates, bool)
|
||||
StoreRates(r *Rates)
|
||||
}
|
||||
|
||||
// Limiter is ratelimit.Limiter, which spaces out the requests to the ECB
|
||||
// like every other request dibs makes.
|
||||
type Limiter interface {
|
||||
WaitCheck(ctx context.Context, url string) error
|
||||
}
|
||||
|
||||
// Service hands out current rates and refreshes them when they are due. It
|
||||
// is safe for concurrent use.
|
||||
type Service struct {
|
||||
store Store
|
||||
limiter Limiter
|
||||
client *http.Client
|
||||
url string
|
||||
now func() time.Time
|
||||
|
||||
mu sync.Mutex
|
||||
rates *Rates
|
||||
lastTry time.Time
|
||||
lastErr error
|
||||
inflight chan struct{} // closed when the running refresh ends
|
||||
}
|
||||
|
||||
func New(store Store, limiter Limiter) *Service {
|
||||
return &Service{
|
||||
store: store,
|
||||
limiter: limiter,
|
||||
client: &http.Client{Timeout: fetchTimeout},
|
||||
url: RatesURL,
|
||||
now: time.Now,
|
||||
}
|
||||
}
|
||||
|
||||
// Warm starts a refresh in the background if the rates are due for one, so
|
||||
// the first conversion does not wait for the network.
|
||||
func (s *Service) Warm() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.load()
|
||||
if s.due() { s.startRefresh() }
|
||||
}
|
||||
|
||||
// Convert converts amount with the newest usable rates. When the rates are
|
||||
// older than MaxAge, it waits for a refresh; if that fails, it fails too.
|
||||
func (s *Service) Convert(ctx context.Context, amount float64, from, to string) (float64, error) {
|
||||
if from == to { return amount, nil }
|
||||
|
||||
r, err := s.current(ctx)
|
||||
if err != nil { return 0, err }
|
||||
|
||||
return r.Convert(amount, from, to)
|
||||
}
|
||||
|
||||
func (s *Service) current(ctx context.Context) (*Rates, error) {
|
||||
s.mu.Lock()
|
||||
|
||||
s.load()
|
||||
if s.due() { s.startRefresh() }
|
||||
|
||||
if s.usable() {
|
||||
r := s.rates
|
||||
s.mu.Unlock()
|
||||
|
||||
return r, nil
|
||||
}
|
||||
|
||||
wait := s.inflight
|
||||
s.mu.Unlock()
|
||||
|
||||
if wait != nil {
|
||||
select {
|
||||
case <-wait:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if s.usable() { return s.rates, nil }
|
||||
|
||||
var cause string
|
||||
if s.lastErr != nil { cause = ": " + s.lastErr.Error() }
|
||||
|
||||
return nil, fmt.Errorf("no exchange rates younger than %s%s", MaxAge, cause)
|
||||
}
|
||||
|
||||
// load picks up rates another dibs process may have fetched. Callers hold
|
||||
// mu.
|
||||
func (s *Service) load() {
|
||||
if s.store == nil { return }
|
||||
|
||||
if r, ok := s.store.LoadRates(); ok && (s.rates == nil || r.Fetched.After(s.rates.Fetched)) { s.rates = r }
|
||||
}
|
||||
|
||||
// due reports whether a refresh should start. Callers hold mu.
|
||||
func (s *Service) due() bool {
|
||||
now := s.now()
|
||||
|
||||
switch {
|
||||
case s.inflight != nil:
|
||||
return false
|
||||
case !s.lastTry.IsZero() && now.Sub(s.lastTry) < retryAfter:
|
||||
return false
|
||||
case s.rates == nil:
|
||||
return true
|
||||
default:
|
||||
return now.Sub(s.rates.Fetched) >= refreshAfter
|
||||
}
|
||||
}
|
||||
|
||||
// usable reports whether the rates are young enough to use. Callers hold
|
||||
// mu.
|
||||
func (s *Service) usable() bool {
|
||||
return s.rates != nil && s.now().Sub(s.rates.Fetched) < MaxAge
|
||||
}
|
||||
|
||||
// startRefresh fetches the rates in the background. Callers hold mu.
|
||||
func (s *Service) startRefresh() {
|
||||
done := make(chan struct{})
|
||||
s.inflight = done
|
||||
s.lastTry = s.now()
|
||||
|
||||
go func() {
|
||||
defer close(done)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), fetchTimeout+time.Minute)
|
||||
defer cancel()
|
||||
|
||||
r, err := s.fetch(ctx)
|
||||
|
||||
s.mu.Lock()
|
||||
s.inflight, s.lastErr = nil, err
|
||||
if err == nil { s.rates = r }
|
||||
s.mu.Unlock()
|
||||
|
||||
if err == nil && s.store != nil {
|
||||
unlock := s.store.Lock()
|
||||
s.store.StoreRates(r)
|
||||
unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
func (s *Service) fetch(ctx context.Context) (*Rates, error) {
|
||||
if s.limiter != nil {
|
||||
if err := s.limiter.WaitCheck(ctx, s.url); err != nil { return nil, err }
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, s.url, nil)
|
||||
if err != nil { return nil, err }
|
||||
|
||||
resp, err := s.client.Do(req)
|
||||
if err != nil { return nil, fmt.Errorf("fetching exchange rates: %w", err) }
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode != http.StatusOK { return nil, fmt.Errorf("fetching exchange rates: %s", resp.Status) }
|
||||
|
||||
r, err := Parse(io.LimitReader(resp.Body, 1<<20))
|
||||
if err != nil { return nil, err }
|
||||
|
||||
r.Fetched = s.now()
|
||||
return r, nil
|
||||
}
|
||||
|
||||
// Parse reads the ECB's eurofxref XML.
|
||||
func Parse(rd io.Reader) (*Rates, error) {
|
||||
var doc 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"`
|
||||
}
|
||||
|
||||
if err := xml.NewDecoder(rd).Decode(&doc); err != nil { return nil, fmt.Errorf("reading exchange rates: %w", err) }
|
||||
if len(doc.Days) == 0 { return nil, errors.New("reading exchange rates: no rates in the feed") }
|
||||
|
||||
day := doc.Days[0]
|
||||
r := &Rates{Date: day.Time, PerEUR: map[string]float64{}}
|
||||
|
||||
for _, c := range day.Rates {
|
||||
rate, err := strconv.ParseFloat(c.Rate, 64)
|
||||
if err != nil || rate <= 0 { return nil, fmt.Errorf("reading exchange rates: bad rate %q for %s", c.Rate, c.Currency) }
|
||||
|
||||
r.PerEUR[c.Currency] = rate
|
||||
}
|
||||
|
||||
if len(r.PerEUR) == 0 { return nil, errors.New("reading exchange rates: no rates in the feed") }
|
||||
|
||||
return r, nil
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package fx
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestConvert(t *testing.T) {
|
||||
r := &Rates{PerEUR: map[string]float64{"USD": 1.25, "GBP": 0.8}}
|
||||
|
||||
cases := []struct {
|
||||
amount float64
|
||||
from, to string
|
||||
want float64
|
||||
} {
|
||||
{100, "EUR", "USD", 125},
|
||||
{125, "USD", "EUR", 100},
|
||||
{100, "GBP", "USD", 156.25},
|
||||
{100, "GBP", "GBP", 100},
|
||||
}
|
||||
|
||||
for _, c := range cases {
|
||||
got, err := r.Convert(c.amount, c.from, c.to)
|
||||
if err != nil || math.Abs(got-c.want) > 1e-9 { t.Errorf("%v %s in %s = %v, %v; want %v", c.amount, c.from, c.to, got, err, c.want) }
|
||||
}
|
||||
|
||||
if _, err := r.Convert(1, "JPY", "EUR"); err == nil { t.Error("converted a currency without a rate") }
|
||||
}
|
||||
Reference in new issue
Block a user