Something went wrong. Try again.
forked from scottlanoue.com/atmosphere-mail
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155// SPDX-License-Identifier: AGPL-3.0-or-later
package server
import ( "fmt" "net/http" "sync" "sync/atomic" "time"
"github.com/gorilla/websocket"
"comail/internal/store")
const ( maxWebSocketConns = 100 maxBackfillLabels = 10000)
// PLCTombstoneStats is the subset of internal/scheduler.TombstoneStats// the metrics endpoint needs. Defining the interface here (rather than// importing scheduler) avoids a server→scheduler import cycle when the// scheduler grows to depend on label, which depends on store, which is// where Server lives via internal/server.type PLCTombstoneStats struct { ChecksOK int64 ChecksTombstoned int64 ChecksErr int64 LastRunAt time.Time // zero if the checker has never run}
// Server handles XRPC endpoints for the labeler.type Server struct { store *store.Store labelerDID string mux *http.ServeMux wsConns atomic.Int64
// plcTombstoneStats, when non-nil, is called by the /metrics handler // to surface PLC-tombstone-check counters. The labeler wires this // after constructing the checker; tests leave it nil to keep the // metrics endpoint behavior stable. plcTombstoneStats func() PLCTombstoneStats
// WebSocket connection tracking for graceful shutdown wsMu sync.Mutex wsTracked map[*websocket.Conn]struct{}}
// SetPLCTombstoneStatsProvider wires a PLC tombstone-check stats source// into the metrics endpoint. Calling with nil unwires it. Safe to call// at most once during startup; not concurrency-safe with active /metrics// requests (those would observe a torn read of the func pointer).func (s *Server) SetPLCTombstoneStatsProvider(fn func() PLCTombstoneStats) { s.plcTombstoneStats = fn}
// New creates a labeler XRPC server.func New(s *store.Store, labelerDID string) *Server { srv := &Server{ store: s, labelerDID: labelerDID, mux: http.NewServeMux(), wsTracked: make(map[*websocket.Conn]struct{}), } srv.mux.HandleFunc("/xrpc/com.atproto.label.queryLabels", srv.handleQueryLabels) srv.mux.HandleFunc("/xrpc/com.atproto.label.subscribeLabels", srv.handleSubscribeLabels) srv.mux.HandleFunc("/xrpc/email.atmos.getVerificationStatus", srv.handleGetVerificationStatus) srv.mux.HandleFunc("/healthz", srv.handleHealthz) srv.mux.HandleFunc("/metrics", srv.handleMetrics) return srv}
// Handler returns the HTTP handler for this server.func (s *Server) Handler() http.Handler { return s.mux}
func (s *Server) handleHealthz(w http.ResponseWriter, r *http.Request) { ctx := r.Context() if err := s.store.Ping(ctx); err != nil { http.Error(w, "database unreachable", http.StatusServiceUnavailable) return } w.WriteHeader(http.StatusOK) w.Write([]byte("ok\n"))}
func (s *Server) handleMetrics(w http.ResponseWriter, r *http.Request) { ctx := r.Context() stats, err := s.store.Stats(ctx) if err != nil { http.Error(w, "internal error", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/plain; version=0.0.4; charset=utf-8") fmt.Fprintf(w, "# HELP atmosphere_labels_total Total number of labels in the store.\n") fmt.Fprintf(w, "# TYPE atmosphere_labels_total gauge\n") fmt.Fprintf(w, "atmosphere_labels_total %d\n", stats.Labels) fmt.Fprintf(w, "# HELP atmosphere_attestations_total Total number of attestations in the store.\n") fmt.Fprintf(w, "# TYPE atmosphere_attestations_total gauge\n") fmt.Fprintf(w, "atmosphere_attestations_total %d\n", stats.Attestations) fmt.Fprintf(w, "# HELP atmosphere_websocket_connections Current number of WebSocket connections.\n") fmt.Fprintf(w, "# TYPE atmosphere_websocket_connections gauge\n") fmt.Fprintf(w, "atmosphere_websocket_connections %d\n", s.wsConns.Load())
if s.plcTombstoneStats != nil { ts := s.plcTombstoneStats() fmt.Fprintf(w, "# HELP labeler_plc_status_checks_total PLC status checks per outcome.\n") fmt.Fprintf(w, "# TYPE labeler_plc_status_checks_total counter\n") fmt.Fprintf(w, "labeler_plc_status_checks_total{result=\"ok\"} %d\n", ts.ChecksOK) fmt.Fprintf(w, "labeler_plc_status_checks_total{result=\"tombstoned\"} %d\n", ts.ChecksTombstoned) fmt.Fprintf(w, "labeler_plc_status_checks_total{result=\"err\"} %d\n", ts.ChecksErr) // last-run timestamp lets ops alert on staleness ("checker // hasn't run in 48h" etc). Zero means never run, so emit only // when populated. if !ts.LastRunAt.IsZero() { fmt.Fprintf(w, "# HELP labeler_plc_status_last_run_unix_seconds Unix timestamp of last completed PLC tombstone-check pass.\n") fmt.Fprintf(w, "# TYPE labeler_plc_status_last_run_unix_seconds gauge\n") fmt.Fprintf(w, "labeler_plc_status_last_run_unix_seconds %d\n", ts.LastRunAt.Unix()) } }}
func (s *Server) trackConn(conn *websocket.Conn) { s.wsMu.Lock() s.wsTracked[conn] = struct{}{} s.wsMu.Unlock()}
func (s *Server) untrackConn(conn *websocket.Conn) { s.wsMu.Lock() delete(s.wsTracked, conn) s.wsMu.Unlock()}
// ShutdownWebSockets sends close frames to all active WebSocket connections// and waits briefly for them to acknowledge.func (s *Server) ShutdownWebSockets() { s.wsMu.Lock() conns := make([]*websocket.Conn, 0, len(s.wsTracked)) for c := range s.wsTracked { conns = append(conns, c) } s.wsMu.Unlock()
closeMsg := websocket.FormatCloseMessage(websocket.CloseGoingAway, "server shutting down") for _, c := range conns { c.WriteControl(websocket.CloseMessage, closeMsg, time.Now().Add(2*time.Second)) c.Close() }}