Skip to content

Commit

Permalink
chore: cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
acha-bill committed Apr 11, 2024
1 parent e268a7c commit 4916047
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 104 deletions.
161 changes: 63 additions & 98 deletions pkg/api/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,86 +26,9 @@ const (
rootPath = "/" + apiVersion
)

func (s *Service) MountTechnicalDebug() {
router := mux.NewRouter()
router.NotFoundHandler = http.HandlerFunc(jsonhttp.NotFoundHandler)
s.router = router

s.mountTechnicalDebug()

s.Handler = web.ChainHandlers(
httpaccess.NewHTTPAccessLogHandler(s.logger, s.tracer, "debug api access"),
handlers.CompressHandler,
s.corsHandler,
web.NoCacheHeadersHandler,
web.FinalHandler(router),
)
}

func (s *Service) MountDebug() {
s.mountBusinessDebug()

s.Handler = web.ChainHandlers(
httpaccess.NewHTTPAccessLogHandler(s.logger, s.tracer, "debug api access"),
handlers.CompressHandler,
s.corsHandler,
web.NoCacheHeadersHandler,
web.FinalHandler(s.router),
)
}

func (s *Service) MountAPI() {
if s.router == nil {
s.router = mux.NewRouter()
s.router.NotFoundHandler = http.HandlerFunc(jsonhttp.NotFoundHandler)
}

s.mountAPI()

compressHandler := func(h http.Handler) http.Handler {
downloadEndpoints := []string{
"/bzz",
"/bytes",
"/chunks",
rootPath + "/bzz",
rootPath + "/bytes",
rootPath + "/chunks",
}

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip compression for GET requests on download endpoints.
// This is done in order to preserve Content-Length header in response,
// because CompressHandler is always removing it.
if r.Method == http.MethodGet {
for _, endpoint := range downloadEndpoints {
if strings.HasPrefix(r.URL.Path, endpoint) {
h.ServeHTTP(w, r)
return
}
}
}

if r.Method == http.MethodHead {
h.ServeHTTP(w, r)
return
}

handlers.CompressHandler(h).ServeHTTP(w, r)
})
}

s.Handler = web.ChainHandlers(
httpaccess.NewHTTPAccessLogHandler(s.logger, s.tracer, "api access"),
compressHandler,
s.responseCodeMetricsHandler,
s.pageviewMetricsHandler,
s.corsHandler,
web.FinalHandler(s.router),
)
}

func (s *Service) mountTechnicalDebug() {
handle := func(path string, handler http.Handler) {
handler = web.ChainHandlers(web.NoCacheHeadersHandler, web.FinalHandler(handler)) // no-cache for debug endpoints
if s.Restricted {
handler = web.ChainHandlers(auth.PermissionCheckHandler(s.auth), web.FinalHandler(handler))
}
Expand Down Expand Up @@ -178,16 +101,6 @@ func (s *Service) mountTechnicalDebug() {
web.FinalHandlerFunc(s.loggerSetVerbosityHandler),
),
})

handle("/readiness", web.ChainHandlers(
httpaccess.NewHTTPAccessSuppressLogHandler(),
web.FinalHandlerFunc(s.readinessHandler),
))

handle("/health", web.ChainHandlers(
httpaccess.NewHTTPAccessSuppressLogHandler(),
web.FinalHandlerFunc(s.healthHandler),
))
}

func (s *Service) mountAPI() {
Expand Down Expand Up @@ -381,6 +294,7 @@ func (s *Service) mountAPI() {

func (s *Service) mountBusinessDebug() {
handle := func(path string, handler http.Handler) {
handler = web.ChainHandlers(web.NoCacheHeadersHandler, web.FinalHandler(handler)) // no-cache for debug endpoints
if s.Restricted {
handler = web.ChainHandlers(auth.PermissionCheckHandler(s.auth), web.FinalHandler(handler))
}
Expand Down Expand Up @@ -579,16 +493,6 @@ func (s *Service) mountBusinessDebug() {
"GET": http.HandlerFunc(s.accountingInfoHandler),
})

handle("/readiness", web.ChainHandlers(
httpaccess.NewHTTPAccessSuppressLogHandler(),
web.FinalHandlerFunc(s.readinessHandler),
))

handle("/health", web.ChainHandlers(
httpaccess.NewHTTPAccessSuppressLogHandler(),
web.FinalHandlerFunc(s.healthHandler),
))

handle("/stake/{amount}", web.ChainHandlers(
s.stakingAccessHandler,
s.gasConfigMiddleware("deposit stake"),
Expand Down Expand Up @@ -630,3 +534,64 @@ func (s *Service) mountBusinessDebug() {
}),
))
}

func (s *Service) MountAPIs() {
router := mux.NewRouter()
router.NotFoundHandler = http.HandlerFunc(jsonhttp.NotFoundHandler)
s.router = router

s.mountTechnicalDebug()
s.mountAPI()
s.mountBusinessDebug()

compressHandler := func(h http.Handler) http.Handler {
downloadEndpoints := []string{
"/bzz",
"/bytes",
"/chunks",
rootPath + "/bzz",
rootPath + "/bytes",
rootPath + "/chunks",
}

return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip compression for GET requests on download endpoints.
// This is done in order to preserve Content-Length header in response,
// because CompressHandler is always removing it.
if r.Method == http.MethodGet {
for _, endpoint := range downloadEndpoints {
if strings.HasPrefix(r.URL.Path, endpoint) {
h.ServeHTTP(w, r)
return
}
}
}

if r.Method == http.MethodHead {
h.ServeHTTP(w, r)
return
}

handlers.CompressHandler(h).ServeHTTP(w, r)
})
}

s.Handler = web.ChainHandlers(
httpaccess.NewHTTPAccessLogHandler(s.logger, s.tracer, "api access"),
compressHandler,
s.responseCodeMetricsHandler,
s.pageviewMetricsHandler,
s.corsHandler,
web.FinalHandler(router),
)
}

func (s *Service) ListEndpoints() []string {
var routes []string
s.router.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error {
tpl, _ := route.GetPathTemplate()
routes = append(routes, tpl)
return nil
})
return routes
}
4 changes: 1 addition & 3 deletions pkg/node/devnode.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,9 +372,7 @@ func NewDevBee(logger log.Logger, o *DevOptions) (b *DevBee, err error) {
WsPingPeriod: 60 * time.Second,
Restricted: o.Restricted,
}, debugOpts, 1, erc20)
apiService.MountAPI()
apiService.MountDebug()
apiService.MountTechnicalDebug()
apiService.MountAPIs()

apiService.SetP2P(p2ps)
apiService.SetSwarmAddress(&swarmAddress)
Expand Down
8 changes: 5 additions & 3 deletions pkg/node/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -1012,9 +1012,7 @@ func NewBee(
Restricted: o.Restricted,
}, extraOpts, chainID, erc20Service)

apiService.MountAPI()
apiService.MountDebug()
apiService.MountTechnicalDebug()
apiService.MountAPIs()

apiServer := &http.Server{
IdleTimeout: 30 * time.Second,
Expand All @@ -1030,6 +1028,10 @@ func NewBee(

go func() {
logger.Info("starting api server", "address", apiListener.Addr())
routes := apiService.ListEndpoints()
for _, r := range routes {
logger.Debug("api endpoint registered", "path", r)
}
if err := apiServer.Serve(apiListener); err != nil && !errors.Is(err, http.ErrServerClosed) {
logger.Debug("api server failed to start", "error", err)
logger.Error(nil, "api server failed to start")
Expand Down

0 comments on commit 4916047

Please sign in to comment.