1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-07-15 01:04:25 +02:00

Refactor configs (#1882)

* trace: Refactor sampling config

* tracer: Refactor TracerProviderConfig

* Update the changelog

* Refactor sdk/metric/controller/basic config

* Refactor sdk/metric/processor/basic config

* Refactor sdk/resource config

* Refactor oteltest config

* Refactor exporters/otlp configs

* Refactor exporters/stdout config

* Refactor exporters/trace/jaeger configs

* Refactor exporters/trace/zipkin config

* Unexport stdout.NewConfig

* Refactor zipkin.go

* Refactor provider.go
This commit is contained in:
Robert Pająk
2021-05-14 22:28:28 +02:00
committed by GitHub
parent 6324adaa66
commit d23cc61b93
27 changed files with 299 additions and 285 deletions

View File

@ -45,6 +45,7 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
- Spans created by the global `Tracer` obtained from `go.opentelemetry.io/otel`, prior to a functioning `TracerProvider` being set, now propagate the span context from their parent if one exists. (#1901) - Spans created by the global `Tracer` obtained from `go.opentelemetry.io/otel`, prior to a functioning `TracerProvider` being set, now propagate the span context from their parent if one exists. (#1901)
- The `"go.opentelemetry.io/otel".Tracer` function now accepts tracer options. (#1902) - The `"go.opentelemetry.io/otel".Tracer` function now accepts tracer options. (#1902)
- Move the `go.opentelemetry.io/otel/unit` package to `go.opentelemetry.io/otel/metric/unit`. (#1903) - Move the `go.opentelemetry.io/otel/unit` package to `go.opentelemetry.io/otel/metric/unit`. (#1903)
- Refactor option types according to the contribution style guide. (#1882)
### Deprecated ### Deprecated

View File

@ -28,7 +28,15 @@ const (
) )
// ExporterOption are setting options passed to an Exporter on creation. // ExporterOption are setting options passed to an Exporter on creation.
type ExporterOption func(*config) type ExporterOption interface {
apply(*config)
}
type exporterOptionFunc func(*config)
func (fn exporterOptionFunc) apply(cfg *config) {
fn(cfg)
}
type config struct { type config struct {
exportKindSelector metricsdk.ExportKindSelector exportKindSelector metricsdk.ExportKindSelector
@ -39,14 +47,14 @@ type config struct {
// aggregation). If not specified otherwise, exporter will use a // aggregation). If not specified otherwise, exporter will use a
// cumulative export kind selector. // cumulative export kind selector.
func WithMetricExportKindSelector(selector metricsdk.ExportKindSelector) ExporterOption { func WithMetricExportKindSelector(selector metricsdk.ExportKindSelector) ExporterOption {
return func(cfg *config) { return exporterOptionFunc(func(cfg *config) {
cfg.exportKindSelector = selector cfg.exportKindSelector = selector
} })
} }
// SplitDriverOption provides options for setting up a split driver. // SplitDriverOption provides options for setting up a split driver.
type SplitDriverOption interface { type SplitDriverOption interface {
Apply(*splitDriver) apply(*splitDriver)
} }
// WithMetricDriver allows one to set the driver used for metrics // WithMetricDriver allows one to set the driver used for metrics
@ -59,7 +67,7 @@ type metricDriverOption struct {
driver ProtocolDriver driver ProtocolDriver
} }
func (o metricDriverOption) Apply(s *splitDriver) { func (o metricDriverOption) apply(s *splitDriver) {
s.metric = o.driver s.metric = o.driver
} }
@ -73,6 +81,6 @@ type traceDriverOption struct {
driver ProtocolDriver driver ProtocolDriver
} }
func (o traceDriverOption) Apply(s *splitDriver) { func (o traceDriverOption) apply(s *splitDriver) {
s.trace = o.driver s.trace = o.driver
} }

View File

@ -66,7 +66,7 @@ func NewUnstartedExporter(driver ProtocolDriver, opts ...ExporterOption) *Export
exportKindSelector: metricsdk.CumulativeExportKindSelector(), exportKindSelector: metricsdk.CumulativeExportKindSelector(),
} }
for _, opt := range opts { for _, opt := range opts {
opt(&cfg) opt.apply(&cfg)
} }
return &Exporter{ return &Exporter{
cfg: cfg, cfg: cfg,

View File

@ -62,7 +62,7 @@ func NewDriver(opts ...Option) otlp.ProtocolDriver {
cfg := otlpconfig.NewDefaultConfig() cfg := otlpconfig.NewDefaultConfig()
otlpconfig.ApplyGRPCEnvConfigs(&cfg) otlpconfig.ApplyGRPCEnvConfigs(&cfg)
for _, opt := range opts { for _, opt := range opts {
opt.ApplyGRPCOption(&cfg) opt.applyGRPCOption(&cfg)
} }
d := &driver{} d := &driver{}

View File

@ -28,57 +28,65 @@ import (
// Option applies an option to the gRPC driver. // Option applies an option to the gRPC driver.
type Option interface { type Option interface {
applyGRPCOption(*otlpconfig.Config)
}
type wrappedOption struct {
otlpconfig.GRPCOption otlpconfig.GRPCOption
} }
func (w wrappedOption) applyGRPCOption(cfg *otlpconfig.Config) {
w.ApplyGRPCOption(cfg)
}
// WithInsecure disables client transport security for the exporter's gRPC connection // WithInsecure disables client transport security for the exporter's gRPC connection
// just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure // just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure
// does. Note, by default, client security is required unless WithInsecure is used. // does. Note, by default, client security is required unless WithInsecure is used.
func WithInsecure() Option { func WithInsecure() Option {
return otlpconfig.WithInsecure() return wrappedOption{otlpconfig.WithInsecure()}
} }
// WithTracesInsecure disables client transport security for the traces exporter's gRPC connection // WithTracesInsecure disables client transport security for the traces exporter's gRPC connection
// just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure // just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure
// does. Note, by default, client security is required unless WithInsecure is used. // does. Note, by default, client security is required unless WithInsecure is used.
func WithTracesInsecure() Option { func WithTracesInsecure() Option {
return otlpconfig.WithInsecureTraces() return wrappedOption{otlpconfig.WithInsecureTraces()}
} }
// WithInsecureMetrics disables client transport security for the metrics exporter's gRPC connection // WithInsecureMetrics disables client transport security for the metrics exporter's gRPC connection
// just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure // just like grpc.WithInsecure() https://pkg.go.dev/google.golang.org/grpc#WithInsecure
// does. Note, by default, client security is required unless WithInsecure is used. // does. Note, by default, client security is required unless WithInsecure is used.
func WithInsecureMetrics() Option { func WithInsecureMetrics() Option {
return otlpconfig.WithInsecureMetrics() return wrappedOption{otlpconfig.WithInsecureMetrics()}
} }
// WithEndpoint allows one to set the endpoint that the exporter will // WithEndpoint allows one to set the endpoint that the exporter will
// connect to the collector on. If unset, it will instead try to use // connect to the collector on. If unset, it will instead try to use
// connect to DefaultCollectorHost:DefaultCollectorPort. // connect to DefaultCollectorHost:DefaultCollectorPort.
func WithEndpoint(endpoint string) Option { func WithEndpoint(endpoint string) Option {
return otlpconfig.WithEndpoint(endpoint) return wrappedOption{otlpconfig.WithEndpoint(endpoint)}
} }
// WithTracesEndpoint allows one to set the traces endpoint that the exporter will // WithTracesEndpoint allows one to set the traces endpoint that the exporter will
// connect to the collector on. If unset, it will instead try to use // connect to the collector on. If unset, it will instead try to use
// connect to DefaultCollectorHost:DefaultCollectorPort. // connect to DefaultCollectorHost:DefaultCollectorPort.
func WithTracesEndpoint(endpoint string) Option { func WithTracesEndpoint(endpoint string) Option {
return otlpconfig.WithTracesEndpoint(endpoint) return wrappedOption{otlpconfig.WithTracesEndpoint(endpoint)}
} }
// WithMetricsEndpoint allows one to set the metrics endpoint that the exporter will // WithMetricsEndpoint allows one to set the metrics endpoint that the exporter will
// connect to the collector on. If unset, it will instead try to use // connect to the collector on. If unset, it will instead try to use
// connect to DefaultCollectorHost:DefaultCollectorPort. // connect to DefaultCollectorHost:DefaultCollectorPort.
func WithMetricsEndpoint(endpoint string) Option { func WithMetricsEndpoint(endpoint string) Option {
return otlpconfig.WithMetricsEndpoint(endpoint) return wrappedOption{otlpconfig.WithMetricsEndpoint(endpoint)}
} }
// WithReconnectionPeriod allows one to set the delay between next connection attempt // WithReconnectionPeriod allows one to set the delay between next connection attempt
// after failing to connect with the collector. // after failing to connect with the collector.
func WithReconnectionPeriod(rp time.Duration) otlpconfig.GRPCOption { func WithReconnectionPeriod(rp time.Duration) Option {
return otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) { return wrappedOption{otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) {
cfg.ReconnectionPeriod = rp cfg.ReconnectionPeriod = rp
}) })}
} }
func compressorToCompression(compressor string) otlp.Compression { func compressorToCompression(compressor string) otlp.Compression {
@ -97,7 +105,7 @@ func compressorToCompression(compressor string) otlp.Compression {
// compressors auto-register on import, such as gzip, which can be registered by calling // compressors auto-register on import, such as gzip, which can be registered by calling
// `import _ "google.golang.org/grpc/encoding/gzip"`. // `import _ "google.golang.org/grpc/encoding/gzip"`.
func WithCompressor(compressor string) Option { func WithCompressor(compressor string) Option {
return otlpconfig.WithCompression(compressorToCompression(compressor)) return wrappedOption{otlpconfig.WithCompression(compressorToCompression(compressor))}
} }
// WithTracesCompression will set the compressor for the gRPC client to use when sending traces requests. // WithTracesCompression will set the compressor for the gRPC client to use when sending traces requests.
@ -106,7 +114,7 @@ func WithCompressor(compressor string) Option {
// compressors auto-register on import, such as gzip, which can be registered by calling // compressors auto-register on import, such as gzip, which can be registered by calling
// `import _ "google.golang.org/grpc/encoding/gzip"`. // `import _ "google.golang.org/grpc/encoding/gzip"`.
func WithTracesCompression(compressor string) Option { func WithTracesCompression(compressor string) Option {
return otlpconfig.WithTracesCompression(compressorToCompression(compressor)) return wrappedOption{otlpconfig.WithTracesCompression(compressorToCompression(compressor))}
} }
// WithMetricsCompression will set the compressor for the gRPC client to use when sending metrics requests. // WithMetricsCompression will set the compressor for the gRPC client to use when sending metrics requests.
@ -115,22 +123,22 @@ func WithTracesCompression(compressor string) Option {
// compressors auto-register on import, such as gzip, which can be registered by calling // compressors auto-register on import, such as gzip, which can be registered by calling
// `import _ "google.golang.org/grpc/encoding/gzip"`. // `import _ "google.golang.org/grpc/encoding/gzip"`.
func WithMetricsCompression(compressor string) Option { func WithMetricsCompression(compressor string) Option {
return otlpconfig.WithMetricsCompression(compressorToCompression(compressor)) return wrappedOption{otlpconfig.WithMetricsCompression(compressorToCompression(compressor))}
} }
// WithHeaders will send the provided headers with gRPC requests. // WithHeaders will send the provided headers with gRPC requests.
func WithHeaders(headers map[string]string) Option { func WithHeaders(headers map[string]string) Option {
return otlpconfig.WithHeaders(headers) return wrappedOption{otlpconfig.WithHeaders(headers)}
} }
// WithTracesHeaders will send the provided headers with gRPC traces requests. // WithTracesHeaders will send the provided headers with gRPC traces requests.
func WithTracesHeaders(headers map[string]string) Option { func WithTracesHeaders(headers map[string]string) Option {
return otlpconfig.WithTracesHeaders(headers) return wrappedOption{otlpconfig.WithTracesHeaders(headers)}
} }
// WithMetricsHeaders will send the provided headers with gRPC metrics requests. // WithMetricsHeaders will send the provided headers with gRPC metrics requests.
func WithMetricsHeaders(headers map[string]string) Option { func WithMetricsHeaders(headers map[string]string) Option {
return otlpconfig.WithMetricsHeaders(headers) return wrappedOption{otlpconfig.WithMetricsHeaders(headers)}
} }
// WithTLSCredentials allows the connection to use TLS credentials // WithTLSCredentials allows the connection to use TLS credentials
@ -139,10 +147,10 @@ func WithMetricsHeaders(headers map[string]string) Option {
// these credentials can be done in many ways e.g. plain file, in code tls.Config // these credentials can be done in many ways e.g. plain file, in code tls.Config
// or by certificate rotation, so it is up to the caller to decide what to use. // or by certificate rotation, so it is up to the caller to decide what to use.
func WithTLSCredentials(creds credentials.TransportCredentials) Option { func WithTLSCredentials(creds credentials.TransportCredentials) Option {
return otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) { return wrappedOption{otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) {
cfg.Traces.GRPCCredentials = creds cfg.Traces.GRPCCredentials = creds
cfg.Metrics.GRPCCredentials = creds cfg.Metrics.GRPCCredentials = creds
}) })}
} }
// WithTracesTLSCredentials allows the connection to use TLS credentials // WithTracesTLSCredentials allows the connection to use TLS credentials
@ -151,9 +159,9 @@ func WithTLSCredentials(creds credentials.TransportCredentials) Option {
// these credentials can be done in many ways e.g. plain file, in code tls.Config // these credentials can be done in many ways e.g. plain file, in code tls.Config
// or by certificate rotation, so it is up to the caller to decide what to use. // or by certificate rotation, so it is up to the caller to decide what to use.
func WithTracesTLSCredentials(creds credentials.TransportCredentials) Option { func WithTracesTLSCredentials(creds credentials.TransportCredentials) Option {
return otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) { return wrappedOption{otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) {
cfg.Traces.GRPCCredentials = creds cfg.Traces.GRPCCredentials = creds
}) })}
} }
// WithMetricsTLSCredentials allows the connection to use TLS credentials // WithMetricsTLSCredentials allows the connection to use TLS credentials
@ -162,43 +170,43 @@ func WithTracesTLSCredentials(creds credentials.TransportCredentials) Option {
// these credentials can be done in many ways e.g. plain file, in code tls.Config // these credentials can be done in many ways e.g. plain file, in code tls.Config
// or by certificate rotation, so it is up to the caller to decide what to use. // or by certificate rotation, so it is up to the caller to decide what to use.
func WithMetricsTLSCredentials(creds credentials.TransportCredentials) Option { func WithMetricsTLSCredentials(creds credentials.TransportCredentials) Option {
return otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) { return wrappedOption{otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) {
cfg.Metrics.GRPCCredentials = creds cfg.Metrics.GRPCCredentials = creds
}) })}
} }
// WithServiceConfig defines the default gRPC service config used. // WithServiceConfig defines the default gRPC service config used.
func WithServiceConfig(serviceConfig string) Option { func WithServiceConfig(serviceConfig string) Option {
return otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) { return wrappedOption{otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) {
cfg.ServiceConfig = serviceConfig cfg.ServiceConfig = serviceConfig
}) })}
} }
// WithDialOption opens support to any grpc.DialOption to be used. If it conflicts // WithDialOption opens support to any grpc.DialOption to be used. If it conflicts
// with some other configuration the GRPC specified via the collector the ones here will // with some other configuration the GRPC specified via the collector the ones here will
// take preference since they are set last. // take preference since they are set last.
func WithDialOption(opts ...grpc.DialOption) Option { func WithDialOption(opts ...grpc.DialOption) Option {
return otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) { return wrappedOption{otlpconfig.NewGRPCOption(func(cfg *otlpconfig.Config) {
cfg.DialOptions = opts cfg.DialOptions = opts
}) })}
} }
// WithTimeout tells the driver the max waiting time for the backend to process // WithTimeout tells the driver the max waiting time for the backend to process
// each spans or metrics batch. If unset, the default will be 10 seconds. // each spans or metrics batch. If unset, the default will be 10 seconds.
func WithTimeout(duration time.Duration) Option { func WithTimeout(duration time.Duration) Option {
return otlpconfig.WithTimeout(duration) return wrappedOption{otlpconfig.WithTimeout(duration)}
} }
// WithTracesTimeout tells the driver the max waiting time for the backend to process // WithTracesTimeout tells the driver the max waiting time for the backend to process
// each spans batch. If unset, the default will be 10 seconds. // each spans batch. If unset, the default will be 10 seconds.
func WithTracesTimeout(duration time.Duration) Option { func WithTracesTimeout(duration time.Duration) Option {
return otlpconfig.WithTracesTimeout(duration) return wrappedOption{otlpconfig.WithTracesTimeout(duration)}
} }
// WithMetricsTimeout tells the driver the max waiting time for the backend to process // WithMetricsTimeout tells the driver the max waiting time for the backend to process
// each metrics batch. If unset, the default will be 10 seconds. // each metrics batch. If unset, the default will be 10 seconds.
func WithMetricsTimeout(duration time.Duration) Option { func WithMetricsTimeout(duration time.Duration) Option {
return otlpconfig.WithMetricsTimeout(duration) return wrappedOption{otlpconfig.WithMetricsTimeout(duration)}
} }
// WithRetry configures the retry policy for transient errors that may occurs when // WithRetry configures the retry policy for transient errors that may occurs when
@ -207,5 +215,5 @@ func WithMetricsTimeout(duration time.Duration) Option {
// retry policy will retry after 5 seconds and increase exponentially after each // retry policy will retry after 5 seconds and increase exponentially after each
// error for a total of 1 minute. // error for a total of 1 minute.
func WithRetry(settings otlp.RetrySettings) Option { func WithRetry(settings otlp.RetrySettings) Option {
return otlpconfig.WithRetry(settings) return wrappedOption{otlpconfig.WithRetry(settings)}
} }

View File

@ -86,7 +86,7 @@ func NewDriver(opts ...Option) otlp.ProtocolDriver {
cfg := otlpconfig.NewDefaultConfig() cfg := otlpconfig.NewDefaultConfig()
otlpconfig.ApplyHTTPEnvConfigs(&cfg) otlpconfig.ApplyHTTPEnvConfigs(&cfg)
for _, opt := range opts { for _, opt := range opts {
opt.ApplyHTTPOption(&cfg) opt.applyHTTPOption(&cfg)
} }
for pathPtr, defaultPath := range map[*string]string{ for pathPtr, defaultPath := range map[*string]string{

View File

@ -43,16 +43,24 @@ const (
// Option applies an option to the HTTP driver. // Option applies an option to the HTTP driver.
type Option interface { type Option interface {
applyHTTPOption(*otlpconfig.Config)
}
type wrappedOption struct {
otlpconfig.HTTPOption otlpconfig.HTTPOption
} }
func (w wrappedOption) applyHTTPOption(cfg *otlpconfig.Config) {
w.ApplyHTTPOption(cfg)
}
// WithEndpoint allows one to set the address of the collector // WithEndpoint allows one to set the address of the collector
// endpoint that the driver will use to send metrics and spans. If // endpoint that the driver will use to send metrics and spans. If
// unset, it will instead try to use // unset, it will instead try to use
// DefaultCollectorHost:DefaultCollectorPort. Note that the endpoint // DefaultCollectorHost:DefaultCollectorPort. Note that the endpoint
// must not contain any URL path. // must not contain any URL path.
func WithEndpoint(endpoint string) Option { func WithEndpoint(endpoint string) Option {
return otlpconfig.WithEndpoint(endpoint) return wrappedOption{otlpconfig.WithEndpoint(endpoint)}
} }
// WithTracesEndpoint allows one to set the address of the collector // WithTracesEndpoint allows one to set the address of the collector
@ -60,7 +68,7 @@ func WithEndpoint(endpoint string) Option {
// unset, it will instead try to use the Endpoint configuration. // unset, it will instead try to use the Endpoint configuration.
// Note that the endpoint must not contain any URL path. // Note that the endpoint must not contain any URL path.
func WithTracesEndpoint(endpoint string) Option { func WithTracesEndpoint(endpoint string) Option {
return otlpconfig.WithTracesEndpoint(endpoint) return wrappedOption{otlpconfig.WithTracesEndpoint(endpoint)}
} }
// WithMetricsEndpoint allows one to set the address of the collector // WithMetricsEndpoint allows one to set the address of the collector
@ -68,132 +76,132 @@ func WithTracesEndpoint(endpoint string) Option {
// unset, it will instead try to use the Endpoint configuration. // unset, it will instead try to use the Endpoint configuration.
// Note that the endpoint must not contain any URL path. // Note that the endpoint must not contain any URL path.
func WithMetricsEndpoint(endpoint string) Option { func WithMetricsEndpoint(endpoint string) Option {
return otlpconfig.WithMetricsEndpoint(endpoint) return wrappedOption{otlpconfig.WithMetricsEndpoint(endpoint)}
} }
// WithCompression tells the driver to compress the sent data. // WithCompression tells the driver to compress the sent data.
func WithCompression(compression otlp.Compression) Option { func WithCompression(compression otlp.Compression) Option {
return otlpconfig.WithCompression(compression) return wrappedOption{otlpconfig.WithCompression(compression)}
} }
// WithTracesCompression tells the driver to compress the sent traces data. // WithTracesCompression tells the driver to compress the sent traces data.
func WithTracesCompression(compression otlp.Compression) Option { func WithTracesCompression(compression otlp.Compression) Option {
return otlpconfig.WithTracesCompression(compression) return wrappedOption{otlpconfig.WithTracesCompression(compression)}
} }
// WithMetricsCompression tells the driver to compress the sent metrics data. // WithMetricsCompression tells the driver to compress the sent metrics data.
func WithMetricsCompression(compression otlp.Compression) Option { func WithMetricsCompression(compression otlp.Compression) Option {
return otlpconfig.WithMetricsCompression(compression) return wrappedOption{otlpconfig.WithMetricsCompression(compression)}
} }
// WithTracesURLPath allows one to override the default URL path used // WithTracesURLPath allows one to override the default URL path used
// for sending traces. If unset, DefaultTracesPath will be used. // for sending traces. If unset, DefaultTracesPath will be used.
func WithTracesURLPath(urlPath string) Option { func WithTracesURLPath(urlPath string) Option {
return otlpconfig.WithTracesURLPath(urlPath) return wrappedOption{otlpconfig.WithTracesURLPath(urlPath)}
} }
// WithMetricsURLPath allows one to override the default URL path used // WithMetricsURLPath allows one to override the default URL path used
// for sending metrics. If unset, DefaultMetricsPath will be used. // for sending metrics. If unset, DefaultMetricsPath will be used.
func WithMetricsURLPath(urlPath string) Option { func WithMetricsURLPath(urlPath string) Option {
return otlpconfig.WithMetricsURLPath(urlPath) return wrappedOption{otlpconfig.WithMetricsURLPath(urlPath)}
} }
// WithMaxAttempts allows one to override how many times the driver // WithMaxAttempts allows one to override how many times the driver
// will try to send the payload in case of retryable errors. If unset, // will try to send the payload in case of retryable errors. If unset,
// DefaultMaxAttempts will be used. // DefaultMaxAttempts will be used.
func WithMaxAttempts(maxAttempts int) Option { func WithMaxAttempts(maxAttempts int) Option {
return otlpconfig.WithMaxAttempts(maxAttempts) return wrappedOption{otlpconfig.WithMaxAttempts(maxAttempts)}
} }
// WithBackoff tells the driver to use the duration as a base of the // WithBackoff tells the driver to use the duration as a base of the
// exponential backoff strategy. If unset, DefaultBackoff will be // exponential backoff strategy. If unset, DefaultBackoff will be
// used. // used.
func WithBackoff(duration time.Duration) Option { func WithBackoff(duration time.Duration) Option {
return otlpconfig.WithBackoff(duration) return wrappedOption{otlpconfig.WithBackoff(duration)}
} }
// WithTLSClientConfig can be used to set up a custom TLS // WithTLSClientConfig can be used to set up a custom TLS
// configuration for the client used to send payloads to the // configuration for the client used to send payloads to the
// collector. Use it if you want to use a custom certificate. // collector. Use it if you want to use a custom certificate.
func WithTLSClientConfig(tlsCfg *tls.Config) Option { func WithTLSClientConfig(tlsCfg *tls.Config) Option {
return otlpconfig.WithTLSClientConfig(tlsCfg) return wrappedOption{otlpconfig.WithTLSClientConfig(tlsCfg)}
} }
// WithTracesTLSClientConfig can be used to set up a custom TLS // WithTracesTLSClientConfig can be used to set up a custom TLS
// configuration for the client used to send traces. // configuration for the client used to send traces.
// Use it if you want to use a custom certificate. // Use it if you want to use a custom certificate.
func WithTracesTLSClientConfig(tlsCfg *tls.Config) Option { func WithTracesTLSClientConfig(tlsCfg *tls.Config) Option {
return otlpconfig.WithTracesTLSClientConfig(tlsCfg) return wrappedOption{otlpconfig.WithTracesTLSClientConfig(tlsCfg)}
} }
// WithMetricsTLSClientConfig can be used to set up a custom TLS // WithMetricsTLSClientConfig can be used to set up a custom TLS
// configuration for the client used to send metrics. // configuration for the client used to send metrics.
// Use it if you want to use a custom certificate. // Use it if you want to use a custom certificate.
func WithMetricsTLSClientConfig(tlsCfg *tls.Config) Option { func WithMetricsTLSClientConfig(tlsCfg *tls.Config) Option {
return otlpconfig.WithMetricsTLSClientConfig(tlsCfg) return wrappedOption{otlpconfig.WithMetricsTLSClientConfig(tlsCfg)}
} }
// WithInsecure tells the driver to connect to the collector using the // WithInsecure tells the driver to connect to the collector using the
// HTTP scheme, instead of HTTPS. // HTTP scheme, instead of HTTPS.
func WithInsecure() Option { func WithInsecure() Option {
return otlpconfig.WithInsecure() return wrappedOption{otlpconfig.WithInsecure()}
} }
// WithInsecureTraces tells the driver to connect to the traces collector using the // WithInsecureTraces tells the driver to connect to the traces collector using the
// HTTP scheme, instead of HTTPS. // HTTP scheme, instead of HTTPS.
func WithInsecureTraces() Option { func WithInsecureTraces() Option {
return otlpconfig.WithInsecureTraces() return wrappedOption{otlpconfig.WithInsecureTraces()}
} }
// WithInsecureMetrics tells the driver to connect to the metrics collector using the // WithInsecureMetrics tells the driver to connect to the metrics collector using the
// HTTP scheme, instead of HTTPS. // HTTP scheme, instead of HTTPS.
func WithInsecureMetrics() Option { func WithInsecureMetrics() Option {
return otlpconfig.WithInsecureMetrics() return wrappedOption{otlpconfig.WithInsecureMetrics()}
} }
// WithHeaders allows one to tell the driver to send additional HTTP // WithHeaders allows one to tell the driver to send additional HTTP
// headers with the payloads. Specifying headers like Content-Length, // headers with the payloads. Specifying headers like Content-Length,
// Content-Encoding and Content-Type may result in a broken driver. // Content-Encoding and Content-Type may result in a broken driver.
func WithHeaders(headers map[string]string) Option { func WithHeaders(headers map[string]string) Option {
return otlpconfig.WithHeaders(headers) return wrappedOption{otlpconfig.WithHeaders(headers)}
} }
// WithTracesHeaders allows one to tell the driver to send additional HTTP // WithTracesHeaders allows one to tell the driver to send additional HTTP
// headers with the trace payloads. Specifying headers like Content-Length, // headers with the trace payloads. Specifying headers like Content-Length,
// Content-Encoding and Content-Type may result in a broken driver. // Content-Encoding and Content-Type may result in a broken driver.
func WithTracesHeaders(headers map[string]string) Option { func WithTracesHeaders(headers map[string]string) Option {
return otlpconfig.WithTracesHeaders(headers) return wrappedOption{otlpconfig.WithTracesHeaders(headers)}
} }
// WithMetricsHeaders allows one to tell the driver to send additional HTTP // WithMetricsHeaders allows one to tell the driver to send additional HTTP
// headers with the metrics payloads. Specifying headers like Content-Length, // headers with the metrics payloads. Specifying headers like Content-Length,
// Content-Encoding and Content-Type may result in a broken driver. // Content-Encoding and Content-Type may result in a broken driver.
func WithMetricsHeaders(headers map[string]string) Option { func WithMetricsHeaders(headers map[string]string) Option {
return otlpconfig.WithMetricsHeaders(headers) return wrappedOption{otlpconfig.WithMetricsHeaders(headers)}
} }
// WithMarshal tells the driver which wire format to use when sending to the // WithMarshal tells the driver which wire format to use when sending to the
// collector. If unset, MarshalProto will be used // collector. If unset, MarshalProto will be used
func WithMarshal(m otlp.Marshaler) Option { func WithMarshal(m otlp.Marshaler) Option {
return otlpconfig.NewHTTPOption(func(cfg *otlpconfig.Config) { return wrappedOption{otlpconfig.NewHTTPOption(func(cfg *otlpconfig.Config) {
cfg.Marshaler = m cfg.Marshaler = m
}) })}
} }
// WithTimeout tells the driver the max waiting time for the backend to process // WithTimeout tells the driver the max waiting time for the backend to process
// each spans or metrics batch. If unset, the default will be 10 seconds. // each spans or metrics batch. If unset, the default will be 10 seconds.
func WithTimeout(duration time.Duration) Option { func WithTimeout(duration time.Duration) Option {
return otlpconfig.WithTimeout(duration) return wrappedOption{otlpconfig.WithTimeout(duration)}
} }
// WithTracesTimeout tells the driver the max waiting time for the backend to process // WithTracesTimeout tells the driver the max waiting time for the backend to process
// each spans batch. If unset, the default will be 10 seconds. // each spans batch. If unset, the default will be 10 seconds.
func WithTracesTimeout(duration time.Duration) Option { func WithTracesTimeout(duration time.Duration) Option {
return otlpconfig.WithTracesTimeout(duration) return wrappedOption{otlpconfig.WithTracesTimeout(duration)}
} }
// WithMetricsTimeout tells the driver the max waiting time for the backend to process // WithMetricsTimeout tells the driver the max waiting time for the backend to process
// each metrics batch. If unset, the default will be 10 seconds. // each metrics batch. If unset, the default will be 10 seconds.
func WithMetricsTimeout(duration time.Duration) Option { func WithMetricsTimeout(duration time.Duration) Option {
return otlpconfig.WithMetricsTimeout(duration) return wrappedOption{otlpconfig.WithMetricsTimeout(duration)}
} }

View File

@ -84,7 +84,7 @@ func NewSplitDriver(opts ...SplitDriverOption) ProtocolDriver {
trace: &noopDriver{}, trace: &noopDriver{},
} }
for _, opt := range opts { for _, opt := range opts {
opt.Apply(&driver) opt.apply(&driver)
} }
return &driver return &driver
} }

View File

@ -30,8 +30,8 @@ var (
defaultDisableMetricExport = false defaultDisableMetricExport = false
) )
// Config contains options for the STDOUT exporter. // config contains options for the STDOUT exporter.
type Config struct { type config struct {
// Writer is the destination. If not set, os.Stdout is used. // Writer is the destination. If not set, os.Stdout is used.
Writer io.Writer Writer io.Writer
@ -53,9 +53,9 @@ type Config struct {
DisableMetricExport bool DisableMetricExport bool
} }
// NewConfig creates a validated Config configured with options. // newConfig creates a validated Config configured with options.
func NewConfig(options ...Option) (Config, error) { func newConfig(options ...Option) (config, error) {
config := Config{ cfg := config{
Writer: defaultWriter, Writer: defaultWriter,
PrettyPrint: defaultPrettyPrint, PrettyPrint: defaultPrettyPrint,
Timestamps: defaultTimestamps, Timestamps: defaultTimestamps,
@ -64,21 +64,15 @@ func NewConfig(options ...Option) (Config, error) {
DisableMetricExport: defaultDisableMetricExport, DisableMetricExport: defaultDisableMetricExport,
} }
for _, opt := range options { for _, opt := range options {
opt.Apply(&config) opt.apply(&cfg)
} }
return config, nil return cfg, nil
} }
// Option sets the value of an option for a Config. // Option sets the value of an option for a Config.
type Option interface { type Option interface {
// Apply option value to Config. apply(*config)
Apply(*Config)
// A private method to prevent users implementing the
// interface and so future additions to it will not
// violate compatibility.
private()
} }
// WithWriter sets the export stream destination. // WithWriter sets the export stream destination.
@ -90,12 +84,10 @@ type writerOption struct {
W io.Writer W io.Writer
} }
func (o writerOption) Apply(config *Config) { func (o writerOption) apply(cfg *config) {
config.Writer = o.W cfg.Writer = o.W
} }
func (writerOption) private() {}
// WithPrettyPrint sets the export stream format to use JSON. // WithPrettyPrint sets the export stream format to use JSON.
func WithPrettyPrint() Option { func WithPrettyPrint() Option {
return prettyPrintOption(true) return prettyPrintOption(true)
@ -103,12 +95,10 @@ func WithPrettyPrint() Option {
type prettyPrintOption bool type prettyPrintOption bool
func (o prettyPrintOption) Apply(config *Config) { func (o prettyPrintOption) apply(cfg *config) {
config.PrettyPrint = bool(o) cfg.PrettyPrint = bool(o)
} }
func (prettyPrintOption) private() {}
// WithoutTimestamps sets the export stream to not include timestamps. // WithoutTimestamps sets the export stream to not include timestamps.
func WithoutTimestamps() Option { func WithoutTimestamps() Option {
return timestampsOption(false) return timestampsOption(false)
@ -116,12 +106,10 @@ func WithoutTimestamps() Option {
type timestampsOption bool type timestampsOption bool
func (o timestampsOption) Apply(config *Config) { func (o timestampsOption) apply(cfg *config) {
config.Timestamps = bool(o) cfg.Timestamps = bool(o)
} }
func (timestampsOption) private() {}
// WithLabelEncoder sets the label encoder used in export. // WithLabelEncoder sets the label encoder used in export.
func WithLabelEncoder(enc attribute.Encoder) Option { func WithLabelEncoder(enc attribute.Encoder) Option {
return labelEncoderOption{enc} return labelEncoderOption{enc}
@ -131,12 +119,10 @@ type labelEncoderOption struct {
LabelEncoder attribute.Encoder LabelEncoder attribute.Encoder
} }
func (o labelEncoderOption) Apply(config *Config) { func (o labelEncoderOption) apply(cfg *config) {
config.LabelEncoder = o.LabelEncoder cfg.LabelEncoder = o.LabelEncoder
} }
func (labelEncoderOption) private() {}
// WithoutTraceExport disables all trace exporting. // WithoutTraceExport disables all trace exporting.
func WithoutTraceExport() Option { func WithoutTraceExport() Option {
return disableTraceExportOption(true) return disableTraceExportOption(true)
@ -144,12 +130,10 @@ func WithoutTraceExport() Option {
type disableTraceExportOption bool type disableTraceExportOption bool
func (o disableTraceExportOption) Apply(config *Config) { func (o disableTraceExportOption) apply(cfg *config) {
config.DisableTraceExport = bool(o) cfg.DisableTraceExport = bool(o)
} }
func (disableTraceExportOption) private() {}
// WithoutMetricExport disables all metric exporting. // WithoutMetricExport disables all metric exporting.
func WithoutMetricExport() Option { func WithoutMetricExport() Option {
return disableMetricExportOption(true) return disableMetricExportOption(true)
@ -157,8 +141,6 @@ func WithoutMetricExport() Option {
type disableMetricExportOption bool type disableMetricExportOption bool
func (o disableMetricExportOption) Apply(config *Config) { func (o disableMetricExportOption) apply(cfg *config) {
config.DisableMetricExport = bool(o) cfg.DisableMetricExport = bool(o)
} }
func (disableMetricExportOption) private() {}

View File

@ -38,13 +38,13 @@ var (
// NewExporter creates an Exporter with the passed options. // NewExporter creates an Exporter with the passed options.
func NewExporter(options ...Option) (*Exporter, error) { func NewExporter(options ...Option) (*Exporter, error) {
config, err := NewConfig(options...) cfg, err := newConfig(options...)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &Exporter{ return &Exporter{
traceExporter: traceExporter{config: config}, traceExporter: traceExporter{config: cfg},
metricExporter: metricExporter{config}, metricExporter: metricExporter{cfg},
}, nil }, nil
} }

View File

@ -28,7 +28,7 @@ import (
) )
type metricExporter struct { type metricExporter struct {
config Config config config
} }
var _ exportmetric.Exporter = &metricExporter{} var _ exportmetric.Exporter = &metricExporter{}

View File

@ -26,7 +26,7 @@ import (
// Exporter is an implementation of trace.SpanSyncer that writes spans to stdout. // Exporter is an implementation of trace.SpanSyncer that writes spans to stdout.
type traceExporter struct { type traceExporter struct {
config Config config config
stoppedMu sync.RWMutex stoppedMu sync.RWMutex
stopped bool stopped bool

View File

@ -180,20 +180,20 @@ func TestEnvOrWithCollectorEndpointOptionsFromEnv(t *testing.T) {
envEndpoint string envEndpoint string
envUsername string envUsername string
envPassword string envPassword string
defaultCollectorEndpointOptions CollectorEndpointOptions defaultCollectorEndpointOptions collectorEndpointConfig
expectedCollectorEndpointOptions CollectorEndpointOptions expectedCollectorEndpointOptions collectorEndpointConfig
}{ }{
{ {
name: "overrides value via environment variables", name: "overrides value via environment variables",
envEndpoint: "http://localhost:14252", envEndpoint: "http://localhost:14252",
envUsername: "username", envUsername: "username",
envPassword: "password", envPassword: "password",
defaultCollectorEndpointOptions: CollectorEndpointOptions{ defaultCollectorEndpointOptions: collectorEndpointConfig{
endpoint: "endpoint not to be used", endpoint: "endpoint not to be used",
username: "foo", username: "foo",
password: "bar", password: "bar",
}, },
expectedCollectorEndpointOptions: CollectorEndpointOptions{ expectedCollectorEndpointOptions: collectorEndpointConfig{
endpoint: "http://localhost:14252", endpoint: "http://localhost:14252",
username: "username", username: "username",
password: "password", password: "password",
@ -204,12 +204,12 @@ func TestEnvOrWithCollectorEndpointOptionsFromEnv(t *testing.T) {
envEndpoint: "", envEndpoint: "",
envUsername: "", envUsername: "",
envPassword: "", envPassword: "",
defaultCollectorEndpointOptions: CollectorEndpointOptions{ defaultCollectorEndpointOptions: collectorEndpointConfig{
endpoint: "endpoint to be used", endpoint: "endpoint to be used",
username: "foo", username: "foo",
password: "bar", password: "bar",
}, },
expectedCollectorEndpointOptions: CollectorEndpointOptions{ expectedCollectorEndpointOptions: collectorEndpointConfig{
endpoint: "endpoint to be used", endpoint: "endpoint to be used",
username: "foo", username: "foo",
password: "bar", password: "bar",

View File

@ -45,7 +45,7 @@ const (
// NewRawExporter returns an OTel Exporter implementation that exports the // NewRawExporter returns an OTel Exporter implementation that exports the
// collected spans to Jaeger. // collected spans to Jaeger.
func NewRawExporter(endpointOption EndpointOption) (*Exporter, error) { func NewRawExporter(endpointOption EndpointOption) (*Exporter, error) {
uploader, err := endpointOption() uploader, err := endpointOption.newBatchUploader()
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -63,9 +63,9 @@ func TestNewExportPipelinePassthroughError(t *testing.T) {
{ {
name: "failing underlying NewRawExporter", name: "failing underlying NewRawExporter",
failing: true, failing: true,
epo: func() (batchUploader, error) { epo: endpointOptionFunc(func() (batchUploader, error) {
return nil, errors.New("error") return nil, errors.New("error")
}, }),
}, },
{ {
name: "with default agent endpoint", name: "with default agent endpoint",
@ -142,16 +142,16 @@ func (c *testCollectorEndpoint) upload(_ context.Context, batch *gen.Batch) erro
var _ batchUploader = (*testCollectorEndpoint)(nil) var _ batchUploader = (*testCollectorEndpoint)(nil)
func withTestCollectorEndpoint() func() (batchUploader, error) { func withTestCollectorEndpoint() EndpointOption {
return func() (batchUploader, error) { return endpointOptionFunc(func() (batchUploader, error) {
return &testCollectorEndpoint{}, nil return &testCollectorEndpoint{}, nil
} })
} }
func withTestCollectorEndpointInjected(ce *testCollectorEndpoint) func() (batchUploader, error) { func withTestCollectorEndpointInjected(ce *testCollectorEndpoint) EndpointOption {
return func() (batchUploader, error) { return endpointOptionFunc(func() (batchUploader, error) {
return ce, nil return ce, nil
} })
} }
func TestExporterExportSpan(t *testing.T) { func TestExporterExportSpan(t *testing.T) {

View File

@ -35,7 +35,15 @@ type batchUploader interface {
shutdown(context.Context) error shutdown(context.Context) error
} }
type EndpointOption func() (batchUploader, error) type EndpointOption interface {
newBatchUploader() (batchUploader, error)
}
type endpointOptionFunc func() (batchUploader, error)
func (fn endpointOptionFunc) newBatchUploader() (batchUploader, error) {
return fn()
}
// WithAgentEndpoint configures the Jaeger exporter to send spans to a jaeger-agent. This will // WithAgentEndpoint configures the Jaeger exporter to send spans to a jaeger-agent. This will
// use the following environment variables for configuration if no explicit option is provided: // use the following environment variables for configuration if no explicit option is provided:
@ -46,8 +54,8 @@ type EndpointOption func() (batchUploader, error)
// The passed options will take precedence over any environment variables and default values // The passed options will take precedence over any environment variables and default values
// will be used if neither are provided. // will be used if neither are provided.
func WithAgentEndpoint(options ...AgentEndpointOption) EndpointOption { func WithAgentEndpoint(options ...AgentEndpointOption) EndpointOption {
return func() (batchUploader, error) { return endpointOptionFunc(func() (batchUploader, error) {
o := &AgentEndpointOptions{ cfg := &agentEndpointConfig{
agentClientUDPParams{ agentClientUDPParams{
AttemptReconnecting: true, AttemptReconnecting: true,
Host: envOr(envAgentHost, "localhost"), Host: envOr(envAgentHost, "localhost"),
@ -55,32 +63,40 @@ func WithAgentEndpoint(options ...AgentEndpointOption) EndpointOption {
}, },
} }
for _, opt := range options { for _, opt := range options {
opt(o) opt.apply(cfg)
} }
client, err := newAgentClientUDP(o.agentClientUDPParams) client, err := newAgentClientUDP(cfg.agentClientUDPParams)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &agentUploader{client: client}, nil return &agentUploader{client: client}, nil
} })
} }
type AgentEndpointOption func(o *AgentEndpointOptions) type AgentEndpointOption interface {
apply(*agentEndpointConfig)
}
type AgentEndpointOptions struct { type agentEndpointConfig struct {
agentClientUDPParams agentClientUDPParams
} }
type agentEndpointOptionFunc func(*agentEndpointConfig)
func (fn agentEndpointOptionFunc) apply(cfg *agentEndpointConfig) {
fn(cfg)
}
// WithAgentHost sets a host to be used in the agent client endpoint. // WithAgentHost sets a host to be used in the agent client endpoint.
// This option overrides any value set for the // This option overrides any value set for the
// OTEL_EXPORTER_JAEGER_AGENT_HOST environment variable. // OTEL_EXPORTER_JAEGER_AGENT_HOST environment variable.
// If this option is not passed and the env var is not set, "localhost" will be used by default. // If this option is not passed and the env var is not set, "localhost" will be used by default.
func WithAgentHost(host string) AgentEndpointOption { func WithAgentHost(host string) AgentEndpointOption {
return func(o *AgentEndpointOptions) { return agentEndpointOptionFunc(func(o *agentEndpointConfig) {
o.Host = host o.Host = host
} })
} }
// WithAgentPort sets a port to be used in the agent client endpoint. // WithAgentPort sets a port to be used in the agent client endpoint.
@ -88,37 +104,37 @@ func WithAgentHost(host string) AgentEndpointOption {
// OTEL_EXPORTER_JAEGER_AGENT_PORT environment variable. // OTEL_EXPORTER_JAEGER_AGENT_PORT environment variable.
// If this option is not passed and the env var is not set, "6832" will be used by default. // If this option is not passed and the env var is not set, "6832" will be used by default.
func WithAgentPort(port string) AgentEndpointOption { func WithAgentPort(port string) AgentEndpointOption {
return func(o *AgentEndpointOptions) { return agentEndpointOptionFunc(func(o *agentEndpointConfig) {
o.Port = port o.Port = port
} })
} }
// WithLogger sets a logger to be used by agent client. // WithLogger sets a logger to be used by agent client.
func WithLogger(logger *log.Logger) AgentEndpointOption { func WithLogger(logger *log.Logger) AgentEndpointOption {
return func(o *AgentEndpointOptions) { return agentEndpointOptionFunc(func(o *agentEndpointConfig) {
o.Logger = logger o.Logger = logger
} })
} }
// WithDisableAttemptReconnecting sets option to disable reconnecting udp client. // WithDisableAttemptReconnecting sets option to disable reconnecting udp client.
func WithDisableAttemptReconnecting() AgentEndpointOption { func WithDisableAttemptReconnecting() AgentEndpointOption {
return func(o *AgentEndpointOptions) { return agentEndpointOptionFunc(func(o *agentEndpointConfig) {
o.AttemptReconnecting = false o.AttemptReconnecting = false
} })
} }
// WithAttemptReconnectingInterval sets the interval between attempts to re resolve agent endpoint. // WithAttemptReconnectingInterval sets the interval between attempts to re resolve agent endpoint.
func WithAttemptReconnectingInterval(interval time.Duration) AgentEndpointOption { func WithAttemptReconnectingInterval(interval time.Duration) AgentEndpointOption {
return func(o *AgentEndpointOptions) { return agentEndpointOptionFunc(func(o *agentEndpointConfig) {
o.AttemptReconnectInterval = interval o.AttemptReconnectInterval = interval
} })
} }
// WithMaxPacketSize sets the maximum UDP packet size for transport to the Jaeger agent. // WithMaxPacketSize sets the maximum UDP packet size for transport to the Jaeger agent.
func WithMaxPacketSize(size int) AgentEndpointOption { func WithMaxPacketSize(size int) AgentEndpointOption {
return func(o *AgentEndpointOptions) { return agentEndpointOptionFunc(func(o *agentEndpointConfig) {
o.MaxPacketSize = size o.MaxPacketSize = size
} })
} }
// WithCollectorEndpoint defines the full url to the Jaeger HTTP Thrift collector. This will // WithCollectorEndpoint defines the full url to the Jaeger HTTP Thrift collector. This will
@ -132,8 +148,8 @@ func WithMaxPacketSize(size int) AgentEndpointOption {
// If neither values are provided for the endpoint, the default value of "http://localhost:14268/api/traces" will be used. // If neither values are provided for the endpoint, the default value of "http://localhost:14268/api/traces" will be used.
// If neither values are provided for the username or the password, they will not be set since there is no default. // If neither values are provided for the username or the password, they will not be set since there is no default.
func WithCollectorEndpoint(options ...CollectorEndpointOption) EndpointOption { func WithCollectorEndpoint(options ...CollectorEndpointOption) EndpointOption {
return func() (batchUploader, error) { return endpointOptionFunc(func() (batchUploader, error) {
o := &CollectorEndpointOptions{ cfg := &collectorEndpointConfig{
endpoint: envOr(envEndpoint, "http://localhost:14268/api/traces"), endpoint: envOr(envEndpoint, "http://localhost:14268/api/traces"),
username: envOr(envUser, ""), username: envOr(envUser, ""),
password: envOr(envPassword, ""), password: envOr(envPassword, ""),
@ -141,21 +157,23 @@ func WithCollectorEndpoint(options ...CollectorEndpointOption) EndpointOption {
} }
for _, opt := range options { for _, opt := range options {
opt(o) opt.apply(cfg)
} }
return &collectorUploader{ return &collectorUploader{
endpoint: o.endpoint, endpoint: cfg.endpoint,
username: o.username, username: cfg.username,
password: o.password, password: cfg.password,
httpClient: o.httpClient, httpClient: cfg.httpClient,
}, nil }, nil
} })
} }
type CollectorEndpointOption func(o *CollectorEndpointOptions) type CollectorEndpointOption interface {
apply(*collectorEndpointConfig)
}
type CollectorEndpointOptions struct { type collectorEndpointConfig struct {
// endpoint for sending spans directly to a collector. // endpoint for sending spans directly to a collector.
endpoint string endpoint string
@ -169,15 +187,21 @@ type CollectorEndpointOptions struct {
httpClient *http.Client httpClient *http.Client
} }
type collectorEndpointOptionFunc func(*collectorEndpointConfig)
func (fn collectorEndpointOptionFunc) apply(cfg *collectorEndpointConfig) {
fn(cfg)
}
// WithEndpoint is the URL for the Jaeger collector that spans are sent to. // WithEndpoint is the URL for the Jaeger collector that spans are sent to.
// This option overrides any value set for the // This option overrides any value set for the
// OTEL_EXPORTER_JAEGER_ENDPOINT environment variable. // OTEL_EXPORTER_JAEGER_ENDPOINT environment variable.
// If this option is not passed and the environment variable is not set, // If this option is not passed and the environment variable is not set,
// "http://localhost:14268/api/traces" will be used by default. // "http://localhost:14268/api/traces" will be used by default.
func WithEndpoint(endpoint string) CollectorEndpointOption { func WithEndpoint(endpoint string) CollectorEndpointOption {
return func(o *CollectorEndpointOptions) { return collectorEndpointOptionFunc(func(o *collectorEndpointConfig) {
o.endpoint = endpoint o.endpoint = endpoint
} })
} }
// WithUsername sets the username to be used in the authorization header sent for all requests to the collector. // WithUsername sets the username to be used in the authorization header sent for all requests to the collector.
@ -185,9 +209,9 @@ func WithEndpoint(endpoint string) CollectorEndpointOption {
// OTEL_EXPORTER_JAEGER_USER environment variable. // OTEL_EXPORTER_JAEGER_USER environment variable.
// If this option is not passed and the environment variable is not set, no username will be set. // If this option is not passed and the environment variable is not set, no username will be set.
func WithUsername(username string) CollectorEndpointOption { func WithUsername(username string) CollectorEndpointOption {
return func(o *CollectorEndpointOptions) { return collectorEndpointOptionFunc(func(o *collectorEndpointConfig) {
o.username = username o.username = username
} })
} }
// WithPassword sets the password to be used in the authorization header sent for all requests to the collector. // WithPassword sets the password to be used in the authorization header sent for all requests to the collector.
@ -195,16 +219,16 @@ func WithUsername(username string) CollectorEndpointOption {
// OTEL_EXPORTER_JAEGER_PASSWORD environment variable. // OTEL_EXPORTER_JAEGER_PASSWORD environment variable.
// If this option is not passed and the environment variable is not set, no password will be set. // If this option is not passed and the environment variable is not set, no password will be set.
func WithPassword(password string) CollectorEndpointOption { func WithPassword(password string) CollectorEndpointOption {
return func(o *CollectorEndpointOptions) { return collectorEndpointOptionFunc(func(o *collectorEndpointConfig) {
o.password = password o.password = password
} })
} }
// WithHTTPClient sets the http client to be used to make request to the collector endpoint. // WithHTTPClient sets the http client to be used to make request to the collector endpoint.
func WithHTTPClient(client *http.Client) CollectorEndpointOption { func WithHTTPClient(client *http.Client) CollectorEndpointOption {
return func(o *CollectorEndpointOptions) { return collectorEndpointOptionFunc(func(o *collectorEndpointConfig) {
o.httpClient = client o.httpClient = client
} })
} }
// agentUploader implements batchUploader interface sending batches to // agentUploader implements batchUploader interface sending batches to

View File

@ -36,7 +36,7 @@ type Exporter struct {
url string url string
client *http.Client client *http.Client
logger *log.Logger logger *log.Logger
o options config config
stoppedMu sync.RWMutex stoppedMu sync.RWMutex
stopped bool stopped bool
@ -47,34 +47,42 @@ var (
) )
// Options contains configuration for the exporter. // Options contains configuration for the exporter.
type options struct { type config struct {
client *http.Client client *http.Client
logger *log.Logger logger *log.Logger
tpOpts []sdktrace.TracerProviderOption tpOpts []sdktrace.TracerProviderOption
} }
// Option defines a function that configures the exporter. // Option defines a function that configures the exporter.
type Option func(*options) type Option interface {
apply(*config)
}
type optionFunc func(*config)
func (fn optionFunc) apply(cfg *config) {
fn(cfg)
}
// WithLogger configures the exporter to use the passed logger. // WithLogger configures the exporter to use the passed logger.
func WithLogger(logger *log.Logger) Option { func WithLogger(logger *log.Logger) Option {
return func(opts *options) { return optionFunc(func(cfg *config) {
opts.logger = logger cfg.logger = logger
} })
} }
// WithClient configures the exporter to use the passed HTTP client. // WithClient configures the exporter to use the passed HTTP client.
func WithClient(client *http.Client) Option { func WithClient(client *http.Client) Option {
return func(opts *options) { return optionFunc(func(cfg *config) {
opts.client = client cfg.client = client
} })
} }
// WithSDKOptions configures options passed to the created TracerProvider. // WithSDKOptions configures options passed to the created TracerProvider.
func WithSDKOptions(tpOpts ...sdktrace.TracerProviderOption) Option { func WithSDKOptions(tpOpts ...sdktrace.TracerProviderOption) Option {
return func(opts *options) { return optionFunc(func(cfg *config) {
opts.tpOpts = tpOpts cfg.tpOpts = tpOpts
} })
} }
// NewRawExporter creates a new Zipkin exporter. // NewRawExporter creates a new Zipkin exporter.
@ -90,18 +98,18 @@ func NewRawExporter(collectorURL string, opts ...Option) (*Exporter, error) {
return nil, errors.New("invalid collector URL") return nil, errors.New("invalid collector URL")
} }
o := options{} cfg := config{}
for _, opt := range opts { for _, opt := range opts {
opt(&o) opt.apply(&cfg)
} }
if o.client == nil { if cfg.client == nil {
o.client = http.DefaultClient cfg.client = http.DefaultClient
} }
return &Exporter{ return &Exporter{
url: collectorURL, url: collectorURL,
client: o.client, client: cfg.client,
logger: o.logger, logger: cfg.logger,
o: o, config: cfg,
}, nil }, nil
} }
@ -113,7 +121,7 @@ func NewExportPipeline(collectorURL string, opts ...Option) (*sdktrace.TracerPro
return nil, err return nil, err
} }
tpOpts := append(exporter.o.tpOpts, sdktrace.WithBatcher(exporter)) tpOpts := append(exporter.config.tpOpts, sdktrace.WithBatcher(exporter))
tp := sdktrace.NewTracerProvider(tpOpts...) tp := sdktrace.NewTracerProvider(tpOpts...)
return tp, err return tp, err

View File

@ -53,7 +53,7 @@ type config struct {
func newConfig(opts ...Option) config { func newConfig(opts ...Option) config {
conf := config{} conf := config{}
for _, opt := range opts { for _, opt := range opts {
opt.Apply(&conf) opt.apply(&conf)
} }
if conf.SpanContextFunc == nil { if conf.SpanContextFunc == nil {
conf.SpanContextFunc = defaultSpanContextFunc() conf.SpanContextFunc = defaultSpanContextFunc()
@ -63,24 +63,14 @@ func newConfig(opts ...Option) config {
// Option applies an option to a config. // Option applies an option to a config.
type Option interface { type Option interface {
Apply(*config) apply(*config)
// A private method to prevent users implementing the
// interface and so future additions to it will not
// violate compatibility.
private()
} }
type option struct{}
func (option) private() {}
type spanContextFuncOption struct { type spanContextFuncOption struct {
option
SpanContextFunc func(context.Context) trace.SpanContext SpanContextFunc func(context.Context) trace.SpanContext
} }
func (o spanContextFuncOption) Apply(c *config) { func (o spanContextFuncOption) apply(c *config) {
c.SpanContextFunc = o.SpanContextFunc c.SpanContextFunc = o.SpanContextFunc
} }
@ -91,11 +81,10 @@ func WithSpanContextFunc(f func(context.Context) trace.SpanContext) Option {
} }
type spanRecorderOption struct { type spanRecorderOption struct {
option
SpanRecorder *SpanRecorder SpanRecorder *SpanRecorder
} }
func (o spanRecorderOption) Apply(c *config) { func (o spanRecorderOption) apply(c *config) {
c.SpanRecorder = o.SpanRecorder c.SpanRecorder = o.SpanRecorder
} }

View File

@ -21,8 +21,8 @@ import (
"go.opentelemetry.io/otel/sdk/resource" "go.opentelemetry.io/otel/sdk/resource"
) )
// Config contains configuration for a basic Controller. // config contains configuration for a basic Controller.
type Config struct { type config struct {
// Resource is the OpenTelemetry resource associated with all Meters // Resource is the OpenTelemetry resource associated with all Meters
// created by the Controller. // created by the Controller.
Resource *resource.Resource Resource *resource.Resource
@ -60,8 +60,8 @@ type Config struct {
// Option is the interface that applies the value to a configuration option. // Option is the interface that applies the value to a configuration option.
type Option interface { type Option interface {
// Apply sets the Option value of a Config. // apply sets the Option value of a Config.
Apply(*Config) apply(*config)
} }
// WithResource sets the Resource configuration option of a Config by merging it // WithResource sets the Resource configuration option of a Config by merging it
@ -73,8 +73,8 @@ func WithResource(r *resource.Resource) Option {
type resourceOption struct{ *resource.Resource } type resourceOption struct{ *resource.Resource }
func (o resourceOption) Apply(config *Config) { func (o resourceOption) apply(cfg *config) {
config.Resource = o.Resource cfg.Resource = o.Resource
} }
// WithCollectPeriod sets the CollectPeriod configuration option of a Config. // WithCollectPeriod sets the CollectPeriod configuration option of a Config.
@ -84,8 +84,8 @@ func WithCollectPeriod(period time.Duration) Option {
type collectPeriodOption time.Duration type collectPeriodOption time.Duration
func (o collectPeriodOption) Apply(config *Config) { func (o collectPeriodOption) apply(cfg *config) {
config.CollectPeriod = time.Duration(o) cfg.CollectPeriod = time.Duration(o)
} }
// WithCollectTimeout sets the CollectTimeout configuration option of a Config. // WithCollectTimeout sets the CollectTimeout configuration option of a Config.
@ -95,8 +95,8 @@ func WithCollectTimeout(timeout time.Duration) Option {
type collectTimeoutOption time.Duration type collectTimeoutOption time.Duration
func (o collectTimeoutOption) Apply(config *Config) { func (o collectTimeoutOption) apply(cfg *config) {
config.CollectTimeout = time.Duration(o) cfg.CollectTimeout = time.Duration(o)
} }
// WithExporter sets the exporter configuration option of a Config. // WithExporter sets the exporter configuration option of a Config.
@ -106,8 +106,8 @@ func WithExporter(exporter export.Exporter) Option {
type exporterOption struct{ exporter export.Exporter } type exporterOption struct{ exporter export.Exporter }
func (o exporterOption) Apply(config *Config) { func (o exporterOption) apply(cfg *config) {
config.Exporter = o.exporter cfg.Exporter = o.exporter
} }
// WithPushTimeout sets the PushTimeout configuration option of a Config. // WithPushTimeout sets the PushTimeout configuration option of a Config.
@ -117,6 +117,6 @@ func WithPushTimeout(timeout time.Duration) Option {
type pushTimeoutOption time.Duration type pushTimeoutOption time.Duration
func (o pushTimeoutOption) Apply(config *Config) { func (o pushTimeoutOption) apply(cfg *config) {
config.PushTimeout = time.Duration(o) cfg.PushTimeout = time.Duration(o)
} }

View File

@ -26,12 +26,12 @@ import (
func TestWithResource(t *testing.T) { func TestWithResource(t *testing.T) {
r := resource.NewWithAttributes(attribute.String("A", "a")) r := resource.NewWithAttributes(attribute.String("A", "a"))
c := &Config{} c := &config{}
WithResource(r).Apply(c) WithResource(r).apply(c)
assert.Equal(t, r.Equivalent(), c.Resource.Equivalent()) assert.Equal(t, r.Equivalent(), c.Resource.Equivalent())
// Ensure overwriting works. // Ensure overwriting works.
c = &Config{Resource: &resource.Resource{}} c = &config{Resource: &resource.Resource{}}
WithResource(r).Apply(c) WithResource(r).apply(c)
assert.Equal(t, r.Equivalent(), c.Resource.Equivalent()) assert.Equal(t, r.Equivalent(), c.Resource.Equivalent())
} }

View File

@ -78,13 +78,13 @@ type Controller struct {
// options (including optional exporter) to configure a metric // options (including optional exporter) to configure a metric
// export pipeline. // export pipeline.
func New(checkpointer export.Checkpointer, opts ...Option) *Controller { func New(checkpointer export.Checkpointer, opts ...Option) *Controller {
c := &Config{ c := &config{
CollectPeriod: DefaultPeriod, CollectPeriod: DefaultPeriod,
CollectTimeout: DefaultPeriod, CollectTimeout: DefaultPeriod,
PushTimeout: DefaultPeriod, PushTimeout: DefaultPeriod,
} }
for _, opt := range opts { for _, opt := range opts {
opt.Apply(c) opt.apply(c)
} }
if c.Resource == nil { if c.Resource == nil {
c.Resource = resource.Default() c.Resource = resource.Default()

View File

@ -93,7 +93,7 @@ type (
} }
state struct { state struct {
config Config config config
// RWMutex implements locking for the `CheckpointSet` interface. // RWMutex implements locking for the `CheckpointSet` interface.
sync.RWMutex sync.RWMutex
@ -139,7 +139,7 @@ func New(aselector export.AggregatorSelector, eselector export.ExportKindSelecto
}, },
} }
for _, opt := range opts { for _, opt := range opts {
opt.ApplyProcessor(&p.config) opt.applyProcessor(&p.config)
} }
return p return p
} }

View File

@ -14,8 +14,8 @@
package basic // import "go.opentelemetry.io/otel/sdk/metric/processor/basic" package basic // import "go.opentelemetry.io/otel/sdk/metric/processor/basic"
// Config contains the options for configuring a basic metric processor. // config contains the options for configuring a basic metric processor.
type Config struct { type config struct {
// Memory controls whether the processor remembers metric // Memory controls whether the processor remembers metric
// instruments and label sets that were previously reported. // instruments and label sets that were previously reported.
// When Memory is true, CheckpointSet.ForEach() will visit // When Memory is true, CheckpointSet.ForEach() will visit
@ -24,7 +24,7 @@ type Config struct {
} }
type Option interface { type Option interface {
ApplyProcessor(*Config) applyProcessor(*config)
} }
// WithMemory sets the memory behavior of a Processor. If this is // WithMemory sets the memory behavior of a Processor. If this is
@ -37,6 +37,6 @@ func WithMemory(memory bool) Option {
type memoryOption bool type memoryOption bool
func (m memoryOption) ApplyProcessor(config *Config) { func (m memoryOption) applyProcessor(cfg *config) {
config.Memory = bool(m) cfg.Memory = bool(m)
} }

View File

@ -28,19 +28,10 @@ type config struct {
// Option is the interface that applies a configuration option. // Option is the interface that applies a configuration option.
type Option interface { type Option interface {
// Apply sets the Option value of a config. // apply sets the Option value of a config.
Apply(*config) apply(*config)
// A private method to prevent users implementing the
// interface and so future additions to it will not
// violate compatibility.
private()
} }
type option struct{}
func (option) private() {}
// WithAttributes adds attributes to the configured Resource. // WithAttributes adds attributes to the configured Resource.
func WithAttributes(attributes ...attribute.KeyValue) Option { func WithAttributes(attributes ...attribute.KeyValue) Option {
return WithDetectors(detectAttributes{attributes}) return WithDetectors(detectAttributes{attributes})
@ -60,12 +51,10 @@ func WithDetectors(detectors ...Detector) Option {
} }
type detectorsOption struct { type detectorsOption struct {
option
detectors []Detector detectors []Detector
} }
// Apply implements Option. func (o detectorsOption) apply(cfg *config) {
func (o detectorsOption) Apply(cfg *config) {
cfg.detectors = append(cfg.detectors, o.detectors...) cfg.detectors = append(cfg.detectors, o.detectors...)
} }

View File

@ -47,7 +47,7 @@ var (
func New(ctx context.Context, opts ...Option) (*Resource, error) { func New(ctx context.Context, opts ...Option) (*Resource, error) {
cfg := config{} cfg := config{}
for _, opt := range opts { for _, opt := range opts {
opt.Apply(&cfg) opt.apply(&cfg)
} }
return Detect(ctx, cfg.detectors...) return Detect(ctx, cfg.detectors...)

View File

@ -31,11 +31,13 @@ const (
defaultTracerName = "go.opentelemetry.io/otel/sdk/tracer" defaultTracerName = "go.opentelemetry.io/otel/sdk/tracer"
) )
// TODO (MrAlias): unify this API option design: // tracerProviderConfig
// https://github.com/open-telemetry/opentelemetry-go/issues/536 type tracerProviderConfig struct {
// processors contains collection of SpanProcessors that are processing pipeline
// TracerProviderConfig // for spans in the trace signal.
type TracerProviderConfig struct { // SpanProcessors registered with a TracerProvider and are called at the start
// and end of a Span's lifecycle, and are called in the order they are
// registered.
processors []SpanProcessor processors []SpanProcessor
// sampler is the default sampler used when creating new spans. // sampler is the default sampler used when creating new spans.
@ -51,8 +53,6 @@ type TracerProviderConfig struct {
resource *resource.Resource resource *resource.Resource
} }
type TracerProviderOption func(*TracerProviderConfig)
type TracerProvider struct { type TracerProvider struct {
mu sync.Mutex mu sync.Mutex
namedTracer map[instrumentation.Library]*tracer namedTracer map[instrumentation.Library]*tracer
@ -76,10 +76,10 @@ var _ trace.TracerProvider = &TracerProvider{}
// The passed opts are used to override these default values and configure the // The passed opts are used to override these default values and configure the
// returned TracerProvider appropriately. // returned TracerProvider appropriately.
func NewTracerProvider(opts ...TracerProviderOption) *TracerProvider { func NewTracerProvider(opts ...TracerProviderOption) *TracerProvider {
o := &TracerProviderConfig{} o := &tracerProviderConfig{}
for _, opt := range opts { for _, opt := range opts {
opt(o) opt.apply(o)
} }
ensureValidTracerProviderConfig(o) ensureValidTracerProviderConfig(o)
@ -234,6 +234,16 @@ func (p *TracerProvider) Shutdown(ctx context.Context) error {
return nil return nil
} }
type TracerProviderOption interface {
apply(*tracerProviderConfig)
}
type traceProviderOptionFunc func(*tracerProviderConfig)
func (fn traceProviderOptionFunc) apply(cfg *tracerProviderConfig) {
fn(cfg)
}
// WithSyncer registers the exporter with the TracerProvider using a // WithSyncer registers the exporter with the TracerProvider using a
// SimpleSpanProcessor. // SimpleSpanProcessor.
// //
@ -254,9 +264,9 @@ func WithBatcher(e SpanExporter, opts ...BatchSpanProcessorOption) TracerProvide
// WithSpanProcessor registers the SpanProcessor with a TracerProvider. // WithSpanProcessor registers the SpanProcessor with a TracerProvider.
func WithSpanProcessor(sp SpanProcessor) TracerProviderOption { func WithSpanProcessor(sp SpanProcessor) TracerProviderOption {
return func(opts *TracerProviderConfig) { return traceProviderOptionFunc(func(cfg *tracerProviderConfig) {
opts.processors = append(opts.processors, sp) cfg.processors = append(cfg.processors, sp)
} })
} }
// WithResource returns a TracerProviderOption that will configure the // WithResource returns a TracerProviderOption that will configure the
@ -267,9 +277,9 @@ func WithSpanProcessor(sp SpanProcessor) TracerProviderOption {
// If this option is not used, the TracerProvider will use the // If this option is not used, the TracerProvider will use the
// resource.Default() Resource by default. // resource.Default() Resource by default.
func WithResource(r *resource.Resource) TracerProviderOption { func WithResource(r *resource.Resource) TracerProviderOption {
return func(opts *TracerProviderConfig) { return traceProviderOptionFunc(func(cfg *tracerProviderConfig) {
opts.resource = resource.Merge(resource.Environment(), r) cfg.resource = resource.Merge(resource.Environment(), r)
} })
} }
// WithIDGenerator returns a TracerProviderOption that will configure the // WithIDGenerator returns a TracerProviderOption that will configure the
@ -280,11 +290,11 @@ func WithResource(r *resource.Resource) TracerProviderOption {
// If this option is not used, the TracerProvider will use a random number // If this option is not used, the TracerProvider will use a random number
// IDGenerator by default. // IDGenerator by default.
func WithIDGenerator(g IDGenerator) TracerProviderOption { func WithIDGenerator(g IDGenerator) TracerProviderOption {
return func(opts *TracerProviderConfig) { return traceProviderOptionFunc(func(cfg *tracerProviderConfig) {
if g != nil { if g != nil {
opts.idGenerator = g cfg.idGenerator = g
}
} }
})
} }
// WithSampler returns a TracerProviderOption that will configure the Sampler // WithSampler returns a TracerProviderOption that will configure the Sampler
@ -295,11 +305,11 @@ func WithIDGenerator(g IDGenerator) TracerProviderOption {
// If this option is not used, the TracerProvider will use a // If this option is not used, the TracerProvider will use a
// ParentBased(AlwaysSample) Sampler by default. // ParentBased(AlwaysSample) Sampler by default.
func WithSampler(s Sampler) TracerProviderOption { func WithSampler(s Sampler) TracerProviderOption {
return func(opts *TracerProviderConfig) { return traceProviderOptionFunc(func(cfg *tracerProviderConfig) {
if s != nil { if s != nil {
opts.sampler = s cfg.sampler = s
}
} }
})
} }
// WithSpanLimits returns a TracerProviderOption that will configure the // WithSpanLimits returns a TracerProviderOption that will configure the
@ -310,13 +320,13 @@ func WithSampler(s Sampler) TracerProviderOption {
// If this option is not used, the TracerProvider will use the default // If this option is not used, the TracerProvider will use the default
// SpanLimits. // SpanLimits.
func WithSpanLimits(sl SpanLimits) TracerProviderOption { func WithSpanLimits(sl SpanLimits) TracerProviderOption {
return func(opts *TracerProviderConfig) { return traceProviderOptionFunc(func(cfg *tracerProviderConfig) {
opts.spanLimits = sl cfg.spanLimits = sl
} })
} }
// ensureValidTracerProviderConfig ensures that given TracerProviderConfig is valid. // ensureValidTracerProviderConfig ensures that given TracerProviderConfig is valid.
func ensureValidTracerProviderConfig(cfg *TracerProviderConfig) { func ensureValidTracerProviderConfig(cfg *tracerProviderConfig) {
if cfg.sampler == nil { if cfg.sampler == nil {
cfg.sampler = ParentBased(AlwaysSample()) cfg.sampler = ParentBased(AlwaysSample())
} }

View File

@ -164,11 +164,11 @@ func ParentBased(root Sampler, samplers ...ParentBasedSamplerOption) Sampler {
type parentBased struct { type parentBased struct {
root Sampler root Sampler
config config config samplerConfig
} }
func configureSamplersForParentBased(samplers []ParentBasedSamplerOption) config { func configureSamplersForParentBased(samplers []ParentBasedSamplerOption) samplerConfig {
c := config{ c := samplerConfig{
remoteParentSampled: AlwaysSample(), remoteParentSampled: AlwaysSample(),
remoteParentNotSampled: NeverSample(), remoteParentNotSampled: NeverSample(),
localParentSampled: AlwaysSample(), localParentSampled: AlwaysSample(),
@ -176,26 +176,21 @@ func configureSamplersForParentBased(samplers []ParentBasedSamplerOption) config
} }
for _, so := range samplers { for _, so := range samplers {
so.Apply(&c) so.apply(&c)
} }
return c return c
} }
// config is a group of options for parentBased sampler. // samplerConfig is a group of options for parentBased sampler.
type config struct { type samplerConfig struct {
remoteParentSampled, remoteParentNotSampled Sampler remoteParentSampled, remoteParentNotSampled Sampler
localParentSampled, localParentNotSampled Sampler localParentSampled, localParentNotSampled Sampler
} }
// ParentBasedSamplerOption configures the sampler for a particular sampling case. // ParentBasedSamplerOption configures the sampler for a particular sampling case.
type ParentBasedSamplerOption interface { type ParentBasedSamplerOption interface {
Apply(*config) apply(*samplerConfig)
// A private method to prevent users implementing the
// interface and so future additions to it will not
// violate compatibility.
private()
} }
// WithRemoteParentSampled sets the sampler for the case of sampled remote parent. // WithRemoteParentSampled sets the sampler for the case of sampled remote parent.
@ -207,12 +202,10 @@ type remoteParentSampledOption struct {
s Sampler s Sampler
} }
func (o remoteParentSampledOption) Apply(config *config) { func (o remoteParentSampledOption) apply(config *samplerConfig) {
config.remoteParentSampled = o.s config.remoteParentSampled = o.s
} }
func (remoteParentSampledOption) private() {}
// WithRemoteParentNotSampled sets the sampler for the case of remote parent // WithRemoteParentNotSampled sets the sampler for the case of remote parent
// which is not sampled. // which is not sampled.
func WithRemoteParentNotSampled(s Sampler) ParentBasedSamplerOption { func WithRemoteParentNotSampled(s Sampler) ParentBasedSamplerOption {
@ -223,12 +216,10 @@ type remoteParentNotSampledOption struct {
s Sampler s Sampler
} }
func (o remoteParentNotSampledOption) Apply(config *config) { func (o remoteParentNotSampledOption) apply(config *samplerConfig) {
config.remoteParentNotSampled = o.s config.remoteParentNotSampled = o.s
} }
func (remoteParentNotSampledOption) private() {}
// WithLocalParentSampled sets the sampler for the case of sampled local parent. // WithLocalParentSampled sets the sampler for the case of sampled local parent.
func WithLocalParentSampled(s Sampler) ParentBasedSamplerOption { func WithLocalParentSampled(s Sampler) ParentBasedSamplerOption {
return localParentSampledOption{s} return localParentSampledOption{s}
@ -238,12 +229,10 @@ type localParentSampledOption struct {
s Sampler s Sampler
} }
func (o localParentSampledOption) Apply(config *config) { func (o localParentSampledOption) apply(config *samplerConfig) {
config.localParentSampled = o.s config.localParentSampled = o.s
} }
func (localParentSampledOption) private() {}
// WithLocalParentNotSampled sets the sampler for the case of local parent // WithLocalParentNotSampled sets the sampler for the case of local parent
// which is not sampled. // which is not sampled.
func WithLocalParentNotSampled(s Sampler) ParentBasedSamplerOption { func WithLocalParentNotSampled(s Sampler) ParentBasedSamplerOption {
@ -254,12 +243,10 @@ type localParentNotSampledOption struct {
s Sampler s Sampler
} }
func (o localParentNotSampledOption) Apply(config *config) { func (o localParentNotSampledOption) apply(config *samplerConfig) {
config.localParentNotSampled = o.s config.localParentNotSampled = o.s
} }
func (localParentNotSampledOption) private() {}
func (pb parentBased) ShouldSample(p SamplingParameters) SamplingResult { func (pb parentBased) ShouldSample(p SamplingParameters) SamplingResult {
psc := trace.SpanContextFromContext(p.ParentContext) psc := trace.SpanContextFromContext(p.ParentContext)
if psc.IsValid() { if psc.IsValid() {