This repository has been archived by the owner on Oct 15, 2018. It is now read-only.
/
channel.go
131 lines (107 loc) · 2.39 KB
/
channel.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
/*
Copyright (C) 2018 Daniel Morandini
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package pubsub
import (
"fmt"
"sync"
"time"
)
type channel struct {
sendc chan interface{}
stopc chan interface{}
sync.Mutex
active bool
ch chan interface{}
}
func (c *channel) run() (chan interface{}, error) {
if c.isActive() {
return nil, fmt.Errorf("channel: unable to run: already active")
}
// create output channel
c.Lock()
c.ch = make(chan interface{})
c.active = true
c.Unlock()
send := func(m interface{}) {
defer func() {
if err := recover(); err != nil {
// we tried to send something trough ch and we found it closed.
// need to remove this channel.
c.stop()
}
}()
select {
case c.out() <- m:
case <-time.After(time.Second):
c.stop()
}
}
go func() {
for {
select {
case m := <-c.sendc:
go send(m)
case <-c.stopc:
return
}
}
}()
return c.out(), nil
}
func newChannel() *channel {
return &channel{
sendc: make(chan interface{}),
stopc: make(chan interface{}),
active: false,
}
}
func (c *channel) send(m interface{}) {
if c.isActive() {
c.sendc <- m
}
}
func (c *channel) stop() {
if !c.isActive() {
return
}
c.stopc <- struct{}{} // stop run()
c.setIsActive(false) // set inactive so we don't forward messages anymore
c.Lock()
closeChanSafe(c.ch) // close output channel
c.ch = nil // and remove it
c.Unlock()
}
func (c *channel) isActive() bool {
c.Lock()
defer c.Unlock()
return c.active
}
func (c *channel) setIsActive(ia bool) {
c.Lock()
c.active = ia
c.Unlock()
}
func (c *channel) out() chan interface{} {
c.Lock()
defer c.Unlock()
return c.ch
}
func closeChanSafe(c chan interface{}) {
defer func() {
if r := recover(); r != nil {
// tried to close c, which was already closed.
}
}()
close(c)
}