| 24 | type dialQueue []dialQueueEntry |
| 25 | |
| 26 | func (queue dialQueue) Sort() { |
| 27 | // Sort the queue with the most recently seen device at the head, |
| 28 | // increasing the likelihood of connecting to a device that we're |
| 29 | // already almost up to date with, index wise. |
| 30 | sort.Slice(queue, func(a, b int) bool { |
| 31 | qa, qb := queue[a], queue[b] |
| 32 | if qa.shortLived != qb.shortLived { |
| 33 | return qb.shortLived |
| 34 | } |
| 35 | return qa.lastSeen.After(qb.lastSeen) |
| 36 | }) |
| 37 | |
| 38 | // Shuffle the part of the connection queue that are devices we haven't |
| 39 | // connected to recently, so that if we only try a limited set of |
| 40 | // devices (or they in turn have limits and we're trying to load balance |
| 41 | // over several) and the usual ones are down it won't be the same ones |
| 42 | // in the same order every time. |
| 43 | idx := 0 |
| 44 | cutoff := time.Now().Add(-recentlySeenCutoff) |
| 45 | for idx < len(queue) { |
| 46 | if queue[idx].lastSeen.Before(cutoff) { |
| 47 | break |
| 48 | } |
| 49 | idx++ |
| 50 | } |
| 51 | if idx < len(queue)-1 { |
| 52 | rand.Shuffle(queue[idx:]) |
| 53 | } |
| 54 | } |