From cf2d3d74f39a569b478c339ac0ffe5f60822c5d5 Mon Sep 17 00:00:00 2001 From: Anselm Jonas Scholl Date: Tue, 2 Apr 2024 09:36:59 +0200 Subject: [PATCH] currency: added in-memory service; This adds an in-memory version of the currency service. Upon initialization, all exchange rates are fetched and stored in memory, making the need for an external update service or data store obsolete. This is intended for tools or other applications which don't run continuesly and need access to the exchange rates without imposing additional infrastrucute requirements or similar. --- pkg/currency/in_memory_service.go | 49 +++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 pkg/currency/in_memory_service.go diff --git a/pkg/currency/in_memory_service.go b/pkg/currency/in_memory_service.go new file mode 100644 index 000000000..2d408eeb3 --- /dev/null +++ b/pkg/currency/in_memory_service.go @@ -0,0 +1,49 @@ +package currency + +import ( + "context" + "fmt" + "time" + + "github.com/justtrackio/gosoline/pkg/cfg" + "github.com/justtrackio/gosoline/pkg/clock" + "github.com/justtrackio/gosoline/pkg/http" + "github.com/justtrackio/gosoline/pkg/kvstore" + "github.com/justtrackio/gosoline/pkg/log" +) + +// NewInMemoryService creates a currency Service which never updates and reads all currency values in the constructor. +// It can be useful when you need to run a tool or similar and don't want to store the currency data somewhere or have +// a complicated module setup. +func NewInMemoryService(ctx context.Context, config cfg.Config, logger log.Logger) (Service, error) { + logger = logger.WithChannel("in-memory-currency-service") + + store, err := kvstore.NewInMemoryKvStore[float64](ctx, config, logger, &kvstore.Settings{ + Ttl: time.Hour * 24 * 365, // data never expires or updates + InMemorySettings: kvstore.InMemorySettings{ + MaxSize: 1_000_000_000, + }, + }) + if err != nil { + return nil, fmt.Errorf(": %w", err) + } + + httpClient, err := http.ProvideHttpClient(ctx, config, logger, "currencyUpdater") + if err != nil { + return nil, fmt.Errorf("can not create http client: %w", err) + } + + updater := NewUpdaterWithInterfaces(logger, store, httpClient, clock.Provider) + + err = updater.EnsureRecentExchangeRates(ctx) + if err != nil { + return nil, fmt.Errorf("failed to fetch recent exchange rates: %w", err) + } + + err = updater.EnsureHistoricalExchangeRates(ctx) + if err != nil { + return nil, fmt.Errorf("failed to fetch historical exchange rates: %w", err) + } + + return NewWithInterfaces(store, clock.Provider), nil +}