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