Skip to content

Commit

Permalink
Major clean-up plus some extras.
Browse files Browse the repository at this point in the history
  • Loading branch information
frobnitzem committed Feb 3, 2022
1 parent 41a71c9 commit f9960a4
Show file tree
Hide file tree
Showing 10 changed files with 373 additions and 183 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
__pycache__
dist
65 changes: 65 additions & 0 deletions COPYING
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
GNU LESSER GENERAL PUBLIC LICENSE

Version 3, 29 June 2007

Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>

Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.

This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
0. Additional Definitions.

As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.

“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.

An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.

A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.

The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.

The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.

You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.

If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:

a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.

3. Object Code Incorporating Material from Library Header Files.

The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:

a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license document.

4. Combined Works.

You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:

a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)

5. Combined Libraries.

You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:

a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.

6. Revised Versions of the GNU Lesser General Public License.

The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.

Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.

If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.
91 changes: 69 additions & 22 deletions README.rst
Original file line number Diff line number Diff line change
@@ -1,52 +1,99 @@
# aiowire - A simple event loop using asyncio
aiowire - A simple event loop using asyncio
============================================

This package implements an `EventLoop` class
This package implements a ``EventLoop`` class
that manages concurrent coroutines.

It is based on the principles of functional
reactive programming and draws inspiration
from Haskell's [Control.Wire](https://hackage.haskell.org/package/netwire-4.0.7/docs/Control-Wire.html) library.
from Haskell's `Control.Wire <https://hackage.haskell.org/package/netwire-4.0.7/docs/Control-Wire.html>`_ library.

In particular, every co-routine started by the
event loop is a `Wire`.
event loop is a ``Wire``.

`Wire`-s either return `None`, indicating they're done,
or another `Wire`.
``Wire``-s either return ``None``, indicating they're done,
or another ``Wire``.

An example helps explain the idea:
An example helps explain the idea::

```
from aiowire import EventLoop
from aiowire import EventLoop

async def show_event(ev, dt=0.2, msg="") \
-> Optional[Callable[[EventLoop],Awaitable]]:
print("Running...")
await asyncio.sleep(dt)
print(msg)
if msg != "":
return show_event
event = 0
async def show_event(ev) \
-> Optional[Callable[[EventLoop],Awaitable]]:
print("Running...")
event += 1
await asyncio.sleep(event*0.15)
print(f"Event {event}")
if event < 5:
return show_event

async with EventLoop(timeout=1) as event:
event.start(show_event(event, 0.2, "last msg."))
event.start(show_event(event, 0.1, "Ding!"))
async with EventLoop(timeout=1) as event:
event.start(show_event)
event.start(show_event)

```

We start up an event loop and drop in two wires.
Each runs, then returns the `show_event` function.
Each runs, then returns the ``show_event`` function.
The event loop runs those functions next... and so on.

But this isn't functional programming. The wires
have access to the event loop, and can start more
tasks. Easy, right?

## What can I do with it?

What can I do with it?
^^^^^^^^^^^^^^^^^^^^^^

What if you have a server that's spawning programs,
working with sockets, and managing timeouts? Drop
in one wire for each program, one polling on socket I/O,
and another acting as a timer (as above).

The canonical task types are thus::

asyncio.create_subprocess_exec # run a process

asyncio.sleep # awake the loop after a given time lapse

zmq.asyncio.Poller.poll # awake the loop after I/O on socket/file
# Note: see aiowire.Poller for a nice interface.

Now your sockets can launch programs, and your program
results can start/stop sockets, and everyone can start
background tasks.


Poller?
^^^^^^^

The ``Poller`` class lets you schedule callbacks in response
to socket or file-descriptor activity. Of course, the callbacks
are wires, and run concurrently.


Tell me more
^^^^^^^^^^^^

Yes, you *could* just send async functions taking one
argument to ``EventLoop.start``, but where's the fun in
writing closures everywhere?

To take it to the next level, aiowire comes with a
``Wire`` convenience class that lets you write ``Wire``-s expressively.
The following class extensions help you make Wire-s out of common
programming idioms:

* Wire(w): acts like an identity over "async func(ev):" functions
* Repeat(w, n): repeat wire ``w`` n times in a row
* Call(fn): call fn, ignore the return, and exit

Consider, for example, printing 4 alarms separated by some time interval::

from aiowire import EventLoop, Call

prog = ( Call(asyncio.sleep, 0.1) >> Call(print, 'beep\a') ) * 4

async with EventLoop() as ev:
ev.start(prog)

8 changes: 6 additions & 2 deletions aiowire/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
__version__ = '0.1.0'
import importlib.metadata

from .event_loop import EventLoop, FDPoller
__version__ = importlib.metadata.version("aiowire")

from .event_loop import EventLoop
from .poller import Poller
from .wire import Wire, Call, Repeat
138 changes: 21 additions & 117 deletions aiowire/event_loop.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
from typing import Optional, Dict, Union, Callable, Awaitable
from typing import Optional, Callable, Awaitable
from inspect import isawaitable
import asyncio

