| 1 | // cloud_usage.go — the cloud half of the usage pipe (#857, |
| 2 | // docs/ai-provisioning.md phase 1): ingest per-space usage reports into the |
| 3 | // ledger, and mint + push the meter tokens that authenticate them. |
| 4 | // |
| 5 | // The pipe measures before any money exists: rows are quantities only (token |
| 6 | // counts, request counts, run counts) keyed by (space, day, model, dimension) |
| 7 | // — never content, never per-member attribution (#668's rule). Phase 3 turns |
| 8 | // the ledger into an allowance/budget answer; until then every report is |
| 9 | // answered "ok". |
| 10 | package main |
| 11 | |
| 12 | import ( |
| 13 | "bytes" |
| 14 | "encoding/json" |
| 15 | "fmt" |
| 16 | "log" |
| 17 | "net/http" |
| 18 | ) |
| 19 | |
| 20 | // usageHandler ingests one instance's report. Auth is the space's meter |
| 21 | // token — minted by the sweep below, pushed into the instance env, and never |
| 22 | // shown anywhere else — so an instance can only ever report as itself. |
| 23 | func (s *cloudServer) usageHandler(w http.ResponseWriter, r *http.Request) { |
| 24 | spaceID, ok := s.db.spaceByMeterToken(bearerTokenHeader(r)) |
| 25 | if !ok { |
| 26 | writeJSON(w, http.StatusForbidden, map[string]any{"error": "bad meter token"}) |
| 27 | return |
| 28 | } |
| 29 | var body struct { |
| 30 | ReportID string `json:"report_id"` |
| 31 | Rows []botUsageRow `json:"rows"` |
| 32 | } |
| 33 | if json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)).Decode(&body) != nil { |
| 34 | writeJSON(w, http.StatusBadRequest, map[string]any{"error": "bad request"}) |
| 35 | return |
| 36 | } |
| 37 | // Same validator as the instance relay, so a report the relay accepted is |
| 38 | // by construction one the ledger accepts. |
| 39 | if err := validateUsageReport(body.ReportID, body.Rows); err != nil { |
| 40 | writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()}) |
| 41 | return |
| 42 | } |
| 43 | // addUsage is idempotent on (space, report id): a replay whose first ack |
| 44 | // was lost lands here again and is dropped, never double-counted. |
| 45 | if err := s.db.addUsage(spaceID, body.ReportID, body.Rows); err != nil { |
| 46 | log.Printf("cloud: usage ingest space %d: %v", spaceID, err) |
| 47 | writeJSON(w, http.StatusInternalServerError, map[string]any{"error": "ledger error"}) |
| 48 | return |
| 49 | } |
| 50 | // The budget answer rides the flush response back to the sidecar — no |
| 51 | // extra channel. Unconfigured, budgetState is a constant "ok" and this is |
| 52 | // exactly phase 1's behavior (cloud_budget.go). |
| 53 | writeJSON(w, http.StatusOK, map[string]any{"ok": true, "budget": map[string]any{"state": s.budgetState(spaceID)}}) |
| 54 | } |
| 55 | |
| 56 | // aiOptInHandler provisions a space's bot sidecar when its admin switches AI |
| 57 | // on (#858, docs/ai-provisioning.md phase 2). Auth is the space's meter token |
| 58 | // — the instance's one cloud-facing credential — so a space can only ever ask |
| 59 | // for itself. Idempotent end to end (controld answers ok for an |
| 60 | // already-staged sidecar), so the instance signals on every flip-to-on. |
| 61 | func (s *cloudServer) aiOptInHandler(w http.ResponseWriter, r *http.Request) { |
| 62 | spaceID, ok := s.db.spaceByMeterToken(bearerTokenHeader(r)) |
| 63 | if !ok { |
| 64 | writeJSON(w, http.StatusForbidden, map[string]any{"error": "bad meter token"}) |
| 65 | return |
| 66 | } |
| 67 | m, err := s.db.spaceBillingByID(spaceID) |
| 68 | if err != nil || m.Host == "" { |
| 69 | writeJSON(w, http.StatusNotFound, map[string]any{"error": "unknown space"}) |
| 70 | return |
| 71 | } |
| 72 | detail, err := s.controlAttachBot(m.Host) |
| 73 | if err != nil { |
| 74 | log.Printf("cloud: ai-optin %s: %v", m.Host, err) |
| 75 | writeJSON(w, http.StatusBadGateway, map[string]any{"error": "provisioning failed"}) |
| 76 | return |
| 77 | } |
| 78 | log.Printf("cloud: ai-optin %s — %s", m.Host, detail) |
| 79 | writeJSON(w, http.StatusOK, map[string]any{"ok": true, "detail": detail}) |
| 80 | } |
| 81 | |
| 82 | // controlAttachBot asks controld to stage one instance's sidecar. |
| 83 | func (s *cloudServer) controlAttachBot(host string) (string, error) { |
| 84 | req, err := http.NewRequest("POST", "http://control/instances/"+host+"/bot", nil) |
| 85 | if err != nil { |
| 86 | return "", err |
| 87 | } |
| 88 | req.Header.Set("Authorization", "Bearer "+s.controlToken) |
| 89 | resp, err := s.control.Do(req) |
| 90 | if err != nil { |
| 91 | return "", err |
| 92 | } |
| 93 | defer resp.Body.Close() |
| 94 | if resp.StatusCode != http.StatusOK { |
| 95 | return "", fmt.Errorf("control attach-bot %s: HTTP %d", host, resp.StatusCode) |
| 96 | } |
| 97 | var out struct { |
| 98 | Detail string `json:"detail"` |
| 99 | } |
| 100 | if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { |
| 101 | return "", err |
| 102 | } |
| 103 | return out.Detail, nil |
| 104 | } |
| 105 | |
| 106 | // ---- meter-token mint + push (sweep-driven) -------------------------------------- |
| 107 | |
| 108 | // pushMeterToken mints a fresh meter token for a space and hands it to the |
| 109 | // instance via controld (LCHAT_METER_URL/_TOKEN in the env). Push first, |
| 110 | // record the hash after: if recording fails the next sweep mints and pushes |
| 111 | // again, and the last push wins — the same self-healing shape as pushQuota. |
| 112 | func (s *cloudServer) pushMeterToken(id int64, host string) { |
| 113 | token, err := randToken() |
| 114 | if err != nil { |
| 115 | log.Printf("cloud: meter token %s: %v", host, err) |
| 116 | return |
| 117 | } |
| 118 | if err := s.controlSetMeter(host, s.usageURL, token); err != nil { |
| 119 | log.Printf("cloud: meter token push %s: %v (sweep will retry)", host, err) |
| 120 | return |
| 121 | } |
| 122 | if err := s.db.setMeterTokenHash(id, hashToken(token)); err != nil { |
| 123 | log.Printf("cloud: meter token record %s: %v (sweep re-mints)", host, err) |
| 124 | return |
| 125 | } |
| 126 | log.Printf("cloud: meter token → %s", host) |
| 127 | } |
| 128 | |
| 129 | // controlSetMeter pushes one instance's meter endpoint + token to controld. |
| 130 | func (s *cloudServer) controlSetMeter(host, url, token string) error { |
| 131 | payload, _ := json.Marshal(map[string]any{"url": url, "token": token}) |
| 132 | req, err := http.NewRequest("POST", "http://control/instances/"+host+"/meter", bytes.NewReader(payload)) |
| 133 | if err != nil { |
| 134 | return err |
| 135 | } |
| 136 | req.Header.Set("Authorization", "Bearer "+s.controlToken) |
| 137 | req.Header.Set("Content-Type", "application/json") |
| 138 | resp, err := s.control.Do(req) |
| 139 | if err != nil { |
| 140 | return err |
| 141 | } |
| 142 | defer resp.Body.Close() |
| 143 | if resp.StatusCode != http.StatusOK { |
| 144 | return fmt.Errorf("control meter %s: HTTP %d", host, resp.StatusCode) |
| 145 | } |
| 146 | return nil |
| 147 | } |
| 148 | |