Skip to content

Commit

Permalink
Fix DB session cloning on each new request
Browse files Browse the repository at this point in the history
  • Loading branch information
violog committed Feb 22, 2024
1 parent d987f1f commit 4c85d77
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 5 deletions.
28 changes: 28 additions & 0 deletions internal/service/handlers/middleware.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package handlers

import (
"context"
"net/http"

"github.com/rarimo/auth-svc/pkg/auth"
"github.com/rarimo/rarime-points-svc/internal/data/pg"
"gitlab.com/distributed_lab/ape"
"gitlab.com/distributed_lab/ape/problems"
"gitlab.com/distributed_lab/kit/pgdb"
"gitlab.com/distributed_lab/logan/v3"
)

Expand All @@ -29,3 +32,28 @@ func AuthMiddleware(auth *auth.Client, log *logan.Entry) func(http.Handler) http
})
}
}

type ctxExtender func(context.Context) context.Context

// DBCloneMiddleware is designed to clone DB session on each request. You must
// put all new DB handlers here instead of ape.CtxMiddleware, unless you have a
// reason to do otherwise.
func DBCloneMiddleware(db *pgdb.DB) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
clone := db.Clone()
ctx := r.Context()

extenders := []ctxExtender{
CtxEventsQ(pg.NewEvents(clone)),
CtxBalancesQ(pg.NewBalances(clone)),
CtxWithdrawalsQ(pg.NewWithdrawals(clone)),
}

for _, extender := range extenders {
ctx = extender(ctx)
}
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
6 changes: 1 addition & 5 deletions internal/service/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,23 @@ import (

"github.com/go-chi/chi"
"github.com/rarimo/rarime-points-svc/internal/config"
"github.com/rarimo/rarime-points-svc/internal/data/pg"
"github.com/rarimo/rarime-points-svc/internal/service/handlers"
"gitlab.com/distributed_lab/ape"
)

func Run(ctx context.Context, cfg config.Config) {
r := chi.NewRouter()
db := cfg.DB().Clone()

r.Use(
ape.RecoverMiddleware(cfg.Log()),
ape.LoganMiddleware(cfg.Log()),
ape.CtxMiddleware(
handlers.CtxLog(cfg.Log()),
handlers.CtxEventsQ(pg.NewEvents(db)),
handlers.CtxBalancesQ(pg.NewBalances(db)),
handlers.CtxWithdrawalsQ(pg.NewWithdrawals(db)),
handlers.CtxEventTypes(cfg.EventTypes()),
handlers.CtxBroadcaster(cfg.Broadcaster()),
handlers.CtxPointPrice(cfg.PointPrice()),
),
handlers.DBCloneMiddleware(cfg.DB()),
)
r.Route("/integrations/rarime-points-svc/v1", func(r chi.Router) {
r.Route("/balances", func(r chi.Router) {
Expand Down

0 comments on commit 4c85d77

Please sign in to comment.