Files
Pulse/internal/api/upgrade_metrics_handlers.go
2026-03-18 16:06:30 +00:00

313 lines
9.1 KiB
Go

package api
import (
"encoding/json"
"net/http"
"strings"
"time"
"github.com/rs/zerolog/log"
)
type ConversionHandlers struct {
recorder *conversionRecorder
health *conversionPipelineHealth
config *conversionCollectionConfig
store *conversionStore
// disableAll, when true, forces all event ingestion to be skipped for privacy.
// This is a hard override; runtime collection config remains mutable but is ignored.
disableAll func() bool
}
func NewConversionHandlers(recorder *conversionRecorder, health *conversionPipelineHealth, config *conversionCollectionConfig, store *conversionStore, disableAll func() bool) *ConversionHandlers {
return &ConversionHandlers{
recorder: recorder,
health: health,
config: config,
store: store,
disableAll: disableAll,
}
}
func (h *ConversionHandlers) HandleRecordEvent(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var event conversionEvent
if err := json.NewDecoder(r.Body).Decode(&event); err != nil {
recordConversionInvalidMetric("invalid_request_body")
writeConversionValidationError(w, "invalid request body")
return
}
if err := event.Validate(); err != nil {
recordConversionInvalidMetric(conversionValidationReason(err))
writeConversionValidationError(w, err.Error())
return
}
contextOrgID := strings.TrimSpace(GetOrgID(r.Context()))
if contextOrgID == "" {
contextOrgID = "default"
}
if !isValidOrganizationID(contextOrgID) {
recordConversionInvalidMetric("invalid_context_org_id")
writeConversionValidationError(w, "invalid tenant context")
return
}
event.OrgID = strings.TrimSpace(event.OrgID)
if event.OrgID == "" {
event.OrgID = contextOrgID
} else {
if !isValidOrganizationID(event.OrgID) {
recordConversionInvalidMetric("invalid_event_org_id")
writeConversionValidationError(w, "invalid org_id")
return
}
if event.OrgID != contextOrgID {
recordConversionInvalidMetric("org_id_mismatch")
writeConversionJSONResponse(w, http.StatusForbidden, map[string]string{
"error": "org_mismatch",
"message": "org_id does not match authenticated tenant",
}, "HandleRecordEvent")
return
}
}
if h != nil && h.disableAll != nil && h.disableAll() {
recordConversionSkippedMetric("system_disabled")
writeConversionAccepted(w)
return
}
if h != nil && h.config != nil && !h.config.IsSurfaceEnabled(event.Surface) {
reason := "surface_disabled"
if !h.config.IsEnabled() {
reason = "collection_disabled"
}
recordConversionSkippedMetric(reason)
writeConversionAccepted(w)
return
}
if h != nil && h.recorder != nil {
if err := h.recorder.Record(event); err != nil {
// Analytics ingestion is fire-and-forget; do not fail UX if recording fails.
log.Warn().Err(err).Str("event_type", event.Type).Msg("Failed to record conversion event")
} else {
recordConversionEventMetric(event.Type, event.Surface)
if h.health != nil {
h.health.RecordEvent(event.Type)
}
}
}
writeConversionAccepted(w)
}
// HandleConversionFunnel returns conversion funnel counts for admin reporting.
// GET /api/admin/upgrade-metrics-funnel?org_id=...&from=...&to=...
func (h *ConversionHandlers) HandleConversionFunnel(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
if h == nil || h.store == nil {
http.Error(w, "Conversion store unavailable", http.StatusServiceUnavailable)
return
}
orgID := strings.TrimSpace(r.URL.Query().Get("org_id"))
contextOrgID := strings.TrimSpace(GetOrgID(r.Context()))
if orgID == "" {
orgID = contextOrgID
} else if contextOrgID != "" && orgID != contextOrgID {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
if orgID == "" {
http.Error(w, "org_id is required", http.StatusBadRequest)
return
}
now := time.Now().UTC()
to, err := parseOptionalTimeParam(r.URL.Query().Get("to"), now)
if err != nil {
http.Error(w, "invalid to", http.StatusBadRequest)
return
}
fromDefault := to.Add(-30 * 24 * time.Hour)
from, err := parseOptionalTimeParam(r.URL.Query().Get("from"), fromDefault)
if err != nil {
http.Error(w, "invalid from", http.StatusBadRequest)
return
}
if from.After(to) {
http.Error(w, "from must be <= to", http.StatusBadRequest)
return
}
summary, err := h.store.FunnelSummary(orgID, from, to)
if err != nil {
http.Error(w, "failed to query funnel", http.StatusInternalServerError)
return
}
writeConversionJSONResponse(w, http.StatusOK, summary, "HandleConversionFunnel")
}
// HandleGetHealth returns conversion pipeline health status.
func (h *ConversionHandlers) HandleGetHealth(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
status := conversionHealthStatus{
Status: "healthy",
LastEventAgeSeconds: 0,
EventsTotal: 0,
EventsByType: map[string]int64{},
StartedAt: time.Now().UnixMilli(),
}
if h != nil && h.health != nil {
status = h.health.CheckHealth()
}
writeConversionJSONResponse(w, http.StatusOK, status, "HandleGetHealth")
}
type conversionStatsBucket struct {
Type string `json:"type"`
Key string `json:"key"`
Count int64 `json:"count"`
TotalValue int64 `json:"total_value"`
}
type conversionStatsResponse struct {
WindowStart int64 `json:"window_start"`
WindowEnd int64 `json:"window_end"`
Buckets []conversionStatsBucket `json:"buckets"`
TotalEvents int64 `json:"total_events"`
}
// HandleGetStats returns a snapshot of current conversion aggregation window state.
func (h *ConversionHandlers) HandleGetStats(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
snapshot := []conversionStatsBucket{}
windowStart := time.Now()
windowEnd := windowStart
var totalEvents int64
if h != nil && h.recorder != nil {
buckets := h.recorder.Snapshot()
snapshot = make([]conversionStatsBucket, 0, len(buckets))
if len(buckets) > 0 {
windowStart = buckets[0].WindowStart
windowEnd = buckets[0].WindowEnd
}
for _, bucket := range buckets {
snapshot = append(snapshot, conversionStatsBucket{
Type: string(bucket.Type),
Key: bucket.Key,
Count: bucket.Count,
TotalValue: bucket.TotalValue,
})
totalEvents += bucket.Count
}
}
writeConversionJSONResponse(w, http.StatusOK, conversionStatsResponse{
WindowStart: windowStart.UnixMilli(),
WindowEnd: windowEnd.UnixMilli(),
Buckets: snapshot,
TotalEvents: totalEvents,
}, "HandleGetStats")
}
// HandleGetConfig returns runtime conversion collection controls.
func (h *ConversionHandlers) HandleGetConfig(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
snapshot := conversionCollectionConfigSnapshot{
Enabled: true,
DisabledSurfaces: []string{},
}
if h != nil && h.config != nil {
snapshot = h.config.GetConfig()
}
writeConversionJSONResponse(w, http.StatusOK, snapshot, "HandleGetConfig")
}
// HandleUpdateConfig updates runtime conversion collection controls.
func (h *ConversionHandlers) HandleUpdateConfig(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var snapshot conversionCollectionConfigSnapshot
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&snapshot); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
if h != nil {
if h.config == nil {
h.config = newCollectionConfigFromLicensing()
}
h.config.UpdateConfig(snapshot)
snapshot = h.config.GetConfig()
} else {
cfg := newCollectionConfigFromLicensing()
cfg.UpdateConfig(snapshot)
snapshot = cfg.GetConfig()
}
writeConversionJSONResponse(w, http.StatusOK, snapshot, "HandleUpdateConfig")
}
func conversionValidationReason(err error) string {
return conversionValidationReasonFromLicensing(err)
}
func writeConversionValidationError(w http.ResponseWriter, message string) {
writeConversionJSONResponse(w, http.StatusBadRequest, map[string]string{
"error": "validation_error",
"message": message,
}, "writeConversionValidationError")
}
func writeConversionAccepted(w http.ResponseWriter) {
writeConversionJSONResponse(w, http.StatusAccepted, map[string]bool{"accepted": true}, "writeConversionAccepted")
}
func writeConversionJSONResponse(w http.ResponseWriter, status int, payload interface{}, operation string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(payload); err != nil {
log.Warn().
Err(err).
Str("operation", operation).
Msg("Failed to encode conversion API response")
}
}
func parseOptionalTimeParam(raw string, defaultValue time.Time) (time.Time, error) {
return parseOptionalTimeParamFromLicensing(raw, defaultValue)
}