forked from mtusi2026/mtusi2026lab4
73 lines
1.8 KiB
Go
73 lines
1.8 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/redis/go-redis/v9"
|
|
|
|
"mtusi2026/internal/blobstore"
|
|
)
|
|
|
|
func handleHealthLive(w http.ResponseWriter, r *http.Request) {
|
|
writeJSON(w, http.StatusOK, newRequestID(), map[string]string{"status": "ok"})
|
|
}
|
|
|
|
type blobProbe struct {
|
|
mu sync.Mutex
|
|
at time.Time
|
|
err error
|
|
st blobstore.Store
|
|
}
|
|
|
|
func (p *blobProbe) check(ctx context.Context) error {
|
|
p.mu.Lock()
|
|
defer p.mu.Unlock()
|
|
if time.Since(p.at) < time.Second {
|
|
return p.err
|
|
}
|
|
cctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
|
defer cancel()
|
|
p.err = p.st.Ping(cctx)
|
|
p.at = time.Now()
|
|
return p.err
|
|
}
|
|
|
|
func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, blobs blobstore.Store, draining *atomic.Bool) http.HandlerFunc {
|
|
var probe *blobProbe
|
|
if blobs != nil {
|
|
probe = &blobProbe{st: blobs}
|
|
}
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
requestID := newRequestID()
|
|
if draining.Load() {
|
|
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "shutting down")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
|
defer cancel()
|
|
|
|
if err := pool.Ping(ctx); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
|
return
|
|
}
|
|
if rdb != nil {
|
|
if err := rdb.Ping(ctx).Err(); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "session store unavailable")
|
|
return
|
|
}
|
|
}
|
|
if probe != nil {
|
|
if err := probe.check(ctx); err != nil {
|
|
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
|
return
|
|
}
|
|
}
|
|
writeJSON(w, http.StatusOK, requestID, map[string]string{"status": "ok"})
|
|
}
|
|
}
|