// cloud_usage.go — the cloud half of the usage pipe (#857, // docs/ai-provisioning.md phase 1): ingest per-space usage reports into the // ledger, and mint + push the meter tokens that authenticate them. // // The pipe measures before any money exists: rows are quantities only (token // counts, request counts, run counts) keyed by (space, day, model, dimension) // — never content, never per-member attribution (#668's rule). Phase 3 turns // the ledger into an allowance/budget answer; until then every report is // answered "ok". package main import ( "bytes" "encoding/json" "fmt" "log" "net/http" ) // usageHandler ingests one instance's report. Auth is the space's meter // token — minted by the sweep below, pushed into the instance env, and never // shown anywhere else — so an instance can only ever report as itself. func (s *cloudServer) usageHandler(w http.ResponseWriter, r *http.Request) { spaceID, ok := s.db.spaceByMeterToken(bearerTokenHeader(r)) if !ok { writeJSON(w, http.StatusForbidden, map[string]any{"error": "bad meter token"}) return } var body struct { ReportID string `json:"report_id"` Rows []botUsageRow `json:"rows"` } if json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&body) != nil { writeJSON(w, http.StatusBadRequest, map[string]any{"error": "bad request"}) return } // Same validator as the instance relay, so a report the relay accepted is // by construction one the ledger accepts. if err := validateUsageReport(body.ReportID, body.Rows); err != nil { writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()}) return } // addUsage is idempotent on (space, report id): a replay whose first ack // was lost lands here again and is dropped, never double-counted. if err := s.db.addUsage(spaceID, body.ReportID, body.Rows); err != nil { log.Printf("cloud: usage ingest space %d: %v", spaceID, err) writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "ledger error"}) return } // The budget answer rides the flush response back to the sidecar — no // extra channel. Unconfigured, budgetState is a constant "ok" and this is // exactly phase 1's behavior (cloud_budget.go). writeJSON(w, http.StatusOK, map[string]any{"ok": true, "budget": map[string]any{"state": s.budgetState(spaceID)}}) } // aiOptInHandler provisions a space's bot sidecar when its admin switches AI // on (#858, docs/ai-provisioning.md phase 2). Auth is the space's meter token // — the instance's one cloud-facing credential — so a space can only ever ask // for itself. Idempotent end to end (controld answers ok for an // already-staged sidecar), so the instance signals on every flip-to-on. func (s *cloudServer) aiOptInHandler(w http.ResponseWriter, r *http.Request) { spaceID, ok := s.db.spaceByMeterToken(bearerTokenHeader(r)) if !ok { writeJSON(w, http.StatusForbidden, map[string]any{"error": "bad meter token"}) return } m, err := s.db.spaceBillingByID(spaceID) if err != nil || m.Host == "" { writeJSON(w, http.StatusNotFound, map[string]any{"error": "unknown space"}) return } detail, err := s.controlAttachBot(m.Host) if err != nil { log.Printf("cloud: ai-optin %s: %v", m.Host, err) writeJSON(w, http.StatusBadGateway, map[string]any{"error": "provisioning failed"}) return } log.Printf("cloud: ai-optin %s — %s", m.Host, detail) writeJSON(w, http.StatusOK, map[string]any{"ok": true, "detail": detail}) } // controlAttachBot asks controld to stage one instance's sidecar. func (s *cloudServer) controlAttachBot(host string) (string, error) { req, err := http.NewRequest("POST", "http://control/instances/"+host+"/bot", nil) if err != nil { return "", err } req.Header.Set("Authorization", "Bearer "+s.controlToken) resp, err := s.control.Do(req) if err != nil { return "", err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return "", fmt.Errorf("control attach-bot %s: HTTP %d", host, resp.StatusCode) } var out struct { Detail string `json:"detail"` } if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { return "", err } return out.Detail, nil } // ---- meter-token mint + push (sweep-driven) -------------------------------------- // pushMeterToken mints a fresh meter token for a space and hands it to the // instance via controld (LCHAT_METER_URL/_TOKEN in the env). Push first, // record the hash after: if recording fails the next sweep mints and pushes // again, and the last push wins — the same self-healing shape as pushQuota. func (s *cloudServer) pushMeterToken(id int64, host string) { token, err := randToken() if err != nil { log.Printf("cloud: meter token %s: %v", host, err) return } if err := s.controlSetMeter(host, s.usageURL, token); err != nil { log.Printf("cloud: meter token push %s: %v (sweep will retry)", host, err) return } if err := s.db.setMeterTokenHash(id, hashToken(token)); err != nil { log.Printf("cloud: meter token record %s: %v (sweep re-mints)", host, err) return } log.Printf("cloud: meter token → %s", host) } // controlSetMeter pushes one instance's meter endpoint + token to controld. func (s *cloudServer) controlSetMeter(host, url, token string) error { payload, _ := json.Marshal(map[string]any{"url": url, "token": token}) req, err := http.NewRequest("POST", "http://control/instances/"+host+"/meter", bytes.NewReader(payload)) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+s.controlToken) req.Header.Set("Content-Type", "application/json") resp, err := s.control.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { return fmt.Errorf("control meter %s: HTTP %d", host, resp.StatusCode) } return nil }