cwtch/protocol/connections/token_manager.go

55 lines
1.4 KiB
Go
Raw Normal View History

2022-09-06 19:13:32 +00:00
package connections
import (
"encoding/json"
2022-09-06 19:13:32 +00:00
"errors"
"git.openprivacy.ca/cwtch.im/tapir/primitives/privacypass"
2022-10-25 20:59:05 +00:00
"git.openprivacy.ca/openprivacy/log"
2022-09-06 19:13:32 +00:00
"sync"
)
// TokenManager maintains a list of tokens associated with a single TokenServer
type TokenManager struct {
lock sync.Mutex
2022-10-25 20:59:05 +00:00
tokens map[string]*privacypass.Token
}
func NewTokenManager() *TokenManager {
tm := new(TokenManager)
2022-10-25 20:59:05 +00:00
tm.tokens = make(map[string]*privacypass.Token)
return tm
2022-09-06 19:13:32 +00:00
}
// StoreNewTokens adds tokens to the internal list managed by this TokenManager
func (tm *TokenManager) StoreNewTokens(tokens []*privacypass.Token) {
2022-09-06 19:13:32 +00:00
tm.lock.Lock()
defer tm.lock.Unlock()
2022-10-25 20:59:05 +00:00
log.Debugf("acquired %v new tokens", tokens)
for _, token := range tokens {
serialized, _ := json.Marshal(token)
2022-10-25 20:59:05 +00:00
tm.tokens[string(serialized)] = token
}
2022-09-06 19:13:32 +00:00
}
// 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")
}
2022-10-25 20:59:05 +00:00
for serializedToken, token := range tm.tokens {
delete(tm.tokens, serializedToken)
return token, len(tm.tokens), nil
}
return nil, 0, errors.New("no more tokens")
2022-09-06 19:13:32 +00:00
}