-
Notifications
You must be signed in to change notification settings - Fork 2
/
peer_inbox.go
61 lines (49 loc) · 1.06 KB
/
peer_inbox.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
// Copyright 2024 The Bombus Authors
//
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package server
import (
"sync"
"github.com/doublemo/nakama-kit/pb"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type PeerInbox struct {
inbox map[string]chan *pb.Frame
sync.RWMutex
}
func NewPeerInbox() *PeerInbox {
return &PeerInbox{
inbox: make(map[string]chan *pb.Frame, 2048),
}
}
func (s *PeerInbox) Register(inbox string, reply chan *pb.Frame) error {
if size := len(inbox); size < 1 {
return status.Error(codes.InvalidArgument, "inbox is empty")
}
s.Lock()
defer s.Unlock()
if _, ok := s.inbox[inbox]; ok {
return status.Error(codes.AlreadyExists, "inbox is already exists")
}
s.inbox[inbox] = reply
return nil
}
func (s *PeerInbox) Deregister(inbox string) {
s.Lock()
delete(s.inbox, inbox)
s.Unlock()
}
func (s *PeerInbox) Send(frame *pb.Frame) {
s.RLock()
reply, ok := s.inbox[frame.Inbox]
s.RUnlock()
if !ok {
return
}
select {
case reply <- frame:
default:
}
}