Skip to content

Commit

Permalink
refactor: Harmonizing naming with others projects
Browse files Browse the repository at this point in the history
Signed-off-by: Vincent Boutour <[email protected]>
  • Loading branch information
ViBiOh committed Jun 23, 2024
1 parent afb7858 commit 9909349
Show file tree
Hide file tree
Showing 20 changed files with 162 additions and 180 deletions.
12 changes: 8 additions & 4 deletions cmd/http/adapter.go → cmd/http/adapters.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"embed"
"fmt"
"time"

Expand All @@ -11,14 +12,17 @@ import (
"github.com/ViBiOh/httputils/v4/pkg/renderer"
)

type adapter struct {
renderer *renderer.Service
//go:embed templates static
var content embed.FS

type adapters struct {
amqp *amqphandler.Service
renderer *renderer.Service
hello *cache.Cache[string, string]
}

func newAdapter(ctx context.Context, config configuration, client client) (adapter, error) {
var output adapter
func newAdapters(ctx context.Context, config configuration, client clients) (adapters, error) {
var output adapters
var err error

if client.amqp != nil {
Expand Down
2 changes: 1 addition & 1 deletion cmd/http/background.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
amqp "github.com/rabbitmq/amqp091-go"
)

func startBackground(ctx context.Context, client client, adapter adapter) {
func startBackground(ctx context.Context, client clients, adapter adapters) {
go redis.SubscribeFor(ctx, client.redis, "httputils:tasks", func(content time.Time, err error) {
if err != nil {
slog.LogAttrs(ctx, slog.LevelError, "consume on pubsub", slog.Any("error", err))
Expand Down
19 changes: 10 additions & 9 deletions cmd/http/client.go → cmd/http/clients.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,19 @@ import (
"github.com/ViBiOh/httputils/v4/pkg/telemetry"
)

type client struct {
redis redis.Client
amqp *amqp.Client
type clients struct {
telemetry *telemetry.Service
pprof *pprof.Service
health *health.Service
telemetry telemetry.Service
pprof pprof.Service

redis redis.Client
amqp *amqp.Client
}

const closeTimeout = time.Second * 10

func newClient(ctx context.Context, config configuration) (client, error) {
var output client
func newClient(ctx context.Context, config configuration) (clients, error) {
var output clients
var err error

logger.Init(ctx, config.logger)
Expand Down Expand Up @@ -57,11 +58,11 @@ func newClient(ctx context.Context, config configuration) (client, error) {
return output, nil
}

func (c client) Start() {
func (c clients) Start() {
go c.pprof.Start(c.health.DoneCtx())
}

func (c client) Close(ctx context.Context) {
func (c clients) Close(ctx context.Context) {
ctx, cancel := context.WithTimeout(ctx, closeTimeout)
defer cancel()

Expand Down
28 changes: 15 additions & 13 deletions cmd/http/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,31 +21,33 @@ import (
)

type configuration struct {
logger *logger.Config
owasp *owasp.Config
alcotest *alcotest.Config
telemetry *telemetry.Config
pprof *pprof.Config
cors *cors.Config
renderer *renderer.Config
logger *logger.Config
alcotest *alcotest.Config
telemetry *telemetry.Config
pprof *pprof.Config
health *health.Config

server *server.Config
owasp *owasp.Config
cors *cors.Config
renderer *renderer.Config

amqp *amqp.Config
redis *redis.Config
amqHandler *amqphandler.Config
appServer *server.Config
health *health.Config
redis *redis.Config
}

func newConfig() configuration {
fs := flag.NewFlagSet("http", flag.ExitOnError)
fs.Usage = flags.Usage(fs)

config := configuration{
appServer: server.Flags(fs, ""),
health: health.Flags(fs, ""),
alcotest: alcotest.Flags(fs, ""),
logger: logger.Flags(fs, "logger"),
alcotest: alcotest.Flags(fs, ""),
telemetry: telemetry.Flags(fs, "telemetry"),
pprof: pprof.Flags(fs, "pprof"),
health: health.Flags(fs, ""),
server: server.Flags(fs, ""),
owasp: owasp.Flags(fs, "", flags.NewOverride("Csp", "default-src 'self'; base-uri 'self'; script-src 'httputils-nonce'")),
cors: cors.Flags(fs, "cors"),
amqp: amqp.Flags(fs, "amqp"),
Expand Down
27 changes: 11 additions & 16 deletions cmd/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package main

import (
"context"
"embed"
"syscall"

"github.com/ViBiOh/httputils/v4/pkg/alcotest"
Expand All @@ -13,34 +12,30 @@ import (
"github.com/ViBiOh/httputils/v4/pkg/server"
)

//go:embed templates static
var content embed.FS

func main() {
config := newConfig()
alcotest.DoAndExit(config.alcotest)

ctx := context.Background()

client, err := newClient(ctx, config)
clients, err := newClient(ctx, config)
logger.FatalfOnErr(ctx, err, "client")

go client.Start()
defer client.Close(ctx)
go clients.Start()
defer clients.Close(ctx)

ctxEnd := client.health.EndCtx()
ctxEnd := clients.health.EndCtx()

adapter, err := newAdapter(ctxEnd, config, client)
adapters, err := newAdapters(ctxEnd, config, clients)
logger.FatalfOnErr(ctx, err, "adapter")

startBackground(ctxEnd, client, adapter)

handler := newPort(config, client, adapter)
startBackground(ctxEnd, clients, adapters)

appServer := server.New(config.appServer)
services := newServices(config)
port := newPort(config, clients, adapters)

go appServer.Start(ctxEnd, httputils.Handler(handler, client.health, client.telemetry.Middleware("http"), owasp.New(config.owasp).Middleware, cors.New(config.cors).Middleware))
go services.server.Start(ctxEnd, httputils.Handler(port, clients.health, clients.telemetry.Middleware("http"), owasp.New(config.owasp).Middleware, cors.New(config.cors).Middleware))

client.health.WaitForTermination(appServer.Done(), syscall.SIGTERM, syscall.SIGINT)
server.GracefulWait(appServer.Done(), adapter.amqp.Done())
clients.health.WaitForTermination(services.server.Done(), syscall.SIGTERM, syscall.SIGINT)
server.GracefulWait(services.server.Done(), adapters.amqp.Done())
}
6 changes: 3 additions & 3 deletions cmd/http/port.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import (
"go.opentelemetry.io/otel/trace"
)

func newPort(config configuration, client client, adapter adapter) http.Handler {
func newPort(config configuration, client clients, adapter adapters) http.Handler {
mux := http.NewServeMux()

adapter.renderer.Register(mux, getDefaultRenderer(config, client, adapter))
mux.Handle(config.renderer.PathPrefix+"/", adapter.renderer.NewServeMux(getDefaultRenderer(config, client, adapter)))

return mux
}

func getDefaultRenderer(config configuration, client client, adapter adapter) func(http.ResponseWriter, *http.Request) (renderer.Page, error) {
func getDefaultRenderer(config configuration, client clients, adapter adapters) func(http.ResponseWriter, *http.Request) (renderer.Page, error) {
portTracer := client.telemetry.TracerProvider().Tracer("port")

return func(_ http.ResponseWriter, r *http.Request) (renderer.Page, error) {
Expand Down
15 changes: 15 additions & 0 deletions cmd/http/services.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package main

import (
"github.com/ViBiOh/httputils/v4/pkg/server"
)

type services struct {
server *server.Server
}

func newServices(config configuration) services {
return services{
server: server.New(config.server),
}
}
2 changes: 1 addition & 1 deletion pkg/amqphandler/retry.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (

var ErrNoDeathCount = errors.New("no death count")

func (s Service) Retry(message amqp.Delivery) error {
func (s *Service) Retry(message amqp.Delivery) error {
count, err := GetDeathCount(message)
if err != nil && !errors.Is(err, ErrNoDeathCount) {
return fmt.Errorf("get death count from message: %w", err)
Expand Down
24 changes: 7 additions & 17 deletions pkg/httputils/httputils.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package httputils

import (
"fmt"
"log/slog"
"net/http"

Expand All @@ -10,26 +11,15 @@ import (
)

func Handler(handler http.Handler, healthService *health.Service, middlewares ...model.Middleware) http.Handler {
versionHandler := versionHandler()
HealthHandler := healthService.HealthHandler()
readyHandler := healthService.ReadyHandler()
appHandler := model.ChainMiddlewares(handler, append([]model.Middleware{httprecover.Middleware}, middlewares...)...)
mux := http.NewServeMux()

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case health.LivePath:
HealthHandler.ServeHTTP(w, r)

case health.ReadyPath:
readyHandler.ServeHTTP(w, r)
mux.Handle(fmt.Sprintf("GET %s", health.LivePath), healthService.HealthHandler())
mux.Handle(fmt.Sprintf("GET %s", health.ReadyPath), healthService.ReadyHandler())

case "/version":
versionHandler.ServeHTTP(w, r)
mux.Handle("GET /version", versionHandler())
mux.Handle("GET /", model.ChainMiddlewares(handler, append([]model.Middleware{httprecover.Middleware}, middlewares...)...))

default:
appHandler.ServeHTTP(w, r)
}
})
return mux
}

func versionHandler() http.Handler {
Expand Down
4 changes: 2 additions & 2 deletions pkg/logger/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,6 @@ func FatalfOnErr(ctx context.Context, err error, msg string, args ...slog.Attr)
os.Exit(1)
}

func AddOpenTelemetryToDefaultLogger(telemetryApp telemetry.Service) {
slog.SetDefault(slog.New(telemetryApp.AddTraceToLogHandler(slog.Default().Handler())))
func AddOpenTelemetryToDefaultLogger(telemetry *telemetry.Service) {
slog.SetDefault(slog.New(telemetry.AddTraceToLogHandler(slog.Default().Handler())))
}
16 changes: 8 additions & 8 deletions pkg/pprof/pprof.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func Flags(fs *flag.FlagSet, prefix string, overrides ...flags.Override) *Config
return &config
}

func New(config *Config, service, version, env string) Service {
func New(config *Config, service, version, env string) *Service {
instance := Service{
port: config.Port,
}
Expand All @@ -61,10 +61,10 @@ func New(config *Config, service, version, env string) Service {
instance.env = env
}

return instance
return &instance
}

func (s Service) Start(ctx context.Context) {
func (s *Service) Start(ctx context.Context) {
if s.port > 0 {
go s.http(ctx)
}
Expand All @@ -74,13 +74,13 @@ func (s Service) Start(ctx context.Context) {
}
}

func (s Service) http(ctx context.Context) {
func (s *Service) http(ctx context.Context) {
if err := http.ListenAndServe(fmt.Sprintf("localhost:%d", s.port), http.DefaultServeMux); err != nil {
slog.LogAttrs(ctx, slog.LevelError, fmt.Sprintf("pprof http: %s", err.Error()))
}
}

func (s Service) push(ctx context.Context) {
func (s *Service) push(ctx context.Context) {
defer recoverer.Logger()

ticker := time.NewTicker(time.Minute)
Expand All @@ -98,7 +98,7 @@ func (s Service) push(ctx context.Context) {
}
}

func (s Service) send(ctx context.Context) error {
func (s *Service) send(ctx context.Context) error {
now := time.Now()

if err := s.getCpuProfile(); err != nil {
Expand All @@ -117,7 +117,7 @@ func (s Service) send(ctx context.Context) error {
return nil
}

func (s Service) getCpuProfile() error {
func (s *Service) getCpuProfile() error {
s.buffer.Reset()

if err := pprof.StartCPUProfile(s.buffer); err != nil {
Expand All @@ -130,7 +130,7 @@ func (s Service) getCpuProfile() error {
return nil
}

func (s Service) writeMultipart(ctx context.Context, now time.Time) func(*multipart.Writer) error {
func (s *Service) writeMultipart(ctx context.Context, now time.Time) func(*multipart.Writer) error {
return func(mw *multipart.Writer) error {
if err := mw.WriteField("version", "3"); err != nil {
return fmt.Errorf("write field `version`: %w", err)
Expand Down
9 changes: 0 additions & 9 deletions pkg/query/path.go

This file was deleted.

39 changes: 0 additions & 39 deletions pkg/query/path_test.go

This file was deleted.

Loading

0 comments on commit 9909349

Please sign in to comment.