Debian Codegraph @

pkg/services/push/mqtt/mqtt_config.go

raw symbols SCIP
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
155 // Enums returns a map of enum type names to their formatters.
156 // This enables proper parsing and formatting of enum values like QoS.
157 //
158 // Returns a map where keys are enum type names and values are formatters
159 // that can convert between string representations and enum values.
160 func (c *Config) Enums() map[string]types.EnumFormatter {
161 return map[string]types.EnumFormatter{
162 "QoS": QoSValues.Enum,
163 }
164 }
165
166 // GetURL constructs a configuration URL from the current config settings.
167 // The URL contains all configuration values and can be used to recreate
168 // an identical service configuration.
169 //
170 // Returns a *url.URL in the format: mqtt://[user:pass@]host:port/topic?options
171 // Returns nil if credential validation fails (password without username).
172 func (c *Config) GetURL() *url.URL {
173 // Create a new property key resolver for building the query string
174 resolver := format.NewPropKeyResolver(c)
175
176 return c.getURL(&resolver)
177 }
178
179 // QueryFields returns a list of all configurable query parameter names.
180 // This is used for documentation generation and validation of URL parameters.
181 //
182 // Returns a slice of query parameter field names.
183 func (c *Config) QueryFields() []string {
184 return format.GetConfigQueryResolver(c).QueryFields()
185 }
186
187 // SetURL parses a configuration URL and populates the config fields.
188 // This is the public entry point for URL-based configuration.
189 //
190 // Parameters:
191 // - url: The configuration URL to parse
192 //
193 // Returns an error if the URL is malformed or required fields are missing.
194 func (c *Config) SetURL(serviceURL *url.URL) error {
195 // Create a new property key resolver for parsing query parameters
196 resolver := format.NewPropKeyResolver(c)
197
198 return c.setURL(&resolver, serviceURL)
199 }
200
201 // ValidateCredentials validates that the configuration has valid credentials.
202 // Returns an error if a password is provided without a username, as this
203 // combination is invalid for URL-based authentication.
204 //
205 // Returns nil if credentials are valid or no credentials are provided.
206 func (c *Config) ValidateCredentials() error {
207 if c.Password != "" && c.Username == "" {
208 return ErrPasswordWithoutUsername
209 }
210
211 return nil
212 }
213
214 // getURL is the internal implementation of GetURL that accepts a resolver interface.
215 // This allows for easier testing and decoupling from the concrete resolver type.
216 //
217 // Parameters:
218 // - resolver: The query resolver to use for building the URL query string
219 //
220 // Returns a complete URL representing the current configuration.
221 // Returns nil if password is provided without username.
222 func (c *Config) getURL(resolver types.ConfigQueryResolver) *url.URL {
223 // Validate credentials before building the URL
224 if err := c.ValidateCredentials(); err != nil {
225 return nil
226 }
227
228 // Build the base URL with scheme, host:port, and topic path
229 result := &url.URL{
230 Scheme: Scheme,
231 Host: fmt.Sprintf("%s:%d", c.Host, c.Port),
232 ForceQuery: true, // Always include the query string separator (?)
233 Path: c.Topic,
234 RawQuery: format.BuildQuery(resolver),
235 }
236
237 // Add user credentials if authentication is configured
238 if c.Username != "" {
239 if c.Password != "" {
240 // Include both username and password in the URL
241 result.User = url.UserPassword(c.Username, c.Password)
242 } else {
243 // Username only (no password)
244 result.User = url.User(c.Username)
245 }
246 }
247
248 return result
249 }
250
251 // setURL is the internal implementation of SetURL that accepts a resolver interface.
252 // It extracts all configuration values from the URL including:
253 // - User credentials from the URL user info (username:password@host)
254 // - Host and port from the URL host component
255 // - Topic from the URL path (with leading slash removed)
256 // - Additional options from URL query parameters
257 //
258 // Parameters:
259 // - resolver: The query resolver to use for parsing query parameters
260 // - url: The configuration URL to parse
261 //
262 // Returns an error if parsing fails or required fields are missing.
263 func (c *Config) setURL(resolver types.ConfigQueryResolver, serviceURL *url.URL) error {
264 // Extract authentication credentials from URL user info if present
265 if serviceURL.User != nil {
266 // Get the password (may be empty if only username is provided)
267 password, _ := serviceURL.User.Password()
268 c.Password = password
269 c.Username = serviceURL.User.Username()
270 } else {
271 // Clear credentials if not present in URL
272 c.Password = ""
273 c.Username = ""
274 }
275
276 // Extract hostname from the URL
277 host := serviceURL.Hostname()
278 if host != "" {
279 c.Host = host
280 }
281
282 // Extract and parse port number from the URL
283 port := serviceURL.Port()
284 if port != "" {
285 // Parse the port string to an integer
286 parsedPort, err := strconv.Atoi(port)
287 if err != nil {
288 return fmt.Errorf("parsing port: %w", err)
289 }
290
291 c.Port = parsedPort
292 } else {
293 // Apply default ports based on URL scheme when no port is specified
294 switch serviceURL.Scheme {
295 case SchemeTLS:
296 c.Port = DefaultTLSPort
297 case Scheme:
298 c.Port = DefaultPort
299 }
300 }
301
302 // Extract topic from URL path, removing the leading slash
303 // Example: "/notifications/alerts" becomes "notifications/alerts"
304 c.Topic = strings.TrimPrefix(serviceURL.Path, "/")
305
306 // Process all query parameters through the resolver
307 // This handles optional parameters like qos, retained, clientid, etc.
308 for key, vals := range serviceURL.Query() {
309 if err := resolver.Set(key, vals[0]); err != nil {
310 return fmt.Errorf("setting query parameter %q to %q: %w", key, vals[0], err)
311 }
312 }
313
314 // Validate that a topic was provided (skip for dummy URL used in docs generation)
315 if serviceURL.String() != "mqtt://[email protected]" {
316 if c.Topic == "" {
317 return ErrTopicRequired
318 }
319 }
320
321 // Validate QoS value is within MQTT protocol range (0-2)
322 if !c.QoS.IsValid() {
323 return fmt.Errorf("validating QoS value %d: %w", c.QoS, ErrInvalidQoS)
324 }
325
326 return nil
327 }
328
329 // IsValid reports whether the QoS value is within the valid MQTT range.
330 // MQTT protocol only supports QoS levels 0 (at most once), 1 (at least once),
331 // and 2 (exactly once). Any value outside this range is invalid.
332 //
333 // Returns true if q is between QoSAtMostOnce (0) and QoSExactlyOnce (2) inclusive.
334 func (q QoS) IsValid() bool {
335 return q >= QoSAtMostOnce && q <= QoSExactlyOnce
336 }
337
338 // String returns the human-readable name of the QoS level.
339 // This implements the fmt.Stringer interface for pretty printing.
340 //
341 // Returns one of "AtMostOnce", "AtLeastOnce", or "ExactlyOnce".
342 func (q QoS) String() string {
343 return QoSValues.Enum.Print(int(q))
344 }