Asyncio

coroutines

使用async/await
函数称为coroutinefunction
函数调用返回的称为coroutine object, 一般当读说coroutine都是指代coroutine object
内部使用使用的generator/yield/yield from,但是为了概念的划分而单独区分开来.
旧版本中使用@asyncio.coroutine装饰器将一个generator函数表述为coroutine function.(Will be removed.)

Awaitables:

  1. coroutine object
  2. Future 使用 生成 low level
  3. Task high level
  • asyncio.run(main()) 生成一个loop, 并run loop. 只能用一次,用于最外层的coroutine
  • asyncio.ensure_futures(coro) 生成一个Future, 在get_running_loop() 中执行
  • asyncio.create_task(coro) 生成一个Task, 在get_running_loop() 中执行
  • awaitable asyncio.gather(*aws, loop=None, return_exceptions=False) coroutine自动包装为Task并执行
  1. for taks in asyncio.all_tasks():
  2. task.cancel()
  3. await asyncio.gather(*tasks, return_exceptions=True)
  • coroutine asyncio.wait_for(aw, timeout, *, loop=None) cancel when timeout
  • coroutine asyncio.wait(aws, *, loop=None, timeout=None, return_when=ALL_COMPLETED) do not cancel when timeout
    • FIRST_COMPLETED
    • FIRST_EXECUTION
    • ALL_COMPLETED
  • asyncio.as_completed(aws, *, loop=None, timeout=None) return a generated, each Future returned represents the earliest result from the set of remaining awaitables.
  1. for f in as_completed(aws):
  2. earliest_result = await f

Task

  • asyncio.current_task
  • asyncio.all_tasks

Stream

top level asyncio functions based on loop.create_connection and loop.create_server

  • coroutine asyncio.open_connection(host=None, port=None, *, loop=None, limit=None, ssl=None, family=0, proto=0, flags=0, sock=None, local_addr=None, server_hostname=None, ssl_handshake_timeout=None)
    • Establish a network connection and return a pair of (reader, writer) object
  • coroutine asyncio.start_server(client_connected_cb, host=None, port=None, *, loop=None, limit=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None, ssl_handshake_timeout=None, start_serving=True)
    • client_connected_cb is a function or coroutine function receive (reader, writer) as parameters. if a coroutine function , it wiil be automatrically scheduled as a Task when server a client.
  • coroutine asyncio.open_unix_connection(path=None, *, loop=None, limit=None, ssl=None, sock=None, server_hostname=None, ssl_handshake_timeout=None)
  • coroutine asyncio.start_unix_server(client_connected_cb, path=None, *, loop=None, limit=None, sock=None, backlog=100, ssl=None, ssl_handshake_timeout=None, start_serving=True)
  • Can bind to a existing socket. For example: rsock, wscok = scoket.socketpair()

asyncio.StreamWriter

  • write/writelines
  • corourine drain Should be used afer write/writelines. Blocks until the size of the buffer is drained down to the low watermark.
  • write_eof close the write end of the stream afetr the bufered write data is flushed.
  • close
  • coroutine wait_closed Should be used afer close. Wait until the underlying connection is closed
  • get_extra_info('peername')

asyncio.StreamReader

  • coroutine read(n=-1)
  • coroutine readline()
  • coroutine readuntil(separator=b'\n')
  • Be cautious about EOF.

Synchronizarion

Not thread safe, Use threading otherwise.

asyncio.Lock

  • couroutine acquire
  • release
  • locked return True if lock is locked.
  1. lock = asyncio.Lock()
  2. async with lock:
  3. pass
  4. # Equal to
  5. await lock.acquire()
  6. try:
  7. pass
  8. finally:
  9. lock.release()

asyncio.Event

Like a awaitable flag with True/False flag.

  • coroutine wait() wait to be setted.
  • set()
  • clear()
  • is_set() return True if setted.

asyncio.Condition

similar to lock

asyncio.Semaphore(value=1)

A waitable counter. Decremented by each acquire() and incrementedby each release(). Can never go below zero.
acqure() blocks when counter is 0.

  • coroutine acquire
  • release
  • locked

asyncio.BoundedSemaphore(value=1)

Raises ValueError in release() when the counter above the initial value after release.

asyncio.Queue(maxsize=0)

asyncio.PriorityQueue(maxsize=0)

  • items are tuples (priority_number, data)

