-
Notifications
You must be signed in to change notification settings - Fork 240
/
happy.py
65 lines (45 loc) · 1.95 KB
/
happy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# happy.py
# An implementation of RFC 6555 (Happy Eyeballs).
# See: https://tools.ietf.org/html/rfc6555
from curio import socket, TaskGroup, ignore_after, run
import itertools
async def open_tcp_stream(hostname, port, delay=0.3):
# Get all of the possible targets for a given host/port
targets = await socket.getaddrinfo(hostname, port, type=socket.SOCK_STREAM)
if not targets:
raise OSError(f'nothing known about {hostname}:{port}')
# Cluster the targets into unique address families (e.g., AF_INET, AF_INET6, etc.)
# and make sure the first entries are from a different family.
families = [ list(g) for _, g in itertools.groupby(targets, key=lambda t: t[0]) ]
targets = [ fam.pop(0) for fam in families ]
targets.extend(itertools.chain(*families))
# List of accumulated errors to report in case of total failure
errors = []
# Task group to manage a collection concurrent tasks.
# Cancels all remaining once an interesting result is returned.
async with TaskGroup(wait=object) as group:
# Attempt to make a connection request
async def try_connect(sockargs, addr, errors):
sock = socket.socket(*sockargs)
try:
await sock.connect(addr)
return sock
except Exception as e:
await sock.close()
errors.append(e)
# Walk the list of targets and try connections with a staggered delay
for *sockargs, _, addr in targets:
await group.spawn(try_connect, sockargs, addr, errors)
async with ignore_after(delay):
sock = await group.next_result()
if sock:
break
if group.completed:
return group.completed.result
else:
raise OSError(errors)
async def main():
result = await open_tcp_stream('www.python.org', 80)
print(result)
if __name__ == '__main__':
run(main)