Skip to content

Commit

Permalink
chore: rename runCtx to run
Browse files Browse the repository at this point in the history
Naming refactoring.
  • Loading branch information
odsod committed Aug 3, 2021
1 parent 244e61d commit 04e0a52
Show file tree
Hide file tree
Showing 6 changed files with 51 additions and 51 deletions.
8 changes: 4 additions & 4 deletions dialservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (

// DialService dials another service using the default service account's Google ID Token authentication.
func DialService(ctx context.Context, target string, opts ...grpc.DialOption) (*grpc.ClientConn, error) {
runCtx, ok := getRunContext(ctx)
run, ok := getRunContext(ctx)
if !ok {
return nil, fmt.Errorf("cloudrunner.DialService %s: must be called with a context from cloudrunner.Run", target)
}
Expand All @@ -20,11 +20,11 @@ func DialService(ctx context.Context, target string, opts ...grpc.DialOption) (*
target,
append(
[]grpc.DialOption{
grpc.WithDefaultServiceConfig(runCtx.runConfig.Client.AsServiceConfigJSON()),
grpc.WithDefaultServiceConfig(run.config.Client.AsServiceConfigJSON()),
grpc.WithChainUnaryInterceptor(
otelgrpc.UnaryClientInterceptor(),
runCtx.requestLoggerMiddleware.GRPCUnaryClientInterceptor,
runCtx.clientMiddleware.GRPCUnaryClientInterceptor,
run.requestLoggerMiddleware.GRPCUnaryClientInterceptor,
run.clientMiddleware.GRPCUnaryClientInterceptor,
),
grpc.WithBlock(),
},
Expand Down
16 changes: 8 additions & 8 deletions grpcserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,31 @@ import (

// NewGRPCServer creates a new gRPC server preconfigured with middleware for request logging, tracing, etc.
func NewGRPCServer(ctx context.Context, opts ...grpc.ServerOption) *grpc.Server {
runCtx, ok := getRunContext(ctx)
run, ok := getRunContext(ctx)
if !ok {
panic("cloudrunner.NewGRPCServer: must be called with a context from cloudrunner.Run")
}
serverOptions := []grpc.ServerOption{
grpc.ChainUnaryInterceptor(
otelgrpc.UnaryServerInterceptor(),
runCtx.loggerMiddleware.GRPCUnaryServerInterceptor, // adds context logger
runCtx.traceMiddleware.GRPCServerUnaryInterceptor, // needs the context logger
runCtx.requestLoggerMiddleware.GRPCUnaryServerInterceptor, // needs to run after trace
runCtx.serverMiddleware.GRPCUnaryServerInterceptor, // needs to run after request logger
run.loggerMiddleware.GRPCUnaryServerInterceptor, // adds context logger
run.traceMiddleware.GRPCServerUnaryInterceptor, // needs the context logger
run.requestLoggerMiddleware.GRPCUnaryServerInterceptor, // needs to run after trace
run.serverMiddleware.GRPCUnaryServerInterceptor, // needs to run after request logger
),
}
serverOptions = append(serverOptions, runCtx.grpcServerOptions...)
serverOptions = append(serverOptions, run.grpcServerOptions...)
serverOptions = append(serverOptions, opts...)
return grpc.NewServer(serverOptions...)
}

// ListenGRPC binds a listener on the configured port and listens for gRPC requests.
func ListenGRPC(ctx context.Context, grpcServer *grpc.Server) error {
runCtx, ok := getRunContext(ctx)
run, ok := getRunContext(ctx)
if !ok {
return fmt.Errorf("cloudrunner.ListenGRPC: must be called with a context from cloudrunner.Run")
}
address := fmt.Sprintf(":%d", runCtx.runConfig.Service.Port)
address := fmt.Sprintf(":%d", run.config.Service.Port)
listener, err := (&net.ListenConfig{}).Listen(
ctx,
"tcp",
Expand Down
20 changes: 10 additions & 10 deletions httphandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,29 +15,29 @@ type HTTPMiddleware = func(http.Handler) http.Handler

// NewHTTPServer creates a new HTTP server preconfigured with middleware for request logging, tracing, etc.
func NewHTTPServer(ctx context.Context, handler http.Handler, middlewares ...HTTPMiddleware) *http.Server {
runCtx, ok := getRunContext(ctx)
run, ok := getRunContext(ctx)
if !ok {
panic("cloudrunner.NewHTTPServer: must be called with a context from cloudrunner.Run")
}
defaultMiddlewares := []cloudserver.HTTPMiddleware{
func(handler http.Handler) http.Handler {
return otelhttp.NewHandler(handler, "server")
},
runCtx.loggerMiddleware.HTTPServer,
runCtx.traceMiddleware.HTTPServer,
runCtx.requestLoggerMiddleware.HTTPServer,
runCtx.serverMiddleware.HTTPServer,
run.loggerMiddleware.HTTPServer,
run.traceMiddleware.HTTPServer,
run.requestLoggerMiddleware.HTTPServer,
run.serverMiddleware.HTTPServer,
}
return &http.Server{
Addr: fmt.Sprintf(":%d", runCtx.runConfig.Service.Port),
Addr: fmt.Sprintf(":%d", run.config.Service.Port),
Handler: cloudserver.ChainHTTPMiddleware(
handler,
append(defaultMiddlewares, middlewares...)...,
),
ReadTimeout: runCtx.serverMiddleware.Config.Timeout,
ReadHeaderTimeout: runCtx.serverMiddleware.Config.Timeout,
WriteTimeout: runCtx.serverMiddleware.Config.Timeout,
IdleTimeout: runCtx.serverMiddleware.Config.Timeout,
ReadTimeout: run.serverMiddleware.Config.Timeout,
ReadHeaderTimeout: run.serverMiddleware.Config.Timeout,
WriteTimeout: run.serverMiddleware.Config.Timeout,
IdleTimeout: run.serverMiddleware.Config.Timeout,
}
}

Expand Down
16 changes: 8 additions & 8 deletions options.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,30 +11,30 @@ type Option func(*runContext)

// WithRequestLoggerMessageTransformer configures the request logger with a message transformer.
func WithRequestLoggerMessageTransformer(transformer func(proto.Message) proto.Message) Option {
return func(runCtx *runContext) {
runCtx.requestLoggerMiddleware.MessageTransformer = transformer
return func(run *runContext) {
run.requestLoggerMiddleware.MessageTransformer = transformer
}
}

// WithConfig configures an additional config struct to be loaded.
func WithConfig(name string, config interface{}) Option {
return func(runCtx *runContext) {
runCtx.configOptions = append(runCtx.configOptions, cloudconfig.WithAdditionalSpec(name, config))
return func(run *runContext) {
run.configOptions = append(run.configOptions, cloudconfig.WithAdditionalSpec(name, config))
}
}

// WithOptions configures the run context with a list of options.
func WithOptions(options []Option) Option {
return func(runCtx *runContext) {
return func(run *runContext) {
for _, option := range options {
option(runCtx)
option(run)
}
}
}

// WithGRPCServerOptions configures the run context with additional default options for NewGRPCServer.
func WithGRPCServerOptions(grpcServerOptions []grpc.ServerOption) Option {
return func(runCtx *runContext) {
runCtx.grpcServerOptions = append(runCtx.grpcServerOptions, grpcServerOptions...)
return func(run *runContext) {
run.grpcServerOptions = append(run.grpcServerOptions, grpcServerOptions...)
}
}
38 changes: 19 additions & 19 deletions run.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,23 +39,23 @@ type runConfig struct {

// Run a service.
// Configuration of the service is loaded from the environment.
func Run(run func(context.Context) error, options ...Option) error {
func Run(fn func(context.Context) error, options ...Option) error {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer cancel()
usage := flag.Bool("help", false, "show help then exit")
yamlServiceSpecificationFile := flag.String("config", "", "load environment from a YAML service specification")
validate := flag.Bool("validate", false, "validate config then exit")
flag.Parse()
var runCtx runContext
var run runContext
for _, option := range options {
option(&runCtx)
option(&run)
}
if *yamlServiceSpecificationFile != "" {
runCtx.configOptions = append(
runCtx.configOptions, cloudconfig.WithYAMLServiceSpecificationFile(*yamlServiceSpecificationFile),
run.configOptions = append(
run.configOptions, cloudconfig.WithYAMLServiceSpecificationFile(*yamlServiceSpecificationFile),
)
}
config, err := cloudconfig.New("cloudrunner", &runCtx.runConfig, runCtx.configOptions...)
config, err := cloudconfig.New("cloudrunner", &run.config, run.configOptions...)
if err != nil {
return fmt.Errorf("cloudrunner.Run: %w", err)
}
Expand All @@ -66,39 +66,39 @@ func Run(run func(context.Context) error, options ...Option) error {
if err := config.Load(); err != nil {
return fmt.Errorf("cloudrunner.Run: %w", err)
}
runCtx.runConfig.Service.loadFromRuntime()
run.config.Service.loadFromRuntime()
if *validate {
return nil
}
runCtx.traceMiddleware.ProjectID = runCtx.runConfig.Service.ProjectID
runCtx.serverMiddleware.Config = runCtx.runConfig.Server
runCtx.requestLoggerMiddleware.Config = runCtx.runConfig.RequestLogger
ctx = withRunContext(ctx, &runCtx)
logger, err := cloudzap.NewLogger(runCtx.runConfig.Logger)
run.traceMiddleware.ProjectID = run.config.Service.ProjectID
run.serverMiddleware.Config = run.config.Server
run.requestLoggerMiddleware.Config = run.config.RequestLogger
ctx = withRunContext(ctx, &run)
logger, err := cloudzap.NewLogger(run.config.Logger)
if err != nil {
return fmt.Errorf("cloudrunner.Run: %w", err)
}
runCtx.loggerMiddleware.Logger = logger
run.loggerMiddleware.Logger = logger
ctx = cloudzap.WithLogger(ctx, logger)
if err := cloudprofiler.Start(runCtx.runConfig.Profiler); err != nil {
if err := cloudprofiler.Start(run.config.Profiler); err != nil {
return fmt.Errorf("cloudrunner.Run: %w", err)
}
resource, err := cloudotel.NewResource(ctx)
if err != nil {
return fmt.Errorf("cloudrunner.Run: %w", err)
}
stopTraceExporter, err := cloudtrace.StartExporter(ctx, runCtx.runConfig.TraceExporter, resource)
stopTraceExporter, err := cloudtrace.StartExporter(ctx, run.config.TraceExporter, resource)
if err != nil {
return fmt.Errorf("cloudrunner.Run: %w", err)
}
defer stopTraceExporter()
logger.Info("up and running", zap.Object("config", config), cloudzap.Resource("resource", resource))
defer logger.Info("goodbye")
return run(ctx)
return fn(ctx)
}

type runContext struct {
runConfig runConfig
config runConfig
configOptions []cloudconfig.Option
grpcServerOptions []grpc.ServerOption
loggerMiddleware cloudzap.Middleware
Expand All @@ -110,8 +110,8 @@ type runContext struct {

type runContextKey struct{}

func withRunContext(ctx context.Context, runCtx *runContext) context.Context {
return context.WithValue(ctx, runContextKey{}, runCtx)
func withRunContext(ctx context.Context, run *runContext) context.Context {
return context.WithValue(ctx, runContextKey{}, run)
}

func getRunContext(ctx context.Context) (*runContext, bool) {
Expand Down
4 changes: 2 additions & 2 deletions service.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ import (

// Service returns the service config for the current context.
func Service(ctx context.Context) ServiceConfig {
runCtx, ok := getRunContext(ctx)
run, ok := getRunContext(ctx)
if !ok {
panic("cloudrunner.Logger must be called with a context from cloudrunner.Run")
}
return runCtx.runConfig.Service
return run.config.Service
}

// ServiceConfig contains generic service configuration.
Expand Down

0 comments on commit 04e0a52

Please sign in to comment.