asyncio.LifoQueue(maxsize=0)

  • maxsize/empty()/full()/qsize()
  • coroutine get() blocks when an item is available
  • coroutine put(item) blocks when queue full
  • get_nowait()/put_nowait() Non block version.Raise asyncio.QueueEmpty or asycio.QueueFull respectively
  • task_done() inform a task fetched from queue is done.
  • coroutine join() wait until the number(all enqueued items) of times task_done has been called.

Event Loop

low level network handling

  • create_connection return a pair of (Transport, Protocol)
  • create_server return a Server object

coroutines.iscoroutine

  • coroutine
  • generator
  • …

    1. _COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
    2. collections.abc.Coroutine, CoroWrapper)
    3. def iscoroutine(obj):
    4. if isinstance(obj, _COROUTINE_TYPES):
    5. # .......
    6. return True
    7. else:
    8. return False

    futures.isfuture

  • sublcass of Future or containing a class data

    1. def isfuture(obj):
    2. return (hasattr(obj.__class__, '_asyncio_future_blocking') and
    3. obj._asyncio_future_blocking is not None)

inspect.isawatable

  • coroutine(async def)
  • types.coroutine decorated generator object
  • subclass of collections.abc.Awaitable
    1. def isawaitable(object):
    2. """Return true if object can be passed to an ``await`` expression."""
    3. return (isinstance(object, types.CoroutineType) or
    4. isinstance(object, types.GeneratorType) and
    5. bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
    6. isinstance(object, collections.abc.Awaitable))
  1. class Future(object):
  2. def set_result(self, res):
  3. self.result = res
  4. self.schedule_callbacks()
  5. def add_done_callback(self, cb):
  6. pass
  7. def schedule_callbacks(self):
  8. for cb in self.callbacks:
  9. loop.call_soon(cb)
  10. class Task(object):
  11. def __init__(self, coro):
  12. self.coro = coro
  13. self.step()
  14. def step(self, exc):
  15. try:
  16. res = self.coro.send(None)
  17. if futures.isfuture(res):
  18. res.add_done_callback(self.step)
  19. except StopIteration as exc:
  20. super().set_result(exc.value)

futures

a representaion of state
Can not self-wake-up. Thus, by any way, all Futures needs to be within a Task.
A Furture must coexist with a io event(directly or indirectly) or a schecdule event like call_soon call_later
Cancel a future has two cases:
set_result called after outer task’s cancel, then the final state of this Future is CANCELLED, so self.result() will raise Cancelled error, and cause in await future.
set_result called before outer task’s cancel, then the final state of this Future is FINISHED, however, as task._must_cancel is True, taks.step will call coro.throw thus raise Cancelled error when resuming from yield self, then catched in await future.

task

a representaion of process(coroutine) state, wrapper of a coroutine(a precess), The state of process is represented as a set of Future yielded within the coroutine.
self wakable coroutine. Wake up(send(None)) the the paused coroutine by adding step callback to the yielded Future object

  1. class Future:
  2. def __await__(self):
  3. if not self.done():
  4. self._asyncio_future_blocking = True
  5. yield self # This tells Task to wait for completion.
  6. if not self.done():
  7. raise RuntimeError("await wasn't used with future")
  8. return self.result() # May raise too.
  9. class Task(Future):
  10. def cancel(self, msg=None):
  11. self._log_traceback = False
  12. if self.done():
  13. return False
  14. if self._fut_waiter is not None:
  15. if self._fut_waiter.cancel(msg=msg):
  16. return True
  17. self._must_cancel = True
  18. self._cancel_message = msg
  19. return True

Main diagram:
step in Task. init will be called when a task is created
Coroutine within the task will be triggered by coro.send(None) in step
Coroutine runs and is paused at some yield position(yield a Future)
set_result function of this Future registered at some IO event will be called
set_result will trigger the call of done_callback added by the outer task
step in done_callback will call coro.send(None),

current_task
enter_task and leave_task will be called before and after coro.send().
thus this data can be used within a coroutine and findout the outer task

asyncio.gather function
return a future, results is a list containing all results of children task/future(ensure_futured)
since it’s a future, itself needs to be within a task.

asyncio.wait async function
return twos lists of done futures and pending futures

asyncio.ascopleted generator function
generate coroutines, await these coroutine can get results of input futures

asyncio.shild return a future ?????

queue

