-
Notifications
You must be signed in to change notification settings - Fork 19
/
tvm.go
101 lines (84 loc) · 2.06 KB
/
tvm.go
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
92
93
94
95
96
97
98
99
100
101
package tvm
import (
"fmt"
"sync"
"time"
"github.com/cocaine/cocaine-framework-go/cocaine12"
"golang.org/x/net/context"
)
const (
tvmTokenType = "TVM"
tokenRefreshTimeout = time.Second * 15
)
func init() {
cocaine12.Register(tvmTokenType, new(TicketVendingMachineTokenManagerFactory))
}
type TicketVendingMachineTokenManagerFactory struct{}
func (f *TicketVendingMachineTokenManagerFactory) Create(appName string, token cocaine12.Token) (cocaine12.TokenManager, error) {
ctx := context.Background()
tvm, err := cocaine12.NewService(ctx, "tvm", nil)
if err != nil {
return nil, err
}
ctx, cancel := context.WithCancel(context.Background())
t := &TicketVendingMachineTokenManager{
appName: appName,
ticker: time.NewTicker(tokenRefreshTimeout),
ctx: ctx,
cancel: cancel,
mu: sync.Mutex{},
ticket: token,
tvm: tvm,
}
go t.run()
return t, nil
}
// TicketVendingMachineTokenManager manages TVM tickets.
type TicketVendingMachineTokenManager struct {
appName string
ticker *time.Ticker
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
ticket cocaine12.Token
tvm *cocaine12.Service
}
func (t *TicketVendingMachineTokenManager) Token() cocaine12.Token {
t.mu.Lock()
defer t.mu.Unlock()
return t.ticket
}
func (t *TicketVendingMachineTokenManager) Stop() {
t.cancel()
}
func (t *TicketVendingMachineTokenManager) run() {
for {
select {
case <-t.ticker.C:
t.mu.Lock()
body := t.ticket.Body()
t.mu.Unlock()
ch, err := t.tvm.Call(t.ctx, "refresh_ticket", t.appName, body)
if err != nil {
fmt.Printf("failed to update ticket %v\n", err)
continue
}
answer, err := ch.Get(t.ctx)
if err != nil {
fmt.Printf("failed to get ticket %v\n", err)
continue
}
var ticketResult string
if err := answer.ExtractTuple(&ticketResult); err != nil {
fmt.Printf("failed to extract ticket %v\n", err)
continue
}
t.mu.Lock()
t.ticket = cocaine12.NewToken(tvmTokenType, ticketResult)
t.mu.Unlock()
case <-t.ctx.Done():
t.ticker.Stop()
return
}
}
}