Skip to content

Commit

Permalink
chore(server): rename configresource (#2797)
Browse files Browse the repository at this point in the history
  • Loading branch information
schoren committed Jun 22, 2023
1 parent b19c3dc commit df1d070
Show file tree
Hide file tree
Showing 20 changed files with 257 additions and 267 deletions.
23 changes: 11 additions & 12 deletions server/app/app.go
Expand Up @@ -15,7 +15,6 @@ import (
"github.com/kubeshop/tracetest/server/analytics"
"github.com/kubeshop/tracetest/server/assertions/comparator"
"github.com/kubeshop/tracetest/server/config"
"github.com/kubeshop/tracetest/server/config/configresource"
"github.com/kubeshop/tracetest/server/config/demoresource"
"github.com/kubeshop/tracetest/server/environment"
"github.com/kubeshop/tracetest/server/executor"
Expand Down Expand Up @@ -48,14 +47,14 @@ var (
var EmptyDemoEnabled []string

type App struct {
cfg *config.Config
cfg *config.AppConfig
provisioningFile string
stopFns []func()

serverID string
}

func New(config *config.Config) (*App, error) {
func New(config *config.AppConfig) (*App, error) {
app := &App{
cfg: config,
}
Expand Down Expand Up @@ -115,9 +114,9 @@ func provision(provisioner *provisioning.Provisioner, file string) {
}

func (app *App) subscribeToConfigChanges(sm *subscription.Manager) {
sm.Subscribe(configresource.ResourceID, subscription.NewSubscriberFunction(
sm.Subscribe(config.ResourceID, subscription.NewSubscriberFunction(
func(m subscription.Message) error {
configFromDB, ok := m.Content.(configresource.Config)
configFromDB, ok := m.Content.(config.Config)
if !ok {
return fmt.Errorf("cannot read update to configFromDB. unexpected type %T", m.Content)
}
Expand All @@ -127,7 +126,7 @@ func (app *App) subscribeToConfigChanges(sm *subscription.Manager) {
)
}

func (app *App) initAnalytics(configFromDB configresource.Config) error {
func (app *App) initAnalytics(configFromDB config.Config) error {
return analytics.Init(configFromDB.IsAnalyticsEnabled(), app.serverID, Version, Env)
}

Expand Down Expand Up @@ -156,7 +155,7 @@ func (app *App) Start(opts ...appOption) error {
subscriptionManager := subscription.NewManager()
app.subscribeToConfigChanges(subscriptionManager)

configRepo := configresource.NewRepository(db, configresource.WithPublisher(subscriptionManager))
configRepo := config.NewRepository(db, config.WithPublisher(subscriptionManager))
configFromDB := configRepo.Current(ctx)

tracer, err := tracing.NewTracer(ctx, app.cfg)
Expand Down Expand Up @@ -380,12 +379,12 @@ func registerTransactionResource(repo *tests.TransactionsRepository, router *mux
provisioner.AddResourceProvisioner(manager)
}

func registerConfigResource(configRepo *configresource.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner, tracer trace.Tracer) {
manager := resourcemanager.New[configresource.Config](
configresource.ResourceName,
configresource.ResourceNamePlural,
func registerConfigResource(configRepo *config.Repository, router *mux.Router, db *sql.DB, provisioner *provisioning.Provisioner, tracer trace.Tracer) {
manager := resourcemanager.New[config.Config](
config.ResourceName,
config.ResourceNamePlural,
configRepo,
resourcemanager.WithOperations(configresource.Operations...),
resourcemanager.WithOperations(config.Operations...),
resourcemanager.WithTracer(tracer),
)
manager.RegisterRoutes(router)
Expand Down
2 changes: 1 addition & 1 deletion server/cmd/root.go
Expand Up @@ -11,7 +11,7 @@ import (
)

var (
cfg *config.Config
cfg *config.AppConfig
appInstance *app.App

rootCmd = &cobra.Command{
Expand Down
2 changes: 1 addition & 1 deletion server/cmd/serve.go
Expand Up @@ -22,7 +22,7 @@ var serveCmd = &cobra.Command{
Use: "serve",
Short: "Start Tracetest server",
RunE: func(cmd *cobra.Command, args []string) error {
cfg.Watch(func(updated *config.Config) {
cfg.Watch(func(updated *config.AppConfig) {
appInstance.HotReload()
})

Expand Down
27 changes: 13 additions & 14 deletions server/config/config.go → server/config/appconfig.go
Expand Up @@ -16,8 +16,8 @@ func SetupFlags(flags *pflag.FlagSet) {
configOptions.registerFlags(flags)
}

func New(confOpts ...Option) (*Config, error) {
cfg := Config{
func New(confOpts ...Option) (*AppConfig, error) {
cfg := AppConfig{
vp: viper.New(),
}

Expand Down Expand Up @@ -58,30 +58,29 @@ type logger interface {
Println(...any)
}

type Config struct {
config *oldConfig
vp *viper.Viper
mu sync.Mutex
logger logger
resources resources
type AppConfig struct {
config *oldConfig
vp *viper.Viper
mu sync.Mutex
logger logger
}

func (c *Config) Watch(updateFn func(c *Config)) {
func (c *AppConfig) Watch(updateFn func(c *AppConfig)) {
c.vp.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:", e.Name)
updateFn(c)
})
c.vp.WatchConfig()
}

func (c *Config) Set(key string, value any) {
func (c *AppConfig) Set(key string, value any) {
c.mu.Lock()
defer c.mu.Unlock()

c.vp.Set(key, value)
}

func (cfg *Config) loadConfig() error {
func (cfg *AppConfig) loadConfig() error {
if confFile := cfg.vp.GetString("config"); confFile != "" {
// if --config is passed, and the file does not exists
// it will trigger a "no such file or directory" error
Expand All @@ -107,7 +106,7 @@ func (cfg *Config) loadConfig() error {
return fmt.Errorf("cannot read config file: %w", err)
}

func (cfg *Config) configureConfigFile() {
func (cfg *AppConfig) configureConfigFile() {
cfg.vp.SetConfigName("tracetest")
// intentionally removed this line, because it allows to have config files without extensions
// cfg.vp.SetConfigType("yaml")
Expand All @@ -116,13 +115,13 @@ func (cfg *Config) configureConfigFile() {
cfg.vp.AddConfigPath(".")
}

func (c *Config) defaults() {
func (c *AppConfig) defaults() {
if c.logger == nil {
c.logger = log.Default()
}
}

func (cfg *Config) warnAboutDeprecatedFields() error {
func (cfg *AppConfig) warnAboutDeprecatedFields() error {
for _, opt := range configOptions {
if !opt.deprecated {
continue
Expand Down
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/stretchr/testify/require"
)

func configWithFlagsE(t *testing.T, inputFlags []string, opts ...config.Option) (*config.Config, error) {
func configWithFlagsE(t *testing.T, inputFlags []string, opts ...config.Option) (*config.AppConfig, error) {
flags := pflag.NewFlagSet("fake", pflag.ExitOnError)
config.SetupFlags(flags)

Expand All @@ -20,18 +20,18 @@ func configWithFlagsE(t *testing.T, inputFlags []string, opts ...config.Option)
return config.New(append(opts, config.WithFlagSet(flags))...)
}

func configWithFlags(t *testing.T, inputFlags []string, opts ...config.Option) *config.Config {
func configWithFlags(t *testing.T, inputFlags []string, opts ...config.Option) *config.AppConfig {
cfg, err := configWithFlagsE(t, inputFlags, opts...)
require.NoError(t, err)

return cfg
}

func configFromFile(t *testing.T, path string, opts ...config.Option) *config.Config {
func configFromFile(t *testing.T, path string, opts ...config.Option) *config.AppConfig {
return configWithFlags(t, []string{"--config", path}, opts...)
}

func configWithEnv(t *testing.T, env map[string]string) *config.Config {
func configWithEnv(t *testing.T, env map[string]string) *config.AppConfig {
for k, v := range env {
os.Setenv(k, v)
}
Expand Down
34 changes: 34 additions & 0 deletions server/config/config_entities.go
@@ -0,0 +1,34 @@
package config

import (
"os"

"github.com/kubeshop/tracetest/server/pkg/id"
)

type Config struct {
ID id.ID `json:"id"`
Name string `json:"name"`

AnalyticsEnabled bool `json:"analyticsEnabled"`
}

func (c Config) HasID() bool {
return c.ID.String() != ""
}

func (c Config) GetID() id.ID {
return c.ID
}

func (c Config) Validate() error {
return nil
}

func (c Config) IsAnalyticsEnabled() bool {
if os.Getenv("TRACETEST_DEV") != "" {
return false
}

return c.AnalyticsEnabled
}
103 changes: 103 additions & 0 deletions server/config/config_entities_test.go
@@ -0,0 +1,103 @@
package config_test

import (
"context"
"os"
"testing"

"github.com/kubeshop/tracetest/server/config"
"github.com/kubeshop/tracetest/server/testmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)

type mockPublisher struct {
mock.Mock
}

func (m *mockPublisher) Publish(resourceID string, message any) {
m.Called(resourceID, message)
}

func TestPublishing(t *testing.T) {
restore := cleanEnv()
defer restore()

updated := config.Config{
ID: "current",
Name: "Config",
AnalyticsEnabled: true,
}

publisher := new(mockPublisher)
publisher.Test(t)

publisher.On("Publish", config.ResourceID, updated)

repo := config.NewRepository(
testmock.CreateMigratedDatabase(),
config.WithPublisher(publisher),
)

_, err := repo.Update(context.TODO(), updated)
require.NoError(t, err)

publisher.AssertExpectations(t)

}

func TestIsAnalyticsEnabled(t *testing.T) {
t.Run("DefaultValues", func(t *testing.T) {
restore := cleanEnv()
defer restore()

repo := config.NewRepository(
testmock.CreateMigratedDatabase(),
)

cfg := repo.Current(context.TODO())
assert.True(t, cfg.IsAnalyticsEnabled())

})

t.Run("FromRepo", func(t *testing.T) {
restore := cleanEnv()
defer restore()
repo := config.NewRepository(
testmock.CreateMigratedDatabase(),
)
repo.Update(context.TODO(), config.Config{
AnalyticsEnabled: false,
})

cfg := repo.Current(context.TODO())
assert.False(t, cfg.IsAnalyticsEnabled())
})

t.Run("EnvOverride", func(t *testing.T) {
restore := cleanEnv()
defer restore()
repo := config.NewRepository(
testmock.CreateMigratedDatabase(),
)
repo.Update(context.TODO(), config.Config{
AnalyticsEnabled: true,
})

cfg := repo.Current(context.TODO())

os.Setenv("TRACETEST_DEV", "yes")
assert.False(t, cfg.IsAnalyticsEnabled())

})
}

func cleanEnv() func() {
val := os.Getenv("TRACETEST_DEV")
// make sure this env is empty
os.Setenv("TRACETEST_DEV", "")
return func() {
os.Setenv("TRACETEST_DEV", val)
}
}
@@ -1,11 +1,10 @@
package configresource
package config

import (
"context"
"database/sql"
"errors"
"fmt"
"os"

"github.com/kubeshop/tracetest/server/pkg/id"
"github.com/kubeshop/tracetest/server/resourcemanager"
Expand All @@ -17,33 +16,6 @@ var Operations = []resourcemanager.Operation{
resourcemanager.OperationUpdate,
}

type Config struct {
ID id.ID `json:"id"`
Name string `json:"name"`

AnalyticsEnabled bool `json:"analyticsEnabled"`
}

func (c Config) HasID() bool {
return c.ID.String() != ""
}

func (c Config) GetID() id.ID {
return c.ID
}

func (c Config) Validate() error {
return nil
}

func (c Config) IsAnalyticsEnabled() bool {
if os.Getenv("TRACETEST_DEV") != "" {
return false
}

return c.AnalyticsEnabled
}

type option func(*Repository)

func WithPublisher(p publisher) option {
Expand Down

0 comments on commit df1d070

Please sign in to comment.