Debian Codegraph @

autopaho/examples/queue/publish.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 "context"
20 "encoding/binary"
21 "errors"
22 "fmt"
23 "net/url"
24 "time"
25
26 "github.com/eclipse/paho.golang/autopaho"
27 "github.com/eclipse/paho.golang/autopaho/queue"
28 "github.com/eclipse/paho.golang/autopaho/queue/file"
29 "github.com/eclipse/paho.golang/autopaho/queue/memory"
30 "github.com/eclipse/paho.golang/paho"
31 )
32
33 // the Queue interface does not include WaitForEmpty because it's not needed in autopaho; however it's
34 // useful here, and both implementations used offer the function.
35 type queueWaitForEmpty interface {
36 queue.Queue
37 WaitForEmpty() chan struct{}
38 }
39
40 // publish connects to the server and publishes the requested number of messages
41 // The body of each message will be the Varint encoded message count (1 - msgCount)
42 func publish(ctx context.Context, serverURL *url.URL, msgCount uint64) {
43 dropAt := make(map[uint64]bool)
44 for _, i := range disconnectAtCount {
45 dropAt[i] = true
46 }
47
48 var q queueWaitForEmpty
49 var err error
50 if useMemoryQueue {
51 q = memory.New()
52 } else {
53 // Store queue files in the current folder (a bit messy but makes it obvious if any files are left behind)
54 q, err = file.New("./", "queue", ".msg")
55 if err != nil {
56 panic(err)
57 }
58 }
59
60 // Previous runs of the test may have left messages queued; remove them!
61 for {
62 entry, err := q.Peek()
63 if errors.Is(err, queue.ErrEmpty) {
64 break
65 }
66 if err != nil {
67 panic(err)
68 }
69 if err := entry.Remove(); err != nil {
70 panic(err)
71 }
72 }
73
74 cliCfg := autopaho.ClientConfig{
75 Queue: q,
76 ServerUrls: []*url.URL{serverURL},
77 KeepAlive: 20, // Keepalive message should be sent every 20 seconds
78 CleanStartOnInitialConnection: true, // Previous tests should not contaminate this one!
79 SessionExpiryInterval: 60, // If connection drops we want session to remain live whilst we reconnect
80 OnConnectionUp: func(cm *autopaho.ConnectionManager, connAck *paho.Connack) {
81 fmt.Println("publish: mqtt connection up")
82 },
83 OnConnectError: func(err error) { fmt.Printf("publish: error whilst attempting connection: %s\n", err) },
84 Errors: logger{prefix: "publish"},
85 // Debug: logger{prefix: "publish: debug"},
86 PahoErrors: logger{prefix: "publishP"},
87 // PahoDebug: logger{prefix: "publishP: debug"},
88 // eclipse/paho.golang/paho provides base mqtt functionality, the below config will be passed in for each connection
89 ClientConfig: paho.ClientConfig{
90 ClientID: "TestPub",
91 OnClientError: func(err error) { fmt.Printf("publish: client error: %s\n", err) },
92 OnServerDisconnect: func(d *paho.Disconnect) {
93 if d.Properties != nil {
94 fmt.Printf("publish: server requested disconnect: %s\n", d.Properties.ReasonString)
95 } else {
96 fmt.Printf("publish:server requested disconnect; reason code: %d\n", d.ReasonCode)
97 }
98 },
99 },
100 }
101
102 c, err := autopaho.NewConnection(ctx, cliCfg)
103 if err != nil {
104 panic(err)
105 }
106 // We do not wait for the connection to come up; we just start publishing and allow autopaho to handle things
107 for i := uint64(1); i <= msgCount; i++ {
108 if dropAt[i] {
109 c.TerminateConnectionForTest()
110 }
111 if err = c.PublishViaQueue(ctx, &autopaho.QueuePublish{
112 Publish: &paho.Publish{
113 QoS: QOS,
114 Topic: testTopic,
115 Payload: binary.AppendUvarint([]byte{}, i),
116 }}); err != nil {
117 panic(err)
118 }
119
120 // The queue relies on the file ModTime to work out what file is oldest; this means the resolution of
121 // update times becomes important. To ensure order is maintained, we add a delay between calls to `publish`
122 // (in real systems it's unlikely messages will be written more quickly).
123 time.Sleep(time.Millisecond)
124
125 if ctx.Err() != nil {
126 fmt.Println("publish: Aborting due to context")
127 return
128 }
129 }
130
131 fmt.Println("publish: Messages queued")
132 q.WaitForEmpty()
133 fmt.Println("publish: Messages all sent or inflight")
134
135 // There is no simple way for us to wait for the messages to be sent (i.e. waiting for QOS2 process to complete),
136 // so, we just wait on the context
137 <-ctx.Done()
138 fmt.Println("publish: Context cancelled")
139 <-c.Done()
140 fmt.Println("publish: Clean Shutdown")
141 }