aboutsummaryrefslogtreecommitdiff
path: root/conn_pool.go
blob: 34c51bb46b0ac278fdb151951042d8d4914cb0b4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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
}