blocky/config/qtype_set.go

77 lines
1.2 KiB
Go
Raw Permalink Normal View History

refactor: configuration rework (usage and printing) (#920) * refactor: make `config.Duration` a struct with `time.Duration` embed Allows directly calling `time.Duration` methods. * refactor(HostsFileResolver): don't copy individual config items The idea is to make adding configuration options easier, and searching for references straight forward. * refactor: move config printing to struct and use a logger Using a logger allows using multiple levels so the whole configuration can be printed in trace/verbose mode, but only important parts are shown by default. * squash: rename `Cast` to `ToDuration` * squash: revert `Duration` to a simple wrapper ("new type" pattern) * squash: `Duration.IsZero` tests * squash: refactor resolvers to rely on their config directly if possible * squash: implement `IsEnabled` and `LogValues` for all resolvers * refactor: use go-enum `--values` to simplify getting all log fields * refactor: simplify `QType` unmarshaling * squash: rename `ValueLogger` to `Configurable` * squash: rename `UpstreamConfig` to `ParallelBestConfig` * squash: rename `RewriteConfig` to `RewriterConfig` * squash: config tests * squash: resolver tests * squash: add `ForEach` test and improve `Chain` ones * squash: simplify implementing `config.Configurable` * squash: minor changes for better coverage * squash: more `UnmarshalYAML` -> `UnmarshalText` * refactor: move `config.Upstream` into own file * refactor: add `Resolver.Type` method * squash: add `log` method to `typed` to use `Resolover.Type` as prefix * squash: tweak startup config logging * squash: add `LogResolverConfig` tests * squash: make sure all options of type `Duration` use `%s`
2023-03-12 22:14:10 +01:00
package config
import (
"fmt"
"sort"
"strings"
"github.com/miekg/dns"
"golang.org/x/exp/maps"
)
type QTypeSet map[QType]struct{}
func NewQTypeSet(qTypes ...dns.Type) QTypeSet {
s := make(QTypeSet, len(qTypes))
for _, qType := range qTypes {
s.Insert(qType)
}
return s
}
func (s QTypeSet) Contains(qType dns.Type) bool {
_, found := s[QType(qType)]
return found
}
func (s *QTypeSet) Insert(qType dns.Type) {
if *s == nil {
*s = make(QTypeSet, 1)
}
(*s)[QType(qType)] = struct{}{}
}
func (s *QTypeSet) UnmarshalYAML(unmarshal func(interface{}) error) error {
var input []QType
if err := unmarshal(&input); err != nil {
return err
}
*s = make(QTypeSet, len(input))
for _, qType := range input {
(*s)[qType] = struct{}{}
}
return nil
}
type QType dns.Type
func (c QType) String() string {
return dns.Type(c).String()
}
// UnmarshalText implements `encoding.TextUnmarshaler`.
func (c *QType) UnmarshalText(data []byte) error {
input := string(data)
t, found := dns.StringToType[input]
if !found {
types := maps.Keys(dns.StringToType)
sort.Strings(types)
return fmt.Errorf("unknown DNS query type: '%s'. Please use following types '%s'",
input, strings.Join(types, ", "))
}
*c = QType(t)
return nil
}