import os, sys, fcntl

import zmq
import zmq.asyncio

class EventLoop:
"""
Create a wire-driven event loop.
Expand All @@ -17,6 +12,9 @@ class EventLoop:
New async tasks can be launched by calling
`EventLoop.start`.
The tasks must be async-functions which take the event-loop
as its only parameter.
The return values of these tasks must be either
None, or else another `async function` which will
be called with the current event loop as its argument.
Expand All @@ -28,37 +26,26 @@ class EventLoop:
several network connections and subprocesses, and
wants to perform task/connection management as
part of some of the callbacks.
The canonical task types are thus:
asyncio.create_subprocess_exec - run a process
asyncio.sleep - awake the loop after a given time lapse
zmq.asyncio.Poller.poll - awake the loop after I/O on socket/file
Example Usage::
async def show_event(ev, dt=0.2, msg="") \
-> Optional[Callable[[EventLoop],Awaitable]]:
print("Running...")
await asyncio.sleep(dt)
print(msg)
if msg != "":
return show_event
async with EventLoop(timeout=1) as event:
event.start(show_event(event, 0.2, "last msg."))
event.start(show_event(event, 0.1, "Ding!"))
"""
def __init__(self, timeout=None):
self.tasks = set()
self.timeout = timeout

def start(self, coro : Awaitable):
t = asyncio.ensure_future(coro)
#t = asyncio.create_task(coro)
self.tasks.add(t)
def start(self, fn) -> None:
if fn is None:
return None
coro = fn(self)
if isawaitable(coro):
t = asyncio.ensure_future(coro)
#t = asyncio.create_task(coro)
self.tasks.add(t)

async def run(self, timeout = None) -> None:
"""
Run the event loop. Usually this is called
automatically when the ``async with EventLoop ...``
context ends.
"""
loop = asyncio.get_running_loop()
t0 = loop.time()
t1 = t0
Expand All @@ -77,13 +64,9 @@ async def run(self, timeout = None) -> None:
return_when = asyncio.FIRST_COMPLETED)
for t in done:
self.tasks.remove(t)
ret = await t
# Execute the task's callback
if ret is not None:
coro = ret(self)
# check if the function actually returned a coroutine
if isawaitable(coro):
self.start(coro)
# Need to await t to get its return value,
# then pass it to start again.
self.start(await t)
t1 = loop.time()

async def __aenter__(self):
Expand All @@ -92,89 +75,10 @@ async def __aenter__(self):
async def __aexit__(self, exc_type, exc, traceback):
# (exc_type, exc, traceback) are *sys.exc_info()
# or else None (on normal exit)
if exc_type is None: # run the event loop (in case we forgot)
if exc_type is None: # run the event loop here
await self.run(self.timeout)

for t in self.tasks: #[max(self.cur-1,0):]:
if not t.done():
t.cancel()
return False # continue to raise any exception

# spawn a subprocess and wait for it to complete
async def runcmd(prog, *args, ret=False, outfile=None) -> Union[int,bytes]:
"""
Run the command as an async process, passing
stdout and stderr through to the terminal.
If ret is True, send stderr through, but capture stdout.
Also ignores outfile.
Check the program exit code,
- if 0, return stdout as a string
- if not, return the exit code
If outfile is a string or Path, send stdout and stderr to it
instead of the terminal.
"""
stdout = None
stderr = None
if ret:
stdout = asyncio.subprocess.PIPE
if outfile:
# TODO: consider https://pypi.org/project/aiofiles/
f = open(outfile, 'ab')
stdout = f
stderr = f
proc = await asyncio.create_subprocess_exec(
prog, *args,
stdout=stdout, stderr=stderr)
stdout, stderr = await proc.communicate()
# note stdout/stderr are binary
if outfile:
f.close()

if ret and proc.returncode == 0:
return stdout
return proc.returncode

class FDPoller:
"""
File descriptor poller that prints
out all contents from files it is watching.
"""
def __init__(self, *fds):
self.done = False
# set files to nonblocking so reads will complete
for fd in fds:
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

self.poller = zmq.asyncio.Poller()
for fd in fds:
self.poller.register(fd, zmq.POLLIN)

def shutdown(self):
self.done = True

# timeout is in milliseconds
async def poll(self, ev, timeout : Optional[int] = 1000):
events = await self.poller.poll(timeout)
for fd, event in events:
s = self.read(fd).decode('utf-8')
print(f"fd {fd}: {s.upper()}")

if not self.done:
return self.poll

def read(self, fd):
data = b''
while True:
if fd == 0:
l = sys.stdin.read(64).encode('utf-8')
else:
l = os.read(fd, 64)
if not l:
break
data += l
return data

Loading

0 comments on commit f9960a4

Please sign in to comment.