// Package alert decides when an item fires: when one of its pages offers it // from an accepted seller at an accepted price, and the item's cooldown // allows another alert. package alert import ( "context" "fmt" "math" "strconv" "sync" "time" "git.security-command.org/Overlord/dibs/internal/config" "git.security-command.org/Overlord/dibs/internal/plugin" ) // Alert is one item becoming buyable. type Alert struct { Item string Shop string // URL is the product page, as the plugin normalized it. URL string Title string Price *float64 Currency string // Converted is Price in the item's currency, when the page uses another // one and the conversion worked. Converted *float64 ConvertedCurrency string Seller string CartLink string Time time.Time // PreviousPrice is the price of the last alert, when this one fires // during the cooldown because the price dropped below it. PreviousPrice *float64 PreviousCurrency string // Cart is what session mode did about the cart, in the order the // notifications go out: CartAdding, then CartAdded or CartFailed. It is // "" without session mode. Cart string // CartURL is the cart page, once the item is in the cart. CartURL string // CartError says why adding to the cart failed. CartError string // Test marks the sample alert of `dibs notify test`. Test bool } // The cart steps of session mode. const ( CartAdding = "adding" CartAdded = "added" CartFailed = "failed" ) // PriceText is the price as notifications show it, such as "129.99 EUR" or // "149.99 USD (≈ 133.95 EUR)". func (a Alert) PriceText() string { if a.Price == nil { return "price unknown" } s := Money(*a.Price, a.Currency) if a.Converted != nil { s += " (≈ " + Money(*a.Converted, a.ConvertedCurrency) + ")" } return s } // SellerText describes the seller for notifications. func (a Alert) SellerText() string { switch a.Seller { case plugin.SellerFirstParty: return "sold by " + a.Shop case plugin.SellerFulfilled: return "shipped by " + a.Shop case plugin.SellerThirdParty: return "marketplace seller" default: return "seller unknown" } } func Money(amount float64, currency string) string { s := strconv.FormatFloat(amount, 'f', 2, 64) if currency != "" { s += " " + currency } return s } // Converter is fx.Service. type Converter interface { Convert(ctx context.Context, amount float64, from, to string) (float64, error) } // Sent is what an item's cooldown remembers about its last alert. type Sent struct { Time time.Time `json:"time"` Price *float64 `json:"price,omitempty"` Currency string `json:"currency,omitempty"` // ItemPrice is the price in the item's currency, so that pages in // different currencies compare. ItemPrice *float64 `json:"item_price,omitempty"` ItemCurrency string `json:"item_currency,omitempty"` } // Store keeps the cooldowns between runs and shares them with other dibs // processes. Lock is held from loading an item's last alert until the new // one is stored, so two processes never both send it. type Store interface { Lock() func() LoadAlert(item string) (Sent, bool) StoreAlert(item string, s Sent) } // Engine turns check results into alerts. It is safe for concurrent use. type Engine struct { cooldown time.Duration fx Converter store Store mu sync.Mutex sent map[string]Sent // used when store is nil } // NewEngine returns an engine. store may be nil to keep cooldowns in memory. func NewEngine(cooldown time.Duration, fx Converter, store Store) *Engine { return &Engine{cooldown: cooldown, fx: fx, store: store, sent: map[string]Sent{}} } // Decision is what Consider made of a checked page. type Decision struct { // Alert is set when the item fires. Alert *Alert // Qualifies reports whether the page passed the seller and price checks, // even if the cooldown held the alert back. Qualifies bool // Reason says why an available page did not fire. Reason string } // Consider decides whether a checked page makes its item fire. A page that // is not available decides nothing. An error means the price could not be // checked, such as when no current exchange rate is available. func (e *Engine) Consider(ctx context.Context, item config.Item, rep *plugin.Report, now time.Time) (Decision, error) { if rep == nil || rep.Result == nil || !rep.Result.Available { return Decision{}, nil } a, why, err := e.qualify(ctx, item, rep, now) if a == nil { return Decision{Reason: why}, err } unlock := e.lock() defer unlock() next := a.sent(item.Currency) last, ok := e.load(item.Name) allowed, drop := Allows(last, ok, next, e.cooldown) switch { case !allowed: return Decision{Qualifies: true, Reason: "in cooldown until " + last.Time.Add(e.cooldown).Format(time.TimeOnly)}, nil case drop && last.Currency == next.Currency: a.PreviousPrice, a.PreviousCurrency = last.Price, last.Currency case drop: a.PreviousPrice, a.PreviousCurrency = last.ItemPrice, last.ItemCurrency } e.save(item.Name, next) return Decision{Alert: a, Qualifies: true}, nil } // sent is what the cooldown remembers of a. func (a *Alert) sent(itemCurrency string) Sent { s := Sent{Time: a.Time, Price: a.Price, Currency: a.Currency} switch { case a.Converted != nil: s.ItemPrice, s.ItemCurrency = a.Converted, a.ConvertedCurrency case a.Price != nil && (a.Currency == itemCurrency || a.Currency == "" || itemCurrency == ""): s.ItemPrice, s.ItemCurrency = a.Price, itemCurrency } return s } // qualify checks an available page against the item's seller policy and // max_price. func (e *Engine) qualify(ctx context.Context, item config.Item, rep *plugin.Report, now time.Time) (*Alert, string, error) { res := rep.Result if !item.AcceptsSeller(res.Seller) { return nil, fmt.Sprintf("seller is %s, the item accepts %s", res.Seller, item.Seller), nil } a := &Alert{ Item: item.Name, Shop: rep.Shop, URL: rep.FetchURL, Title: res.Title, Price: res.Price, Currency: res.Currency, Seller: res.Seller, CartLink: rep.CartLink, Time: now, } // A page without a currency is taken to use the item's. foreign := item.Currency != "" && res.Currency != "" && res.Currency != item.Currency var convErr error if foreign && res.Price != nil { v, err := e.fx.Convert(ctx, *res.Price, res.Currency, item.Currency) v = math.Round(v*100) / 100 if err == nil { a.Converted, a.ConvertedCurrency = &v, item.Currency } else { convErr = err } } if item.MaxPrice == nil { return a, "", nil } limit := *item.MaxPrice switch { case res.Price == nil: return nil, "no price on the page to compare with max_price", nil case foreign && convErr != nil: return nil, "", fmt.Errorf("cannot compare %s with max_price %s: %w", Money(*res.Price, res.Currency), Money(limit, item.Currency), convErr) case foreign: if p := *a.Converted * (1 + item.FXMargin); p > limit { return nil, fmt.Sprintf("price %s with fx_margin is above max_price %s", Money(p, item.Currency), Money(limit, item.Currency)), nil } case *res.Price > limit: return nil, fmt.Sprintf("price %s is above max_price %s", Money(*res.Price, res.Currency), Money(limit, item.Currency)), nil } return a, "", nil } // Allows applies an item's cooldown: after an alert, the item stays quiet // for cooldown unless its price drops below the last alert's. It also // reports whether next is for such a drop. // // Prices in the same page currency compare as they are, so that exchange // rates moving overnight never look like a price drop. Prices in different // currencies compare in the item's currency. func Allows(last Sent, hasLast bool, next Sent, cooldown time.Duration) (allowed, drop bool) { if !hasLast || !next.Time.Before(last.Time.Add(cooldown)) { return true, false } switch { case next.Price != nil && last.Price != nil && next.Currency == last.Currency: drop = *next.Price < *last.Price case next.ItemPrice != nil && last.ItemPrice != nil && next.ItemCurrency == last.ItemCurrency: drop = *next.ItemPrice < *last.ItemPrice default: // Without a price in a shared currency, nothing compares. } return drop, drop } func (e *Engine) lock() func() { if e.store == nil { return func() {} } return e.store.Lock() } func (e *Engine) load(item string) (Sent, bool) { if e.store != nil { return e.store.LoadAlert(item) } e.mu.Lock() defer e.mu.Unlock() s, ok := e.sent[item] return s, ok } func (e *Engine) save(item string, s Sent) { if e.store != nil { e.store.StoreAlert(item, s) return } e.mu.Lock() defer e.mu.Unlock() e.sent[item] = s }