Passed
Push — master ( 9e53c9...4fac29 )
by Tolga
01:30 queued 15s
created

cmd.NewGCPHandler   A

Complexity

Conditions 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nop 2
dl 0
loc 20
rs 9.85
c 0
b 0
f 0
1
package cmd
2
3
import (
4
	"context"
5
	"errors"
6
	"fmt"
7
	"log/slog"
8
	"os"
9
10
	"github.com/Permify/permify/pkg/telemetry"
11
	"github.com/Permify/permify/pkg/telemetry/logexporters"
12
	"github.com/Permify/sloggcp"
13
	"github.com/agoda-com/opentelemetry-go/otelslog"
14
)
15
16
// HandlerFactory - Create log handler according to given params
17
func HandlerFactory(name string, endpoint string, insecure bool, urlpath string, headers map[string]string, protocol string, level slog.Leveler) (slog.Handler, error) {
18
	switch name {
19
	case "otlp", "otlp-http", "otlp-grpc":
20
		return NewOTLPHandler(endpoint, insecure, urlpath, headers, protocol, level.Level())
21
	case "gcp":
22
		return NewGCPHandler(headers, level)
23
	default:
24
		return nil, fmt.Errorf("%s log handler is unsupported", name)
25
	}
26
}
27
28
func NewOTLPHandler(endpoint string, insecure bool, urlPath string, headers map[string]string, protocol string, level slog.Leveler) (slog.Handler, error) {
29
	// Set up the OTLP exporter based on the protocol
30
	exporter, err := logexporters.ExporterFactory("otlp", endpoint, insecure, urlPath, headers, protocol)
31
	if err != nil {
32
		return nil, errors.New("failed to create OTLP exporter")
33
	}
34
35
	// Initialize the OpenTelemetry handler with the exporter
36
	lp := telemetry.NewLog(exporter)
37
	otelHandler := otelslog.NewOtelHandler(lp, &otelslog.HandlerOptions{
38
		Level: level,
39
	})
40
41
	// Shut down the exporter when needed
42
	return otelHandler, nil
43
}
44
45
func NewGCPHandler(headers map[string]string, level slog.Leveler) (slog.Handler, error) {
46
	// Retrieve Google Cloud credentials from headers
47
	creds := headers["google-application-credentials"]
48
	projectId := headers["google-cloud-project"]
49
50
	if projectId == "" {
51
		return nil, errors.New("missing GOOGLE_CLOUD_PROJECT in headers")
52
	}
53
54
	// Set credentials for Google Cloud access
55
	if creds != "" {
56
		os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", creds)
57
	}
58
59
	// Initialize GCP-specific log handler
60
	logName := "permify"
61
	gcpHandler := sloggcp.NewGoogleCloudSlogHandler(context.Background(), projectId, logName, &slog.HandlerOptions{
62
		Level: level,
63
	})
64
	return gcpHandler, nil
65
}
66