Files
temporal/common/dynamicconfig/client_subscriptions.go
David Reiss eb37cb1f77 Refactor dynamicconfig.FileBasedClient to make reusable (#8147)
## What changed?
Pull out parts of FileBasedConfig to make them reusable.

## Why?
Make it easier to build other Clients.

## How did you test it?
- [x] built
- [x] covered by existing tests
2025-12-03 14:34:10 -08:00

55 lines
1.3 KiB
Go

package dynamicconfig
import (
"sync"
expmaps "golang.org/x/exp/maps"
)
type (
// NotifyingClientImpl implements NotifyingClient and is intended to be embedded in another struct.
// NotifyingClientImpl must not be copied after first use.
NotifyingClientImpl struct {
subscriptionLock sync.Mutex
subscriptionIdx int
subscriptions map[int]ClientUpdateFunc
}
)
var _ NotifyingClient = (*NotifyingClientImpl)(nil)
func NewNotifyingClientImpl() NotifyingClientImpl {
return NotifyingClientImpl{subscriptions: make(map[int]ClientUpdateFunc)}
}
// Subscribe adds a subscription to all updates from this Client.
func (n *NotifyingClientImpl) Subscribe(f ClientUpdateFunc) (cancel func()) {
n.subscriptionLock.Lock()
defer n.subscriptionLock.Unlock()
n.subscriptionIdx++
id := n.subscriptionIdx
n.subscriptions[id] = f
return func() {
n.subscriptionLock.Lock()
defer n.subscriptionLock.Unlock()
delete(n.subscriptions, id)
}
}
// PublishUpdates calls all subscribed update functions with the changed keys.
func (n *NotifyingClientImpl) PublishUpdates(changed map[Key][]ConstrainedValue) {
if len(changed) == 0 {
return
}
n.subscriptionLock.Lock()
subscriptions := expmaps.Values(n.subscriptions)
n.subscriptionLock.Unlock()
for _, update := range subscriptions {
update(changed)
}
}