terraform/helper/shadow/keyed_value.go

99 lines
2.0 KiB
Go
Raw Normal View History

2016-10-01 02:00:01 +02:00
package shadow
2016-10-01 03:48:53 +02:00
import (
"sync"
)
// KeyedValue is a struct that coordinates a value by key. If a value is
// not available for a give key, it'll block until it is available.
2016-10-01 02:00:01 +02:00
type KeyedValue struct {
2016-10-01 03:48:53 +02:00
lock sync.Mutex
once sync.Once
values map[string]interface{}
waiters map[string]*Value
2016-10-05 05:20:07 +02:00
closed bool
}
// Close closes the value. This can never fail. For a definition of
// "close" see the ErrClosed docs.
func (w *KeyedValue) Close() error {
w.lock.Lock()
defer w.lock.Unlock()
// Set closed to true always
w.closed = true
// For all waiters, complete with ErrClosed
for _, w := range w.waiters {
w.SetValue(ErrClosed)
}
return nil
2016-10-01 03:48:53 +02:00
}
// Value returns the value that was set for the given key, or blocks
// until one is available.
func (w *KeyedValue) Value(k string) interface{} {
2016-10-01 22:10:07 +02:00
v, val := w.valueWaiter(k)
2016-10-01 03:48:53 +02:00
if val == nil {
2016-10-01 22:10:07 +02:00
return v
2016-10-01 03:48:53 +02:00
}
return val.Value()
}
2016-10-01 22:10:07 +02:00
// ValueOk gets the value for the given key, returning immediately if the
// value doesn't exist. The second return argument is true if the value exists.
func (w *KeyedValue) ValueOk(k string) (interface{}, bool) {
v, val := w.valueWaiter(k)
return v, val == nil
}
2016-10-01 03:48:53 +02:00
func (w *KeyedValue) SetValue(k string, v interface{}) {
w.lock.Lock()
defer w.lock.Unlock()
w.once.Do(w.init)
// Set the value, always
w.values[k] = v
// If we have a waiter, set it
if val, ok := w.waiters[k]; ok {
val.SetValue(v)
w.waiters[k] = nil
}
}
// Must be called with w.lock held.
func (w *KeyedValue) init() {
w.values = make(map[string]interface{})
w.waiters = make(map[string]*Value)
2016-10-01 02:00:01 +02:00
}
2016-10-01 22:10:07 +02:00
func (w *KeyedValue) valueWaiter(k string) (interface{}, *Value) {
w.lock.Lock()
w.once.Do(w.init)
// If we have this value already, return it
if v, ok := w.values[k]; ok {
w.lock.Unlock()
return v, nil
}
2016-10-05 05:20:07 +02:00
// If we're closed, return that
if w.closed {
return ErrClosed, nil
}
2016-10-01 22:10:07 +02:00
// No pending value, check for a waiter
val := w.waiters[k]
if val == nil {
val = new(Value)
w.waiters[k] = val
}
w.lock.Unlock()
// Return the waiter
return nil, val
}