| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "slices" |
| 8 | "sort" |
| 9 | "time" |
| 10 | |
| 11 | "github.com/go-chi/chi/v5" |
| 12 | "gorm.io/gorm" |
| 13 | |
| 14 | "amadan.net/oficina/equipo/internal/equipo/personapi" |
| 15 | "amadan.net/oficina/equipo/internal/wire" |
| 16 | ) |
| 17 | |
| 18 | // The Usage page's data (Connections rev 3 §6, connectors spec S4): the |
| 19 | // person's own recorded token use over today, this week or this month |
| 20 | // in their zone, grouped by connection, role, project or task (four |
| 21 | // views of one dataset), with the estimate where a price table priced |
| 22 | // the rows, and the price table each metered connection was last |
| 23 | // charged by. |
| 24 | |
| 25 | // usageFrom is where period starts in loc: today, Monday, or the 1st. |
| 26 | func usageFrom(period string, now time.Time, loc *time.Location) (time.Time, bool) { |
| 27 | l := now.In(loc) |
| 28 | day := time.Date(l.Year(), l.Month(), l.Day(), 0, 0, 0, 0, loc) |
| 29 | switch period { |
| 30 | case wire.UsageDay: |
| 31 | return day.UTC(), true |
| 32 | case wire.UsageWeek: |
| 33 | back := (int(day.Weekday()) + 6) % 7 |
| 34 | return day.AddDate(0, 0, -back).UTC(), true |
| 35 | case wire.UsageMonth: |
| 36 | return time.Date(l.Year(), l.Month(), 1, 0, 0, 0, 0, loc).UTC(), true |
| 37 | } |
| 38 | return time.Time{}, false |
| 39 | } |
| 40 | |
| 41 | // UsageTotals is GET /api/v1/usage?period=&by=: the person's own usage |
| 42 | // rows for the period, summed per grouping. Rows that overcount are left |
| 43 | // out and said so. |
| 44 | func (s *Store) UsageTotals(ctx context.Context, person, period, by string) (out wire.UsageTotals, err error) { |
| 45 | if !slices.Contains(wire.UsageGroupings, by) { |
| 46 | return out, ErrInvalid |
| 47 | } |
| 48 | now := s.now() |
| 49 | from, ok := usageFrom(period, now, s.Zone(person)) |
| 50 | if !ok { |
| 51 | return out, ErrInvalid |
| 52 | } |
| 53 | out = wire.UsageTotals{Period: period, By: by, From: from, To: now.UTC(), Rows: []wire.UsageRow{}, Prices: []wire.PriceSource{}} |
| 54 | err = s.read(ctx, func(tx *gorm.DB) error { |
| 55 | if err := s.authority.CurrentPerson(ctx, tx); err != nil { |
| 56 | return err |
| 57 | } |
| 58 | var conns []connectionRecord |
| 59 | if err := tx.Where("person = ?", person).Order("created_at, id").Find(&conns).Error; err != nil { |
| 60 | return err |
| 61 | } |
| 62 | // A usage row names the runner's local id; the page names the |
| 63 | // instance's connection. |
| 64 | byLocal := map[string]connectionRecord{} |
| 65 | for _, c := range conns { |
| 66 | if _, seen := byLocal[c.LocalID]; c.LocalID != "" && !seen { |
| 67 | byLocal[c.LocalID] = c |
| 68 | } |
| 69 | } |
| 70 | var rows []usageRecord |
| 71 | if err := tx.Where("person = ? AND recorded_at >= ?", person, from).Order("recorded_at, id").Find(&rows).Error; err != nil { |
| 72 | return err |
| 73 | } |
| 74 | tasks := map[string]taskRecord{} |
| 75 | projects := map[string]projectRecord{} |
| 76 | if by == wire.UsageByTask || by == wire.UsageByProject { |
| 77 | var ids []string |
| 78 | for _, r := range rows { |
| 79 | if r.TaskID != "" { |
| 80 | ids = append(ids, r.TaskID) |
| 81 | } |
| 82 | } |
| 83 | if len(ids) > 0 { |
| 84 | var ks []taskRecord |
| 85 | if err := tx.Where("id IN ?", ids).Find(&ks).Error; err != nil { |
| 86 | return err |
| 87 | } |
| 88 | var pids []string |
| 89 | for _, k := range ks { |
| 90 | tasks[k.ID] = k |
| 91 | pids = append(pids, k.ProjectID) |
| 92 | } |
| 93 | var ps []projectRecord |
| 94 | if err := tx.Where("id IN ?", pids).Find(&ps).Error; err != nil { |
| 95 | return err |
| 96 | } |
| 97 | for _, p := range ps { |
| 98 | projects[p.ID] = p |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | // By role, a step a maker made (Design's, Engineering's kind) |
| 103 | // is the maker's: its profile, not Engineering. |
| 104 | makers := map[string]string{} |
| 105 | if by == wire.UsageByRole { |
| 106 | var ids []string |
| 107 | for _, r := range rows { |
| 108 | if r.Role == wire.SpecialistEngineering && r.StepID != "" { |
| 109 | ids = append(ids, r.StepID) |
| 110 | } |
| 111 | } |
| 112 | if len(ids) > 0 { |
| 113 | var bound []stepRecord |
| 114 | if err := tx.Select("id", "specialist_id").Where("id IN ? AND specialist_id <> ''", ids).Find(&bound).Error; err != nil { |
| 115 | return err |
| 116 | } |
| 117 | var sids []string |
| 118 | for _, st := range bound { |
| 119 | sids = append(sids, st.SpecialistID) |
| 120 | } |
| 121 | var sps []specialistRecord |
| 122 | if err := tx.Select("id", "profile").Where("id IN ?", sids).Find(&sps).Error; err != nil { |
| 123 | return err |
| 124 | } |
| 125 | profiles := map[string]string{} |
| 126 | for _, sp := range sps { |
| 127 | profiles[sp.ID] = sp.Profile |
| 128 | } |
| 129 | for _, st := range bound { |
| 130 | if p := profiles[st.SpecialistID]; p != "" { |
| 131 | makers[st.ID] = p |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | sums := map[string]*wire.UsageRow{} |
| 137 | for _, r := range rows { |
| 138 | if r.Overcount { |
| 139 | out.LeftOut = true |
| 140 | continue |
| 141 | } |
| 142 | id, label := "", "" |
| 143 | switch by { |
| 144 | case wire.UsageByConnection: |
| 145 | id, label = r.Connection, r.Provider |
| 146 | if c, ok := byLocal[r.Connection]; ok { |
| 147 | id, label = c.ID, c.Provider |
| 148 | } |
| 149 | case wire.UsageByRole: |
| 150 | id, label = r.Role, r.Role |
| 151 | if p := makers[r.StepID]; p != "" && r.Role == wire.SpecialistEngineering { |
| 152 | id, label = p, p |
| 153 | } |
| 154 | case wire.UsageByTask: |
| 155 | if k, ok := tasks[r.TaskID]; ok { |
| 156 | id, label = k.ID, k.Title |
| 157 | } |
| 158 | case wire.UsageByModel: |
| 159 | id, label = r.Model, r.Model |
| 160 | case wire.UsageByProject: |
| 161 | if k, ok := tasks[r.TaskID]; ok { |
| 162 | id = k.ProjectID |
| 163 | if p, ok := projects[k.ProjectID]; ok { |
| 164 | label = ProjectName(p.Repo) |
| 165 | } |
| 166 | } |
| 167 | } |
| 168 | row := sums[id] |
| 169 | if row == nil { |
| 170 | row = &wire.UsageRow{ID: id, Label: label} |
| 171 | sums[id] = row |
| 172 | } |
| 173 | one := rowSpend(r) |
| 174 | row.Input += one.Tokens - figure(r.OutputTokens) |
| 175 | row.CachedInput += one.Cached |
| 176 | row.Output += figure(r.OutputTokens) |
| 177 | row.Partial = row.Partial || one.Partial |
| 178 | row.Attempts++ |
| 179 | if r.CostMicros != nil { |
| 180 | cost := *r.CostMicros |
| 181 | if row.Cost != nil { |
| 182 | cost += *row.Cost |
| 183 | } |
| 184 | row.Cost, row.Currency = &cost, r.Currency |
| 185 | } |
| 186 | } |
| 187 | for _, row := range sums { |
| 188 | out.Rows = append(out.Rows, *row) |
| 189 | } |
| 190 | sort.Slice(out.Rows, func(i, j int) bool { |
| 191 | a, b := out.Rows[i], out.Rows[j] |
| 192 | if a.Input+a.Output != b.Input+b.Output { |
| 193 | return a.Input+a.Output > b.Input+b.Output |
| 194 | } |
| 195 | return a.ID < b.ID |
| 196 | }) |
| 197 | // The price table each metered connection was last charged by. |
| 198 | var priced []usageRecord |
| 199 | if err := tx.Where("person = ? AND price_version <> ''", person).Order("recorded_at DESC, id DESC").Find(&priced).Error; err != nil { |
| 200 | return err |
| 201 | } |
| 202 | seen := map[string]bool{} |
| 203 | for _, r := range priced { |
| 204 | id := r.Connection |
| 205 | if c, ok := byLocal[r.Connection]; ok { |
| 206 | id = c.ID |
| 207 | } |
| 208 | if seen[id] { |
| 209 | continue |
| 210 | } |
| 211 | seen[id] = true |
| 212 | out.Prices = append(out.Prices, wire.PriceSource{Connection: id, PriceVersion: r.PriceVersion, TierVersion: r.TierVersion}) |
| 213 | } |
| 214 | return nil |
| 215 | }) |
| 216 | return out, err |
| 217 | } |
| 218 | |
| 219 | // mountUsage adds the Usage resources (§10, Connections rev 3 §6). |
| 220 | func (h *HTTP) mountUsage(r chi.Router) { |
| 221 | r.Get("/usage", h.bearer(h.usage)) |
| 222 | r.Get("/advice", h.bearer(h.advice)) |
| 223 | r.Post("/advice/{id}/act", h.bearer(h.actAdvice)) |
| 224 | r.Post("/advice/{id}/dismiss", h.bearer(h.dismissAdvice)) |
| 225 | } |
| 226 | |
| 227 | func (h *HTTP) usage(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 228 | period, by := r.URL.Query().Get("period"), r.URL.Query().Get("by") |
| 229 | if period == "" { |
| 230 | period = wire.UsageMonth |
| 231 | } |
| 232 | if by == "" { |
| 233 | by = wire.UsageByConnection |
| 234 | } |
| 235 | out, err := h.Store.UsageTotals(r.Context(), p.Address, period, by) |
| 236 | if err != nil { |
| 237 | h.fail(w, r, err) |
| 238 | return |
| 239 | } |
| 240 | writeJSON(w, 200, out) |
| 241 | } |
| 242 | |
| 243 | func (h *HTTP) advice(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 244 | out, err := h.Store.Advice(r.Context(), p.Address) |
| 245 | if err != nil { |
| 246 | h.fail(w, r, err) |
| 247 | return |
| 248 | } |
| 249 | writeJSON(w, 200, out) |
| 250 | } |
| 251 | |
| 252 | // actAdvice is POST /api/v1/advice/{id}/act {revision}: 200 with the |
| 253 | // advice acted on; 409 revision_conflict when it moved, was answered, |
| 254 | // or its facts no longer hold. |
| 255 | func (h *HTTP) actAdvice(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 256 | h.adviceAction(w, r, p, h.Store.ActAdvice) |
| 257 | } |
| 258 | |
| 259 | // dismissAdvice is POST /api/v1/advice/{id}/dismiss {revision}: Not now. |
| 260 | func (h *HTTP) dismissAdvice(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal) { |
| 261 | h.adviceAction(w, r, p, h.Store.DismissAdvice) |
| 262 | } |
| 263 | |
| 264 | func (h *HTTP) adviceAction(w http.ResponseWriter, r *http.Request, p personapi.PersonPrincipal, do func(context.Context, string, string, wire.AdviceAction) (wire.Advice, error)) { |
| 265 | var in wire.AdviceAction |
| 266 | if err := readJSON(r, &in); err != nil { |
| 267 | h.fail(w, r, err) |
| 268 | return |
| 269 | } |
| 270 | out, err := do(r.Context(), p.Address, chi.URLParam(r, "id"), in) |
| 271 | if errors.Is(err, ErrConflict) { |
| 272 | current := out.Revision |
| 273 | personapi.WriteError(w, r, http.StatusConflict, "revision_conflict", ¤t) |
| 274 | return |
| 275 | } |
| 276 | if err != nil { |
| 277 | h.fail(w, r, err) |
| 278 | return |
| 279 | } |
| 280 | writeJSON(w, 200, out) |
| 281 | } |
| 282 | |