Debian Codegraph @

go/examples/electron/broker.go

raw
1 /*
2 Licensed to the Apache Software Foundation (ASF) under one
3 or more contributor license agreements. See the NOTICE file
4 distributed with this work for additional information
5 regarding copyright ownership. The ASF licenses this file
6 to you under the Apache License, Version 2.0 (the
7 "License"); you may not use this file except in compliance
8 with the License. You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing,
13 software distributed under the License is distributed on an
14 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 KIND, either express or implied. See the License for the
16 specific language governing permissions and limitations
17 under the License.
18 */
19
20 //
21 // This is a simple AMQP broker implemented using the procedural electron package.
22 //
23 // It maintains a set of named in-memory queues of messages. Clients can send
24 // messages to queues or subscribe to receive messages from them.
25 //
26
27 package main
28
29 import (
30 "flag"
31 "fmt"
32 "log"
33 "net"
34 "os"
35 "github.com/apache/qpid-proton/go/pkg/amqp"
36 "github.com/apache/qpid-proton/go/pkg/electron"
37 "sync"
38 )
39
40 // Usage and command-line flags
41 func usage() {
42 fmt.Fprintf(os.Stderr, `
43 Usage: %s
44 A simple message broker.
45 Queues are created automatically for sender or receiver addresses.
46 `, os.Args[0])
47 flag.PrintDefaults()
48 }
49
50 var addr = flag.String("addr", ":amqp", "Network address to listen on, in the form \"host:port\"")
51 var credit = flag.Int("credit", 100, "Receiver credit window")
52 var qsize = flag.Int("qsize", 1000, "Max queue size")
53 var debug = flag.Bool("debug", false, "Print detailed debug output")
54 var debugf = func(format string, data ...interface{}) {} // Default no debugging output
55
56 func main() {
57 flag.Usage = usage
58 flag.Parse()
59
60 if *debug {
61 debugf = func(format string, data ...interface{}) { log.Printf(format, data...) }
62 }
63
64 b := &broker{
65 queues: makeQueues(*qsize),
66 container: electron.NewContainer(fmt.Sprintf("broker[%v]", os.Getpid())),
67 acks: make(chan electron.Outcome),
68 sent: make(chan sentMessage),
69 }
70 if err := b.run(); err != nil {
71 log.Fatal(err)
72 }
73 }
74
75 // State for the broker
76 type broker struct {
77 queues queues // A collection of queues.
78 container electron.Container // electron.Container manages AMQP connections.
79 sent chan sentMessage // Channel to record sent messages.
80 acks chan electron.Outcome // Channel to receive the Outcome of sent messages.
81 }
82
83 // Record of a sent message and the queue it came from.
84 // If a message is rejected or not acknowledged due to a failure, we will put it back on the queue.
85 type sentMessage struct {
86 m amqp.Message
87 q queue
88 }
89
90 // run listens for incoming net.Conn connections and starts an electron.Connection for each one.
91 func (b *broker) run() error {
92 listener, err := net.Listen("tcp", *addr)
93 if err != nil {
94 return err
95 }
96 defer listener.Close()
97 fmt.Printf("Listening on %v\n", listener.Addr())
98
99 go b.acknowledgements() // Handles acknowledgements for all connections.
100
101 // Start a goroutine for each new connections
102 for {
103 c, err := b.container.Accept(listener)
104 if err != nil {
105 debugf("Accept error: %v", err)
106 continue
107 }
108 cc := &connection{b, c}
109 go cc.run() // Handle the connection
110 debugf("Accepted %v", c)
111 }
112 }
113
114 // State for a broker connection
115 type connection struct {
116 broker *broker
117 connection electron.Connection
118 }
119
120 // accept remotely-opened endpoints (Session, Sender and Receiver) on a connection
121 // and start goroutines to service them.
122 func (c *connection) run() {
123 for in := range c.connection.Incoming() {
124 debugf("incoming %v", in)
125
126 switch in := in.(type) {
127
128 case *electron.IncomingSender:
129 s := in.Accept().(electron.Sender)
130 go c.sender(s)
131
132 case *electron.IncomingReceiver:
133 in.SetPrefetch(true)
134 in.SetCapacity(*credit) // Pre-fetch up to credit window.
135 r := in.Accept().(electron.Receiver)
136 go c.receiver(r)
137
138 default:
139 in.Accept() // Accept sessions unconditionally
140 }
141 }
142 debugf("incoming closed: %v", c.connection)
143 }
144
145 // receiver receives messages and pushes to a queue.
146 func (c *connection) receiver(receiver electron.Receiver) {
147 q := c.broker.queues.Get(receiver.Target())
148 for {
149 if rm, err := receiver.Receive(); err == nil {
150 debugf("%v: received %v", receiver, rm.Message.Body())
151 q <- rm.Message
152 rm.Accept()
153 } else {
154 debugf("%v error: %v", receiver, err)
155 break
156 }
157 }
158 }
159
160 // sender pops messages from a queue and sends them.
161 func (c *connection) sender(sender electron.Sender) {
162 q := c.broker.queues.Get(sender.Source())
163 for {
164 if sender.Error() != nil {
165 debugf("%v closed: %v", sender, sender.Error())
166 return
167 }
168 select {
169
170 case m := <-q:
171 debugf("%v: sent %v", sender, m.Body())
172 sm := sentMessage{m, q}
173 c.broker.sent <- sm // Record sent message
174 sender.SendAsync(m, c.broker.acks, sm) // Receive outcome on c.broker.acks with Value sm
175
176 case <-sender.Done(): // break if sender is closed
177 break
178 }
179 }
180 }
181
182 // acknowledgements keeps track of sent messages and receives outcomes.
183 //
184 // We could have handled outcomes separately per-connection, per-sender or even
185 // per-message. Message outcomes are returned via channels defined by the user
186 // so they can be grouped in any way that suits the application.
187 func (b *broker) acknowledgements() {
188 sentMap := make(map[sentMessage]bool)
189 for {
190 select {
191 case sm, ok := <-b.sent: // A local sender records that it has sent a message.
192 if ok {
193 sentMap[sm] = true
194 } else {
195 return // Closed
196 }
197 case outcome := <-b.acks: // The message outcome is available
198 sm := outcome.Value.(sentMessage)
199 delete(sentMap, sm)
200 if outcome.Status != electron.Accepted { // Error, release or rejection
201 sm.q.PutBack(sm.m) // Put the message back on the queue.
202 debugf("message %v put back, status %v, error %v", sm.m.Body(), outcome.Status, outcome.Error)
203 }
204 }
205 }
206 }
207
208 // Use a buffered channel as a very simple queue.
209 type queue chan amqp.Message
210
211 // Put a message back on the queue, does not block.
212 func (q queue) PutBack(m amqp.Message) {
213 select {
214 case q <- m:
215 default:
216 // Not an efficient implementation but ensures we don't block the caller.
217 go func() { q <- m }()
218 }
219 }
220
221 // Concurrent-safe map of queues.
222 type queues struct {
223 queueSize int
224 m map[string]queue
225 lock sync.Mutex
226 }
227
228 func makeQueues(queueSize int) queues {
229 return queues{queueSize: queueSize, m: make(map[string]queue)}
230 }
231
232 // Create a queue if not found.
233 func (qs *queues) Get(name string) queue {
234 qs.lock.Lock()
235 defer qs.lock.Unlock()
236 q := qs.m[name]
237 if q == nil {
238 q = make(queue, qs.queueSize)
239 qs.m[name] = q
240 }
241 return q
242 }