|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +package currencies |
| 16 | + |
| 17 | +import ( |
| 18 | + "context" |
| 19 | + "encoding/json" |
| 20 | + "errors" |
| 21 | + "fmt" |
| 22 | + "net/http" |
| 23 | + "net/url" |
| 24 | + "sync" |
| 25 | + "time" |
| 26 | + |
| 27 | + "github.com/honeycombio/beeline-go" |
| 28 | + "github.com/redis/go-redis/v9" |
| 29 | + |
| 30 | + "github.com/pebble-dev/bobby-assistant/service/assistant/config" |
| 31 | + "github.com/pebble-dev/bobby-assistant/service/assistant/util/storage" |
| 32 | +) |
| 33 | + |
| 34 | +type CurrencyExchangeData struct { |
| 35 | + Result string `json:"result"` |
| 36 | + ErrorType string `json:"error-type,omitempty"` |
| 37 | + TimeLastUpdateUnix int `json:"time_last_update_unix"` |
| 38 | + TimeNextUpdateUnix int `json:"time_next_update_unix"` |
| 39 | + BaseCode string `json:"base_code"` |
| 40 | + ConversionRates map[string]float64 `json:"conversion_rates"` |
| 41 | +} |
| 42 | + |
| 43 | +var sharedCurrencyDataManager *DataManager |
| 44 | +var sharedCurrencyDataManagerOnce sync.Once |
| 45 | + |
| 46 | +func GetCurrencyDataManager() *DataManager { |
| 47 | + sharedCurrencyDataManagerOnce.Do(func() { |
| 48 | + sharedCurrencyDataManager = &DataManager{ |
| 49 | + redisClient: storage.GetRedis(), |
| 50 | + } |
| 51 | + }) |
| 52 | + return sharedCurrencyDataManager |
| 53 | +} |
| 54 | + |
| 55 | +type DataManager struct { |
| 56 | + redisClient *redis.Client |
| 57 | +} |
| 58 | + |
| 59 | +var ErrUnknownCurrency = errors.New("unknown currency code") |
| 60 | +var ErrQuotaExceeded = errors.New("quota exceeded") |
| 61 | + |
| 62 | +func (dm *DataManager) GetExchangeData(ctx context.Context, from string) (*CurrencyExchangeData, error) { |
| 63 | + ctx, span := beeline.StartSpan(ctx, "get_exchange_data") |
| 64 | + defer span.Send() |
| 65 | + if !IsValidCurrency(from) { |
| 66 | + return nil, fmt.Errorf("unknown currency code %q", from) |
| 67 | + } |
| 68 | + data, err := dm.loadCachedData(ctx, from) |
| 69 | + if err != nil { |
| 70 | + return nil, fmt.Errorf("couldn't load cached data: %w", err) |
| 71 | + } |
| 72 | + if data != nil { |
| 73 | + return data, nil |
| 74 | + } |
| 75 | + // TODO: if we had high usage, we should prevent multiple concurrent requests for the same currency |
| 76 | + // but in practice this seems unlikely to be a major issue at our anticipated scale. |
| 77 | + data, err = dm.fetchExchangeRateData(ctx, from) |
| 78 | + if err != nil { |
| 79 | + return nil, fmt.Errorf("couldn't fetch exchange rate data: %w", err) |
| 80 | + } |
| 81 | + if err := dm.cacheData(ctx, from, data); err != nil { |
| 82 | + return nil, fmt.Errorf("error caching exchange rate data: %w", err) |
| 83 | + } |
| 84 | + return data, nil |
| 85 | +} |
| 86 | + |
| 87 | +func (dm *DataManager) fetchExchangeRateData(ctx context.Context, from string) (*CurrencyExchangeData, error) { |
| 88 | + ctx, span := beeline.StartSpan(ctx, "fetch_exchange_rate_data") |
| 89 | + defer span.Send() |
| 90 | + escaped := url.QueryEscape(from) |
| 91 | + request, err := http.NewRequest("GET", "https://v6.exchangerate-api.com/v6/"+config.GetConfig().ExchangeRateApiKey+"/latest/"+escaped, nil) |
| 92 | + if err != nil { |
| 93 | + return nil, err |
| 94 | + } |
| 95 | + resp, err := http.DefaultClient.Do(request) |
| 96 | + if err != nil { |
| 97 | + return nil, err |
| 98 | + } |
| 99 | + defer resp.Body.Close() |
| 100 | + var data CurrencyExchangeData |
| 101 | + if err := json.NewDecoder(resp.Body).Decode(&data); err != nil { |
| 102 | + return nil, err |
| 103 | + } |
| 104 | + if data.Result != "success" { |
| 105 | + if data.Result != "error" { |
| 106 | + return nil, fmt.Errorf("unexpected result %q", data.Result) |
| 107 | + } |
| 108 | + switch data.ErrorType { |
| 109 | + case "unsupported-code": |
| 110 | + return nil, ErrUnknownCurrency |
| 111 | + case "quota-reached": |
| 112 | + return nil, ErrQuotaExceeded |
| 113 | + default: |
| 114 | + return nil, fmt.Errorf("error fetching currency data: %s", data.ErrorType) |
| 115 | + } |
| 116 | + } |
| 117 | + return &data, nil |
| 118 | +} |
| 119 | + |
| 120 | +func (dm *DataManager) cacheData(ctx context.Context, currency string, data *CurrencyExchangeData) error { |
| 121 | + ctx, span := beeline.StartSpan(ctx, "cache_data") |
| 122 | + defer span.Send() |
| 123 | + encoded, err := json.Marshal(data) |
| 124 | + if err != nil { |
| 125 | + return err |
| 126 | + } |
| 127 | + expirationTime := time.Unix(int64(data.TimeNextUpdateUnix+5), 0) |
| 128 | + if err := dm.redisClient.Set(ctx, keyFromCurrency(currency), encoded, expirationTime.Sub(time.Now())).Err(); err != nil { |
| 129 | + return err |
| 130 | + } |
| 131 | + return nil |
| 132 | +} |
| 133 | + |
| 134 | +func (dm *DataManager) loadCachedData(ctx context.Context, currency string) (*CurrencyExchangeData, error) { |
| 135 | + ctx, span := beeline.StartSpan(ctx, "load_cached_data") |
| 136 | + defer span.Send() |
| 137 | + data, err := dm.redisClient.Get(ctx, keyFromCurrency(currency)).Result() |
| 138 | + if err != nil { |
| 139 | + if errors.Is(err, redis.Nil) { |
| 140 | + return nil, nil |
| 141 | + } |
| 142 | + return nil, err |
| 143 | + } |
| 144 | + var decoded CurrencyExchangeData |
| 145 | + if err := json.Unmarshal([]byte(data), &decoded); err != nil { |
| 146 | + return nil, err |
| 147 | + } |
| 148 | + return &decoded, nil |
| 149 | +} |
| 150 | + |
| 151 | +func keyFromCurrency(from string) string { |
| 152 | + return "currency:" + from |
| 153 | +} |
0 commit comments