snapshot of https://github.com/livekit/livekit.git @ 08c5433449c106943231037d0b892895f6e92d3b (2026-09-15)
This commit is contained in:
112
pkg/utils/changenotifier.go
Normal file
112
pkg/utils/changenotifier.go
Normal file
@@ -0,0 +1,112 @@
|
||||
/*
|
||||
* Copyright 2023 LiveKit, Inc
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package utils
|
||||
|
||||
import "sync"
|
||||
|
||||
type ChangeNotifier struct {
|
||||
lock sync.Mutex
|
||||
observers map[string]func()
|
||||
}
|
||||
|
||||
func NewChangeNotifier() *ChangeNotifier {
|
||||
return &ChangeNotifier{
|
||||
observers: make(map[string]func()),
|
||||
}
|
||||
}
|
||||
|
||||
func (n *ChangeNotifier) AddObserver(key string, onChanged func()) {
|
||||
n.lock.Lock()
|
||||
defer n.lock.Unlock()
|
||||
|
||||
n.observers[key] = onChanged
|
||||
}
|
||||
|
||||
func (n *ChangeNotifier) RemoveObserver(key string) {
|
||||
n.lock.Lock()
|
||||
defer n.lock.Unlock()
|
||||
|
||||
delete(n.observers, key)
|
||||
}
|
||||
|
||||
func (n *ChangeNotifier) HasObservers() bool {
|
||||
n.lock.Lock()
|
||||
defer n.lock.Unlock()
|
||||
|
||||
return len(n.observers) > 0
|
||||
}
|
||||
|
||||
func (n *ChangeNotifier) NotifyChanged() {
|
||||
n.lock.Lock()
|
||||
if len(n.observers) == 0 {
|
||||
n.lock.Unlock()
|
||||
return
|
||||
}
|
||||
observers := make([]func(), 0, len(n.observers))
|
||||
for _, f := range n.observers {
|
||||
observers = append(observers, f)
|
||||
}
|
||||
n.lock.Unlock()
|
||||
|
||||
go func() {
|
||||
for _, f := range observers {
|
||||
f()
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
type ChangeNotifierManager struct {
|
||||
lock sync.Mutex
|
||||
notifiers map[string]*ChangeNotifier
|
||||
}
|
||||
|
||||
func NewChangeNotifierManager() *ChangeNotifierManager {
|
||||
return &ChangeNotifierManager{
|
||||
notifiers: make(map[string]*ChangeNotifier),
|
||||
}
|
||||
}
|
||||
|
||||
func (m *ChangeNotifierManager) GetNotifier(key string) *ChangeNotifier {
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
|
||||
return m.notifiers[key]
|
||||
}
|
||||
|
||||
func (m *ChangeNotifierManager) GetOrCreateNotifier(key string) *ChangeNotifier {
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
|
||||
if notifier, ok := m.notifiers[key]; ok {
|
||||
return notifier
|
||||
}
|
||||
|
||||
notifier := NewChangeNotifier()
|
||||
m.notifiers[key] = notifier
|
||||
return notifier
|
||||
}
|
||||
|
||||
func (m *ChangeNotifierManager) RemoveNotifier(key string, force bool) {
|
||||
m.lock.Lock()
|
||||
defer m.lock.Unlock()
|
||||
|
||||
if notifier, ok := m.notifiers[key]; ok {
|
||||
if force || !notifier.HasObservers() {
|
||||
delete(m.notifiers, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
122
pkg/utils/changenotifier_test.go
Normal file
122
pkg/utils/changenotifier_test.go
Normal file
@@ -0,0 +1,122 @@
|
||||
// Copyright 2026 LiveKit, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestChangeNotifier(t *testing.T) {
|
||||
t.Run("Observer management", func(t *testing.T) {
|
||||
notifier := NewChangeNotifier()
|
||||
require.False(t, notifier.HasObservers())
|
||||
|
||||
called := false
|
||||
notifier.AddObserver("test-key", func() {
|
||||
called = true
|
||||
})
|
||||
require.True(t, notifier.HasObservers())
|
||||
|
||||
notifier.RemoveObserver("test-key")
|
||||
require.False(t, notifier.HasObservers())
|
||||
require.False(t, called)
|
||||
})
|
||||
|
||||
t.Run("Notification triggers callbacks asynchronously", func(t *testing.T) {
|
||||
notifier := NewChangeNotifier()
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(2)
|
||||
|
||||
var mu sync.Mutex
|
||||
callCounts := make(map[string]int)
|
||||
|
||||
notifier.AddObserver("obs1", func() {
|
||||
mu.Lock()
|
||||
callCounts["obs1"]++
|
||||
mu.Unlock()
|
||||
wg.Done()
|
||||
})
|
||||
|
||||
notifier.AddObserver("obs2", func() {
|
||||
mu.Lock()
|
||||
callCounts["obs2"]++
|
||||
mu.Unlock()
|
||||
wg.Done()
|
||||
})
|
||||
|
||||
notifier.NotifyChanged()
|
||||
|
||||
// Wait for async execution of observers
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
// Success
|
||||
case <-time.After(1 * time.Second):
|
||||
t.Fatal("Timeout waiting for change notification callbacks")
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
require.Equal(t, 1, callCounts["obs1"])
|
||||
require.Equal(t, 1, callCounts["obs2"])
|
||||
mu.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
func TestChangeNotifierManager(t *testing.T) {
|
||||
t.Run("Get and Create Notifiers", func(t *testing.T) {
|
||||
manager := NewChangeNotifierManager()
|
||||
require.Nil(t, manager.GetNotifier("non-existent"))
|
||||
|
||||
notifier := manager.GetOrCreateNotifier("room1")
|
||||
require.NotNil(t, notifier)
|
||||
|
||||
retrieved := manager.GetNotifier("room1")
|
||||
require.Equal(t, notifier, retrieved)
|
||||
|
||||
// GetOrCreate should return the existing one
|
||||
again := manager.GetOrCreateNotifier("room1")
|
||||
require.Equal(t, notifier, again)
|
||||
})
|
||||
|
||||
t.Run("Remove Notifiers with HasObservers check", func(t *testing.T) {
|
||||
manager := NewChangeNotifierManager()
|
||||
_ = manager.GetOrCreateNotifier("room1")
|
||||
|
||||
// Case 1: notifier has no observers, should be removed
|
||||
manager.RemoveNotifier("room1", false)
|
||||
require.Nil(t, manager.GetNotifier("room1"))
|
||||
|
||||
// Re-create and add an observer
|
||||
notifier := manager.GetOrCreateNotifier("room1")
|
||||
notifier.AddObserver("observer", func() {})
|
||||
|
||||
// Case 2: notifier has observer, RemoveNotifier(..., false) should not remove it
|
||||
manager.RemoveNotifier("room1", false)
|
||||
require.NotNil(t, manager.GetNotifier("room1"))
|
||||
|
||||
// Case 3: notifier has observer, RemoveNotifier(..., true) (force) should remove it
|
||||
manager.RemoveNotifier("room1", true)
|
||||
require.Nil(t, manager.GetNotifier("room1"))
|
||||
})
|
||||
}
|
||||
48
pkg/utils/context.go
Normal file
48
pkg/utils/context.go
Normal file
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* Copyright 2023 LiveKit, Inc
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
type attemptKey struct{}
|
||||
type loggerKey = struct{}
|
||||
|
||||
func ContextWithAttempt(ctx context.Context, attempt int) context.Context {
|
||||
return context.WithValue(ctx, attemptKey{}, attempt)
|
||||
}
|
||||
|
||||
func GetAttempt(ctx context.Context) int {
|
||||
if attempt, ok := ctx.Value(attemptKey{}).(int); ok {
|
||||
return attempt
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func ContextWithLogger(ctx context.Context, logger logger.Logger) context.Context {
|
||||
return context.WithValue(ctx, loggerKey{}, logger)
|
||||
}
|
||||
|
||||
func GetLogger(ctx context.Context) logger.Logger {
|
||||
if l, ok := ctx.Value(loggerKey{}).(logger.Logger); ok {
|
||||
return l
|
||||
}
|
||||
return logger.GetLogger()
|
||||
}
|
||||
42
pkg/utils/iceconfigcache.go
Normal file
42
pkg/utils/iceconfigcache.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/jellydator/ttlcache/v3"
|
||||
|
||||
"github.com/livekit/protocol/livekit"
|
||||
)
|
||||
|
||||
const (
|
||||
iceConfigTTLMin = 5 * time.Minute
|
||||
)
|
||||
|
||||
type IceConfigCache[T comparable] struct {
|
||||
c *ttlcache.Cache[T, *livekit.ICEConfig]
|
||||
}
|
||||
|
||||
func NewIceConfigCache[T comparable](ttl time.Duration) *IceConfigCache[T] {
|
||||
cache := ttlcache.New(
|
||||
ttlcache.WithTTL[T, *livekit.ICEConfig](max(ttl, iceConfigTTLMin)),
|
||||
ttlcache.WithDisableTouchOnHit[T, *livekit.ICEConfig](),
|
||||
)
|
||||
go cache.Start()
|
||||
|
||||
return &IceConfigCache[T]{cache}
|
||||
}
|
||||
|
||||
func (icc *IceConfigCache[T]) Stop() {
|
||||
icc.c.Stop()
|
||||
}
|
||||
|
||||
func (icc *IceConfigCache[T]) Put(key T, iceConfig *livekit.ICEConfig) {
|
||||
icc.c.Set(key, iceConfig, ttlcache.DefaultTTL)
|
||||
}
|
||||
|
||||
func (icc *IceConfigCache[T]) Get(key T) *livekit.ICEConfig {
|
||||
if it := icc.c.Get(key); it != nil {
|
||||
return it.Value()
|
||||
}
|
||||
return &livekit.ICEConfig{}
|
||||
}
|
||||
18
pkg/utils/iceconfigcache_test.go
Normal file
18
pkg/utils/iceconfigcache_test.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/livekit/protocol/livekit"
|
||||
)
|
||||
|
||||
func TestIceConfigCache(t *testing.T) {
|
||||
cache := NewIceConfigCache[string](10 * time.Second)
|
||||
t.Cleanup(cache.Stop)
|
||||
|
||||
cache.Put("test", &livekit.ICEConfig{})
|
||||
require.NotNil(t, cache)
|
||||
}
|
||||
86
pkg/utils/incrementaldispatcher.go
Normal file
86
pkg/utils/incrementaldispatcher.go
Normal file
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright 2024 LiveKit, Inc
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/frostbyte73/core"
|
||||
)
|
||||
|
||||
// IncrementalDispatcher is a dispatcher that allows multiple consumers to consume items as they become
|
||||
// available, while producers can add items at anytime.
|
||||
type IncrementalDispatcher[T any] struct {
|
||||
done core.Fuse
|
||||
lock sync.RWMutex
|
||||
cond *sync.Cond
|
||||
items []T
|
||||
}
|
||||
|
||||
func NewIncrementalDispatcher[T any]() *IncrementalDispatcher[T] {
|
||||
p := &IncrementalDispatcher[T]{}
|
||||
p.cond = sync.NewCond(&p.lock)
|
||||
return p
|
||||
}
|
||||
|
||||
func (d *IncrementalDispatcher[T]) Add(item T) {
|
||||
if d.done.IsBroken() {
|
||||
return
|
||||
}
|
||||
d.lock.Lock()
|
||||
d.items = append(d.items, item)
|
||||
d.cond.Broadcast()
|
||||
d.lock.Unlock()
|
||||
}
|
||||
|
||||
func (d *IncrementalDispatcher[T]) Done() {
|
||||
d.lock.Lock()
|
||||
d.done.Break()
|
||||
d.cond.Broadcast()
|
||||
d.lock.Unlock()
|
||||
}
|
||||
|
||||
func (d *IncrementalDispatcher[T]) ForEach(fn func(T)) {
|
||||
idx := 0
|
||||
dispatchFromIdx := func() {
|
||||
var itemsToDispatch []T
|
||||
d.lock.RLock()
|
||||
for idx < len(d.items) {
|
||||
itemsToDispatch = append(itemsToDispatch, d.items[idx])
|
||||
idx++
|
||||
}
|
||||
d.lock.RUnlock()
|
||||
for _, item := range itemsToDispatch {
|
||||
fn(item)
|
||||
}
|
||||
}
|
||||
for !d.done.IsBroken() {
|
||||
dispatchFromIdx()
|
||||
d.lock.Lock()
|
||||
// need to check again because Done may have been called while dispatching
|
||||
if d.done.IsBroken() {
|
||||
d.lock.Unlock()
|
||||
break
|
||||
}
|
||||
if idx == len(d.items) {
|
||||
d.cond.Wait()
|
||||
}
|
||||
d.lock.Unlock()
|
||||
}
|
||||
|
||||
dispatchFromIdx()
|
||||
}
|
||||
97
pkg/utils/incrementaldispatcher_test.go
Normal file
97
pkg/utils/incrementaldispatcher_test.go
Normal file
@@ -0,0 +1,97 @@
|
||||
/*
|
||||
* Copyright 2024 LiveKit, Inc
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package utils_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"go.uber.org/atomic"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/livekit/livekit-server/pkg/testutils"
|
||||
"github.com/livekit/livekit-server/pkg/utils"
|
||||
)
|
||||
|
||||
func TestForEach(t *testing.T) {
|
||||
producer := utils.NewIncrementalDispatcher[int]()
|
||||
go func() {
|
||||
defer producer.Done()
|
||||
producer.Add(1)
|
||||
producer.Add(2)
|
||||
producer.Add(3)
|
||||
}()
|
||||
|
||||
sum := 0
|
||||
producer.ForEach(func(item int) {
|
||||
sum += item
|
||||
})
|
||||
|
||||
require.Equal(t, 6, sum)
|
||||
}
|
||||
|
||||
func TestConcurrentConsumption(t *testing.T) {
|
||||
producer := utils.NewIncrementalDispatcher[int]()
|
||||
numConsumers := 100
|
||||
sums := make([]atomic.Int32, numConsumers)
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := range numConsumers {
|
||||
wg.Add(1)
|
||||
i := i
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
producer.ForEach(func(item int) {
|
||||
sums[i].Add(int32(item))
|
||||
})
|
||||
}()
|
||||
}
|
||||
|
||||
// Add items
|
||||
expectedSum := 0
|
||||
for i := range 20 {
|
||||
expectedSum += i
|
||||
producer.Add(i)
|
||||
}
|
||||
|
||||
for i := range numConsumers {
|
||||
testutils.WithTimeout(t, func() string {
|
||||
if sums[i].Load() != int32(expectedSum) {
|
||||
return fmt.Sprintf("consumer %d did not consume all the items. expected %d, actual: %d",
|
||||
i, expectedSum, sums[i].Load())
|
||||
}
|
||||
return ""
|
||||
}, time.Second)
|
||||
}
|
||||
|
||||
// keep adding and ensure it's consumed
|
||||
for i := 20; i < 30; i++ {
|
||||
expectedSum += i
|
||||
producer.Add(i)
|
||||
}
|
||||
|
||||
// wait for all consumers to finish
|
||||
producer.Done()
|
||||
wg.Wait()
|
||||
|
||||
for i := range numConsumers {
|
||||
require.Equal(t, int32(expectedSum), sums[i].Load(), "consumer %d did not match", i)
|
||||
}
|
||||
}
|
||||
28
pkg/utils/logging.go
Normal file
28
pkg/utils/logging.go
Normal file
@@ -0,0 +1,28 @@
|
||||
/*
|
||||
* Copyright 2023 LiveKit, Inc
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package utils
|
||||
|
||||
const (
|
||||
ComponentPub = "pub"
|
||||
ComponentSub = "sub"
|
||||
ComponentRoom = "room"
|
||||
ComponentAPI = "api"
|
||||
ComponentTransport = "transport"
|
||||
ComponentSFU = "sfu"
|
||||
// transport subcomponents
|
||||
ComponentCongestionControl = "cc"
|
||||
)
|
||||
69
pkg/utils/math.go
Normal file
69
pkg/utils/math.go
Normal file
@@ -0,0 +1,69 @@
|
||||
// Copyright 2023 LiveKit, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"slices"
|
||||
)
|
||||
|
||||
// OrderedNumber defines a constraint for numeric types that can be ordered and divided.
|
||||
type OrderedNumber interface {
|
||||
cmp.Ordered
|
||||
~int | ~int8 | ~int16 | ~int32 | ~int64 |
|
||||
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
|
||||
~uintptr | ~float32 | ~float64
|
||||
}
|
||||
|
||||
// Median gets the median value for a slice without modifying the original slice.
|
||||
//
|
||||
// Note:
|
||||
// 1. For integer types, if the slice has an even length, the division (/ 2)
|
||||
// is performed using integer division, which truncates the result towards zero.
|
||||
// 2. Uses an overflow-safe formula left + (right-left)/2 to support narrow integer types.
|
||||
func Median[T OrderedNumber](input []T) T {
|
||||
num := len(input)
|
||||
switch num {
|
||||
case 0:
|
||||
var zero T
|
||||
return zero
|
||||
case 1:
|
||||
return input[0]
|
||||
}
|
||||
|
||||
// Clone the slice to avoid mutating the caller's slice
|
||||
sortedInput := slices.Clone(input)
|
||||
slices.Sort(sortedInput)
|
||||
|
||||
if num%2 != 0 {
|
||||
return sortedInput[num/2]
|
||||
}
|
||||
left := sortedInput[num/2-1]
|
||||
right := sortedInput[num/2]
|
||||
return left + (right-left)/T(2)
|
||||
}
|
||||
|
||||
func Signum[T int | int8 | int16 | int32 | int64 | float32 | float64](val T) int {
|
||||
switch {
|
||||
case val < 0:
|
||||
return -1
|
||||
|
||||
case val > 0:
|
||||
return 1
|
||||
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
89
pkg/utils/math_test.go
Normal file
89
pkg/utils/math_test.go
Normal file
@@ -0,0 +1,89 @@
|
||||
// Copyright 2026 LiveKit, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestMedian(t *testing.T) {
|
||||
t.Run("Empty slice", func(t *testing.T) {
|
||||
require.Equal(t, float32(0), Median([]float32{}))
|
||||
require.Equal(t, int(0), Median([]int{}))
|
||||
})
|
||||
|
||||
t.Run("Single element", func(t *testing.T) {
|
||||
require.Equal(t, float32(42), Median([]float32{42}))
|
||||
require.Equal(t, int(42), Median([]int{42}))
|
||||
})
|
||||
|
||||
t.Run("Odd length float32", func(t *testing.T) {
|
||||
input := []float32{3.0, 1.0, 2.0}
|
||||
require.Equal(t, float32(2.0), Median(input))
|
||||
})
|
||||
|
||||
t.Run("Even length float32 - exact average", func(t *testing.T) {
|
||||
input := []float32{1.0, 2.0, 3.0, 4.0}
|
||||
require.Equal(t, float32(2.5), Median(input))
|
||||
})
|
||||
|
||||
t.Run("Even length int - integer truncation", func(t *testing.T) {
|
||||
input := []int{1, 2}
|
||||
// (1 + 2) / 2 = 1.5 -> truncates to 1
|
||||
require.Equal(t, int(1), Median(input))
|
||||
|
||||
inputOddAverage := []int{1, 3}
|
||||
// (1 + 3) / 2 = 2
|
||||
require.Equal(t, int(2), Median(inputOddAverage))
|
||||
})
|
||||
|
||||
t.Run("Int8 overflow prevention", func(t *testing.T) {
|
||||
// Without overflow protection: 120 + 126 = 246 (overflows int8 to -10) -> -10 / 2 = -5
|
||||
// With overflow protection: 120 + (126-120)/2 = 123
|
||||
input := []int8{120, 126}
|
||||
require.Equal(t, int8(123), Median(input))
|
||||
})
|
||||
|
||||
t.Run("Uint8 overflow prevention", func(t *testing.T) {
|
||||
input := []uint8{250, 254}
|
||||
require.Equal(t, uint8(252), Median(input))
|
||||
})
|
||||
|
||||
t.Run("Immutability test - caller slice is not sorted/mutated", func(t *testing.T) {
|
||||
original := []int{3, 1, 4, 2}
|
||||
input := slices.Clone(original)
|
||||
|
||||
median := Median(input)
|
||||
require.Equal(t, int(2), median)
|
||||
require.Equal(t, original, input, "Input slice must not be modified by Median")
|
||||
})
|
||||
}
|
||||
|
||||
func TestSignum(t *testing.T) {
|
||||
t.Run("Integer values", func(t *testing.T) {
|
||||
require.Equal(t, -1, Signum(-42))
|
||||
require.Equal(t, 0, Signum(0))
|
||||
require.Equal(t, 1, Signum(42))
|
||||
})
|
||||
|
||||
t.Run("Floating point values", func(t *testing.T) {
|
||||
require.Equal(t, -1, Signum(float32(-0.01)))
|
||||
require.Equal(t, 0, Signum(float32(0.0)))
|
||||
require.Equal(t, 1, Signum(float32(0.01)))
|
||||
})
|
||||
}
|
||||
157
pkg/utils/opsqueue.go
Normal file
157
pkg/utils/opsqueue.go
Normal file
@@ -0,0 +1,157 @@
|
||||
// Copyright 2023 LiveKit, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/gammazero/deque"
|
||||
|
||||
"github.com/livekit/protocol/logger"
|
||||
)
|
||||
|
||||
type OpsQueueParams struct {
|
||||
Name string
|
||||
MinSize uint
|
||||
FlushOnStop bool
|
||||
Logger logger.Logger
|
||||
}
|
||||
|
||||
type UntypedQueueOp func()
|
||||
|
||||
func (op UntypedQueueOp) run() {
|
||||
op()
|
||||
}
|
||||
|
||||
type OpsQueue struct {
|
||||
opsQueueBase[UntypedQueueOp]
|
||||
}
|
||||
|
||||
func NewOpsQueue(params OpsQueueParams) *OpsQueue {
|
||||
return &OpsQueue{*newOpsQueueBase[UntypedQueueOp](params)}
|
||||
}
|
||||
|
||||
type typedQueueOp[T any] struct {
|
||||
fn func(T)
|
||||
arg T
|
||||
}
|
||||
|
||||
func (op typedQueueOp[T]) run() {
|
||||
op.fn(op.arg)
|
||||
}
|
||||
|
||||
type TypedOpsQueue[T any] struct {
|
||||
opsQueueBase[typedQueueOp[T]]
|
||||
}
|
||||
|
||||
func NewTypedOpsQueue[T any](params OpsQueueParams) *TypedOpsQueue[T] {
|
||||
return &TypedOpsQueue[T]{*newOpsQueueBase[typedQueueOp[T]](params)}
|
||||
}
|
||||
|
||||
func (oq *TypedOpsQueue[T]) Enqueue(fn func(T), arg T) {
|
||||
oq.opsQueueBase.Enqueue(typedQueueOp[T]{fn, arg})
|
||||
}
|
||||
|
||||
type opsQueueItem interface {
|
||||
run()
|
||||
}
|
||||
|
||||
type opsQueueBase[T opsQueueItem] struct {
|
||||
params OpsQueueParams
|
||||
|
||||
lock sync.Mutex
|
||||
ops deque.Deque[T]
|
||||
wake chan struct{}
|
||||
isStarted bool
|
||||
doneChan chan struct{}
|
||||
isStopped bool
|
||||
}
|
||||
|
||||
func newOpsQueueBase[T opsQueueItem](params OpsQueueParams) *opsQueueBase[T] {
|
||||
o := &opsQueueBase[T]{
|
||||
params: params,
|
||||
wake: make(chan struct{}, 1),
|
||||
doneChan: make(chan struct{}),
|
||||
}
|
||||
o.ops.SetBaseCap(int(min(params.MinSize, 128)))
|
||||
return o
|
||||
}
|
||||
|
||||
func (oq *opsQueueBase[T]) Start() {
|
||||
oq.lock.Lock()
|
||||
if oq.isStarted {
|
||||
oq.lock.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
oq.isStarted = true
|
||||
oq.lock.Unlock()
|
||||
|
||||
go oq.process()
|
||||
}
|
||||
|
||||
func (oq *opsQueueBase[T]) Stop() <-chan struct{} {
|
||||
oq.lock.Lock()
|
||||
if oq.isStopped {
|
||||
oq.lock.Unlock()
|
||||
return oq.doneChan
|
||||
}
|
||||
|
||||
oq.isStopped = true
|
||||
close(oq.wake)
|
||||
oq.lock.Unlock()
|
||||
return oq.doneChan
|
||||
}
|
||||
|
||||
func (oq *opsQueueBase[T]) Enqueue(op T) {
|
||||
oq.lock.Lock()
|
||||
defer oq.lock.Unlock()
|
||||
|
||||
if oq.isStopped {
|
||||
return
|
||||
}
|
||||
|
||||
oq.ops.PushBack(op)
|
||||
if oq.ops.Len() == 1 {
|
||||
select {
|
||||
case oq.wake <- struct{}{}:
|
||||
default:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (oq *opsQueueBase[T]) process() {
|
||||
defer close(oq.doneChan)
|
||||
|
||||
for {
|
||||
<-oq.wake
|
||||
for {
|
||||
oq.lock.Lock()
|
||||
if oq.isStopped && (!oq.params.FlushOnStop || oq.ops.Len() == 0) {
|
||||
oq.lock.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
if oq.ops.Len() == 0 {
|
||||
oq.lock.Unlock()
|
||||
break
|
||||
}
|
||||
op := oq.ops.PopFront()
|
||||
oq.lock.Unlock()
|
||||
|
||||
op.run()
|
||||
}
|
||||
}
|
||||
}
|
||||
31
pkg/utils/protocol.go
Normal file
31
pkg/utils/protocol.go
Normal file
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* Copyright 2023 LiveKit, Inc
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"github.com/livekit/protocol/livekit"
|
||||
"github.com/livekit/protocol/utils"
|
||||
)
|
||||
|
||||
func ClientInfoWithoutAddress(c *livekit.ClientInfo) *livekit.ClientInfo {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
clone := utils.CloneProto(c)
|
||||
clone.Address = ""
|
||||
return clone
|
||||
}
|
||||
11
pkg/utils/slice.go
Normal file
11
pkg/utils/slice.go
Normal file
@@ -0,0 +1,11 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func DedupeSlice[T cmp.Ordered](s []T) []T {
|
||||
slices.Sort(s)
|
||||
return slices.Compact(s)
|
||||
}
|
||||
47
pkg/utils/slice_test.go
Normal file
47
pkg/utils/slice_test.go
Normal file
@@ -0,0 +1,47 @@
|
||||
// Copyright 2026 LiveKit, Inc.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package utils
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestDedupeSlice(t *testing.T) {
|
||||
t.Run("Empty slice", func(t *testing.T) {
|
||||
var input []int
|
||||
result := DedupeSlice(input)
|
||||
require.Empty(t, result)
|
||||
})
|
||||
|
||||
t.Run("Single element", func(t *testing.T) {
|
||||
input := []string{"hello"}
|
||||
result := DedupeSlice(input)
|
||||
require.Equal(t, []string{"hello"}, result)
|
||||
})
|
||||
|
||||
t.Run("Unsorted slice with duplicates", func(t *testing.T) {
|
||||
input := []int{4, 2, 4, 1, 3, 2}
|
||||
result := DedupeSlice(input)
|
||||
require.Equal(t, []int{1, 2, 3, 4}, result)
|
||||
})
|
||||
|
||||
t.Run("Already sorted and unique", func(t *testing.T) {
|
||||
input := []string{"apple", "banana", "cherry"}
|
||||
result := DedupeSlice(input)
|
||||
require.Equal(t, []string{"apple", "banana", "cherry"}, result)
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user