Download this file
| 1 | package chat |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/copydesk" |
| 5 | "amadan.net/oficina/equipo/internal/wire" |
| 6 | "gorm.io/gorm" |
| 7 | "gorm.io/gorm/clause" |
| 8 | ) |
| 9 | |
| 10 | type copyAttemptRecord struct { |
| 11 | ID string `gorm:"primaryKey"` |
| 12 | TaskID string |
| 13 | StepID string |
| 14 | Attempt int64 |
| 15 | Tokens int64 |
| 16 | Known bool |
| 17 | } |
| 18 | |
| 19 | func (copyAttemptRecord) TableName() string { return "chat_copy_attempts" } |
| 20 | func (t *txn) copyBudget(task string) (int64, bool, error) { |
| 21 | var rows []copyAttemptRecord |
| 22 | if err := t.db.Where("task_id = ?", task).Find(&rows).Error; err != nil { |
| 23 | return 0, false, err |
| 24 | } |
| 25 | left, known := int64(copydesk.TaskTokens), true |
| 26 | for _, r := range rows { |
| 27 | tokens := r.Tokens |
| 28 | if !r.Known { |
| 29 | tokens = max(tokens, int64(copydesk.PassTokens)) |
| 30 | } |
| 31 | left -= tokens |
| 32 | known = known && r.Tokens >= 0 |
| 33 | } |
| 34 | return left, known, nil |
| 35 | } |
| 36 | func (t *txn) reserveCopy(k taskRecord, s stepRecord) error { |
| 37 | return t.db.Clauses(clause.OnConflict{DoNothing: true}).Create(©AttemptRecord{ID: stepAttempt(s), TaskID: k.ID, StepID: s.ID, Attempt: s.Attempt}).Error |
| 38 | } |
| 39 | func (t *txn) copyUsageReport(k taskRecord, s stepRecord, v *wire.StepReport) error { |
| 40 | if v.Copy == nil { |
| 41 | return nil |
| 42 | } |
| 43 | c := v.Copy |
| 44 | if c.Owner != s.CopyOwner || c.Delegation != s.CopyRevision || c.Input != s.CandidateSHA || c.Tokens < 0 { |
| 45 | return ErrInvalid |
| 46 | } |
| 47 | if err := t.reserveCopy(k, s); err != nil { |
| 48 | return err |
| 49 | } |
| 50 | return t.db.Model(©AttemptRecord{}).Where("id = ?", stepAttempt(s)).Select("tokens", "known").Updates(map[string]any{"tokens": gorm.Expr("MAX(tokens, ?)", c.Tokens), "known": c.UsageKnown}).Error |
| 51 | } |
| 52 | |