Debian Codegraph @

exporter/exporterhelper/internal/timeout_sender.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package internal // import "go.opentelemetry.io/collector/exporter/exporterhelper/internal"
5
6 import (
7 "context"
8 "errors"
9 "time"
10
11 "go.opentelemetry.io/collector/component"
12 "go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender"
13 )
14
15 // TimeoutConfig for timeout. The timeout applies to individual attempts to send data to the backend.
16 type TimeoutConfig struct {
17 // Timeout is the timeout for every attempt to send data to the backend.
18 // A zero timeout means no timeout.
19 Timeout time.Duration `mapstructure:"timeout"`
20 }
21
22 func (ts *TimeoutConfig) Validate() error {
23 // Negative timeouts are not acceptable, since all sends will fail.
24 if ts.Timeout < 0 {
25 return errors.New("'timeout' must be non-negative")
26 }
27 return nil
28 }
29
30 // NewDefaultTimeoutConfig returns the default config for TimeoutConfig.
31 func NewDefaultTimeoutConfig() TimeoutConfig {
32 return TimeoutConfig{
33 Timeout: 5 * time.Second,
34 }
35 }
36
37 // timeoutSender is a requestSender that adds a `timeout` to every request that passes this sender.
38 type timeoutSender[T any] struct {
39 component.StartFunc
40 component.ShutdownFunc
41 cfg TimeoutConfig
42 next sender.Sender[T]
43 }
44
45 func newTimeoutSender[T any](cfg TimeoutConfig, next sender.Sender[T]) sender.Sender[T] {
46 return &timeoutSender[T]{cfg: cfg, next: next}
47 }
48
49 func (ts *timeoutSender[T]) Send(ctx context.Context, req T) error {
50 // Intentionally don't overwrite the context inside the request, because in case of retries deadline will not be
51 // updated because this deadline most likely is before the next one.
52 tCtx, cancelFunc := context.WithTimeout(ctx, ts.cfg.Timeout)
53 defer cancelFunc()
54 return ts.next.Send(tCtx, req)
55 }