• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

goto / shield / 10787256047

10 Sep 2024 06:47AM UTC coverage: 51.953% (+0.01%) from 51.943%
10787256047

Pull #91

github

FemiNoviaLina
fix: core function name
Pull Request #91: feat: list resource of a user

66 of 143 new or added lines in 8 files covered. (46.15%)

1 existing line in 1 file now uncovered.

6809 of 13106 relevant lines covered (51.95%)

11.55 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/internal/server/server.go
1
package server
2

3
import (
4
        "context"
5
        "errors"
6
        "fmt"
7
        "net/http"
8
        "time"
9

10
        "github.com/goto/salt/log"
11
        "github.com/goto/salt/mux"
12
        "github.com/goto/shield/internal/api"
13
        "github.com/goto/shield/internal/api/v1beta1"
14
        "github.com/goto/shield/internal/server/grpc_interceptors"
15
        "github.com/goto/shield/internal/server/health"
16

17
        shieldv1beta1 "github.com/goto/shield/proto/v1beta1"
18
        grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
19
        grpc_zap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap"
20
        grpc_recovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
21
        grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
22
        "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
23
        "github.com/newrelic/go-agent/v3/integrations/nrgrpc"
24
        "github.com/newrelic/go-agent/v3/newrelic"
25
        "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
26
        "go.uber.org/zap"
27
        "google.golang.org/grpc"
28
        "google.golang.org/grpc/codes"
29
        "google.golang.org/grpc/credentials/insecure"
30
        "google.golang.org/grpc/health/grpc_health_v1"
31
        "google.golang.org/grpc/reflection"
32
        "google.golang.org/grpc/status"
33
)
34

35
func Serve(
36
        ctx context.Context,
37
        logger log.Logger,
38
        cfg Config,
39
        nrApp *newrelic.Application,
40
        deps api.Deps,
41
) error {
×
42
        httpMux := http.NewServeMux()
×
43

×
44
        grpcDialCtx, grpcDialCancel := context.WithTimeout(ctx, time.Second*5)
×
45
        defer grpcDialCancel()
×
46

×
47
        grpcConn, err := grpc.DialContext(
×
48
                grpcDialCtx,
×
49
                cfg.grpcAddr(),
×
50
                grpc.WithTransportCredentials(insecure.NewCredentials()),
×
51
                grpc.WithDefaultCallOptions(
×
52
                        grpc.MaxCallRecvMsgSize(cfg.GRPC.MaxRecvMsgSize),
×
53
                        grpc.MaxCallSendMsgSize(cfg.GRPC.MaxSendMsgSize),
×
54
                ))
×
55
        if err != nil {
×
56
                return err
×
57
        }
×
58

59
        grpcGateway := runtime.NewServeMux(
×
60
                runtime.WithHealthEndpointAt(grpc_health_v1.NewHealthClient(grpcConn), "/ping"),
×
61
                runtime.WithIncomingHeaderMatcher(customHeaderMatcherFunc(map[string]bool{cfg.IdentityProxyHeader: true})),
×
62
        )
×
63

×
64
        httpMux.Handle("/admin/", http.StripPrefix("/admin", grpcGateway))
×
65

×
66
        if err := shieldv1beta1.RegisterShieldServiceHandler(ctx, grpcGateway, grpcConn); err != nil {
×
67
                return err
×
68
        }
×
69

70
        grpcServiceDataGateway := runtime.NewServeMux(
×
71
                runtime.WithHealthEndpointAt(grpc_health_v1.NewHealthClient(grpcConn), "/ping"),
×
72
                runtime.WithIncomingHeaderMatcher(customHeaderMatcherFunc(map[string]bool{cfg.IdentityProxyHeader: true})),
×
73
        )
×
74

×
75
        httpMux.Handle(fmt.Sprintf("%s/", cfg.PublicAPIPrefix), http.StripPrefix(cfg.PublicAPIPrefix, grpcServiceDataGateway))
×
76

×
77
        if err := shieldv1beta1.RegisterServiceDataServiceHandler(ctx, grpcServiceDataGateway, grpcConn); err != nil {
×
78
                return err
×
79
        }
×
80

NEW
81
        if err := shieldv1beta1.RegisterPublicServiceHandler(ctx, grpcServiceDataGateway, grpcConn); err != nil {
×
NEW
82
                return err
×
NEW
83
        }
×
84

85
        grpcServer := grpc.NewServer(
×
86
                grpc.StatsHandler(otelgrpc.NewServerHandler()),
×
87
                getGRPCMiddleware(cfg, logger, nrApp),
×
88
        )
×
89
        reflection.Register(grpcServer)
×
90

×
91
        healthHandler := health.NewHandler()
×
92
        grpc_health_v1.RegisterHealthServer(grpcServer, healthHandler)
×
93

×
94
        serviceDataConfig := v1beta1.ServiceDataConfig{MaxUpsert: cfg.ServiceData.MaxNumUpsertData, DefaultServiceDataProject: cfg.ServiceData.DefaultServiceDataProject}
×
95
        err = v1beta1.Register(ctx, grpcServer, deps, cfg.CheckAPILimit, serviceDataConfig)
×
96
        if err != nil {
×
97
                return err
×
98
        }
×
99

100
        httpMuxMetrics := http.NewServeMux()
×
101

×
102
        logger.Info("[shield] api server starting", "http-port", cfg.Port, "grpc-port", cfg.GRPC.Port, "metrics-port", cfg.MetricsPort)
×
103

×
104
        if err := mux.Serve(
×
105
                ctx,
×
106
                mux.WithHTTPTarget(fmt.Sprintf(":%d", cfg.Port), &http.Server{
×
107
                        Handler:        httpMux,
×
108
                        ReadTimeout:    120 * time.Second,
×
109
                        WriteTimeout:   120 * time.Second,
×
110
                        MaxHeaderBytes: 1 << 20,
×
111
                }),
×
112
                mux.WithHTTPTarget(fmt.Sprintf(":%d", cfg.MetricsPort), &http.Server{
×
113
                        Handler:        httpMuxMetrics,
×
114
                        ReadTimeout:    120 * time.Second,
×
115
                        WriteTimeout:   120 * time.Second,
×
116
                        MaxHeaderBytes: 1 << 20,
×
117
                }),
×
118
                mux.WithGRPCTarget(fmt.Sprintf(":%d", cfg.GRPC.Port), grpcServer),
×
119
                mux.WithGracePeriod(5*time.Second),
×
120
        ); !errors.Is(err, context.Canceled) {
×
121
                logger.Error("mux serve error", "err", err)
×
122
                return nil
×
123
        }
×
124

125
        logger.Info("server stopped gracefully")
×
126
        return nil
×
127
}
128

