alps/conn_pool.go

84 lines
1.4 KiB
Go
Raw Normal View History

2019-12-02 16:24:19 +00:00
package koushin
import (
"crypto/rand"
"encoding/base64"
"errors"
2019-12-02 16:40:53 +00:00
"sync"
2019-12-02 16:24:19 +00:00
imapclient "github.com/emersion/go-imap/client"
)
func generateToken() (string, error) {
b := make([]byte, 32)
_, err := rand.Read(b)
if err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(b), nil
}
var ErrSessionExpired = errors.New("session expired")
type Session struct {
2019-12-03 15:27:49 +00:00
imapConn *imapclient.Client
username, password string
}
2019-12-02 16:24:19 +00:00
// TODO: expiration timer
type ConnPool struct {
2019-12-03 15:27:49 +00:00
locker sync.Mutex
sessions map[string]*Session
2019-12-02 16:24:19 +00:00
}
func NewConnPool() *ConnPool {
return &ConnPool{
sessions: make(map[string]*Session),
2019-12-02 16:24:19 +00:00
}
}
func (pool *ConnPool) Get(token string) (*Session, error) {
2019-12-02 16:40:53 +00:00
pool.locker.Lock()
defer pool.locker.Unlock()
session, ok := pool.sessions[token]
2019-12-02 16:24:19 +00:00
if !ok {
return nil, ErrSessionExpired
}
return session, nil
2019-12-02 16:24:19 +00:00
}
func (pool *ConnPool) Put(imapConn *imapclient.Client, username, password string) (token string, err error) {
2019-12-02 16:40:53 +00:00
pool.locker.Lock()
defer pool.locker.Unlock()
2019-12-02 16:24:19 +00:00
for {
var err error
token, err = generateToken()
if err != nil {
imapConn.Logout()
2019-12-02 16:24:19 +00:00
return "", err
}
if _, ok := pool.sessions[token]; !ok {
2019-12-02 16:24:19 +00:00
break
}
}
pool.sessions[token] = &Session{
imapConn: imapConn,
username: username,
password: password,
}
2019-12-02 16:36:43 +00:00
go func() {
<-imapConn.LoggedOut()
2019-12-02 16:40:53 +00:00
pool.locker.Lock()
delete(pool.sessions, token)
2019-12-02 16:40:53 +00:00
pool.locker.Unlock()
2019-12-02 16:36:43 +00:00
}()
2019-12-02 16:24:19 +00:00
return token, nil
}