diff --git a/pkg/config/config.go b/pkg/config/config.go new file mode 100644 index 0000000..143087c --- /dev/null +++ b/pkg/config/config.go @@ -0,0 +1,148 @@ +// /futriis/pkg/config/config.go +// Пакет config предоставляет функциональность для загрузки и управления конфигурацией СУБД Futriis. +// Он определяет структуры конфигурации для кластера, узла, хранилища, репликации и Lua плагинов. +// Пакет поддерживает загрузку из TOML файлов, установку значений по умолчанию и глобальный доступ +// к конфигурации через атомарные операции для потокобезопасности. + +package config + +import ( + "sync/atomic" + + "github.com/BurntSushi/toml" +) + +// Цветовые коды ANSI (скопированы из utils для избежания циклического импорта) +const ( + ColorReset = "\033[0m" + ColorDeepSkyBlue = "\033[38;2;0;191;255m" +) + +// ClusterConfig конфигурация кластера +type ClusterConfig struct { + Name string `toml:"name"` + CoordinatorAddress string `toml:"coordinator_address"` + ReplicationFactor int `toml:"replication_factor"` + SyncReplication bool `toml:"sync_replication"` + AutoRebalance bool `toml:"auto_rebalance"` + Enabled bool `toml:"enabled"` +} + +// NodeConfig конфигурация узла +type NodeConfig struct { + ID string `toml:"id"` + Address string `toml:"address"` + DataDir string `toml:"data_dir"` + AOFEnabled bool `toml:"aof_enabled"` + AOFFile string `toml:"aof_file"` + AOFRecovery string `toml:"aof_recovery"` // "enable" или "disable" +} + +// StorageConfig конфигурация хранилища +type StorageConfig struct { + PageSize int `toml:"page_size"` + MaxMemory string `toml:"max_memory"` + EvictionPolicy string `toml:"eviction_policy"` +} + +// ReplicationConfig конфигурация репликации +type ReplicationConfig struct { + Enabled bool `toml:"enabled"` + SyncMode string `toml:"sync_mode"` + HeartbeatInterval int `toml:"heartbeat_interval"` + Timeout int `toml:"timeout"` + MasterMaster bool `toml:"master_master"` // Включение мастер-мастер репликации +} + +// LuaConfig конфигурация Lua плагинов +type LuaConfig struct { + Enabled bool `toml:"enabled"` + PluginsDir string `toml:"plugins_dir"` + MaxMemory string `toml:"max_memory"` +} + +// Config основная структура конфигурации +type Config struct { + Cluster ClusterConfig `toml:"cluster"` + Node NodeConfig `toml:"node"` + Storage StorageConfig `toml:"storage"` + Replication ReplicationConfig `toml:"replication"` + Lua LuaConfig `toml:"lua"` +} + +var globalConfig atomic.Value + +// Load загружает конфигурацию из файла +func Load(path string) (*Config, error) { + var config Config + + if _, err := toml.DecodeFile(path, &config); err != nil { + return nil, err + } + + // Устанавливаем значения по умолчанию, если не указаны + if config.Cluster.CoordinatorAddress == "" { + config.Cluster.CoordinatorAddress = "127.0.0.1:7379" + } + + if config.Node.Address == "" { + config.Node.Address = "127.0.0.1:7380" + } + + if config.Node.DataDir == "" { + config.Node.DataDir = "./data" + } + + if config.Node.AOFFile == "" { + config.Node.AOFFile = "./data/futriis.aof" + } + + // Устанавливаем значение по умолчанию для aof_recovery, если не указано + if config.Node.AOFRecovery == "" { + config.Node.AOFRecovery = "enable" // По умолчанию включено + } + + if config.Storage.PageSize == 0 { + config.Storage.PageSize = 4096 + } + + if config.Replication.HeartbeatInterval == 0 { + config.Replication.HeartbeatInterval = 5 + } + + if config.Replication.Timeout == 0 { + config.Replication.Timeout = 30 + } + + if config.Lua.PluginsDir == "" { + config.Lua.PluginsDir = "./plugins" + } + + globalConfig.Store(&config) + + return &config, nil +} + +// Get возвращает глобальную конфигурацию +func Get() *Config { + if cfg := globalConfig.Load(); cfg != nil { + return cfg.(*Config) + } + return nil +} + +// GetClusterConfig возвращает конфигурацию кластера +func GetClusterConfig() *ClusterConfig { + if cfg := Get(); cfg != nil { + return &cfg.Cluster + } + return nil +} + +// GetNodeConfig возвращает конфигурацию узла +func GetNodeConfig() *NodeConfig { + if cfg := Get(); cfg != nil { + return &cfg.Node + } + return nil +}