cwtch/protocol/connections/token_manager.go

41 lines
1.0 KiB
Go

package connections
import (
"errors"
"git.openprivacy.ca/cwtch.im/tapir/primitives/privacypass"
"sync"
)
// TokenManager maintains a list of tokens associated with a single TokenServer
type TokenManager struct {
lock sync.Mutex
tokens []*privacypass.Token
}
// NewTokens adds tokens to the internal list managed by this TokenManager
func (tm *TokenManager) NewTokens(tokens []*privacypass.Token) {
tm.lock.Lock()
defer tm.lock.Unlock()
tm.tokens = append(tm.tokens, tokens...)
}
// NumTokens returns the current number of tokens
func (tm *TokenManager) NumTokens() int {
tm.lock.Lock()
defer tm.lock.Unlock()
return len(tm.tokens)
}
// FetchToken removes a token from the internal list and returns it, along with a count of the remaining tokens.
// Errors if no tokens available.
func (tm *TokenManager) FetchToken() (*privacypass.Token, int, error) {
tm.lock.Lock()
defer tm.lock.Unlock()
if len(tm.tokens) == 0 {
return nil, 0, errors.New("no more tokens")
}
token := tm.tokens[0]
tm.tokens = tm.tokens[1:]
return token, len(tm.tokens), nil
}