feat(indices): add authenticated OpenFIGI search

Add the bounded OpenFIGI v3 adapter, authenticated search route, and server-side configuration.

Refs #3

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 22:31:35 +01:00
parent 461f525f20
commit 5cb45138df
15 changed files with 741 additions and 16 deletions

View File

@ -0,0 +1,185 @@
package openfigi
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"net"
"net/http"
"strconv"
"strings"
"sync"
"time"
"unicode"
"unicode/utf8"
"github.com/tradarr/backend/internal/indices"
)
var ErrRateLimited = indices.ErrRateLimited
type HTTPClient interface {
Do(*http.Request) (*http.Response, error)
}
type Config struct {
APIKey, BaseURL string
Timeout time.Duration
}
type Adapter struct {
cfg Config
client HTTPClient
mu sync.Mutex
calls []time.Time
now func() time.Time
blockedUntil time.Time
}
var _ indices.IndexSearcher = (*Adapter)(nil)
func New(cfg Config, client HTTPClient) *Adapter {
if cfg.BaseURL == "" {
cfg.BaseURL = "https://api.openfigi.com"
}
if cfg.Timeout <= 0 {
cfg.Timeout = 5 * time.Second
}
if client == nil {
client = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
}
if hc, ok := client.(*http.Client); ok {
clone := *hc
clone.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
client = &clone
}
// The composed singleton shares its quota across all authenticated accounts.
return &Adapter{cfg: cfg, client: client, now: time.Now}
}
func (a *Adapter) reserve() bool {
a.mu.Lock()
defer a.mu.Unlock()
now := a.now()
if now.Before(a.blockedUntil) {
return false
}
valid := a.calls[:0]
for _, call := range a.calls {
if now.Sub(call) < time.Minute {
valid = append(valid, call)
}
}
a.calls = valid
max := 5
if a.cfg.APIKey != "" {
max = 20
}
if len(a.calls) >= max {
return false
}
a.calls = append(a.calls, now)
return true
}
func clean(value string) string {
if !utf8.ValidString(value) {
return ""
}
return strings.TrimSpace(strings.Map(func(r rune) rune {
if unicode.IsControl(r) {
return -1
}
return r
}, value))
}
func (a *Adapter) Search(ctx context.Context, query string, limit int) ([]indices.Index, error) {
query = strings.TrimSpace(query)
if !indices.ValidQuery(query, limit) {
return nil, indices.ErrInvalidQuery
}
if err := ctx.Err(); err != nil {
return nil, err
}
if !a.reserve() {
return nil, ErrRateLimited
}
payload, _ := json.Marshal(struct {
Query string `json:"query"`
Market string `json:"marketSecDes"`
}{query, "Index"})
ctx, cancel := context.WithTimeout(ctx, a.cfg.Timeout)
defer cancel()
request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(a.cfg.BaseURL, "/")+"/v3/search", bytes.NewReader(payload))
if err != nil {
return nil, indices.ErrUnavailable
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Accept", "application/json")
if a.cfg.APIKey != "" {
request.Header.Set("X-OPENFIGI-APIKEY", a.cfg.APIKey)
}
response, err := a.client.Do(request)
if err != nil {
var timeout net.Error
if errors.Is(err, context.DeadlineExceeded) || errors.Is(ctx.Err(), context.DeadlineExceeded) || (errors.As(err, &timeout) && timeout.Timeout()) {
return nil, context.DeadlineExceeded
}
return nil, indices.ErrUnavailable
}
defer response.Body.Close()
if response.StatusCode == http.StatusTooManyRequests {
delay := time.Minute
if seconds, err := strconv.Atoi(response.Header.Get("Retry-After")); err == nil && seconds > 0 && seconds <= 86400 {
delay = time.Duration(seconds) * time.Second
}
a.mu.Lock()
a.blockedUntil = a.now().Add(delay)
a.mu.Unlock()
return nil, ErrRateLimited
}
if response.StatusCode != http.StatusOK {
return nil, indices.ErrUnavailable
}
raw, err := io.ReadAll(io.LimitReader(response.Body, 2*1024*1024+1))
if err != nil {
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return nil, context.DeadlineExceeded
}
return nil, indices.ErrUnavailable
}
if len(raw) > 2*1024*1024 {
return nil, indices.ErrUnavailable
}
var result struct {
Data json.RawMessage `json:"data"`
Error json.RawMessage `json:"error"`
}
if json.Unmarshal(raw, &result) != nil || len(result.Error) > 0 || len(result.Data) == 0 || bytes.Equal(bytes.TrimSpace(result.Data), []byte("null")) {
return nil, indices.ErrUnavailable
}
var rows []struct {
Name string `json:"name"`
Ticker string `json:"ticker"`
FIGI string `json:"figi"`
MarketSector string `json:"marketSector"`
}
if json.Unmarshal(result.Data, &rows) != nil {
return nil, indices.ErrUnavailable
}
selected := []indices.Index{}
seen := map[string]bool{}
for _, row := range rows {
if row.MarketSector != "Index" {
continue
}
name, symbol, figi := clean(row.Name), clean(row.Ticker), clean(row.FIGI)
if name == "" || symbol == "" || figi == "" || seen[figi] {
continue
}
seen[figi] = true
selected = append(selected, indices.Index{Name: name, Symbol: symbol, FIGI: figi})
if len(selected) == limit {
break
}
}
return selected, nil
}