69 lines
2.6 KiB
Go
69 lines
2.6 KiB
Go
// Package httpserver exposes health and authenticated task-management endpoints.
|
|
package httpserver
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.yuntuo.hk/k2safe/orbit/internal/buildinfo"
|
|
"git.yuntuo.hk/k2safe/orbit/internal/observability"
|
|
"git.yuntuo.hk/k2safe/orbit/pulse/service"
|
|
)
|
|
|
|
type Checker func(context.Context) error
|
|
|
|
func New(addr string, ready Checker, tasks ...*service.Service) *http.Server {
|
|
mux := http.NewServeMux()
|
|
write := func(w http.ResponseWriter, status int, body map[string]string) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(status)
|
|
_ = json.NewEncoder(w).Encode(body)
|
|
}
|
|
mux.HandleFunc("GET /health/live", func(w http.ResponseWriter, r *http.Request) {
|
|
write(w, http.StatusOK, map[string]string{"status": "alive"})
|
|
})
|
|
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, r *http.Request) {
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
if ready == nil || ready(ctx) != nil {
|
|
write(w, http.StatusServiceUnavailable, map[string]string{"status": "not_ready"})
|
|
return
|
|
}
|
|
write(w, http.StatusOK, map[string]string{"status": "ready", "scope": "database_and_schema"})
|
|
})
|
|
mux.HandleFunc("GET /version", func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
w.Header().Set("X-Content-Type-Options", "nosniff")
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
_ = json.NewEncoder(w).Encode(buildinfo.Current())
|
|
})
|
|
if len(tasks) > 0 && tasks[0] != nil {
|
|
registerTasks(mux, tasks[0])
|
|
registerHistory(mux, tasks[0])
|
|
}
|
|
return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 10 * time.Second, WriteTimeout: 15 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10}
|
|
}
|
|
|
|
// WrapMetrics must run after all Register* functions because those functions
|
|
// intentionally register routes on the underlying ServeMux.
|
|
func WrapMetrics(server *http.Server, metrics *observability.Registry) {
|
|
if server == nil || metrics == nil {
|
|
return
|
|
}
|
|
server.Handler = metrics.Middleware(server.Handler)
|
|
}
|
|
|
|
// NewMetricsServer uses a distinct listener so public API routing cannot expose
|
|
// operational aggregates. It does not provide business or database endpoints.
|
|
func NewMetricsServer(addr string, metrics *observability.Registry) *http.Server {
|
|
mux := http.NewServeMux()
|
|
if metrics != nil {
|
|
mux.Handle("GET /metrics", metrics)
|
|
}
|
|
return &http.Server{Addr: addr, Handler: mux, ReadHeaderTimeout: 2 * time.Second,
|
|
ReadTimeout: 3 * time.Second, WriteTimeout: 5 * time.Second, IdleTimeout: 15 * time.Second, MaxHeaderBytes: 8 << 10}
|
|
}
|