-
-
Notifications
You must be signed in to change notification settings - Fork 625
/
dispatcher.go
65 lines (59 loc) · 1.18 KB
/
dispatcher.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
package udp
import (
"bytes"
"fmt"
"sync"
)
type Dispatcher struct {
mu sync.RWMutex
transactions map[TransactionId]Transaction
}
// The caller owns b.
func (me *Dispatcher) Dispatch(b []byte) error {
buf := bytes.NewBuffer(b)
var rh ResponseHeader
err := Read(buf, &rh)
if err != nil {
return err
}
me.mu.RLock()
defer me.mu.RUnlock()
if t, ok := me.transactions[rh.TransactionId]; ok {
t.h(DispatchedResponse{
Header: rh,
Body: append([]byte(nil), buf.Bytes()...),
})
return nil
} else {
return fmt.Errorf("unknown transaction id %v", rh.TransactionId)
}
}
func (me *Dispatcher) forgetTransaction(id TransactionId) {
me.mu.Lock()
defer me.mu.Unlock()
delete(me.transactions, id)
}
func (me *Dispatcher) NewTransaction(h TransactionResponseHandler) Transaction {
me.mu.Lock()
defer me.mu.Unlock()
for {
id := RandomTransactionId()
if _, ok := me.transactions[id]; ok {
continue
}
t := Transaction{
d: me,
h: h,
id: id,
}
if me.transactions == nil {
me.transactions = make(map[TransactionId]Transaction)
}
me.transactions[id] = t
return t
}
}
type DispatchedResponse struct {
Header ResponseHeader
Body []byte
}