129
// REVISIT: passing config.Shield as reference
130
func getGRPCMiddleware(cfg Config, logger log.Logger, nrApp *newrelic.Application) grpc.ServerOption {
×
131
        recoveryFunc := func(p interface{}) (err error) {
×
132
                fmt.Println("-----------------------------")
×
133
                return status.Errorf(codes.Internal, "internal server error")
×
134
        }
×
135

136
        grpcRecoveryOpts := []grpc_recovery.Option{
×
137
                grpc_recovery.WithRecoveryHandler(recoveryFunc),
×
138
        }
×
139

×
140
        grpcZapLogger := zap.NewExample().Sugar()
×
141
        loggerZap, ok := logger.(*log.Zap)
×
142
        if ok {
×
143
                grpcZapLogger = loggerZap.GetInternalZapLogger()
×
144
        }
×
145
        return grpc.UnaryInterceptor(
×
146
                grpc_middleware.ChainUnaryServer(
×
147
                        grpc_interceptors.EnrichCtxWithIdentity(cfg.IdentityProxyHeader),
×
148
                        grpc_zap.UnaryServerInterceptor(grpcZapLogger.Desugar()),
×
149
                        grpc_recovery.UnaryServerInterceptor(grpcRecoveryOpts...),
×
150
                        grpc_ctxtags.UnaryServerInterceptor(),
×
151
                        nrgrpc.UnaryServerInterceptor(nrApp),
×
152
                ))
×
153
}
154

155
func customHeaderMatcherFunc(headerKeys map[string]bool) func(key string) (string, bool) {
×
156
        return func(key string) (string, bool) {
×
157
                if _, ok := headerKeys[key]; ok {
×
158
                        return key, true
×
159
                }
×
160
                return runtime.DefaultHeaderMatcher(key)
×
161
        }
162
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc