Debian Codegraph @

autopaho/examples/queue/subscribe.go

raw symbols SCIP
1 /*
2 * Copyright (c) 2024 Contributors to the Eclipse Foundation
3 *
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v2.0
6 * and Eclipse Distribution License v1.0 which accompany this distribution.
7 *
8 * The Eclipse Public License is available at
9 * https://www.eclipse.org/legal/epl-2.0/
10 * and the Eclipse Distribution License is available at
11 * http://www.eclipse.org/org/documents/edl-v10.php.
12 *
13 * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
14 */
15
16 package main
17
18 import (
19 "bytes"
20 "context"
21 "encoding/binary"
22 "fmt"
23 "net/url"
24 "time"
25
26 "github.com/eclipse/paho.golang/autopaho"
27 "github.com/eclipse/paho.golang/paho"
28 )
29
30 // subscribe connects to the server and subscribes to the test topic. It then expects to receive
31 // msgCount messages each containing the varint encoded message count.
32 // Generally messages should be received once and in order, but this is only guaranteed where the message number is even
33 // (because publish uses QOS2 for those).
34 // ready will be closed when we are ready to receive messages
35 // Exists when all expected messages have been received
36 func subscribe(ctx context.Context, serverURL *url.URL, msgCount uint64, ready chan struct{}) {
37 var msgRcvCount uint64
38 msgReceived := make(map[uint64]bool, msgCount)
39 allReceived := make(chan struct{})
40
41 ping := make(chan uint64)
42
43 cliCfg := autopaho.ClientConfig{
44 ServerUrls: []*url.URL{serverURL},
45 KeepAlive: 20, // Keepalive message should be sent every 20 seconds
46 CleanStartOnInitialConnection: true, // Previous tests should not contaminate this one!
47 SessionExpiryInterval: 60, // If connection drops we want session to remain live whilst we reconnect
48 OnConnectionUp: func(cm *autopaho.ConnectionManager, connAck *paho.Connack) {
49 fmt.Println("mqtt connection up")
50 if _, err := cm.Subscribe(ctx, &paho.Subscribe{
51 Subscriptions: []paho.SubscribeOptions{
52 {Topic: testTopic, QoS: QOS},
53 },
54 }); err != nil {
55 fmt.Printf("subscribe: failed to subscribe (%s). Probably due to connection drop so will retry\n", err)
56 return // likely connection has dropped
57 }
58 fmt.Println("subscribe: mqtt subscription made")
59 if ready != nil {
60 close(ready)
61 ready = nil
62 }
63 },
64 OnConnectError: func(err error) { fmt.Printf("subscribe: error whilst attempting connection: %s\n", err) },
65 Errors: logger{prefix: "subscribe"},
66
67 // eclipse/paho.golang/paho provides base mqtt functionality, the below config will be passed in for each connection
68 ClientConfig: paho.ClientConfig{
69 ClientID: "TestSub",
70 OnPublishReceived: []func(paho.PublishReceived) (bool, error){
71 func(pr paho.PublishReceived) (bool, error) {
72 msgNo, err := binary.ReadUvarint(bytes.NewReader(pr.Packet.Payload))
73 if err != nil {
74 panic(err) // Message corruption or something else is using our topic!
75 }
76 // pubQos := msgNo%2 + 1
77
78 newMessage := false
79
80 if QOS == 1 {
81 // Messages may be received out of order as pub/sub at QOS1 meaning we may receive multiple copies
82 if !msgReceived[msgNo] {
83 newMessage = true
84 }
85 } else {
86 // Messages should always be in order and received once
87 if msgReceived[msgNo] {
88 panic(fmt.Sprintf("subscribe: message # %d already received", msgNo))
89 }
90 newMessage = true
91 }
92 if newMessage {
93 msgReceived[msgNo] = true
94 msgRcvCount++
95
96 // We test that messages are received in the expected order (ordered delivery per topic is
97 // required by the MQTT v5 spec)
98 if msgNo > 1 && !msgReceived[msgNo-1] {
99 panic(fmt.Sprintf("subscribe: message # %d received but we don't have previous QOS2 msg", msgNo))
100 }
101 if msgReceived[msgNo+1] {
102 panic(fmt.Sprintf("subscribe: message # %d received but we have already received next QOS2 msg ", msgNo))
103 }
104
105 ping <- msgRcvCount
106 if msgRcvCount%NotifyEvery == 0 {
107 fmt.Printf("subscribe: received %d messages\n", msgRcvCount)
108 }
109 if msgRcvCount == msgCount {
110 close(allReceived)
111 }
112 }
113 return true, nil
114 }},
115 OnClientError: func(err error) { fmt.Printf("subscribe: client error: %s\n", err) },
116 OnServerDisconnect: func(d *paho.Disconnect) {
117 if d.Properties != nil {
118 fmt.Printf("subscribe: server requested disconnect: %s\n", d.Properties.ReasonString)
119 } else {
120 fmt.Printf("subscribe:server requested disconnect; reason code: %d\n", d.ReasonCode)
121 }
122 },
123 },
124 }
125
126 c, err := autopaho.NewConnection(ctx, cliCfg)
127 if err != nil {
128 panic(err)
129 }
130
131 // Ensure that program will always exit (even if we don't get all messages expected)
132 lastMsgTime := time.Now()
133 tick := time.NewTicker(timeoutSecs * time.Second)
134 defer tick.Stop()
135
136 waitLoop:
137 for {
138 select {
139 case <-ctx.Done():
140 err = ctx.Err()
141 break waitLoop
142 case <-allReceived:
143 break waitLoop
144 case <-ping:
145 lastMsgTime = time.Now()
146 continue
147 case <-tick.C:
148 if time.Since(lastMsgTime) > timeoutSecs*time.Second {
149 var missing []uint64
150 for i := uint64(1); i <= msgCount; i++ {
151 if !msgReceived[i] {
152 missing = append(missing, i)
153 }
154 }
155 fmt.Printf("subscribe: Aborting because no messages received (received %d unique messages - missing %v)\n", msgRcvCount, missing)
156 break waitLoop
157 }
158 }
159 }
160
161 if err != nil {
162 fmt.Println("subscribe: Aborting due to: ", err)
163 return
164 }
165
166 fmt.Println("subscribe: All received, disconnecting")
167 if err = c.Disconnect(context.Background()); err != nil {
168 panic(err)
169 }
170 <-c.Done()
171 fmt.Println("subscribe: Done")
172 }