Use deque or list or heapq as the item container

  1. # no matter a cancel is happend before or after put_nowait, the next getter will be released.
  2. # case1
  3. tget1.cancel() # since getter is pending, will set canceled sucessfuly
  4. q.put_noawait() # will pass the firs getter as it's already done, so the second getter will be set
  5. # and will raise CancelledError when the first getter resumes, however since it's cancelled,
  6. # the last if statement will not pass, thus no wake_up_next will be called
  7. await asyncio.sleep(1)
  8. # case2
  9. q.put_nowait() # set the first getter
  10. tget1.cacel()
  11. await asyncio.sleep(1)
  12. # all Cancelled error will reraised and cathced by step function in Task, then it just simply igore it
  1. def _wakeup_next(self, waiters):
  2. while waiters:
  3. waiter = waiters.popleft()
  4. if not waiter.done():
  5. waiter.set_result(None)
  6. break
  7. def put_nowait(self, item):
  8. if self.full():
  9. raise QueueFull
  10. self._wakeup_next(self._getters)
  11. async def get(self):
  12. while self.empty():
  13. getter = self._loop.create_future()
  14. self._getters.append(getter)
  15. try:
  16. await getter # put_noawait will set_result(None)
  17. except:
  18. # incase of the task(containing await q.get) is cancelled, will raise CancelledError(comes from throw(err)).
  19. # Even through, getter's state is FINISHED and with no exception
  20. getter.cancel() # Just in case getter is not done yet.
  21. try:
  22. # Clean self._getters from canceled getters.
  23. self._getters.remove(getter)
  24. except ValueError:
  25. # The getter could be removed from self._getters by a
  26. # previous put_nowait call.
  27. pass
  28. # normally getter will always be FINISHED. so (not getter.cancelled()) is True
  29. if not self.empty() and not getter.cancelled():
  30. # We were woken up by put_nowait(), but can't take
  31. # the call. Wake up the next in line.
  32. self._wakeup_next(self._getters)
  33. raise
  34. return self.get_nowait()

lock

asyncio.Lock

  1. async def acquire(self):
  2. if (not self._locked and (self._waiters is None or
  3. all(w.cancelled() for w in self._waiters))):
  4. self._locked = True
  5. return True
  6. if self._waiters is None:
  7. self._waiters = collections.deque()
  8. fut = self._loop.create_future()
  9. self._waiters.append(fut)
  10. try:
  11. try:
  12. await fut
  13. finally:
  14. self._waiters.remove(fut)
  15. except exceptions.CancelledError:
  16. if not self._locked:
  17. self._wake_up_first()
  18. raise
  19. self._locked = True
  20. return True
  21. def release(self):
  22. if self._locked:
  23. self._locked = False
  24. self._wake_up_first()
  25. else:
  26. raise RuntimeError('Lock is not acquired.')
  27. def _wake_up_first(self):
  28. if not self._waiters:
  29. return
  30. try:
  31. fut = next(iter(self._waiters))
  32. except StopIteration:
  33. return
  34. # if this fut is CANCELLED, then next step will throw CancelledError in fut's __await__,
  35. # then will be catched in resumed acquare, then falls agin in this function
  36. # if this fut is FINISHED, no need to set_result again
  37. if not fut.done():
  38. fut.set_result(True)

protocols

为抽象接口,底层的IO在触发相应的事件后会调用相应的接口
connection_made
data_received
eof_received
connection_lost
transport的write buffer在高位和地位的时候会调用这两个函数
pause_writing
resume_writing

总之,write的buffer时间在内核,而read的buffer是现在应用层,存在buffer的地方可以通过调用相应的函数来通告另一方暂停或者继续

streams

FlowControlMixin(Protocol)

主要控制与write相关的流程
pasuse_writing/resume_writing操控self._drain_waiter,_data_helper()生成_drain_waiter并阻塞写
connnection_lost与resume_writing都会set_result self._dain_waiter

SteamReader()

实现各种读的接口,数据的来源都是来源于protocol.data_received()
实现了读的buffer,通过, feed_data/feed_eof 控制self._waiter, _wait_for_data生成_waiter并阻塞读,feed_data的时候检测buffer总大小,如果超过一定值则调用self._transport.pause_reading进行暂停读取
注意的是,不能直接读取数据,通过feed函数供给protocol的data_received进行调用

StreamReaderProtocol(FlowControlMixin)(reader, client_connected_cb)

connection_made(transport)
设置reader.transport
如果client_connected_cb存在话,CreateTask(cb),并且生成write
data_received,connection_lost,eof_received都需要调用reader的feed_data()/feed_oef()进行传输可读取的数据

StreamWriter(transport, protocoll, reader)

