Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use events library for config observer #912

Merged
merged 1 commit into from
Dec 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 12 additions & 28 deletions utils/configobserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,15 @@
package utils

import (
"container/list"
"fmt"
"os"
"sync"

"github.com/fsnotify/fsnotify"
"go.uber.org/atomic"
"gopkg.in/yaml.v3"

"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/utils/events"
)

type ConfigBuilder[T any] interface {
Expand All @@ -35,16 +35,16 @@ type ConfigDefaulter[T any] interface {
}

type ConfigObserver[T any] struct {
builder ConfigBuilder[T]
watcher *fsnotify.Watcher
mu sync.Mutex
cbs list.List
conf *T
builder ConfigBuilder[T]
watcher *fsnotify.Watcher
observers *events.ObserverList[*T]
conf atomic.Pointer[T]
}

func NewConfigObserver[T any](path string, builder ConfigBuilder[T]) (*ConfigObserver[T], *T, error) {
c := &ConfigObserver[T]{
builder: builder,
builder: builder,
observers: events.NewObserverList[*T](events.WithBlocking()),
}

conf, err := c.load(path)
Expand Down Expand Up @@ -74,32 +74,18 @@ func (c *ConfigObserver[T]) Close() {
}

func (c *ConfigObserver[T]) EmitConfigUpdate(conf *T) {
c.mu.Lock()
defer c.mu.Unlock()
for e := c.cbs.Front(); e != nil; e = e.Next() {
e.Value.(func(*T))(conf)
}
c.observers.Emit(conf)
}

func (c *ConfigObserver[T]) Observe(cb func(*T)) func() {
if c == nil {
return func() {}
}
c.mu.Lock()
e := c.cbs.PushBack(cb)
c.mu.Unlock()

return func() {
c.mu.Lock()
c.cbs.Remove(e)
c.mu.Unlock()
}
return c.observers.On(cb)
}

func (c *ConfigObserver[T]) Load() *T {
c.mu.Lock()
defer c.mu.Unlock()
return c.conf
return c.conf.Load()
}

func (c *ConfigObserver[T]) watch() {
Expand Down Expand Up @@ -165,9 +151,7 @@ func (c *ConfigObserver[T]) load(path string) (*T, error) {
d.InitDefaults(conf)
}

c.mu.Lock()
c.conf = conf
c.mu.Unlock()
c.conf.Store(conf)

return conf, err
}
Loading