-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmessage.go
90 lines (76 loc) · 1.74 KB
/
message.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
// Copyright 2018 Atelier Disko. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
"log"
"math/rand"
)
const (
// MessageTypeTreeSynced happens whenever the node tree has
// been (initially or after a rsync) synchronized.
MessageTypeTreeSynced = "tree-synced"
// MessageTypeTreeChanged happens when something in the tree has
// been changed and a resync needs to happen.
MessageTypeTreeChanged = "tree-changed"
)
func NewMessage(typ string, text string) *Message {
return &Message{
id: rand.Int(),
typ: typ,
text: text,
}
}
type Message struct {
id int
typ string
text string
}
func (m *Message) String() string {
return fmt.Sprintf("<Message %d %s>%s</Message>", m.id, m.typ, m.text)
}
func NewMessageBroker() *MessageBroker {
return &MessageBroker{
Subscribable: &Subscribable{},
incoming: make(chan *Message, 10),
done: make(chan bool),
}
}
type MessageBroker struct {
*Subscribable
// Incoming messages are sent here.
incoming chan *Message
// Quit channel, receiving true, when de-initialized.
done chan bool
}
func (b *MessageBroker) Start() {
go func() {
for {
select {
case m := <-b.incoming:
b.NotifyAll(m)
case <-b.done:
log.Print("Message broker is closing...")
return
}
}
}()
}
func (b *MessageBroker) Close() {
b.UnsubscribeAll()
b.done <- true
}
// Accept a message for fan-out. Will never block. When the
// buffer is full the message will be discarded and not delivered.
func (b *MessageBroker) Accept(m *Message) (ok bool) {
select {
case b.incoming <- m:
ok = true
default:
log.Printf("Message buffer full, discarded: %s", m)
ok = false
}
return
}