| 1 | package planning |
| 2 | |
| 3 | import ( |
| 4 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 5 | "encoding/json" |
| 6 | "gorm.io/gorm" |
| 7 | "slices" |
| 8 | "sort" |
| 9 | "time" |
| 10 | ) |
| 11 | |
| 12 | type Connection struct { |
| 13 | Label string |
| 14 | RevokedAt *time.Time |
| 15 | ID string `gorm:"primaryKey"` |
| 16 | RunnerID string `gorm:"uniqueIndex:connection_local"` |
| 17 | Person string `gorm:"index:connection_person"` |
| 18 | LocalID string `gorm:"uniqueIndex:connection_local"` |
| 19 | Revision int64 |
| 20 | LastSeen time.Time |
| 21 | Reports []runnerproto.ConnectionReport `gorm:"-"` |
| 22 | } |
| 23 | |
| 24 | type ConnectionRecord struct { |
| 25 | Connection `gorm:"embedded"` |
| 26 | ReportsJSON string |
| 27 | SecurityHash string |
| 28 | } |
| 29 | |
| 30 | func (ConnectionRecord) TableName() string { return "connections" } |
| 31 | |
| 32 | type ConnectionChoice struct { |
| 33 | ProjectID, Revision int64 |
| 34 | ConnectionIDs []string |
| 35 | PinnedID string |
| 36 | Mode string |
| 37 | } |
| 38 | |
| 39 | type ConnectionChoiceRecord struct { |
| 40 | Person string `gorm:"primaryKey"` |
| 41 | ProjectID int64 `gorm:"primaryKey;autoIncrement:false"` |
| 42 | Revision int64 |
| 43 | ConnectionIDsJSON string |
| 44 | PinnedID string |
| 45 | Mode string `gorm:"not null;default:best_fit"` |
| 46 | } |
| 47 | |
| 48 | func (ConnectionChoiceRecord) TableName() string { return "connection_choices" } |
| 49 | |
| 50 | func ConnectionChoiceAt(tx *gorm.DB, person string, project int64) (ConnectionChoiceRecord, []string, error) { |
| 51 | var c ConnectionChoiceRecord |
| 52 | if err := tx.Where("person = ? AND project_id = ?", person, project).First(&c).Error; err != nil { |
| 53 | return c, nil, err |
| 54 | } |
| 55 | var ids []string |
| 56 | err := json.Unmarshal([]byte(c.ConnectionIDsJSON), &ids) |
| 57 | return c, ids, err |
| 58 | } |
| 59 | |
| 60 | func NormalizeConnectionChoice(choice ConnectionChoice, invalid error) (ConnectionChoice, error) { |
| 61 | if choice.Mode == "" { |
| 62 | choice.Mode = "best_fit" |
| 63 | } |
| 64 | if choice.Mode != "best_fit" && choice.Mode != "pinned" && choice.Mode != "ask" || choice.Mode == "pinned" && choice.PinnedID == "" { |
| 65 | return choice, invalid |
| 66 | } |
| 67 | if choice.ProjectID <= 0 || choice.Revision < 0 || len(choice.ConnectionIDs) > 256 { |
| 68 | return choice, invalid |
| 69 | } |
| 70 | ids := slices.Clone(choice.ConnectionIDs) |
| 71 | sort.Strings(ids) |
| 72 | for i, id := range ids { |
| 73 | if id == "" || (i > 0 && ids[i-1] == id) { |
| 74 | return choice, invalid |
| 75 | } |
| 76 | } |
| 77 | if choice.PinnedID != "" && !slices.Contains(ids, choice.PinnedID) { |
| 78 | return choice, invalid |
| 79 | } |
| 80 | |
| 81 | choice.ConnectionIDs = ids |
| 82 | return choice, nil |
| 83 | } |
| 84 | |