aboutsummaryrefslogtreecommitdiff
path: root/conn_pool.go
diff options
context:
space:
mode:
authorSimon Ser <contact@emersion.fr>2019-12-09 18:16:27 +0100
committerSimon Ser <contact@emersion.fr>2019-12-09 18:16:31 +0100
commitefd401bfbf62b2216fe92b4d8be8c07e77b78482 (patch)
tree7eba39da086f891d564ce04ae0b43457e4f6edce /conn_pool.go
parent800a83059d95abb56cdd28049aeeaeb1f16699da (diff)
downloadalps-efd401bfbf62b2216fe92b4d8be8c07e77b78482.tar.gz
alps-efd401bfbf62b2216fe92b4d8be8c07e77b78482.zip
Rename ConnPool to SessionManager
Diffstat (limited to 'conn_pool.go')
-rw-r--r--conn_pool.go91
1 files changed, 0 insertions, 91 deletions
diff --git a/conn_pool.go b/conn_pool.go
deleted file mode 100644
index 34c51bb..0000000
--- a/conn_pool.go
+++ /dev/null
@@ -1,91 +0,0 @@
-package koushin
-
-import (
- "crypto/rand"
- "encoding/base64"
- "errors"
- "sync"
-
- 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 {
- locker sync.Mutex
- imapConn *imapclient.Client
- username, password string
-}
-
-func (s *Session) Do(f func(*imapclient.Client) error) error {
- s.locker.Lock()
- defer s.locker.Unlock()
-
- return f(s.imapConn)
-}
-
-// TODO: expiration timer
-type ConnPool struct {
- locker sync.Mutex
- sessions map[string]*Session
-}
-
-func NewConnPool() *ConnPool {
- return &ConnPool{
- sessions: make(map[string]*Session),
- }
-}
-
-func (pool *ConnPool) Get(token string) (*Session, error) {
- pool.locker.Lock()
- defer pool.locker.Unlock()
-
- session, ok := pool.sessions[token]
- if !ok {
- return nil, ErrSessionExpired
- }
- return session, nil
-}
-
-func (pool *ConnPool) Put(imapConn *imapclient.Client, username, password string) (token string, err error) {
- pool.locker.Lock()
- defer pool.locker.Unlock()
-
- for {
- var err error
- token, err = generateToken()
- if err != nil {
- imapConn.Logout()
- return "", err
- }
-
- if _, ok := pool.sessions[token]; !ok {
- break
- }
- }
-
- pool.sessions[token] = &Session{
- imapConn: imapConn,
- username: username,
- password: password,
- }
-
- go func() {
- <-imapConn.LoggedOut()
-
- pool.locker.Lock()
- delete(pool.sessions, token)
- pool.locker.Unlock()
- }()
-
- return token, nil
-}