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