Перейти к содержимому

Wildberries / WB - 3 (Команда отзывов)

Актуальность: 3 кв 2025

Задача: GetData возвращает данные из getter, страхуя кэшом в случае ошибки. Проблема: getter может отвечать очень долго. Задача: в случае ответа дольше timeout отдавать кэш, и правильно обработать кейс, когда getter всегда отвечает долго. go/concurrency

Заголовок раздела «Задача: GetData возвращает данные из getter, страхуя кэшом в случае ошибки. Проблема: getter может отвечать очень долго. Задача: в случае ответа дольше timeout отдавать кэш, и правильно обработать кейс, когда getter всегда отвечает долго. go/concurrency»
var cacheStore sync.Map
const timeout = time.Second
func GetData(key string, getter func(k string) (any, error)) (any, error) {
data, err := getter(key)
if err == nil {
cacheStore.Store(key, data)
return data, nil
}
fmt.Printf("Getter result err: %s ", err)
if data, ok := cacheStore.Load(key); ok {
return data, nil
}
return nil, err
}
type parrotType int
const (
TypeEuropean parrotType = iota
TypeAfrican
TypeNorwegianBlue parrotType = 3
)
type Parrot interface {
Speed() (float64, error)
}
type mixedParrot struct {
_type parrotType
numberOfCoconuts int
voltage float64
nailed bool
}
func CreateParrot(t parrotType, numberOfCoconuts int, voltage float64, nailed bool) Parrot {
return &mixedParrot{t, numberOfCoconuts, voltage, nailed}
}
func (parrot mixedParrot) Speed() (float64, error) {
switch parrot._type {
case TypeEuropean:
return parrot.baseSpeed(), nil
case TypeAfrican:
return math.Max(0, parrot.baseSpeed()-parrot.loadFactor()*float64(parrot.numberOfCoconuts)), nil
case TypeNorwegianBlue:
if parrot.nailed {
return 0, nil
}
return parrot.computeBaseSpeedForVoltage(parrot.voltage), nil
default:
return 0, errors.New("should be unreachable ")
}
}
func (parrot mixedParrot) computeBaseSpeedForVoltage(voltage float64) float64 {
return math.Min(24.0, voltage*parrot.baseSpeed())
}
func (parrot mixedParrot) loadFactor() float64 {
return 9.0
}
func (parrot mixedParrot) baseSpeed() float64 {
return 12.0
}