Skip to content

Commit

Permalink
refactor(SPV-1071): cleanup in config package. (#722)
Browse files Browse the repository at this point in the history
  • Loading branch information
dorzepowski authored Oct 7, 2024
1 parent 62ba56c commit ce45722
Show file tree
Hide file tree
Showing 35 changed files with 1,110 additions and 1,234 deletions.
65 changes: 40 additions & 25 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,22 @@ import (
"time"

"github.com/bitcoin-sv/spv-wallet/config"
"github.com/bitcoin-sv/spv-wallet/dictionary"
_ "github.com/bitcoin-sv/spv-wallet/docs"
"github.com/bitcoin-sv/spv-wallet/engine"
"github.com/bitcoin-sv/spv-wallet/logging"
"github.com/bitcoin-sv/spv-wallet/server"
)

// version of the application that can be overridden with ldflags during build
// (e.g. go build -ldflags "-X main.version=1.2.3").
var version = "development"

// main method starts everything for the SPV Wallet
// @title SPV Wallet
// @version v0.12.0
// @version v1.0.0-beta
// @securityDefinitions.apikey x-auth-xpub
// @in header
// @name x-auth-xpub

// @securityDefinitions.apikey callback-auth
// @in header
// @name authorization
Expand All @@ -31,40 +34,43 @@ func main() {
defaultLogger := logging.GetDefaultLogger()

// Load the Application Configuration
appConfig, err := config.Load(defaultLogger)
appConfig, err := config.Load(version, defaultLogger)
if err != nil {
defaultLogger.Fatal().Msgf(dictionary.GetInternalMessage(dictionary.ErrorLoadingConfig), err.Error())
defaultLogger.Fatal().Err(err).Msg("Error while loading configuration")
return
}

// Validate configuration (before services have been loaded)
if err = appConfig.Validate(); err != nil {
defaultLogger.Fatal().Msgf(dictionary.GetInternalMessage(dictionary.ErrorLoadingConfig), err.Error())
defaultLogger.Fatal().Err(err).Msg("Invalid configuration")
return
}

// Load the Application Services
var services *config.AppServices
if services, err = appConfig.LoadServices(context.Background()); err != nil {
defaultLogger.Fatal().Msgf(dictionary.GetInternalMessage(dictionary.ErrorLoadingService), config.ApplicationName, err.Error())
logger, err := logging.CreateLoggerWithConfig(appConfig)
if err != nil {
defaultLogger.Fatal().Err(err).Msg("Error while creating logger")
return
}

// Try to ping the Block Headers Service if enabled
appConfig.CheckBlockHeadersService(context.Background(), services.Logger)

// (debugging: show services that are enabled or not)
if appConfig.Debug {
services.Logger.Debug().Msgf(
"datastore: %s | cachestore: %s | taskmanager: %s",
appConfig.Db.Datastore.Engine.String(),
appConfig.Cache.Engine.String(),
appConfig.TaskManager.Factory.String(),
)
appCtx := context.Background()

opts, err := appConfig.ToEngineOptions(logger)
if err != nil {
defaultLogger.Fatal().Err(err).Msg("Error while creating engine options")
return
}

spvWalletEngine, err := engine.NewClient(appCtx, opts...)
if err != nil {
defaultLogger.Fatal().Err(err).Msg("Error while creating SPV Wallet Engine")
return
}

// Try to ping the Block Headers Service if enabled
appConfig.CheckBlockHeadersService(appCtx, &logger)

// Create a new app server
appServer := server.NewServer(appConfig, services)
appServer := server.NewServer(appConfig, spvWalletEngine, logger)

idleConnectionsClosed := make(chan struct{})
go func() {
Expand All @@ -73,17 +79,26 @@ func main() {
<-sigint

// We received an interrupt signal, shut down.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
ctx, cancel := context.WithTimeout(appCtx, 5*time.Second)
defer cancel()
fatal := false
if err = spvWalletEngine.Close(ctx); err != nil {
logger.Error().Err(err).Msg("error when closing the engine")
fatal = true
}

if err = appServer.Shutdown(ctx); err != nil {
services.Logger.Fatal().Msgf("error shutting down: %s", err.Error())
logger.Error().Err(err).Msg("error shutting down the server")
fatal = true
}

close(idleConnectionsClosed)
if fatal {
os.Exit(1)
}
}()

// Listen and serve
services.Logger.Debug().Msgf("starting %s server version %s at port %d...", config.ApplicationName, config.Version, appConfig.Server.Port)
appServer.Serve()

<-idleConnectionsClosed
Expand Down
7 changes: 5 additions & 2 deletions config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,6 @@ db:
max_open_connections: 0
shared: true
table_prefix: ""
# enable debug mode
debug: true
# enable endpoints that provides profiling information
debug_profiling: true
# enable (ITC) incoming transaction checking
Expand Down Expand Up @@ -121,3 +119,8 @@ task_manager:
# Prometheus metrics configuration
metrics:
enabled: false
logging:
# log level: trace, debug, info, warn, error
level: info
# log format: json, console
format: console
10 changes: 5 additions & 5 deletions config/check_block_header_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,12 @@ const (
// CheckBlockHeadersService tries to make a request to the Block Headers Service to check if it is online and ready to verify transactions.
// AppConfig should be validated before calling this method.
// This method returns nothing, instead it logs either an error or a warning based on the state of the Block Headers Service.
func (config *AppConfig) CheckBlockHeadersService(ctx context.Context, logger *zerolog.Logger) {
if !config.BlockHeadersServiceEnabled() {
func (c *AppConfig) CheckBlockHeadersService(ctx context.Context, logger *zerolog.Logger) {
if !c.BlockHeadersServiceEnabled() {
// this method works only with Beef/Block Headers Service enabled
return
}
b := config.Paymail.Beef
b := c.Paymail.Beef

logger.Info().Msg("checking Block Headers Service")

Expand Down Expand Up @@ -83,6 +83,6 @@ func (config *AppConfig) CheckBlockHeadersService(ctx context.Context, logger *z
}

// BlockHeadersServiceEnabled returns true if the Block Headers Service is enabled in the AppConfig
func (config *AppConfig) BlockHeadersServiceEnabled() bool {
return config.Paymail != nil && config.Paymail.Beef.enabled()
func (c *AppConfig) BlockHeadersServiceEnabled() bool {
return c.Paymail != nil && c.Paymail.Beef.enabled()
}
17 changes: 10 additions & 7 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
package config

import (
"fmt"
"time"

"github.com/bitcoin-sv/spv-wallet/engine/cluster"
Expand All @@ -10,20 +11,24 @@ import (
"github.com/mrz1836/go-cachestore"
)

const (
applicationName = "SPV Wallet"
envPrefix = "SPVWALLET"
)

// Config constants used for spv-wallet
const (
ApplicationName = "SPVWallet"
APIVersion = "v1"
HealthRequestPath = "health"
Version = "v0.12.0"
ConfigFilePathKey = "config_file"
DefaultConfigFilePath = "config.yaml"
EnvPrefix = "SPVWALLET"
BroadcastCallbackRoute = "/transaction/broadcast/callback"
)

// AppConfig is the configuration values and associated env vars
type AppConfig struct {
// Version is the version of the application.
Version string `json:"version" mapstructure:"version"`
// TaskManager is a configuration for Task Manager in SPV Wallet.
TaskManager *TaskManagerConfig `json:"task_manager" mapstructure:"task_manager"`
// Authentication is the configuration for keys authentication in SPV Wallet.
Expand All @@ -50,8 +55,6 @@ type AppConfig struct {
BHS *BHSConfig `json:"block_headers_service" mapstructure:"block_headers_service"`
// ImportBlockHeaders is a URL from where the headers can be downloaded.
ImportBlockHeaders string `json:"import_block_headers" mapstructure:"import_block_headers"`
// Debug is a flag for enabling additional information from SPV Wallet.
Debug bool `json:"debug" mapstructure:"debug"`
// DebugProfiling is a flag for enabling additinal debug profiling.
DebugProfiling bool `json:"debug_profiling" mapstructure:"debug_profiling"`
// DisableITC is a flag for disabling Incoming Transaction Checking.
Expand Down Expand Up @@ -241,6 +244,6 @@ type ExperimentalConfig struct {
}

// GetUserAgent will return the outgoing user agent
func (a *AppConfig) GetUserAgent() string {
return "SPV Wallet " + Version
func (c *AppConfig) GetUserAgent() string {
return fmt.Sprintf("%s version %s", applicationName, c.Version)
}
122 changes: 0 additions & 122 deletions config/config_test.go

This file was deleted.

Loading

0 comments on commit ce45722

Please sign in to comment.