File: signal.go

package info (click to toggle)
golang-opentelemetry-contrib 0.56.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,884 kB
  • sloc: makefile: 278; sh: 211; sed: 1
file content (61 lines) | stat: -rw-r--r-- 1,286 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package autoexport // import "go.opentelemetry.io/contrib/exporters/autoexport"

import (
	"context"
	"os"
)

type signal[T any] struct {
	envKey   string
	registry *registry[T]
}

func newSignal[T any](envKey string) signal[T] {
	return signal[T]{
		envKey: envKey,
		registry: &registry[T]{
			names: make(map[string]func(context.Context) (T, error)),
		},
	}
}

func (s signal[T]) create(ctx context.Context, opts ...option[T]) (T, error) {
	var cfg config[T]
	for _, opt := range opts {
		opt.apply(&cfg)
	}

	expType := os.Getenv(s.envKey)
	if expType == "" {
		if cfg.fallbackFactory != nil {
			return cfg.fallbackFactory(ctx)
		}
		expType = "otlp"
	}

	return s.registry.load(ctx, expType)
}

type config[T any] struct {
	fallbackFactory func(ctx context.Context) (T, error)
}

type option[T any] interface {
	apply(cfg *config[T])
}

type optionFunc[T any] func(cfg *config[T])

//lint:ignore U1000 https://github.com/dominikh/go-tools/issues/1440
func (fn optionFunc[T]) apply(cfg *config[T]) {
	fn(cfg)
}

func withFallbackFactory[T any](fallbackFactory func(ctx context.Context) (T, error)) option[T] {
	return optionFunc[T](func(cfg *config[T]) {
		cfg.fallbackFactory = fallbackFactory
	})
}