实现各种写的接口,但都是直接通过transort进行调用
drain用于阻塞write,内部是调用protocol._drain_helper,内部是只有protocol.resume_writing被调用后,drain_waiter才会被set_result

coroutines

inspect

  1. def isgeneratorfunction(object):
  2. return bool((isfunction(object) or ismethod(object)) and
  3. object.__code__.co_flags & CO_GENERATOR)
  4. def iscoroutinefunction(object):
  5. return bool((isfunction(object) or ismethod(object)) and
  6. object.__code__.co_flags & CO_COROUTINE)
  7. def isgenerator(object):
  8. return isinstance(object, types.GeneratorType)
  9. def iscoroutine(object):
  10. return isinstance(object, types.CoroutineType)
  11. def isawaitable(object):
  12. """Return true if object can be passed to an ``await`` expression."""
  13. return (isinstance(object, types.CoroutineType) or
  14. isinstance(object, types.GeneratorType) and
  15. bool(object.gi_code.co_flags & CO_ITERABLE_COROUTINE) or
  16. isinstance(object, collections.abc.Awaitable))
  1. _COROUTINE_TYPES = (types.CoroutineType, types.GeneratorType,
  2. collections.abc.Coroutine, CoroWrapper)
  3. _iscoroutine_typecache = set()
  4. def iscoroutine(obj):
  5. if isinstance(obj, _COROUTINE_TYPES):
  6. return True
  7. else:
  8. return False

events

AbstractEventLoop

BaseDefaultEventLoopProlicy

Handle

TimerHandle(Handle)

base_events

BaseEventLoop(events.AbstractEventLoop)

run_in_executor

调用futures.wrap_future,将threadPool里的concurrent.Future与新生成的Future绑定,给两者加上done_callback,任何一方done后会激活另一方done

sock_sendfile

内部会调用run_in_executor不断的把文件读进memoryview中,之后再调用sock_sendall()

get_addrinfo/nameinfo

都是调用的run_in_executor

create_connection

先通过get_addrinfo获取host ips,从第一个ip开始,绑定local ip/port(有必要的话),建立连接后break
另外还支持happy_eyeball,可以自动选择ipv4/ipv6连接(调用staggered.staggered_race)
获得建立连接的socket后
transport, protocol = await self._create_connection_transport(socket, protocol_factory,ssl)

_create_connection_transport

socket.setblocking(False)
protocol = protocol_factory()
transport = self.make_transport(socket, protocol) 会区分有没有ssl
await 一个新生成的Future

create_datagram_endpoint

与SOCK_STREAM相比,多了reuse_port,allow_broadcast选项
与create_connection一样,也会创建protocol,transport和一个新的Future

create_server

支持绑定多个host,会生成多个sockets
支持reuse_addr, reuse_port
之后创建一个server
server = Server(self, sockets, protocol_factory, ssl)
server._start_serving
socket.listen()
loop._start_serving(protocol_factory, socket)
await asyncio.sleep()

_run_once

调度器主要的循环单元

  • 移除cancelled schedules
  • 在一定的timeout内将selectIO事件的reader/writer(都是Handle对象)加入到_ready队列中
    • selector注册的时候为
  • 将schedulu中到期handle转移到_ready队列中
  • 调用所有_ready中的非cancelled handle的_run()函数
  • Handle._run() 调用Hanhel._callback

unix_events

包含真正的evenloopPolicy 和EventLoop
eventloop由self._loop_factory生成
_loop_factory为unix下的SelectoEventLoop 或者windows下的ProactorEventloop
sock_connect

  • socket.connect
  • 生成Future
  • add_writer
    • _add_reader/writer就是注册不同的事件,将Handle注册为event.data,每个Handle的_callback就是set_resultFuture
  • Fut.add_done_callback 是remove_writer
  • await Future
  • 当Future done时,表示建立连接,create_connection 完毕
    create_sock_transport
    socket已经建立连接(write事件已结束)
    接受scoket,空protocol,loop

_start_serving

_add_reader(fd, self._accept_connection, protocol_factory, sock, sslcontext, server)

_accept_connection

socket.accept
create_task(self._accept_connection2(pf, conn, extra, sslcontext, server))
_accept_connection2
protocol = pf()
waiter = self.create_future()
transport = self.mak_socket_transport()
await waiter

SelectorTransport

init
disable Nagle algorithm
call_soon(protocol.connection_made)
call_soon(loop.add_reader)
call_soon(waiter) 目的是在connection_made调用后才返回transport 和protocol