Debian Codegraph @

pkg/router/router.go

raw
1 package router
2
3 import (
4 "context"
5 "errors"
6 "fmt"
7 "net/http"
8 "net/url"
9 "strings"
10 "time"
11
12 "github.com/nicholas-fedor/shoutrrr/pkg/types"
13 )
14
15 // ServiceRouter is responsible for routing a message to a specific notification service using the notification URL.
16 type ServiceRouter struct {
17 logger types.StdLogger
18 services []types.Service
19 queue []string
20 Timeout time.Duration
21 httpClient types.HTTPClient
22 dialContext types.DialContextFunc
23 //nolint:containedctx // Intentional: router derives per-service timeout contexts from this base.
24 ctx context.Context
25 }
26
27 // DefaultTimeout is the default duration for service operation timeouts.
28 const DefaultTimeout = 10 * time.Second
29
30 var (
31 ErrNoSenders = errors.New("error sending message: no senders")
32 ErrServiceTimeout = errors.New("failed to send: timed out")
33 ErrCustomURLsNotSupported = errors.New("custom URLs are not supported by service")
34 ErrUnknownService = errors.New("unknown service")
35 ErrParseURLFailed = errors.New("failed to parse URL")
36 ErrSendFailed = errors.New("failed to send message")
37 ErrCustomURLConversion = errors.New("failed to convert custom URL")
38 )
39
40 // New creates a new service router using the specified logger and service URLs.
41 //
42 // Deprecated: Use NewWithOptions.
43 //
44 //go:fix inline
45 func New(logger types.StdLogger, serviceURLs ...string) (*ServiceRouter, error) {
46 return NewWithOptions(logger, types.SenderOptions{}, serviceURLs...)
47 }
48
49 // NewWithOptions creates a new service router using the specified logger, options,
50 // and service URLs. If opts.HTTPClient is non-nil, it will be injected into
51 // services that support it (via SetHTTPClient). If opts.DialContext is non-nil,
52 // it will be injected into services that implement [types.DialContextSetter].
53 //
54 // Parameters:
55 // - logger: the logger to use for service output.
56 // - opts: the sender options, including timeout, HTTP client, and dial function.
57 // - serviceURLs: the service URLs to initialize.
58 //
59 // Returns:
60 // - *ServiceRouter: the initialized router.
61 // - error: an error if any service fails to initialize.
62 func NewWithOptions(logger types.StdLogger, opts types.SenderOptions, serviceURLs ...string) (*ServiceRouter, error) {
63 router := ServiceRouter{
64 logger: logger,
65 services: nil,
66 queue: nil,
67 Timeout: DefaultTimeout,
68 httpClient: opts.HTTPClient,
69 dialContext: opts.DialContext,
70 ctx: context.Background(),
71 }
72
73 if opts.Timeout > 0 {
74 router.Timeout = opts.Timeout
75 }
76
77 for _, serviceURL := range serviceURLs {
78 if err := router.AddService(serviceURL); err != nil {
79 return nil, fmt.Errorf("error initializing router services: %w", err)
80 }
81 }
82
83 return &router, nil
84 }
85
86 // AddService initializes the specified service from its URL, and adds it if no errors occur.
87 //
88 // Parameters:
89 // - serviceURL: the service URL to initialize and add.
90 //
91 // Returns:
92 // - error: an error if initialization fails.
93 func (r *ServiceRouter) AddService(serviceURL string) error {
94 service, err := r.initService(serviceURL)
95 if err == nil {
96 r.services = append(r.services, service)
97 }
98
99 return err
100 }
101
102 // Enqueue adds the message to an internal queue and sends it when Flush is invoked.
103 //
104 // Parameters:
105 // - message: the message to queue.
106 // - v: optional format arguments for the message.
107 func (r *ServiceRouter) Enqueue(message string, v ...any) {
108 if len(v) > 0 {
109 message = fmt.Sprintf(message, v...)
110 }
111
112 r.queue = append(r.queue, message)
113 }
114
115 // ExtractServiceName extracts the service name from a service URL.
116 //
117 // Parameters:
118 // - rawURL: the raw service URL.
119 //
120 // Returns:
121 // - string: the extracted service scheme.
122 // - *url.URL: the parsed URL.
123 // - error: an error if parsing fails.
124 func (r *ServiceRouter) ExtractServiceName(rawURL string) (string, *url.URL, error) {
125 serviceURL, err := url.Parse(rawURL)
126 if err != nil {
127 return "", &url.URL{}, fmt.Errorf("%s: %w", rawURL, ErrParseURLFailed)
128 }
129
130 scheme := serviceURL.Scheme
131 schemeParts := strings.Split(scheme, "+")
132
133 if len(schemeParts) > 1 {
134 scheme = schemeParts[0]
135 }
136
137 return scheme, serviceURL, nil
138 }
139
140 // Flush sends all messages that have been queued up as a combined message.
141 //
142 // Parameters:
143 // - params: the parameters to apply to the combined message.
144 func (r *ServiceRouter) Flush(params *types.Params) {
145 // Since this method is supposed to be deferred we just have to ignore errors
146 _ = r.Send(strings.Join(r.queue, "\n"), params)
147 r.queue = []string{}
148 }
149
150 // ListServices returns the available services.
151 //
152 // Returns:
153 // - []string: the list of supported service schemas.
154 func (r *ServiceRouter) ListServices() []string {
155 services := make([]string, len(serviceMap))
156
157 i := 0
158
159 for key := range serviceMap {
160 services[i] = key
161 i++
162 }
163
164 return services
165 }
166
167 // Locate returns the service implementation that corresponds to the given service URL.
168 //
169 // Parameters:
170 // - rawURL: the service URL to locate.
171 //
172 // Returns:
173 // - types.Service: the located service implementation.
174 // - error: an error if the service cannot be located or initialized.
175 func (r *ServiceRouter) Locate(rawURL string) (types.Service, error) {
176 service, err := r.initService(rawURL)
177
178 return service, err
179 }
180
181 // NewService returns a new uninitialized service instance.
182 //
183 // Parameters:
184 // - serviceScheme: the service scheme to instantiate.
185 //
186 // Returns:
187 // - types.Service: the new service instance.
188 // - error: an error if the scheme is unknown.
189 func (*ServiceRouter) NewService(serviceScheme string) (types.Service, error) {
190 return newService(serviceScheme)
191 }
192
193 // Route sends a message to a specific notification service using the notification URL.
194 //
195 // Parameters:
196 // - rawURL: the service URL to send to.
197 // - message: the message to send.
198 //
199 // Returns:
200 // - error: an error if the send fails, wrapped in *types.TargetError.
201 func (r *ServiceRouter) Route(rawURL, message string) error {
202 service, err := r.Locate(rawURL)
203 if err != nil {
204 return err
205 }
206
207 if err := service.Send(message, nil); err != nil {
208 return &types.TargetError{URL: service.GetID(), Err: err}
209 }
210
211 return nil
212 }
213
214 // Send sends the specified message using the routers underlying services.
215 //
216 // Parameters:
217 // - message: the message to send.
218 // - params: the parameters to apply.
219 //
220 // Returns:
221 // - []error: one error per service, in the same order as the configured URLs.
222 func (r *ServiceRouter) Send(message string, params *types.Params) []error {
223 if r == nil {
224 return []error{ErrNoSenders}
225 }
226
227 serviceCount := len(r.services)
228 errs := make([]error, serviceCount)
229 results := r.SendAsync(message, params)
230
231 for i := range r.services {
232 errs[i] = <-results
233 }
234
235 return errs
236 }
237
238 // SendAsync sends the specified message using the routers underlying services.
239 //
240 // Parameters:
241 // - message: the message to send.
242 // - params: the parameters to apply.
243 //
244 // Returns:
245 // - chan error: a channel that will contain one error per service.
246 func (r *ServiceRouter) SendAsync(message string, params *types.Params) chan error {
247 serviceCount := len(r.services)
248 proxy := make(chan error, serviceCount)
249 errs := make(chan error, serviceCount)
250
251 if params == nil {
252 params = &types.Params{}
253 }
254
255 for _, service := range r.services {
256 go sendToService(service, proxy, r.Timeout, message, *params, r.ctx)
257 }
258
259 go func() {
260 for range serviceCount {
261 errs <- <-proxy
262 }
263
264 close(errs)
265 }()
266
267 return errs
268 }
269
270 // SendItems sends the specified message items using the routers underlying services.
271 //
272 // Parameters:
273 // - items: the message items to send.
274 // - params: the parameters to apply.
275 //
276 // Returns:
277 // - []error: one error per service, in the same order as the configured URLs.
278 func (r *ServiceRouter) SendItems(items []types.MessageItem, params types.Params) []error {
279 if r == nil {
280 return []error{ErrNoSenders}
281 }
282
283 serviceCount := len(r.services)
284 proxy := make(chan error, serviceCount)
285 errs := make([]error, serviceCount)
286
287 for _, service := range r.services {
288 go sendItemsToService(service, proxy, r.Timeout, items, params, r.ctx)
289 }
290
291 for i := range r.services {
292 errs[i] = <-proxy
293 }
294
295 return errs
296 }
297
298 // SetLogger sets the logger that the services will use to write progress logs.
299 //
300 // Parameters:
301 // - logger: the logger to set on all services.
302 func (r *ServiceRouter) SetLogger(logger types.StdLogger) {
303 r.logger = logger
304 for _, service := range r.services {
305 service.SetLogger(logger)
306 }
307 }
308
309 // initService initializes a service from the given URL.
310 //
311 // Parameters:
312 // - rawURL: the raw service URL.
313 //
314 // Returns:
315 // - types.Service: the initialized service.
316 // - error: an error if initialization fails.
317 func (r *ServiceRouter) initService(rawURL string) (types.Service, error) {
318 scheme, serviceURL, err := r.ExtractServiceName(rawURL)
319 if err != nil {
320 return nil, err
321 }
322
323 service, err := newService(scheme)
324 if err != nil {
325 return nil, err
326 }
327
328 if serviceURL.Scheme != scheme {
329 r.log("Got custom URL:", serviceURL.String())
330
331 customURLService, ok := service.(types.CustomURLService)
332 if !ok {
333 return nil, fmt.Errorf("%w: '%s' service", ErrCustomURLsNotSupported, scheme)
334 }
335
336 serviceURL, err = customURLService.GetServiceURLFromCustom(serviceURL)
337 if err != nil {
338 return nil, fmt.Errorf("%s: %w", serviceURL.String(), ErrCustomURLConversion)
339 }
340
341 r.log("Converted service URL:", serviceURL.String())
342 }
343
344 err = service.Initialize(serviceURL, r.logger)
345 if err != nil {
346 return service, fmt.Errorf("%s: %w", scheme, err)
347 }
348
349 // Inject custom HTTP client if provided and the service supports it.
350 if r.httpClient != nil {
351 if client, ok := r.httpClient.(*http.Client); ok && client == nil {
352 // skip typed-nil
353 } else if setter, ok := service.(types.HTTPClientSetter); ok {
354 setter.SetHTTPClient(r.httpClient)
355 }
356 }
357
358 if r.dialContext != nil {
359 if setter, ok := service.(types.DialContextSetter); ok {
360 setter.SetDialContext(r.dialContext)
361 }
362 }
363
364 return service, nil
365 }
366
367 // log writes a log message if a logger is configured.
368 //
369 // Parameters:
370 // - v: the values to log.
371 func (r *ServiceRouter) log(v ...any) {
372 if r.logger == nil {
373 return
374 }
375
376 r.logger.Println(v...)
377 }
378
379 // newService returns a new uninitialized service instance.
380 func newService(serviceScheme string) (types.Service, error) {
381 serviceFactory, valid := serviceMap[strings.ToLower(serviceScheme)]
382 if !valid {
383 return nil, fmt.Errorf("%w: %q", ErrUnknownService, serviceScheme)
384 }
385
386 return serviceFactory(), nil
387 }
388
389 // awaitResult waits for either the service result or a timeout, wrapping the
390 // result in a TargetError if needed.
391 //
392 // Parameters:
393 // - results: the channel to report the final error to.
394 // - result: the channel carrying the service result.
395 // - timeout: the operation timeout.
396 // - serviceID: the identifier of the service for error wrapping.
397 func awaitResult(results chan error, result <-chan error, timeout time.Duration, serviceID string) {
398 select {
399 case res := <-result:
400 if res != nil {
401 if errors.Is(res, context.DeadlineExceeded) {
402 res = &types.TargetError{URL: serviceID, Err: fmt.Errorf("%w: %v", ErrServiceTimeout, serviceID)}
403 } else {
404 res = &types.TargetError{URL: serviceID, Err: res}
405 }
406 }
407
408 results <- res
409 case <-time.After(timeout):
410 results <- &types.TargetError{URL: serviceID, Err: fmt.Errorf("%w: %v", ErrServiceTimeout, serviceID)}
411 }
412 }
413
414 // sendToService sends a message to a single service, respecting context and timeout.
415 //
416 // Parameters:
417 // - service: the service to send to.
418 // - results: the channel to report the result error to.
419 // - timeout: the operation timeout.
420 // - message: the message to send.
421 // - params: the parameters to apply.
422 // - ctx: the base context for the operation.
423 func sendToService(
424 service types.Service,
425 results chan error,
426 timeout time.Duration,
427 message string,
428 params types.Params,
429 ctx context.Context,
430 ) {
431 result := make(chan error, 1)
432
433 serviceID := service.GetID()
434
435 if sender, ok := service.(types.ContextSender); ok {
436 sendCtx, cancel := context.WithTimeout(ctx, timeout)
437 defer cancel()
438
439 go func() { result <- sender.SendContext(sendCtx, message, &params) }()
440 } else {
441 go func() { result <- service.Send(message, &params) }()
442 }
443
444 awaitResult(results, result, timeout, serviceID)
445 }
446
447 // sendItemsToService sends message items to a single service, respecting context and timeout.
448 //
449 // Parameters:
450 // - service: the service to send to.
451 // - results: the channel to report the result error to.
452 // - timeout: the operation timeout.
453 // - items: the message items to send.
454 // - params: the parameters to apply.
455 // - ctx: the base context for the operation.
456 func sendItemsToService(
457 service types.Service,
458 results chan error,
459 timeout time.Duration,
460 items []types.MessageItem,
461 params types.Params,
462 ctx context.Context,
463 ) {
464 result := make(chan error, 1)
465
466 serviceID := service.GetID()
467
468 switch sender := service.(type) {
469 case types.ContextAttachmentSender:
470 sendCtx, cancel := context.WithTimeout(ctx, timeout)
471 defer cancel()
472
473 go func() { result <- sender.SendItemsContext(sendCtx, items, params) }()
474 case types.RichSender:
475 go func() { result <- sender.SendItems(items, params) }()
476 case types.ContextSender:
477 sendCtx, cancel := context.WithTimeout(ctx, timeout)
478 defer cancel()
479
480 go func() { result <- sender.SendContext(sendCtx, types.ItemsToPlain(items), &params) }()
481 default:
482 go func() { result <- service.Send(types.ItemsToPlain(items), &params) }()
483 }
484
485 awaitResult(results, result, timeout, serviceID)
486 }