Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(),
Expand Down
2 changes: 1 addition & 1 deletion app/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() })
}
}
Expand Down
3 changes: 3 additions & 0 deletions config/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
16 changes: 14 additions & 2 deletions routing/response/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package response
import (
"fmt"
"net/http"
"os"
"sort"

"github.com/gonstruct/core/routing/resource"
Expand All @@ -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
Expand Down Expand Up @@ -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 }),
})

Expand Down
1 change: 1 addition & 0 deletions routing/routing.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
8 changes: 5 additions & 3 deletions scheduling/engine.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package scheduling
import (
"context"
"fmt"
"os"
"slices"
"time"

Expand Down Expand Up @@ -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
}
Expand All @@ -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
}

Expand Down
8 changes: 8 additions & 0 deletions scheduling/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
Expand Down
3 changes: 3 additions & 0 deletions scheduling/scheduling.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions app/container_test.go → tests/app/container_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"testing"

"github.com/gonstruct/core/app"
"github.com/gonstruct/core/config"
)

type service struct{ built int }
Expand All @@ -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) {
Expand Down
33 changes: 33 additions & 0 deletions tests/routing/errors_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
}
}
36 changes: 36 additions & 0 deletions tests/scheduling/environment_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}