Debian Codegraph @

pkg/services/push/mqtt/mqtt_config.go

raw
1 package mqtt
2
3 import (
4 "fmt"
5 "net/url"
6 "strconv"
7 "strings"
8
9 "github.com/nicholas-fedor/shoutrrr/pkg/format"
10 "github.com/nicholas-fedor/shoutrrr/pkg/types"
11 )
12
13 // Config holds all configuration settings for the MQTT service.
14 // Each field can be set via URL parameters or struct tags, with defaults
15 // applied when values are not explicitly provided.
16 type Config struct {
17 // Host is the MQTT broker hostname or IP address.
18 // Default: "localhost"
19 Host string `default:"localhost" desc:"MQTT broker hostname" url:"host"`
20
21 // Port is the MQTT broker port number.
22 // Default: 1883 (standard MQTT), 8883 (MQTT over TLS)
23 Port int `default:"1883" desc:"MQTT broker port" url:"port"`
24
25 // Topic is the MQTT topic path to publish messages to.
26 // This is a required field and must be provided in the URL path.
27 // Example: "notifications/alerts" for topic notifications/alerts
28 Topic string `desc:"Target topic name" required:"" url:"path"`
29
30 // Username for MQTT broker authentication.
31 // Optional: Leave empty for anonymous connections or when password-only auth is used.
32 Username string `desc:"Auth username" optional:"" url:"user"`
33
34 // Password for MQTT broker authentication.
35 // Optional: Leave empty for anonymous connections or username-only auth.
36
37 Password string `desc:"Auth password" optional:"" url:"password"`
38
39 // ClientID is the unique identifier for this MQTT client connection.
40 // The broker uses this to identify the client across sessions and for
41 // persistent session management. Must be unique among all clients connecting
42 // to the same broker.
43 // Default: "shoutrrr"
44 ClientID string `default:"shoutrrr" desc:"MQTT client identifier" key:"clientid"`
45
46 // QoS (Quality of Service) determines the message delivery guarantee level.
47 // See QoS constants for available levels and their semantics.
48 // Default: 0 (QoSAtMostOnce)
49 QoS QoS `default:"0" desc:"Quality of Service level (0, 1, or 2)" key:"qos"`
50
51 // Retained controls whether the broker stores the last message on this topic.
52 // When true, new subscribers immediately receive the last retained message.
53 // Useful for status updates or configuration data that should be available
54 // immediately when clients subscribe.
55 // Default: false
56 Retained bool `default:"no" desc:"Retain message on broker" key:"retained"`
57
58 // CleanSession determines whether to start a fresh session on connect.
59 // When true, the broker discards any previous session state (subscriptions,
60 // queued messages). When false, the broker resumes the previous session
61 // if the ClientID matches.
62 // Default: true
63 CleanSession bool `default:"yes" desc:"Start with a clean session" key:"cleansession"`
64
65 // DisableTLS turns off TLS encryption for the connection.
66 // When true, connections use plain TCP which is faster but insecure.
67 // Should only be used on trusted networks or for testing.
68 // Default: false (TLS enabled)
69 DisableTLS bool `default:"no" desc:"Disable TLS encryption" key:"disabletls"`
70
71 // DisableTLSVerification skips TLS certificate validation.
72 // When true, the client accepts any certificate from the broker.
73 // WARNING: This makes the connection vulnerable to man-in-the-middle attacks.
74 // Only use for testing or with self-signed certificates in trusted environments.
75 // Default: false (verification enabled)
76 DisableTLSVerification bool `default:"no" desc:"Disable TLS certificate verification" key:"disabletlsverification"`
77 }
78
79 // QoS represents the Quality of Service (QoS) level for MQTT message delivery.
80 // Higher QoS levels provide stronger delivery guarantees but with increased overhead.
81 type QoS int
82
83 // qosVals holds the QoS enum value constants and formatter.
84 // This struct enables type-safe QoS value handling with flexible parsing.
85 type qosVals struct {
86 // AtMostOnce is the fire-and-forget QoS level (0).
87 AtMostOnce QoS
88 // AtLeastOnce is the acknowledged delivery QoS level (1).
89 AtLeastOnce QoS
90 // ExactlyOnce is the guaranteed delivery QoS level (2).
91 ExactlyOnce QoS
92 // Enum provides parsing and formatting for QoS values.
93 Enum types.EnumFormatter
94 }
95
96 // Scheme identifies the URL scheme for MQTT service URLs.
97 const Scheme = "mqtt"
98
99 // SchemeTLS identifies the URL scheme for MQTT over TLS service URLs.
100 const SchemeTLS = "mqtts"
101
102 // DefaultPort is the standard MQTT port (1883).
103 const DefaultPort = 1883
104
105 // DefaultTLSPort is the standard MQTT over TLS port (8883).
106 const DefaultTLSPort = 8883
107
108 // QoS constants define the three MQTT Quality of Service levels.
109 const (
110 // QoSAtMostOnce (fire-and-forget): The broker delivers the message at most once.
111 // No acknowledgment is required. Messages may be lost if the client disconnects
112 // or the broker fails. Best for high-throughput, non-critical data.
113 QoSAtMostOnce QoS = 0
114
115 // QoSAtLeastOnce: The broker delivers the message at least once.
116 // Requires acknowledgment from the subscriber. Duplicates may occur if
117 // acknowledgments are lost. Suitable for important data where occasional
118 // duplicates are acceptable.
119 QoSAtLeastOnce QoS = 1
120
121 // QoSExactlyOnce: The broker delivers the message exactly once.
122 // Uses a two-phase commit handshake to guarantee exactly-once delivery.
123 // Highest overhead but strongest guarantee. Best for critical data where
124 // duplicates must be avoided.
125 QoSExactlyOnce QoS = 2
126 )
127
128 // QoSValues holds the QoS enum values and their associated formatter.
129 // This provides both the concrete enum values and the machinery for
130 // parsing and formatting QoS values from strings.
131 var QoSValues = &qosVals{
132 AtMostOnce: QoSAtMostOnce,
133 AtLeastOnce: QoSAtLeastOnce,
134 ExactlyOnce: QoSExactlyOnce,
135 // Create an enum formatter that accepts multiple string representations:
136 // - Standard names: "AtMostOnce", "AtLeastOnce", "ExactlyOnce"
137 // - Numeric strings: "0", "1", "2"
138 // - Snake case: "at_most_once", "at_least_once", "exactly_once"
139 Enum: format.CreateEnumFormatter(
140 []string{
141 "AtMostOnce",
142 "AtLeastOnce",
143 "ExactlyOnce",
144 }, map[string]int{
145 "0": int(QoSAtMostOnce),
146 "1": int(QoSAtLeastOnce),
147 "2": int(QoSExactlyOnce),
148 "at_most_once": int(QoSAtMostOnce),
149 "at_least_once": int(QoSAtLeastOnce),
150 "exactly_once": int(QoSExactlyOnce),
151 }),
152 }
153
154 // Enums returns a map of enum type names to their formatters.
155 // This enables proper parsing and formatting of enum values like QoS.
156 //
157 // Returns a map where keys are enum type names and values are formatters
158 // that can convert between string representations and enum values.
159 func (c *Config) Enums() map[string]types.EnumFormatter {
160 return map[string]types.EnumFormatter{
161 "QoS": QoSValues.Enum,
162 }
163 }
164
165 // GetURL constructs a configuration URL from the current config settings.
166 // The URL contains all configuration values and can be used to recreate
167 // an identical service configuration.
168 //
169 // Returns a *url.URL in the format: mqtt://[user:pass@]host:port/topic?options
170 // Returns nil if credential validation fails (password without username).
171 func (c *Config) GetURL() *url.URL {
172 // Create a new property key resolver for building the query string
173 resolver := format.NewPropKeyResolver(c)
174
175 return c.getURL(&resolver)
176 }
177
178 // QueryFields returns a list of all configurable query parameter names.
179 // This is used for documentation generation and validation of URL parameters.
180 //
181 // Returns a slice of query parameter field names.
182 func (c *Config) QueryFields() []string {
183 return format.GetConfigQueryResolver(c).QueryFields()
184 }
185
186 // SetURL parses a configuration URL and populates the config fields.
187 // This is the public entry point for URL-based configuration.
188 //
189 // Parameters:
190 // - url: The configuration URL to parse
191 //
192 // Returns an error if the URL is malformed or required fields are missing.
193 func (c *Config) SetURL(serviceURL *url.URL) error {
194 // Create a new property key resolver for parsing query parameters
195 resolver := format.NewPropKeyResolver(c)
196
197 return c.setURL(&resolver, serviceURL)
198 }
199
200 // ValidateCredentials validates that the configuration has valid credentials.
201 // Returns an error if a password is provided without a username, as this
202 // combination is invalid for URL-based authentication.
203 //
204 // Returns nil if credentials are valid or no credentials are provided.
205 func (c *Config) ValidateCredentials() error {
206 if c.Password != "" && c.Username == "" {
207 return ErrPasswordWithoutUsername
208 }
209
210 return nil
211 }
212
213 // getURL is the internal implementation of GetURL that accepts a resolver interface.
214 // This allows for easier testing and decoupling from the concrete resolver type.
215 //
216 // Parameters:
217 // - resolver: The query resolver to use for building the URL query string
218 //
219 // Returns a complete URL representing the current configuration.
220 // Returns nil if password is provided without username.
221 func (c *Config) getURL(resolver types.ConfigQueryResolver) *url.URL {
222 // Validate credentials before building the URL
223 if err := c.ValidateCredentials(); err != nil {
224 return nil
225 }
226
227 // Build the base URL with scheme, host:port, and topic path
228 result := &url.URL{
229 Scheme: Scheme,
230 Host: fmt.Sprintf("%s:%d", c.Host, c.Port),
231 ForceQuery: true, // Always include the query string separator (?)
232 Path: c.Topic,
233 RawQuery: format.BuildQuery(resolver),
234 }
235
236 // Add user credentials if authentication is configured
237 if c.Username != "" {
238 if c.Password != "" {
239 // Include both username and password in the URL
240 result.User = url.UserPassword(c.Username, c.Password)
241 } else {
242 // Username only (no password)
243 result.User = url.User(c.Username)
244 }
245 }
246
247 return result
248 }
249
250 // setURL is the internal implementation of SetURL that accepts a resolver interface.
251 // It extracts all configuration values from the URL including:
252 // - User credentials from the URL user info (username:password@host)
253 // - Host and port from the URL host component
254 // - Topic from the URL path (with leading slash removed)
255 // - Additional options from URL query parameters
256 //
257 // Parameters:
258 // - resolver: The query resolver to use for parsing query parameters
259 // - url: The configuration URL to parse
260 //
261 // Returns an error if parsing fails or required fields are missing.
262 func (c *Config) setURL(resolver types.ConfigQueryResolver, serviceURL *url.URL) error {
263 // Extract authentication credentials from URL user info if present
264 if serviceURL.User != nil {
265 // Get the password (may be empty if only username is provided)
266 password, _ := serviceURL.User.Password()
267 c.Password = password
268 c.Username = serviceURL.User.Username()
269 } else {
270 // Clear credentials if not present in URL
271 c.Password = ""
272 c.Username = ""
273 }
274
275 // Extract hostname from the URL
276 host := serviceURL.Hostname()
277 if host != "" {
278 c.Host = host
279 }
280
281 // Extract and parse port number from the URL
282 port := serviceURL.Port()
283 if port != "" {
284 // Parse the port string to an integer
285 parsedPort, err := strconv.Atoi(port)
286 if err != nil {
287 return fmt.Errorf("parsing port: %w", err)
288 }
289
290 c.Port = parsedPort
291 } else {
292 // Apply default ports based on URL scheme when no port is specified
293 switch serviceURL.Scheme {
294 case SchemeTLS:
295 c.Port = DefaultTLSPort
296 case Scheme:
297 c.Port = DefaultPort
298 }
299 }
300
301 // Extract topic from URL path, removing the leading slash
302 // Example: "/notifications/alerts" becomes "notifications/alerts"
303 c.Topic = strings.TrimPrefix(serviceURL.Path, "/")
304
305 // Process all query parameters through the resolver
306 // This handles optional parameters like qos, retained, clientid, etc.
307 for key, vals := range serviceURL.Query() {
308 if err := resolver.Set(key, vals[0]); err != nil {
309 return fmt.Errorf("setting query parameter %q to %q: %w", key, vals[0], err)
310 }
311 }
312
313 // Validate that a topic was provided (skip for dummy URL used in docs generation)
314 if serviceURL.String() != "mqtt://[email protected]" {
315 if c.Topic == "" {
316 return ErrTopicRequired
317 }
318 }
319
320 // Validate QoS value is within MQTT protocol range (0-2)
321 if !c.QoS.IsValid() {
322 return fmt.Errorf("validating QoS value %d: %w", c.QoS, ErrInvalidQoS)
323 }
324
325 return nil
326 }
327
328 // IsValid reports whether the QoS value is within the valid MQTT range.
329 // MQTT protocol only supports QoS levels 0 (at most once), 1 (at least once),
330 // and 2 (exactly once). Any value outside this range is invalid.
331 //
332 // Returns true if q is between QoSAtMostOnce (0) and QoSExactlyOnce (2) inclusive.
333 func (q QoS) IsValid() bool {
334 return q >= QoSAtMostOnce && q <= QoSExactlyOnce
335 }
336
337 // String returns the human-readable name of the QoS level.
338 // This implements the fmt.Stringer interface for pretty printing.
339 //
340 // Returns one of "AtMostOnce", "AtLeastOnce", or "ExactlyOnce".
341 func (q QoS) String() string {
342 return QoSValues.Enum.Print(int(q))
343 }