-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathexample_test.go
213 lines (179 loc) · 5.73 KB
/
example_test.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
package mqtt_test
import (
"context"
"crypto/tls"
"errors"
"fmt"
"log"
"time"
"github.com/pascaldekloe/mqtt"
"github.com/pascaldekloe/mqtt/mqtttest"
)
// Publish is a method from mqtt.Client.
var Publish func(quit <-chan struct{}, message []byte, topic string) error
// PublishAtLeastOnce is a method from mqtt.Client.
var PublishAtLeastOnce func(message []byte, topic string) (ack <-chan error, err error)
// Subscribe is a method from mqtt.Client.
var Subscribe func(quit <-chan struct{}, topicFilters ...string) error
// Online is a method from mqtt.Client.
var Online func() <-chan struct{}
func init() {
PublishAtLeastOnce = mqtttest.NewPublishExchangeStub(nil)
Subscribe = mqtttest.NewSubscribeStub(nil)
Online = func() <-chan struct{} { return nil }
}
// Some brokers permit authentication with TLS client certificates.
func ExampleNewTLSDialer_clientCertificate() {
certPEM := []byte(`-----BEGIN CERTIFICATE-----
MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
6MF9+Yw1Yy0t
-----END CERTIFICATE-----`)
keyPEM := []byte(`-----BEGIN EC PRIVATE KEY-----
MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
-----END EC PRIVATE KEY-----`)
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Fatal(err)
}
mqtt.NewTLSDialer("tcp", "mq1.example.com:8883", &tls.Config{
Certificates: []tls.Certificate{cert},
})
// Output:
}
// It is good practice to install the client from main.
func ExampleClient_setup() {
client, err := mqtt.VolatileSession("demo-client", &mqtt.Config{
Dialer: mqtt.NewDialer("tcp", "localhost:1883"),
PauseTimeout: 4 * time.Second,
})
if err != nil {
log.Fatal("exit on broken setup: ", err)
}
// launch read-routine
go func() {
var big *mqtt.BigMessage
for {
message, topic, err := client.ReadSlices()
switch {
case err == nil:
// do something with inbound message
log.Printf("📥 %q: %q", topic, message)
case errors.As(err, &big):
log.Printf("📥 %q: %d byte message omitted", big.Topic, big.Size)
case errors.Is(err, mqtt.ErrClosed):
log.Print(err)
return // terminated
case mqtt.IsConnectionRefused(err):
log.Print(err) // explains rejection
// mqtt.ErrDown for a while
time.Sleep(15 * time.Minute)
default:
log.Print("broker unavailable: ", err)
// mqtt.ErrDown during backoff
time.Sleep(2 * time.Second)
}
}
}()
// Install each method in use as a package variable. Such setup is
// compatible with the tools proveded from the mqtttest subpackage.
Publish = client.Publish
// Output:
}
// Demonstrates all error scenario and the respective recovery options.
func ExampleClient_PublishAtLeastOnce_critical() {
for {
exchange, err := PublishAtLeastOnce([]byte("🍸🆘"), "demo/alert")
switch {
case err == nil:
fmt.Println("alert submitted…")
break
case mqtt.IsDeny(err), errors.Is(err, mqtt.ErrClosed):
fmt.Println("🚨 alert not send:", err)
return
case errors.Is(err, mqtt.ErrMax):
fmt.Println("⚠️ alert submission hold-up:", err)
time.Sleep(time.Second / 4)
continue
default:
fmt.Println("⚠️ alert submission blocked on persistence malfunction:", err)
time.Sleep(4 * time.Second)
continue
}
for err := range exchange {
if errors.Is(err, mqtt.ErrClosed) {
fmt.Println("🚨 alert exchange suspended:", err)
// An AdoptSession may continue the transaction.
return
}
fmt.Println("⚠️ alert request transfer interrupted:", err)
}
fmt.Println("alert acknowledged ✓")
break
}
// Output:
// alert submitted…
// alert acknowledged ✓
}
// Demonstrates all error scenario and the respective recovery options.
func ExampleClient_Subscribe_sticky() {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
for {
err := Subscribe(ctx.Done(), "demo/+")
switch {
case err == nil:
fmt.Println("subscribe confirmed by broker")
return
case errors.As(err, new(mqtt.SubscribeError)):
fmt.Println("subscribe failed by broker")
return
case mqtt.IsDeny(err): // illegal topic filter
fmt.Println(err)
return
case errors.Is(err, mqtt.ErrClosed):
fmt.Println("no subscribe due client close")
return
case errors.Is(err, mqtt.ErrCanceled):
fmt.Println("no subscribe due timeout")
return
case errors.Is(err, mqtt.ErrAbandoned):
fmt.Println("subscribe state unknown due timeout")
return
case errors.Is(err, mqtt.ErrBreak):
fmt.Println("subscribe state unknown due connection loss")
select {
case <-Online():
fmt.Println("subscribe retry with new connection")
case <-ctx.Done():
fmt.Println("subscribe timeout")
return
}
case errors.Is(err, mqtt.ErrDown):
fmt.Println("subscribe delay while service is down")
select {
case <-Online():
fmt.Println("subscribe retry with new connection")
case <-ctx.Done():
fmt.Println("subscribe timeout")
return
}
case errors.Is(err, mqtt.ErrMax):
fmt.Println("subscribe hold-up due excessive number of pending requests")
time.Sleep(2 * time.Second) // backoff
default:
fmt.Println("subscribe request transfer interrupted:", err)
time.Sleep(time.Second / 2) // backoff
}
}
// Output:
// subscribe confirmed by broker
}