1// Copyright (C) 2020 Storj Labs, Inc.
2// See LICENSE for copying information.
3
4package telemetry
5
6import (
7	"context"
8
9	"storj.io/common/telemetry"
10	"storj.io/uplink/internal/telemetryclient"
11)
12
13type telemetryKey int
14
15const telemetryOptsKey telemetryKey = iota
16
17// Options specify telemetry client options.
18type Options struct {
19	Endpoint    string
20	Application string
21}
22
23// createClient creates a new client using the options.
24func (options *Options) createClient(satelliteAddress string) (telemetryclient.Client, error) {
25	client, err := telemetry.NewClient(options.Endpoint, telemetry.ClientOpts{
26		Application: options.Application,
27		Headers: map[string]string{
28			"sat": satelliteAddress,
29		},
30	})
31	return client, err
32}
33
34// Enable will attach default telemetry information to the ctx so telemetry
35// will be reported during the project lifecycle.
36func Enable(ctx context.Context) (context.Context, context.CancelFunc) {
37	return EnableWith(ctx, &Options{
38		Endpoint:    "collectora.storj.io:9000",
39		Application: "uplink",
40	})
41}
42
43// EnableWith will attach custom telemetry information to the ctx.
44func EnableWith(ctx context.Context, opts *Options) (context.Context, context.CancelFunc) {
45	ctx = context.WithValue(ctx, telemetryOptsKey, opts)
46	ctx = telemetryclient.WithConstructor(ctx, opts.createClient)
47	return context.WithCancel(ctx)
48}
49
50// ExtractOptions returns a bool whether the context has telemetry enabled
51// and the options set.
52func ExtractOptions(ctx context.Context) *Options {
53	v := ctx.Value(telemetryOptsKey)
54	if v == nil {
55		return nil
56	}
57
58	opts, ok := v.(*Options)
59	if !ok {
60		return nil
61	}
62
63	return opts
64}
65