Files
Repinoid 3036572ccc P1-9: readiness-проба /ready отражает состояние bridge/consumer
/health остаётся liveness (процесс жив); /ready возвращает 503, если bridge или
consumer не в строю (горутина упала/не поднялась). Добавлен api.Readiness с
atomic-флагами, NewRouter принимает *Readiness, main поднимает/опускает флаги
вокруг фоновых горутин.
2026-10-07 07:25:09 +03:00

91 lines
4.0 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package api — HTTP-сервер монолита: маршруты, CORS, health.
package api
import (
"log/slog"
"net/http"
"github.com/gorilla/mux"
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/api/handler"
"gitea.services.ngcloud.ru/Nail/IoT/internal/service/api/middleware"
)
// corsMiddleware добавляет CORS-заголовки (консоль и API на одном домене платформы).
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
// NewRouter собирает все маршруты сервиса.
func NewRouter(h *handler.Handler, log *slog.Logger, authTestMode bool, jwtHMACSecret string, version string, ready *Readiness) http.Handler {
r := mux.NewRouter()
// Health — для платформенных проверок контейнера (liveness).
r.HandleFunc("/health", healthHandler(version)).Methods(http.MethodGet)
r.HandleFunc("/healthz", healthHandler(version)).Methods(http.MethodGet)
// Ready — readiness: 503, если фоновые подсистемы (bridge/consumer) не в строю.
r.HandleFunc("/ready", readyHandler(ready)).Methods(http.MethodGet)
// Лендинг "/" — инструкция (дизайн Nubes, как у shared-sqs) + статика.
r.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
ServeLanding(w, req, version)
}).Methods(http.MethodGet)
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", StaticHandler()))
// UI — публичные страницы (без данных).
r.HandleFunc("/console", ServeIoTConsole).Methods(http.MethodGet)
r.HandleFunc("/iot-admin", ServeIoTAdmin).Methods(http.MethodGet)
// Админ-статистика — свой Bearer-токен.
r.HandleFunc("/iot-admin/stats", h.AdminStats).Methods(http.MethodGet)
// /v1 — под JWT.
v1 := r.PathPrefix("/v1").Subrouter()
v1.HandleFunc("/namespaces/{namespace}/iot/devices", h.ListIoTDevices).Methods(http.MethodGet)
v1.HandleFunc("/namespaces/{namespace}/iot/devices", h.CreateIoTDevice).Methods(http.MethodPost)
v1.HandleFunc("/namespaces/{namespace}/iot/devices/{name}", h.GetIoTDevice).Methods(http.MethodGet)
v1.HandleFunc("/namespaces/{namespace}/iot/devices/{name}", h.DeleteIoTDevice).Methods(http.MethodDelete)
v1.HandleFunc("/namespaces/{namespace}/iot/devices/{name}", h.UpdateIoTDevice).Methods(http.MethodPatch)
v1.HandleFunc("/namespaces/{namespace}/iot/telemetry", h.ListIoTTelemetry).Methods(http.MethodGet)
v1.Use(func(next http.Handler) http.Handler {
return middleware.Auth(authTestMode, jwtHMACSecret, log, next)
})
return corsMiddleware(middleware.Logging(log, r))
}
// healthHandler отдаёт статус сервиса и версию (для платформы).
func healthHandler(version string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ok","version":"` + version + `"}`))
}
}
// readyHandler отдаёт 200 если все подсистемы в строю, иначе 503.
// Отделяет readiness от liveness: процесс может быть жив, но pipeline стоять.
func readyHandler(ready *Readiness) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if ready != nil && !ready.Ready() {
w.WriteHeader(http.StatusServiceUnavailable)
_, _ = w.Write([]byte(`{"status":"not ready"}`))
return
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"status":"ready"}`))
}
}