forked from hyperledger-labs/go-perun
-
Notifications
You must be signed in to change notification settings - Fork 2
/
relay.go
192 lines (157 loc) · 4.28 KB
/
relay.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// Copyright 2019 - See NOTICE file for copyright holders.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package wire
import (
stdsync "sync"
"github.com/pkg/errors"
"perun.network/go-perun/log"
"polycry.pt/poly-go/sync"
)
// Relay handles (un)registering Consumers for a message Relay's messages.
type Relay struct {
sync.Closer
mutex stdsync.RWMutex
consumers []subscription
cache Cache
defaultMsgHandler func(*Envelope) // Handles messages with no subscriber.
}
type subscription struct {
consumer Consumer
predicate Predicate
}
// NewRelay returns a new Relay which logs unhandled messages.
func NewRelay() *Relay {
return &Relay{
defaultMsgHandler: logUnhandledMsg,
cache: MakeCache(),
}
}
// Close closes the relay.
func (p *Relay) Close() error {
if err := p.Closer.Close(); err != nil {
return err
}
p.mutex.Lock()
defer p.mutex.Unlock()
p.consumers = nil
cs := p.cache.Size()
if cs != 0 {
p.cache.Flush() // GC
return errors.Errorf("cache was not empty (%d)", cs)
}
return nil
}
// Cache enables caching of messages that don't match any consumer. They are
// only cached if they match the given predicate.
func (p *Relay) Cache(predicate *Predicate) {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.IsClosed() {
return
}
p.cache.Cache(predicate)
}
// ReleaseCache disable caching for the given predicate.
func (p *Relay) ReleaseCache(predicate *Predicate) {
p.mutex.Lock()
defer p.mutex.Unlock()
p.cache.Release(predicate)
}
// Subscribe adds a Consumer to the subscriptions.
// If the Consumer is already subscribed, Subscribe panics.
// If the producer is closed, Subscribe returns an error.
// Otherwise, Subscribe returns nil.
func (p *Relay) Subscribe(c Consumer, predicate Predicate) error {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.IsClosed() {
return errors.New("producer closed")
}
for _, rec := range p.consumers {
if rec.consumer == c {
log.Panic("duplicate subscription")
}
}
// Execute the callback asynchronously to prevent deadlock if it executes
// immediately. This can only happen if the consumer is closed while
// subscribing.
if !c.OnClose(func() { go p.delete(c) }) {
return errors.New("consumer closed")
}
p.consumers = append(p.consumers, subscription{consumer: c, predicate: predicate})
// Put cached messages into consumer in a go routine because receiving on it
// probably starts after subscription.
cached := p.cache.Messages(predicate)
go func() {
for _, m := range cached {
c.Put(m)
}
}()
return nil
}
func (p *Relay) delete(c Consumer) {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.IsClosed() {
return
}
for i, sub := range p.consumers {
if sub.consumer == c {
p.consumers[i] = p.consumers[len(p.consumers)-1]
p.consumers[len(p.consumers)-1] = subscription{} // For the GC.
p.consumers = p.consumers[:len(p.consumers)-1]
return
}
}
log.Panic("deleted consumer that was not subscribed")
}
func (p *Relay) isEmpty() bool {
p.mutex.RLock()
defer p.mutex.RUnlock()
return len(p.consumers) == 0
}
// Put puts an Envelope in the relay.
func (p *Relay) Put(e *Envelope) {
p.mutex.RLock()
defer p.mutex.RUnlock()
if p.IsClosed() {
return
}
found := false
for _, sub := range p.consumers {
if sub.predicate(e) {
sub.consumer.Put(e)
found = true
}
}
if !found {
if !p.cache.Put(e) {
p.defaultMsgHandler(e)
}
}
}
func logUnhandledMsg(e *Envelope) {
log.WithField("sender", e.Sender).
WithField("recipient", e.Recipient).
Debugf("Received %T message without subscription: %v", e.Msg, e.Msg)
}
// SetDefaultMsgHandler sets the default message handler.
func (p *Relay) SetDefaultMsgHandler(handler func(*Envelope)) {
if handler == nil {
handler = logUnhandledMsg
}
p.mutex.Lock()
defer p.mutex.Unlock()
p.defaultMsgHandler = handler
}