| 1 | package geo |
| 2 | |
| 3 | import "math" |
| 4 | |
| 5 | // Candidate is one region a guess may pick. Code is in the record |
| 6 | // vocabulary ("" is the deployment's home); the caller has already |
| 7 | // filtered to eligible, policy-allowed candidates. |
| 8 | type Candidate struct { |
| 9 | Code string |
| 10 | Home bool |
| 11 | AWSRegion string |
| 12 | } |
| 13 | |
| 14 | // NearestWith returns the candidate nearest p, measured to each |
| 15 | // candidate's AWS region through pointOf. |
| 16 | // |
| 17 | // - A candidate whose region has no point is left out. |
| 18 | // - If the HOME is among cands and has no point, ok is false: picking |
| 19 | // among the rest could choose a far region over an unmeasured near |
| 20 | // home, and the home is where today's behaviour lives (spec §6.3). |
| 21 | // - Distances are compared in whole kilometres. A tie goes to the home, |
| 22 | // then to the lexically smallest code, so every console answers alike. |
| 23 | func NearestWith(p Point, cands []Candidate, pointOf func(string) (Point, bool)) (code string, ok bool) { |
| 24 | best := -1 |
| 25 | bestKm := math.MaxInt |
| 26 | for i, c := range cands { |
| 27 | cp, has := pointOf(c.AWSRegion) |
| 28 | if !has { |
| 29 | if c.Home { |
| 30 | return "", false |
| 31 | } |
| 32 | continue |
| 33 | } |
| 34 | km := int(math.Round(DistanceKm(p, cp))) |
| 35 | switch { |
| 36 | case best < 0, km < bestKm: |
| 37 | case km == bestKm && better(c, cands[best]): |
| 38 | default: |
| 39 | continue |
| 40 | } |
| 41 | best, bestKm = i, km |
| 42 | } |
| 43 | if best < 0 { |
| 44 | return "", false |
| 45 | } |
| 46 | return cands[best].Code, true |
| 47 | } |
| 48 | |
| 49 | // better breaks an exact tie: the home first, then the smaller code. |
| 50 | func better(a, b Candidate) bool { |
| 51 | if a.Home != b.Home { |
| 52 | return a.Home |
| 53 | } |
| 54 | return a.Code < b.Code |
| 55 | } |
| 56 | |