Scoop API

scoop:scoop.asyncio:0.1.0

src/tcp_connect_plan.scoop

Selected production source · src/tcp_connect_plan.scoop

1package scoop.asyncio
3import scoop.collections.HashSet
4import scoop.platform.net.*
6private class TcpFamilyCandidates {
7 var addresses: Array<SocketAddress> = []
8 var next: Long = 0L
9 var finished: Boolean = false
10 val available: Boolean get() = next < addresses.size
13internal class TcpConnectPlan(private val maximum: Long) {
14 private val ipv4: TcpFamilyCandidates = TcpFamilyCandidates()
15 private val ipv6: TcpFamilyCandidates = TcpFamilyCandidates()
16 private val seen: HashSet<SocketAddress> = HashSet<SocketAddress>()
17 private var previous: AddressFamily = AddressFamily.Ipv4
18 private var started: Boolean = false
19 private var resolutionReady: Boolean = false
20 private var attemptReady: Boolean = true
21 private var pending: Long = 0L
22 private var attemptGeneration: Long = 0L
23 val generation: Long get() = attemptGeneration
24 val resolutionComplete: Boolean get() = ipv4.finished && ipv6.finished
26 fun isResolved(family: AddressFamily): Boolean = if (family == AddressFamily.Ipv4) ipv4.finished else ipv6.finished
28 val needsResolutionDelay: Boolean get() =
29 !started && !resolutionReady && ipv4.available && !ipv6.finished
31 val exhausted: Boolean get() =
32 ipv4.finished && ipv6.finished && !ipv4.available && !ipv6.available && pending == 0L
34 fun resolved(family: AddressFamily, addresses: Array<SocketAddress>) {
35 if (isResolved(family)) return
36 val unique = ArrayList<SocketAddress>()
37 for (address in addresses) if (seen.add(address)) unique.add(address)
38 val queue = if (family == AddressFamily.Ipv4) ipv4 else ipv6
39 queue.addresses = unique.toArray()
40 queue.finished = true
41 }
43 fun resolutionDelayElapsed() { resolutionReady = true }
45 fun attemptDelayElapsed(id: Long) {
46 if (id == attemptGeneration) attemptReady = true
47 }
49 fun attemptFailed() {
50 pending -= 1L
51 attemptReady = true
52 }
54 fun takeNext(): SocketAddress? {
55 if (pending >= maximum || !attemptReady || needsResolutionDelay) return None
56 if (!ipv4.available && !ipv6.available) return None
57 val family = if (previous == AddressFamily.Ipv4 && ipv6.available) AddressFamily.Ipv6
58 else if (previous == AddressFamily.Ipv6 && ipv4.available) AddressFamily.Ipv4
59 else if (ipv6.available) AddressFamily.Ipv6 else AddressFamily.Ipv4
60 val queue = if (family == AddressFamily.Ipv4) ipv4 else ipv6
61 val result = queue.addresses[queue.next]
62 queue.next += 1L
63 previous = family
64 started = true
65 pending += 1L
66 attemptReady = false
67 attemptGeneration += 1L
68 return Some(result)
69 }