Debian Codegraph @

cpp/examples/tutorial.dox

raw
1 // -*-markdown-*-
2 // NOTE: doxygen can include markdown pages directly but there seems to be a bug
3 // that shows messed-up line numbers in \skip \until code extracts. This file
4 // is markdown wrapped in a doxygen comment - which works. The file is best viewed/edited
5 // as markdown.
6
7 /**
8
9 @page tutorial_page Tutorial
10
11 This is a brief guide to to the fundamentals of building messaging
12 applications using Qpid Proton C++.
13
14 Proton provides an "event-driven" programming model, where you
15 implement a subclass of `proton::messaging_handler` and override
16 functions that react to various AMQP events (connections opening and
17 closing, messages being delivered, and so on).
18
19 The examples below show how to implement handlers for clients and
20 servers and how to run them using the `proton::container`, a portable,
21 easy-to-use way to build single-threaded clients or servers.
22
23 Some of the examples require an AMQP *broker* that can receive, store,
24 and send messages. @ref broker.cpp defines a simple example broker. If
25 run without arguments, it listens on `0.0.0.0:5672`, the standard AMQP
26 port on all network interfaces. To use a different port or network
27 interface, use the `-a` option.
28
29 broker -a <host>:<port>
30
31 Instead of the example broker, you can use any AMQP 1.0-compliant
32 broker. You must configure your broker to have a queue (or topic)
33 named "examples".
34
35 The `helloworld` examples take an optional URL argument. The other
36 examples take an option `-a URL`. A URL looks like this:
37
38 HOST:PORT/ADDRESS
39
40 It usually defaults to `127.0.0.1:5672/examples`, but you can change
41 this if your broker is on a different host or port, or you want to use
42 a different queue or topic name (the ADDRESS part of the URL).
43
44 Hello World!
45 ------------
46
47 \dontinclude helloworld.cpp
48
49 Tradition dictates that we start with Hello World! This example sends
50 a message to a broker and then receives the same message back. In a
51 realistic system the sender and receiver would normally be in
52 different processes. The complete example is @ref helloworld.cpp
53
54 We will include the following classes. `proton::container` runs an
55 event loop which dispatches events to a
56 `proton::messaging_handler`. This allows a *reactive* style of
57 programming which is well suited to messaging
58 applications. `proton::connection` and `proton::delivery` are AMQP
59 entities used in the handler functions. `proton::url` is a simple
60 parser for the URL format mentioned above.
61
62 \skip proton/connection
63 \until proton/url
64
65 We will define a class `hello_world` which is a subclass of
66 `proton::messaging_handler` and overrides functions to handle the
67 events of interest in sending and receiving a message.
68
69 \skip class hello_world
70 \until {}
71
72 `proton::messaging_handler::on_container_start()` is called when the
73 event loop first starts. We handle that by establishing a connection
74 and creating a sender and a receiver.
75
76 \skip on_container_start
77 \until }
78 \until }
79
80 `proton::messaging_handler::on_sendable()` is called when the message
81 can be transferred over the associated sender link to the remote
82 peer. We create a `proton::message`, set the message body to `"Hello
83 World!"`, and send the message. Then we close the sender, since we
84 only want to send one message. Closing the sender will prevent further
85 calls to `proton::messaging_handler::on_sendable()`.
86
87 \skip on_sendable
88 \until }
89
90 `proton::messaging_handler::on_message()` is called when a message is
91 received. We just print the body of the message and close the
92 connection, as we only want one message.
93
94 \skip on_message
95 \until }
96
97 The message body is a `proton::value`. See @ref types_page for more
98 on how to extract the message body as type-safe C++ values.
99
100 Our `main` function creates an instance of the `hello_world` handler
101 and a `proton::container` using that handler. Calling
102 `proton::container::run()` sets things in motion and returns when we
103 close the connection. It may throw an exception, which will be a
104 subclass of `proton::error`. That in turn is a subclass of
105 `std::exception`.
106
107 \skip main
108 \until }
109 \until }
110 \until }
111
112 Asynchronous send and receive
113 -----------------------------
114
115 Of course, these `Hello World!` examples are very artificial,
116 communicating as they do over a network connection but with the same
117 process. A more realistic example involves communication between
118 separate processes, which could indeed be running on completely
119 separate machines.
120
121 Let's separate the sender from the receiver, and transfer more than a
122 single message between them.
123
124 We'll start with a simple sender, @ref simple_send.cpp.
125
126 \dontinclude simple_send.cpp
127
128 As with the previous example, we define the application logic in a
129 class that handles events. Because we are transferring more than one
130 message, we need to keep track of how many we have sent. We'll use a
131 `sent` member variable for that. The `total` member variable will
132 hold the number of messages we want to send.
133
134 \skip class simple_send
135 \until total
136
137 As before, we use the
138 `proton::messaging_handler::on_container_start()` event to establish
139 our sender link over which we will transfer messages.
140
141 \skip on_container_start
142 \until }
143
144 AMQP defines a credit-based flow-control mechanism. Flow control
145 allows the receiver to control how many messages it is prepared to
146 receive at a given time and thus prevents any component being
147 overwhelmed by the number of messages it is sent.
148
149 In the `proton::messaging_handler::on_sendable()` callback, we check
150 that our sender has credit before sending messages. We also check that
151 we haven't already sent the required number of messages.
152
153 \skip on_sendable
154 \until }
155 \until }
156
157 The `proton::sender::send()` call above is asynchronous. When it
158 returns, the message has not yet actually been transferred across the
159 network to the receiver. By handling the
160 `proton::messaging_handler::on_tracker_accept()` event, we can get
161 notified when the receiver has received and accepted the message. In
162 our example we use this event to track the confirmation of the
163 messages we have sent. We only close the connection and exit when the
164 receiver has received all the messages we wanted to send.
165
166 \skip on_tracker_accept
167 \until }
168 \until }
169
170 If we are disconnected after a message is sent and before it has been
171 confirmed by the receiver, it is said to be "in doubt". We don't know
172 whether or not it was received. In this example, we will handle that
173 by resending any in-doubt messages. This is known as an
174 "at-least-once" guarantee, since each message should eventually be
175 received at least once, though a given message may be received more
176 than once (i.e., duplicates are possible). In the
177 `proton::messaging_handler::on_transport_close()` callback, we reset
178 the sent count to reflect only those that have been confirmed. The
179 library will automatically try to reconnect for us, and when our
180 sender is sendable again, we can restart from the point we know the
181 receiver got to.
182
183 \skip on_transport_close
184 \until }
185
186 \dontinclude simple_recv.cpp
187
188 Now let's look at the corresponding receiver, @ref simple_recv.cpp.
189
190 This time we'll use an `expected` member variable for for the number
191 of messages we expect and a `received` variable to count how many we
192 have received so far.
193
194 \skip class simple_recv
195 \until received
196
197 We handle `proton::messaging_handler::on_container_start()` by
198 creating our receiver, much like we did for the sender.
199
200 \skip on_container_start
201 \until }
202
203 We also handle the `proton::messaging_handler::on_message()` event for
204 received messages and print the message out as in the `Hello World!`
205 examples. However, we add some logic to allow the receiver to wait
206 for a given number of messages and then close the connection and
207 exit. We also add some logic to check for and ignore duplicates, using
208 a simple sequential ID scheme.
209
210 \skip on_message
211 \until }
212
213 Direct send and receive
214 -----------------------
215
216 Sending between these two examples requires an intermediary broker
217 since neither accepts incoming connections. AMQP allows us to send
218 messages directly between two processes. In that case, one or other of
219 the processes needs to accept incoming connections. Let's create a
220 modified version of the receiving example that does this with @ref
221 direct_recv.cpp.
222
223 \dontinclude direct_recv.cpp
224
225 There are only two differences here. Instead of initiating a link (and
226 implicitly a connection), we listen for incoming connections.
227
228 \skip on_container_start
229 \until }
230
231 When we have received all the expected messages, we then stop
232 listening for incoming connections by calling
233 `proton::listener::stop()`
234
235 \skip on_message
236 \until }
237 \until }
238 \until }
239 \until }
240
241 You can use the @ref simple_send.cpp example to send to this receiver
242 directly. (Note: you will need to stop any broker that is listening on
243 the 5672 port, or else change the port used by specifying a different
244 address to each example via the `-a` command-line switch).
245
246 We can also modify the sender to allow the original receiver to
247 connect to it, in @ref direct_send.cpp. Again, that requires just two
248 modifications:
249
250 \dontinclude direct_send.cpp
251
252 As with the modified receiver, instead of initiating establishment of a
253 link, we listen for incoming connections.
254
255 \skip on_container_start
256 \until }
257
258 When we have received confirmation of all the messages we sent, we call
259 `container::listener::stop()` to exit.
260
261 \skip on_tracker_accept
262 \until }
263 \until }
264
265 To try this modified sender, run the original @ref simple_recv.cpp
266 against it.
267
268 The symmetry in the underlying AMQP wire protocol that enables this is
269 quite unique and elegant, and in reflecting this the Proton API
270 provides a flexible toolkit for implementing all sorts of interesting
271 intermediaries.
272
273 Request and response
274 --------------------
275
276 A common pattern is to send a request message and expect a response
277 message in return. AMQP has special support for this pattern. Let's
278 have a look at a simple example. We'll start with @ref server.cpp, the
279 program that will process the request and send the response. Note that
280 we are still using a broker in this example.
281
282 Our server will provide a very simple service: it will respond with
283 the body of the request converted to uppercase.
284
285 \dontinclude server.cpp
286 \skip class server
287 \until };
288
289 The code here is not too different from the simple receiver example.
290 However, when we receive a request in
291 `proton::messaging_handler::on_message`, we look at the
292 `proton::message::reply_to` address and create a sender with that
293 address for the response. We'll cache the senders in case we get
294 further requests with the same `reply_to`.
295
296 Now let's create a simple @ref client.cpp to test this service out.
297
298 \dontinclude client.cpp
299
300 Our client takes a list of strings to send as requests.
301
302 \skipline client(
303
304 Since we will be sending and receiving, we create a sender and a
305 receiver in `proton::messaging_handler::on_container_start`. Our
306 receiver has a blank address and sets the `dynamic` flag to true,
307 which means we expect the remote end (the broker or server) to assign
308 a unique address for us.
309
310 \skip on_container_start
311 \until }
312
313 Now we need a function to send the next request from our list of
314 requests. We set the `reply_to` address to be the dynamically assigned
315 address of our receiver.
316
317 \skip send_request
318 \until }
319
320 We need to use the address assigned by the broker as the `reply_to`
321 address of our requests, so we can't send them until our receiver has
322 been set up. To do that, we add an
323 `proton::messaging_handler::on_receiver_open()` method to our handler
324 class and use that as the trigger to send our first request.
325
326 \skip on_receiver_open
327 \until }
328
329 When we receive a reply, we send the next request.
330
331 \skip on_message
332 \until }
333 \until }
334 \until }
335
336 Direct request and response
337 ---------------------------
338
339 We can avoid the intermediary process by writing a server that accepts
340 connections directly, @ref server_direct.cpp. It involves the
341 following changes to our original server:
342
343 \dontinclude server_direct.cpp
344
345 Our server must generate unique `reply-to` addresses for links from
346 the client that request a dynamic address (previously this was done by
347 the broker). We use a simple counter.
348
349 \skip generate_address
350 \until }
351
352 Next we need to handle incoming requests for links with dynamic
353 addresses from the client. We give the link a unique address and
354 record it in our `senders` map.
355
356 \skip on_sender_open
357 \until }
358
359 Note that we are interested in *sender* links above because we are
360 implementing the server. A *receiver* link created on the client
361 corresponds to a *sender* link on the server.
362
363 Finally when we receive a message we look up its `reply_to` in our
364 senders map and send the reply.
365
366 \skip on_message
367 \until }
368 \until }
369 \until }
370
371 */