diff --git a/app/app.go b/app/app.go index 50c6f5d..9d97ec9 100644 --- a/app/app.go +++ b/app/app.go @@ -16,11 +16,10 @@ import ( "github.com/gonstruct/core/scheduling" "github.com/rs/zerolog/log" - - "github.com/gonstruct/validation/env" ) type App struct { + config config.App environment config.Environment ctx context.Context @@ -53,9 +52,12 @@ func Instance() *App { var instance *App -func New(options ...option) *App { +// New builds the application from its config, which the rest of it reads: +// its environment decides which scheduled commands run. +func New(configuration config.App, options ...option) *App { application := &App{ - environment: env.Enum[config.Environment]("APP_ENV"), + config: configuration, + environment: configuration.Environment, ctx: context.Background(), createdAt: time.Now(), console: console.New(), diff --git a/app/options.go b/app/options.go index 9e09338..b575460 100644 --- a/app/options.go +++ b/app/options.go @@ -69,7 +69,7 @@ func WithRouting(options ...routing.Option) option { func WithScheduling(options ...scheduling.Option) option { return func(a *App) { - a.scheduling = scheduling.New(options...) + a.scheduling = scheduling.New(append([]scheduling.Option{scheduling.WithEnvironment(a.environment.String())}, options...)...) a.console.Register("schedule:work", func(*console.Console, []string) error { return a.scheduling.Run() }) } } diff --git a/config/server.go b/config/server.go index 3f4b20a..b9a573a 100644 --- a/config/server.go +++ b/config/server.go @@ -18,4 +18,7 @@ type Server struct { // TrustedPlatform is the header the platform in front of the server // puts the client's IP in, as gin's TrustedPlatform: none when empty. TrustedPlatform string + // ShowErrors has a failed response say the error behind it: for a + // developer's own machine, never production. + ShowErrors bool } diff --git a/routing/response/options.go b/routing/response/options.go index 3b5a5ff..6840341 100644 --- a/routing/response/options.go +++ b/routing/response/options.go @@ -3,7 +3,6 @@ package response import ( "fmt" "net/http" - "os" "sort" "github.com/gonstruct/core/routing/resource" @@ -13,6 +12,19 @@ import ( type ErrorsMap map[string]string +// showErrorsKey is where a request keeps whether its failed response says +// the error behind it. +const showErrorsKey = "gonstruct.response.show-errors" + +// ShowErrors has the failed responses of the requests it runs before say +// the error behind them, or not: routing runs it as its config says. +func ShowErrors(show bool) gin.HandlerFunc { + return func(context *gin.Context) { + context.Set(showErrorsKey, show) + context.Next() + } +} + type value[T any] struct { isSet bool value T @@ -86,7 +98,7 @@ func (options *responseOptions) resolve(context *gin.Context) { context.AbortWithStatusJSON(options.StatusCode, resource.Resource{ "message": resource.When(options.Message.isSet, func() string { return options.Message.value }), "code": resource.When(options.Code.isSet, func() string { return options.Code.value }), - "error": resource.When(options.Error.isSet && os.Getenv("APP_ENV") != "production", func() string { return options.Error.value.Error() }), + "error": resource.When(options.Error.isSet && context.GetBool(showErrorsKey), func() string { return options.Error.value.Error() }), "errors": resource.When(options.Errors.isSet, func() ErrorsMap { return options.Errors.value }), }) diff --git a/routing/routing.go b/routing/routing.go index e09091b..8443d17 100644 --- a/routing/routing.go +++ b/routing/routing.go @@ -47,6 +47,7 @@ func (r *Routing) Engine() *Engine { server := r.server() router.TrustedPlatform = server.TrustedPlatform + router.Engine.Use(response.ShowErrors(server.ShowErrors)) router.ContextWithFallback = true router.RemoteIPHeaders = []string{ "CF-Connecting-IP", diff --git a/scheduling/engine.go b/scheduling/engine.go index 8f594e7..b3eba87 100644 --- a/scheduling/engine.go +++ b/scheduling/engine.go @@ -3,7 +3,6 @@ package scheduling import ( "context" "fmt" - "os" "slices" "time" @@ -35,6 +34,9 @@ func NewSynchronousEngine() *Engine { type Engine struct { gocron.Scheduler + // Environment is the one commands limited to some run in. + Environment string + synchronous bool Commands []command.Command } @@ -50,8 +52,8 @@ func (e *Engine) Command(cmd command.Command, options ...command.Option) { opts := command.NewOptions(options...) - if len(opts.Environments) > 0 && !slices.Contains(opts.Environments, os.Getenv("APP_ENV")) { - log.Info().Msgf("[scheduling] skipping command %s for environment %s", cmd.Name(), os.Getenv("APP_ENV")) + if len(opts.Environments) > 0 && !slices.Contains(opts.Environments, e.Environment) { + log.Info().Msgf("[scheduling] skipping command %s for environment %s", cmd.Name(), e.Environment) return } diff --git a/scheduling/options.go b/scheduling/options.go index f6df823..9082ca7 100644 --- a/scheduling/options.go +++ b/scheduling/options.go @@ -2,6 +2,14 @@ package scheduling type Option func(*Scheduling) +// WithEnvironment is the environment commands limited to some run in. The +// app passes its own. +func WithEnvironment(environment string) Option { + return func(r *Scheduling) { + r.Environment = environment + } +} + func WithSchedulers(schedulers ...func(*Engine)) Option { return func(r *Scheduling) { r.Schedulers = append(r.Schedulers, schedulers...) diff --git a/scheduling/scheduling.go b/scheduling/scheduling.go index 540e7ba..dcb1d3d 100644 --- a/scheduling/scheduling.go +++ b/scheduling/scheduling.go @@ -2,6 +2,8 @@ package scheduling type Scheduling struct { Schedulers []func(*Engine) + // Environment is the one commands limited to some run in. + Environment string } func New(options ...Option) *Scheduling { @@ -19,6 +21,7 @@ func (s *Scheduling) Run() error { if err != nil { return err } + scheduler.Environment = s.Environment for _, f := range s.Schedulers { f(scheduler) diff --git a/app/container_test.go b/tests/app/container_test.go similarity index 94% rename from app/container_test.go rename to tests/app/container_test.go index f9c9c6b..db3826b 100644 --- a/app/container_test.go +++ b/tests/app/container_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/gonstruct/core/app" + "github.com/gonstruct/core/config" ) type service struct{ built int } @@ -13,9 +14,8 @@ type service struct{ built int } // entrypoint does. func boot(t *testing.T, bindings ...app.Binding) { t.Helper() - t.Setenv("APP_ENV", "testing") - app.New(app.WithSingletons(app.Singletons(bindings...))).SetInstance() + app.New(config.App{Environment: config.TestingEnvironment}, app.WithSingletons(app.Singletons(bindings...))).SetInstance() } func TestSingletonBuildsOnceAndShares(t *testing.T) { diff --git a/tests/routing/errors_test.go b/tests/routing/errors_test.go new file mode 100644 index 0000000..f57b9ec --- /dev/null +++ b/tests/routing/errors_test.go @@ -0,0 +1,33 @@ +package routing_test + +import ( + "errors" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gonstruct/core/config" + "github.com/gonstruct/core/routing" + "github.com/gonstruct/core/routing/response" + + "github.com/gin-gonic/gin" +) + +// A failed response says the error behind it only when the server's config +// shows errors, as an app does outside production. +func TestFailedResponsesShowTheirErrorOnlyWhenAsked(t *testing.T) { + for _, show := range []bool{true, false} { + engine := routing.New(routing.WithConfig(config.Server{ShowErrors: show}), routing.WithRouters(func(engine *routing.Engine) { + engine.GET("/broken", func(*gin.Context) response.Response { + return response.Error(errors.New("the database is down")) + }) + })).Engine() + recorder := httptest.NewRecorder() + engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/broken", nil)) + + if said := strings.Contains(recorder.Body.String(), "the database is down"); said != show { + t.Errorf("showing errors %v: the response said it %v: %s", show, said, recorder.Body.String()) + } + } +} diff --git a/tests/scheduling/environment_test.go b/tests/scheduling/environment_test.go new file mode 100644 index 0000000..8c4be8a --- /dev/null +++ b/tests/scheduling/environment_test.go @@ -0,0 +1,36 @@ +package scheduling_test + +import ( + "context" + "testing" + + "github.com/gonstruct/core/scheduling" + "github.com/gonstruct/core/scheduling/command" +) + +type nightly struct{} + +func (nightly) Name() string { return "nightly" } +func (nightly) Handle(context.Context) error { return nil } + +// A command limited to some environments is left out of the others, as the +// app's config says, whatever APP_ENV is. +func TestCommandsRunInTheirEnvironmentsOnly(t *testing.T) { + t.Setenv("APP_ENV", "production") + + for _, each := range []struct { + environment string + registered bool + }{{"production", true}, {"staging", false}} { + engine, err := scheduling.NewEngine() + if err != nil { + t.Fatal(err) + } + engine.Environment = each.environment + engine.Command(nightly{}, command.EveryMinute(), command.Environment[string]("production")) + + if got := len(engine.Jobs()) > 0; got != each.registered { + t.Errorf("in %s: expected registered %v, got %v", each.environment, each.registered, got) + } + } +}