refactor - moved common code to livekit/protocol

This commit is contained in:
David Zhao
2021-03-13 22:01:51 -08:00
parent e20c831c14
commit 7d02c01fd8
79 changed files with 6771 additions and 1410 deletions
-81
View File
@@ -1,81 +0,0 @@
package auth
import (
"time"
"gopkg.in/square/go-jose.v2"
"gopkg.in/square/go-jose.v2/jwt"
)
const (
defaultValidDuration = 6 * time.Hour
)
// Signer that produces token signed with API key and secret
type AccessToken struct {
apiKey string
secret string
identity string
videoGrant *VideoGrant
metadata map[string]interface{}
validFor time.Duration
}
func NewAccessToken(key string, secret string) *AccessToken {
return &AccessToken{
apiKey: key,
secret: secret,
}
}
func (t *AccessToken) SetIdentity(identity string) *AccessToken {
t.identity = identity
return t
}
func (t *AccessToken) SetValidFor(duration time.Duration) *AccessToken {
t.validFor = duration
return t
}
func (t *AccessToken) AddGrant(grant *VideoGrant) *AccessToken {
t.videoGrant = grant
return t
}
func (t *AccessToken) SetMetadata(md map[string]interface{}) *AccessToken {
t.metadata = md
return t
}
func (t *AccessToken) ToJWT() (string, error) {
if t.apiKey == "" || t.secret == "" {
return "", ErrKeysMissing
}
sig, err := jose.NewSigner(jose.SigningKey{Algorithm: jose.HS256, Key: []byte(t.secret)},
(&jose.SignerOptions{}).WithType("JWT"))
if err != nil {
return "", err
}
validFor := defaultValidDuration
if t.validFor > 0 {
validFor = t.validFor
}
cl := jwt.Claims{
Issuer: t.apiKey,
NotBefore: jwt.NewNumericDate(time.Now()),
Expiry: jwt.NewNumericDate(time.Now().Add(validFor)),
ID: t.identity,
}
grants := &ClaimGrants{}
if t.videoGrant != nil {
grants.Video = t.videoGrant
}
if t.metadata != nil {
grants.Metadata = t.metadata
}
return jwt.Signed(sig).Claims(cl).Claims(grants).CompactSerialize()
}
-69
View File
@@ -1,69 +0,0 @@
package auth_test
import (
"strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"gopkg.in/square/go-jose.v2/jwt"
"github.com/livekit/livekit-server/pkg/auth"
"github.com/livekit/livekit-server/pkg/utils"
)
func TestAccessToken(t *testing.T) {
t.Parallel()
t.Run("keys must be set", func(t *testing.T) {
token := auth.NewAccessToken("", "")
_, err := token.ToJWT()
assert.Equal(t, auth.ErrKeysMissing, err)
})
t.Run("generates a decodeable key", func(t *testing.T) {
apiKey, secret := apiKeypair()
videoGrant := &auth.VideoGrant{RoomJoin: true, Room: "myroom"}
at := auth.NewAccessToken(apiKey, secret).
AddGrant(videoGrant).
SetValidFor(time.Minute * 5).
SetIdentity("user")
value, err := at.ToJWT()
//fmt.Println(raw)
assert.NoError(t, err)
assert.Len(t, strings.Split(value, "."), 3)
// ensure it's a valid JWT
token, err := jwt.ParseSigned(value)
assert.NoError(t, err)
decodedGrant := auth.ClaimGrants{}
err = token.UnsafeClaimsWithoutVerification(&decodedGrant)
assert.NoError(t, err)
assert.EqualValues(t, videoGrant, decodedGrant.Video)
})
t.Run("default validity should be more than a minute", func(t *testing.T) {
apiKey, secret := apiKeypair()
videoGrant := &auth.VideoGrant{RoomJoin: true, Room: "myroom"}
at := auth.NewAccessToken(apiKey, secret).
AddGrant(videoGrant)
value, err := at.ToJWT()
token, err := jwt.ParseSigned(value)
claim := jwt.Claims{}
decodedGrant := auth.ClaimGrants{}
err = token.UnsafeClaimsWithoutVerification(&claim, &decodedGrant)
assert.NoError(t, err)
assert.EqualValues(t, videoGrant, decodedGrant.Video)
// default validity
assert.True(t, claim.Expiry.Time().Sub(claim.IssuedAt.Time()) > time.Minute)
})
}
func apiKeypair() (string, string) {
return utils.NewGuid(utils.APIKeyPrefix), utils.RandomSecret()
}
-176
View File
@@ -1,176 +0,0 @@
// Code generated by counterfeiter. DO NOT EDIT.
package authfakes
import (
"sync"
"github.com/livekit/livekit-server/pkg/auth"
)
type FakeKeyProvider struct {
GetSecretStub func(string) string
getSecretMutex sync.RWMutex
getSecretArgsForCall []struct {
arg1 string
}
getSecretReturns struct {
result1 string
}
getSecretReturnsOnCall map[int]struct {
result1 string
}
NumKeysStub func() int
numKeysMutex sync.RWMutex
numKeysArgsForCall []struct {
}
numKeysReturns struct {
result1 int
}
numKeysReturnsOnCall map[int]struct {
result1 int
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeKeyProvider) GetSecret(arg1 string) string {
fake.getSecretMutex.Lock()
ret, specificReturn := fake.getSecretReturnsOnCall[len(fake.getSecretArgsForCall)]
fake.getSecretArgsForCall = append(fake.getSecretArgsForCall, struct {
arg1 string
}{arg1})
stub := fake.GetSecretStub
fakeReturns := fake.getSecretReturns
fake.recordInvocation("GetSecret", []interface{}{arg1})
fake.getSecretMutex.Unlock()
if stub != nil {
return stub(arg1)
}
if specificReturn {
return ret.result1
}
return fakeReturns.result1
}
func (fake *FakeKeyProvider) GetSecretCallCount() int {
fake.getSecretMutex.RLock()
defer fake.getSecretMutex.RUnlock()
return len(fake.getSecretArgsForCall)
}
func (fake *FakeKeyProvider) GetSecretCalls(stub func(string) string) {
fake.getSecretMutex.Lock()
defer fake.getSecretMutex.Unlock()
fake.GetSecretStub = stub
}
func (fake *FakeKeyProvider) GetSecretArgsForCall(i int) string {
fake.getSecretMutex.RLock()
defer fake.getSecretMutex.RUnlock()
argsForCall := fake.getSecretArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeKeyProvider) GetSecretReturns(result1 string) {
fake.getSecretMutex.Lock()
defer fake.getSecretMutex.Unlock()
fake.GetSecretStub = nil
fake.getSecretReturns = struct {
result1 string
}{result1}
}
func (fake *FakeKeyProvider) GetSecretReturnsOnCall(i int, result1 string) {
fake.getSecretMutex.Lock()
defer fake.getSecretMutex.Unlock()
fake.GetSecretStub = nil
if fake.getSecretReturnsOnCall == nil {
fake.getSecretReturnsOnCall = make(map[int]struct {
result1 string
})
}
fake.getSecretReturnsOnCall[i] = struct {
result1 string
}{result1}
}
func (fake *FakeKeyProvider) NumKeys() int {
fake.numKeysMutex.Lock()
ret, specificReturn := fake.numKeysReturnsOnCall[len(fake.numKeysArgsForCall)]
fake.numKeysArgsForCall = append(fake.numKeysArgsForCall, struct {
}{})
stub := fake.NumKeysStub
fakeReturns := fake.numKeysReturns
fake.recordInvocation("NumKeys", []interface{}{})
fake.numKeysMutex.Unlock()
if stub != nil {
return stub()
}
if specificReturn {
return ret.result1
}
return fakeReturns.result1
}
func (fake *FakeKeyProvider) NumKeysCallCount() int {
fake.numKeysMutex.RLock()
defer fake.numKeysMutex.RUnlock()
return len(fake.numKeysArgsForCall)
}
func (fake *FakeKeyProvider) NumKeysCalls(stub func() int) {
fake.numKeysMutex.Lock()
defer fake.numKeysMutex.Unlock()
fake.NumKeysStub = stub
}
func (fake *FakeKeyProvider) NumKeysReturns(result1 int) {
fake.numKeysMutex.Lock()
defer fake.numKeysMutex.Unlock()
fake.NumKeysStub = nil
fake.numKeysReturns = struct {
result1 int
}{result1}
}
func (fake *FakeKeyProvider) NumKeysReturnsOnCall(i int, result1 int) {
fake.numKeysMutex.Lock()
defer fake.numKeysMutex.Unlock()
fake.NumKeysStub = nil
if fake.numKeysReturnsOnCall == nil {
fake.numKeysReturnsOnCall = make(map[int]struct {
result1 int
})
}
fake.numKeysReturnsOnCall[i] = struct {
result1 int
}{result1}
}
func (fake *FakeKeyProvider) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.getSecretMutex.RLock()
defer fake.getSecretMutex.RUnlock()
fake.numKeysMutex.RLock()
defer fake.numKeysMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeKeyProvider) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ auth.KeyProvider = new(FakeKeyProvider)
-181
View File
@@ -1,181 +0,0 @@
// Code generated by counterfeiter. DO NOT EDIT.
package authfakes
import (
"sync"
"github.com/livekit/livekit-server/pkg/auth"
)
type FakeTokenVerifier struct {
IdentityStub func() string
identityMutex sync.RWMutex
identityArgsForCall []struct {
}
identityReturns struct {
result1 string
}
identityReturnsOnCall map[int]struct {
result1 string
}
VerifyStub func(interface{}) (*auth.ClaimGrants, error)
verifyMutex sync.RWMutex
verifyArgsForCall []struct {
arg1 interface{}
}
verifyReturns struct {
result1 *auth.ClaimGrants
result2 error
}
verifyReturnsOnCall map[int]struct {
result1 *auth.ClaimGrants
result2 error
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeTokenVerifier) Identity() string {
fake.identityMutex.Lock()
ret, specificReturn := fake.identityReturnsOnCall[len(fake.identityArgsForCall)]
fake.identityArgsForCall = append(fake.identityArgsForCall, struct {
}{})
stub := fake.IdentityStub
fakeReturns := fake.identityReturns
fake.recordInvocation("Identity", []interface{}{})
fake.identityMutex.Unlock()
if stub != nil {
return stub()
}
if specificReturn {
return ret.result1
}
return fakeReturns.result1
}
func (fake *FakeTokenVerifier) IdentityCallCount() int {
fake.identityMutex.RLock()
defer fake.identityMutex.RUnlock()
return len(fake.identityArgsForCall)
}
func (fake *FakeTokenVerifier) IdentityCalls(stub func() string) {
fake.identityMutex.Lock()
defer fake.identityMutex.Unlock()
fake.IdentityStub = stub
}
func (fake *FakeTokenVerifier) IdentityReturns(result1 string) {
fake.identityMutex.Lock()
defer fake.identityMutex.Unlock()
fake.IdentityStub = nil
fake.identityReturns = struct {
result1 string
}{result1}
}
func (fake *FakeTokenVerifier) IdentityReturnsOnCall(i int, result1 string) {
fake.identityMutex.Lock()
defer fake.identityMutex.Unlock()
fake.IdentityStub = nil
if fake.identityReturnsOnCall == nil {
fake.identityReturnsOnCall = make(map[int]struct {
result1 string
})
}
fake.identityReturnsOnCall[i] = struct {
result1 string
}{result1}
}
func (fake *FakeTokenVerifier) Verify(arg1 interface{}) (*auth.ClaimGrants, error) {
fake.verifyMutex.Lock()
ret, specificReturn := fake.verifyReturnsOnCall[len(fake.verifyArgsForCall)]
fake.verifyArgsForCall = append(fake.verifyArgsForCall, struct {
arg1 interface{}
}{arg1})
stub := fake.VerifyStub
fakeReturns := fake.verifyReturns
fake.recordInvocation("Verify", []interface{}{arg1})
fake.verifyMutex.Unlock()
if stub != nil {
return stub(arg1)
}
if specificReturn {
return ret.result1, ret.result2
}
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeTokenVerifier) VerifyCallCount() int {
fake.verifyMutex.RLock()
defer fake.verifyMutex.RUnlock()
return len(fake.verifyArgsForCall)
}
func (fake *FakeTokenVerifier) VerifyCalls(stub func(interface{}) (*auth.ClaimGrants, error)) {
fake.verifyMutex.Lock()
defer fake.verifyMutex.Unlock()
fake.VerifyStub = stub
}
func (fake *FakeTokenVerifier) VerifyArgsForCall(i int) interface{} {
fake.verifyMutex.RLock()
defer fake.verifyMutex.RUnlock()
argsForCall := fake.verifyArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeTokenVerifier) VerifyReturns(result1 *auth.ClaimGrants, result2 error) {
fake.verifyMutex.Lock()
defer fake.verifyMutex.Unlock()
fake.VerifyStub = nil
fake.verifyReturns = struct {
result1 *auth.ClaimGrants
result2 error
}{result1, result2}
}
func (fake *FakeTokenVerifier) VerifyReturnsOnCall(i int, result1 *auth.ClaimGrants, result2 error) {
fake.verifyMutex.Lock()
defer fake.verifyMutex.Unlock()
fake.VerifyStub = nil
if fake.verifyReturnsOnCall == nil {
fake.verifyReturnsOnCall = make(map[int]struct {
result1 *auth.ClaimGrants
result2 error
})
}
fake.verifyReturnsOnCall[i] = struct {
result1 *auth.ClaimGrants
result2 error
}{result1, result2}
}
func (fake *FakeTokenVerifier) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.identityMutex.RLock()
defer fake.identityMutex.RUnlock()
fake.verifyMutex.RLock()
defer fake.verifyMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeTokenVerifier) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ auth.TokenVerifier = new(FakeTokenVerifier)
-18
View File
@@ -1,18 +0,0 @@
package auth
type VideoGrant struct {
// actions on rooms
RoomCreate bool `json:"roomCreate,omitempty"`
RoomList bool `json:"roomList,omitempty"`
// actions on a particular room
RoomAdmin bool `json:"roomAdmin,omitempty"`
RoomJoin bool `json:"roomJoin,omitempty"`
Room string `json:"room,omitempty"`
}
type ClaimGrants struct {
Identity string `json:"-"`
Video *VideoGrant `json:"video,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
}
-23
View File
@@ -1,23 +0,0 @@
package auth
import (
"errors"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
var (
ErrKeysMissing = errors.New("missing API key or secret key")
)
//counterfeiter:generate . TokenVerifier
type TokenVerifier interface {
Identity() string
Verify(key interface{}) (*ClaimGrants, error)
}
//counterfeiter:generate . KeyProvider
type KeyProvider interface {
GetSecret(key string) string
NumKeys() int
}
-38
View File
@@ -1,38 +0,0 @@
package auth
import (
"io"
"gopkg.in/yaml.v3"
)
type FileBasedKeyProvider struct {
keys map[string]string
}
func NewFileBasedKeyProviderFromReader(r io.Reader) (p *FileBasedKeyProvider, err error) {
keys := make(map[string]string)
decoder := yaml.NewDecoder(r)
if err = decoder.Decode(&keys); err != nil {
return
}
p = &FileBasedKeyProvider{
keys: keys,
}
return
}
func NewFileBasedKeyProviderFromMap(keys map[string]string) *FileBasedKeyProvider {
return &FileBasedKeyProvider{
keys: keys,
}
}
func (p *FileBasedKeyProvider) GetSecret(key string) string {
return p.keys[key]
}
func (p *FileBasedKeyProvider) NumKeys() int {
return len(p.keys)
}
-40
View File
@@ -1,40 +0,0 @@
package auth_test
import (
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/livekit/livekit-server/pkg/auth"
)
func TestFileBasedKeyProvider(t *testing.T) {
keys := map[string]string{
"key1": "secret1",
"key2": "secret2",
"key3": "secret3",
}
f, err := ioutil.TempFile("", "keyfile")
assert.NoError(t, err)
defer func() {
os.Remove(f.Name())
}()
f.WriteString("key1: secret1\n")
f.WriteString("key2: secret2 \r\n")
f.WriteString("\n")
f.WriteString("key3: secret3")
f.Close()
r, err := os.Open(f.Name())
defer r.Close()
p, err := auth.NewFileBasedKeyProviderFromReader(r)
assert.NoError(t, err)
for key, val := range keys {
assert.Equal(t, val, p.GetSecret(key))
}
}
-61
View File
@@ -1,61 +0,0 @@
package auth
import (
"time"
"gopkg.in/square/go-jose.v2/jwt"
)
type APIKeyTokenVerifier struct {
token *jwt.JSONWebToken
identity string
apiKey string
}
func ParseAPIToken(raw string) (*APIKeyTokenVerifier, error) {
tok, err := jwt.ParseSigned(raw)
if err != nil {
return nil, err
}
out := jwt.Claims{}
if err := tok.UnsafeClaimsWithoutVerification(&out); err != nil {
return nil, err
}
return &APIKeyTokenVerifier{
token: tok,
apiKey: out.Issuer,
identity: out.ID,
}, nil
}
// Returns the API key this token was signed with
func (v *APIKeyTokenVerifier) APIKey() string {
return v.apiKey
}
func (v *APIKeyTokenVerifier) Identity() string {
return v.identity
}
func (v *APIKeyTokenVerifier) Verify(key interface{}) (*ClaimGrants, error) {
if key == nil || key == "" {
return nil, ErrKeysMissing
}
if s, ok := key.(string); ok {
key = []byte(s)
}
out := jwt.Claims{}
claims := ClaimGrants{}
if err := v.token.Claims(key, &out, &claims); err != nil {
return nil, err
}
if err := out.Validate(jwt.Expected{Issuer: v.apiKey, Time: time.Now()}); err != nil {
return nil, err
}
// copy over identity
claims.Identity = out.ID
return &claims, nil
}
-77
View File
@@ -1,77 +0,0 @@
package auth_test
import (
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/livekit/livekit-server/pkg/auth"
)
func TestVerifier(t *testing.T) {
apiKey := "APID3B67uxk4Nj2GKiRPibAZ9"
secret := "YHC-CUhbQhGeVCaYgn1BNA++"
accessToken := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDg5MzAzMDgsImlzcyI6IkFQSUQzQjY3dXhrNE5qMkdLaVJQaWJBWjkiLCJuYmYiOjE2MDg5MjY3MDgsInJvb21fam9pbiI6dHJ1ZSwicm9vbV9zaWQiOiJteWlkIiwic3ViIjoiQVBJRDNCNjd1eGs0TmoyR0tpUlBpYkFaOSJ9.cmHEBq0MLyRqphmVLM2cLXg5ao5Sro7am8yXhcYKcwE"
t.Run("cannot decode with incorrect key", func(t *testing.T) {
v, err := auth.ParseAPIToken(accessToken)
assert.NoError(t, err)
assert.Equal(t, apiKey, v.APIKey())
_, err = v.Verify("")
assert.Error(t, err)
_, err = v.Verify("anothersecret")
assert.Error(t, err)
})
t.Run("key has expired", func(t *testing.T) {
v, err := auth.ParseAPIToken(accessToken)
_, err = v.Verify(secret)
assert.Error(t, err)
})
t.Run("unexpired token is verified", func(t *testing.T) {
claim := auth.VideoGrant{RoomCreate: true}
at := auth.NewAccessToken(apiKey, secret).
AddGrant(&claim).
SetValidFor(time.Minute).
SetIdentity("me")
authToken, err := at.ToJWT()
assert.NoError(t, err)
v, err := auth.ParseAPIToken(authToken)
assert.NoError(t, err)
assert.Equal(t, apiKey, v.APIKey())
assert.Equal(t, "me", v.Identity())
decoded, err := v.Verify(secret)
assert.NoError(t, err)
assert.Equal(t, &claim, decoded.Video)
})
t.Run("ensure metadata can be passed through", func(t *testing.T) {
metadata := map[string]interface{}{
"user": "value",
"number": float64(3),
}
at := auth.NewAccessToken(apiKey, secret).
AddGrant(&auth.VideoGrant{
RoomAdmin: true,
Room: "myroom",
}).
SetMetadata(metadata)
authToken, err := at.ToJWT()
assert.NoError(t, err)
v, err := auth.ParseAPIToken(authToken)
assert.NoError(t, err)
decoded, err := v.Verify(secret)
assert.NoError(t, err)
assert.EqualValues(t, metadata, decoded.Metadata)
})
}
+1 -1
View File
@@ -3,7 +3,7 @@ package routing
import (
"google.golang.org/protobuf/proto"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
+2 -2
View File
@@ -5,8 +5,8 @@ import (
"time"
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
// a router of messages on the same node, basic implementation for local testing
+1 -1
View File
@@ -3,7 +3,7 @@ package routing
import (
"google.golang.org/protobuf/proto"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/protocol/utils"
)
type MessageChannel struct {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"testing"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
func TestMessageChannel_WriteMessageClosed(t *testing.T) {
+2 -2
View File
@@ -13,8 +13,8 @@ import (
"github.com/pkg/errors"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
type NodeStats struct {
+1 -2
View File
@@ -1,9 +1,8 @@
package routing
import (
livekit "github.com/livekit/livekit-server/proto"
"github.com/thoas/go-funk"
"github.com/livekit/livekit-server/proto/livekit"
)
type RandomSelector struct {
+2 -2
View File
@@ -6,8 +6,8 @@ import (
"github.com/go-redis/redis/v8"
"google.golang.org/protobuf/proto"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
const (
+2 -2
View File
@@ -9,8 +9,8 @@ import (
"google.golang.org/protobuf/proto"
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
const (
@@ -5,7 +5,7 @@ import (
"sync"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
type FakeNodeSelector struct {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"sync"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
type FakeRouter struct {
+1 -2
View File
@@ -5,9 +5,8 @@ import (
"strings"
"time"
livekit "github.com/livekit/livekit-server/proto"
"github.com/thoas/go-funk"
"github.com/livekit/livekit-server/proto/livekit"
)
// checks if a node has been updated recently to be considered for selection
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
func TestIsAvailable(t *testing.T) {
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
const (
+2 -2
View File
@@ -2,8 +2,8 @@ package rtc_test
import (
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
func newMockParticipant(identity string) *typesfakes.FakeParticipant {
+2 -2
View File
@@ -15,8 +15,8 @@ import (
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
var (
+2 -2
View File
@@ -18,9 +18,9 @@ import (
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/livekit-server/version"
"github.com/livekit/protocol/utils"
)
const (
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/livekit/livekit-server/pkg/routing/routingfakes"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
//func Test
+2 -2
View File
@@ -8,8 +8,8 @@ import (
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
const (
+1 -1
View File
@@ -12,7 +12,7 @@ import (
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/rtc/types/typesfakes"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
const (
+2 -2
View File
@@ -4,8 +4,8 @@ import (
"github.com/pion/ion-sfu/pkg/sfu"
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
type SubscribedTrack struct {
+1 -1
View File
@@ -9,7 +9,7 @@ import (
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
const (
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/pion/webrtc/v3"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/pion/rtcp"
webrtc "github.com/pion/webrtc/v3"
)
@@ -5,7 +5,7 @@ import (
"sync"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
type FakePublishedTrack struct {
@@ -5,7 +5,7 @@ import (
"sync"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/pion/ion-sfu/pkg/sfu"
)
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
const (
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/twitchtv/twirp"
"github.com/livekit/livekit-server/pkg/auth"
"github.com/livekit/protocol/auth"
)
const (
+2 -2
View File
@@ -7,9 +7,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/livekit/livekit-server/pkg/auth"
"github.com/livekit/livekit-server/pkg/auth/authfakes"
"github.com/livekit/livekit-server/pkg/service"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/auth/authfakes"
)
func TestAuthMiddleware(t *testing.T) {
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"github.com/thoas/go-funk"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
// encapsulates CRUD operations for room settings
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/pkg/errors"
"google.golang.org/protobuf/proto"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
const (
+1 -1
View File
@@ -6,7 +6,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/livekit/livekit-server/pkg/service"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
func TestParticipantPersisence(t *testing.T) {
+2 -2
View File
@@ -13,8 +13,8 @@ import (
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/protocol/utils"
)
const (
+1 -1
View File
@@ -7,7 +7,7 @@ import (
"github.com/thoas/go-funk"
"github.com/twitchtv/twirp"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
// A rooms service that supports a single node
+1 -1
View File
@@ -1,7 +1,7 @@
package service
import (
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
+1 -1
View File
@@ -13,7 +13,7 @@ import (
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
type RTCService struct {
+3 -3
View File
@@ -11,13 +11,13 @@ import (
"github.com/pion/turn/v2"
"github.com/urfave/negroni"
"github.com/livekit/livekit-server/pkg/auth"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
"github.com/livekit/livekit-server/version"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/utils"
)
type LivekitServer struct {
+1 -1
View File
@@ -5,7 +5,7 @@ import (
"sync"
"github.com/livekit/livekit-server/pkg/service"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
type FakeRoomStore struct {
+1 -1
View File
@@ -8,7 +8,7 @@ import (
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
var ServiceSet = wire.NewSet(
+1 -1
View File
@@ -5,9 +5,9 @@ package service
import (
"github.com/google/wire"
"github.com/livekit/livekit-server/pkg/auth"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/protocol/auth"
)
func InitializeServer(conf *config.Config, keyProvider auth.KeyProvider,
+1 -1
View File
@@ -6,9 +6,9 @@
package service
import (
"github.com/livekit/livekit-server/pkg/auth"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/protocol/auth"
)
// Injectors from wire.go:
+1 -1
View File
@@ -10,7 +10,7 @@ import (
"github.com/livekit/livekit-server/pkg/logger"
"github.com/livekit/livekit-server/pkg/rtc/types"
"github.com/livekit/livekit-server/proto/livekit"
livekit "github.com/livekit/livekit-server/proto"
)
const (
-64
View File
@@ -1,64 +0,0 @@
package utils
import (
"context"
"time"
"github.com/go-redis/redis/v8"
"github.com/karlseguin/ccache/v2"
"github.com/pkg/errors"
)
const (
defaultCacheTTL = time.Minute
)
type CachedRedis struct {
ctx context.Context
rc *redis.Client
cache *ccache.Cache
}
func NewCachedRedis(ctx context.Context, rc *redis.Client) *CachedRedis {
return &CachedRedis{
ctx: ctx,
rc: rc,
cache: ccache.New(ccache.Configure()),
}
}
func (r *CachedRedis) CachedHGet(key, hashKey string) (string, error) {
cacheKey := key + ":" + hashKey
item := r.cache.Get(cacheKey)
if item != nil && !item.Expired() {
return item.Value().(string), nil
}
val, err := r.rc.HGet(r.ctx, key, hashKey).Result()
if err != nil {
return "", errors.Wrapf(err, "could not hget %s[%s]", key, hashKey)
}
r.cache.Set(key, val, defaultCacheTTL)
return val, nil
}
func (r *CachedRedis) CachedGet(key string) (string, error) {
item := r.cache.Get(key)
if item != nil && !item.Expired() {
return item.Value().(string), nil
}
val, err := r.rc.Get(r.ctx, key).Result()
if err != nil {
return "", errors.Wrapf(err, "could not get %s", key)
}
r.cache.Set(key, val, defaultCacheTTL)
return val, nil
}
func (r *CachedRedis) ExpireHash(key, hashKey string) {
r.cache.Delete(key + ":" + hashKey)
}
func (r *CachedRedis) Expire(key string) {
r.cache.Delete(key)
}
-29
View File
@@ -1,29 +0,0 @@
package utils
import (
"crypto/sha1"
"github.com/lithammer/shortuuid/v3"
"github.com/lytics/base62"
)
const (
RoomPrefix = "RM_"
NodePrefix = "ND_"
ParticipantPrefix = "PA_"
TrackPrefix = "TR_"
APIKeyPrefix = "API"
)
func NewGuid(prefix string) string {
return prefix + shortuuid.New()[:12]
}
// Creates a hashed ID from a unique string
func HashedID(str string) string {
h := sha1.New()
h.Write([]byte(str))
val := h.Sum(nil)
return base62.StdEncoding.EncodeToString(val)
}
-19
View File
@@ -1,19 +0,0 @@
package utils
import (
"crypto/rand"
"io"
"github.com/lytics/base62"
)
func RandomSecret() string {
// 256 bit secret
buf := make([]byte, 32)
_, err := io.ReadFull(rand.Reader, buf)
// cannot error
if err != nil {
panic("could not read random")
}
return base62.StdEncoding.EncodeToString(buf)
}
-63
View File
@@ -1,63 +0,0 @@
package utils
import (
"errors"
"sync/atomic"
)
var (
ErrChannelClosed = errors.New("cannot write to closed channel")
)
type AtomicFlag struct {
val int32
}
// set flag to value if existing flag is different, otherwise return
func (b *AtomicFlag) TrySet(bVal bool) bool {
var v int32
if bVal {
v = 1
}
prev := atomic.SwapInt32(&b.val, v)
// already set. unsuccessful
if prev == v {
return false
}
return true
}
func (b *AtomicFlag) Get() bool {
return atomic.LoadInt32(&b.val) == 1
}
// a channel that ignores writes when it closes instead of panic
type CalmChannel struct {
channel chan interface{}
isClosed AtomicFlag
}
func NewCalmChannel(size int) *CalmChannel {
return &CalmChannel{
channel: make(chan interface{}, size),
}
}
func (c *CalmChannel) Close() {
if !c.isClosed.TrySet(true) {
return
}
close(c.channel)
}
func (c *CalmChannel) ReadChan() <-chan interface{} {
return c.channel
}
func (c *CalmChannel) Write(o interface{}) error {
if c.isClosed.Get() {
return ErrChannelClosed
}
c.channel <- o
return nil
}
-46
View File
@@ -1,46 +0,0 @@
package utils
import (
"sync"
"sync/atomic"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAtomicFlag(t *testing.T) {
t.Run("single thread, basic functionality", func(t *testing.T) {
f := AtomicFlag{}
assert.False(t, f.TrySet(false))
assert.False(t, f.Get())
assert.True(t, f.TrySet(true))
assert.True(t, f.Get())
})
t.Run("only one thread should succeed", func(t *testing.T) {
var numSets uint32
f := AtomicFlag{}
wg := sync.WaitGroup{}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
if f.TrySet(true) {
atomic.AddUint32(&numSets, 1)
}
wg.Done()
}()
}
wg.Wait()
assert.Equal(t, 1, int(numSets))
})
}
func TestCalmChannel(t *testing.T) {
t.Run("should receive nil after close", func(t *testing.T) {
c := NewCalmChannel(1)
c.Close()
assert.Equal(t, nil, <-c.ReadChan())
})
}