Skip to content

Commit

Permalink
Alternate timeout system
Browse files Browse the repository at this point in the history
  • Loading branch information
yottapanda committed Jan 19, 2025
1 parent a3eeaec commit 4b25326
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 19 deletions.
5 changes: 2 additions & 3 deletions internal/routes/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ import (
"io/fs"
"net/http"
"strings"
"time"
)

func CreateRouter(cfg *config.Config) *chi.Mux {
r := chi.NewRouter()

cspParts := []string{"default-src 'self'", "style-src 'self' 'unsafe-inline'"}
scriptSources := []string{"'self'"}
connectSources := []string{"'self'"}
connectSources := []string{"'self' accounts.spotify.com"}
if cfg.Plausible.ScriptUrl != "" {
scriptSources = append(scriptSources, cfg.Plausible.Origin)
connectSources = append(connectSources, cfg.Plausible.Origin)
Expand All @@ -42,7 +41,7 @@ func CreateRouter(cfg *config.Config) *chi.Mux {

r.Route("/", func(r chi.Router) {
r.Get("/", Root)
r.With(TimeoutMiddleware(5*time.Minute)).Get("/sync", Sync)
r.Get("/sync", Sync)
r.Get("/login", Login)
r.Get("/logout", Logout)
r.Get("/callback", Callback)
Expand Down
21 changes: 5 additions & 16 deletions internal/routes/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,6 @@ import (
"time"
)

func TimeoutMiddleware(timeout time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), timeout)
defer cancel()

next.ServeHTTP(w, r.WithContext(ctx))

deadline, ok := ctx.Deadline()
if !ok || time.Now().Before(deadline) {
logrus.Errorln("Request timed out")
}
})
}
}

func Sync(w http.ResponseWriter, r *http.Request) {
s, err := auth.GetClient(r)
if err != nil {
Expand All @@ -34,6 +18,11 @@ func Sync(w http.ResponseWriter, r *http.Request) {
return
}

// Custom long context timeout
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute)
defer cancel()
r = r.WithContext(ctx)

syncResponse := sync.Sync(r.Context(), s)

err = views.Outcome(&syncResponse).Render(w)
Expand Down

0 comments on commit 4b25326

Please sign in to comment.