Skip to content

Commit

Permalink
Initial working aio package
Browse files Browse the repository at this point in the history
  • Loading branch information
skeeto committed Mar 10, 2019
0 parents commit 2eb1460
Show file tree
Hide file tree
Showing 5 changed files with 522 additions and 0 deletions.
19 changes: 19 additions & 0 deletions Makefile
@@ -0,0 +1,19 @@
.POSIX:
EMACS = emacs

compile: aio.elc aio-test.elc

aio.elc: aio.el
aio-test.elc: aio-test.el

clean:
rm -f aio.elc aio-test.elc

check: aio.elc aio-test.elc
emacs -Q -nw -L . -l aio-test.elc -f aio-run-tests

.SUFFIXES: .el .elc
.el.elc:
$(EMACS) -batch -Q -L . -f batch-byte-compile $<


80 changes: 80 additions & 0 deletions README.md
@@ -0,0 +1,80 @@
# aio: async/await for Emacs Lisp

`aio` is to Emacs Lisp as [`asyncio`][asyncio] is to Python. This
package builds upon Emacs 25 generators to provide functions that
pause while they wait on asynchronous events. They do not block any
thread while paused.

## Usage

An async function is defined using `aio-defun` or `aio-lambda`. The
body of such functions can use `aio-await` to pause the function and
wait on a given promise. The function continues with the promise's
resolved value when it's ready. The package provides a number of
functions that return promises, and every async function returns a
promise representing its future return value.

For example:

```el
(aio-defun foo (url)
(aio-await (aio-sleep 3))
(message "Done sleeping. Now fetching %s" url)
(let* ((buffer (aio-await (aio-url-retrieve url)))
(contents (with-current-buffer buffer
(prog1 (buffer-string)
(kill-buffer)))))
(message "Result: %s" contents)))
```

If an uncaught signal terminates an asynchronous function, that signal
is captured by its return value promise and propagated into any
function that awaits on that function.

```el
(aio-defun arith-error-example ()
(/ 0 0))
(aio-defun consumer-example ()
(condition-case error
(aio-await (arith-error-example))
(arith-error (message "Caught %S" error))))
(consumer-example)
;; => #s(aio-promise nil nil)
;; *Messages*: Caught (arith-error)
```

Converting a callback-based function into a promise-returning,
async-friendly function is simple. Create a new promise object with
`aio-promise`, then `aio-resolve` that promise in your callback. To
chain onto an existing promise, use `aio-listen` to attach a new
callback.

## Promise-returning functions

Here are some useful promise-returning — i.e. awaitable — functions
defined by this package.

```el
(aio-sleep seconds &optional result)
;; Return a promise that is resolved after SECONDS with RESULT.
(aio-url-retrieve url &optional silent inhibit-cookies)
;; Wraps `url-retrieve' in a promise.
(aio-process-sentinel process)
;; Return a promise representing the sentinel of PROCESS.
(aio-process-filter process)
;; Return a promise representing the filter of PROCESS.
(aio-select promises)
;; Return a promise that resolves when any in PROMISES resolves.
(aio-all (promises)
;; Return a promise that resolves when all PROMISES are resolved."
```


[asyncio]: https://docs.python.org/3/library/asyncio.html
24 changes: 24 additions & 0 deletions UNLICENSE
@@ -0,0 +1,24 @@
This is free and unencumbered software released into the public domain.

Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.

In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

For more information, please refer to <http://unlicense.org/>
122 changes: 122 additions & 0 deletions aio-test.el
@@ -0,0 +1,122 @@
;;; aio-tests.el --- async unit test suite for aio -*- lexical-binding: t; -*-

;;; Commentary:

;; emacs -Q -nw -L . -l aio-test.elc -f aio-run-tests

;; Because the tests run as async functions, the test suite cannot be
;; run in batch mode. The results will be written into a buffer and
;; Emacs will be left running so you can see the results.

;;; Code:

(require 'aio)
(require 'cl-lib)

(defvar aio-tests ())

(defvar aio-test-total nil)
(defvar aio-test-failures nil)

(defun aio-run-tests ()
(setf aio-test-total 0
aio-test-failures 0)
(let* ((buffer (get-buffer-create "*aio-results*"))
(promises
(cl-loop for (name . test) in (reverse aio-tests)
for promise = (funcall test)
for cb =
(let ((test-name name))
(lambda (value)
(insert (format "%S: %S\n" test-name (funcall value)))))
collect promise
do (aio-listen (aio-catch promise) cb)))
(done (aio-all promises)))
(switch-to-buffer buffer)
(erase-buffer)
(aio-listen done (lambda (_)
(with-current-buffer buffer
(insert "*** aio-run-tests complete ***\n")
(insert (format "%d / %d PASS\n"
(- aio-test-total aio-test-failures)
aio-test-total)))))))

(defun aio--should (result value-a value-b expr-a expr-b)
(cl-incf aio-test-total)
(unless result
(cl-incf aio-test-failures)
(insert (format "FAIL:\n%S\n= %S\n%S\n= %S\n"
expr-a value-a expr-b value-b))))

(defmacro aio-should (cmp expr-a expr-b)
(let ((value-a (make-symbol "a"))
(value-b (make-symbol "b")))
`(let ((,value-a ,expr-a)
(,value-b ,expr-b))
(aio--should (,cmp ,value-a ,value-b)
,value-a ,value-b ',expr-a ',expr-b))))

(defmacro aio-deftest (name _ &rest body)
(declare (indent defun))
`(push (cons ',name (aio-lambda () ,@body)) aio-tests))

;; Tests:

(aio-deftest sleep ()
(let ((start (float-time)))
(dotimes (i 3)
(aio-should eql i (aio-await (aio-sleep 0.5 i))))
(aio-should > (- (float-time) start) 1.4)))

(aio-deftest chain ()
(let ((sub (aio-lambda (result) (aio-await (aio-sleep .1 result)))))
(aio-should eq :a (aio-await (funcall sub :a)))
(aio-should eq :b (aio-await (funcall sub :b)))))

(aio-deftest timeout ()
(let ((sleep (aio-sleep 1 t)))
(prog1 nil
(aio-should equal
'(:error aio-timeout . 0.5)
(aio-await (aio-catch (aio-timeout sleep 0.5)))))))

(defun aio-test--shuffle (values)
"Return a shuffled copy of VALUES."
(let ((v (vconcat values)))
(cl-loop for i from (1- (length v)) downto 1
for j = (cl-random (+ i 1))
do (cl-rotatef (aref v i) (aref v j))
finally return (append v nil))))

(aio-deftest sleep-sort ()
(let* ((values (cl-loop for i from 5 to 60
collect (/ i 20.0) into values
finally return (aio-test--shuffle values)))
(promises (cl-loop for value in values
collect (aio-sleep value value)))
(last 0.0))
(while promises
(let ((promise (aio-await (aio-select promises))))
(setf promises (delq promise promises))
(let ((result (aio-await promise)))
(aio-should > result last)
(setf last result))))))

(aio-deftest process-sentinel ()
(let ((process (start-process-shell-command "test" nil "")))
(aio-should equal
"finished\n"
(aio-await (aio-process-sentinel process)))))

(aio-deftest process-filter ()
(let ((process (start-process-shell-command
"test" nil "echo a b c; sleep 1; echo 1 2 3; sleep 1")))
(aio-should equal
"a b c\n"
(aio-await (aio-process-filter process)))
(aio-should equal
"1 2 3\n"
(aio-await (aio-process-filter process)))
(aio-should equal
nil
(aio-await (aio-process-filter process)))))

0 comments on commit 2eb1460

Please sign in to comment.