1 ;;; 8sync --- Asynchronous programming for Guile
2 ;;; Copyright (C) 2015, 2016 Christopher Allan Webber <cwebber@dustycloud.org>
4 ;;; This file is part of 8sync.
6 ;;; 8sync is free software: you can redistribute it and/or modify it
7 ;;; under the terms of the GNU Lesser General Public License as
8 ;;; published by the Free Software Foundation, either version 3 of the
9 ;;; License, or (at your option) any later version.
11 ;;; 8sync is distributed in the hope that it will be useful,
12 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;;; GNU Lesser General Public License for more details.
16 ;;; You should have received a copy of the GNU Lesser General Public
17 ;;; License along with 8sync. If not, see <http://www.gnu.org/licenses/>.
19 (define-module (8sync agenda)
20 #:use-module (srfi srfi-1)
21 #:use-module (srfi srfi-9)
22 #:use-module (srfi srfi-9 gnu)
23 #:use-module (ice-9 q)
24 #:use-module (ice-9 match)
25 #:use-module (ice-9 receive)
26 #:use-module (ice-9 suspendable-ports)
29 agenda-queue agenda-prompt-tag
30 agenda-read-port-map agenda-write-port-map
38 make-time-segment time-segment?
39 time-segment-time time-segment-queue
41 time< time= time<= time-delta+
45 make-time-delta tdelta time-delta?
46 time-delta-sec time-delta-usec
49 make-schedule schedule?
50 schedule-add! schedule-empty?
54 schedule-segments-split schedule-extract-until!
55 add-segments-contents-to-queue!
58 make-run-request run-request?
59 run-request-proc run-request-when
61 run-it wrap wrap-apply run run-at run-delay
64 8sync-run 8sync-run-at 8sync-run-delay
68 ;; used for introspecting the error, but a method for making
71 wrapped-exception-key wrapped-exception-args
72 wrapped-exception-stacks
74 print-error-and-continue
79 start-agenda agenda-run-once))
81 ;; @@: Using immutable agendas here, so wouldn't it make sense to
82 ;; replace this queue stuff with using pfds based immutable queues?
88 ;;; The agenda consists of:
89 ;;; - a queue of immediate items to handle
90 ;;; - sheduled future events to be added to a future queue
91 ;;; - a tag by which running processes can escape for some asynchronous
92 ;;; operation (from which they can be returned later)
93 ;;; - a mapping of ports to various handler procedures
95 ;;; The goal, eventually, is for this all to be immutable and functional.
96 ;;; However, we aren't there yet. Some tricky things:
97 ;;; - The schedule needs to be immutable, yet reasonably efficient.
98 ;;; - Need to use immutable queues (ijp's pfds library?)
99 ;;; - Modeling reading from ports as something repeatable,
100 ;;; and with reasonable separation from functional components?
102 (define-immutable-record-type <agenda>
103 (make-agenda-intern queue prompt-tag
104 read-port-map write-port-map
105 schedule time catch-handler pre-unwind-handler)
108 (prompt-tag agenda-prompt-tag)
109 (read-port-map agenda-read-port-map)
110 (write-port-map agenda-write-port-map)
111 (schedule agenda-schedule)
113 (catch-handler agenda-catch-handler)
114 (pre-unwind-handler agenda-pre-unwind-handler))
116 (define (make-async-prompt-tag)
117 "Make an async prompt tag for an agenda.
119 Generally done automatically for the user through (make-agenda)."
120 (make-prompt-tag "prompt"))
122 (define* (make-agenda #:key
124 (prompt (make-prompt-tag))
125 (read-port-map (make-hash-table))
126 (write-port-map (make-hash-table))
127 (schedule (make-schedule))
128 (time (gettimeofday))
130 (pre-unwind-handler print-error-and-continue))
131 ;; TODO: document arguments
132 "Make a fresh agenda."
133 (make-agenda-intern queue prompt
134 read-port-map write-port-map
136 catch-handler pre-unwind-handler))
138 (define (current-agenda-prompt)
139 "Get the prompt for the current agenda; signal an error if there isn't one."
140 (let ((current-agenda (%current-agenda)))
141 (if (not current-agenda)
144 "Can't get current agenda prompt if there's no current agenda!")
145 (agenda-prompt-tag current-agenda))))
147 ;; helper for making queues for an agenda
148 (define (list->q lst)
149 "Makes a queue composed of LST items"
157 (define (make-q* . args)
158 "Makes a queue and populates it with this invocation's ARGS"
165 ;;; This is where we handle timed events for the future
167 ;; This section totally borrows from the ideas in SICP
170 ;; NOTE: time is a cons of (seconds . microseconds)
172 (define-record-type <time-segment>
173 (make-time-segment-intern time queue)
175 (time time-segment-time)
176 (queue time-segment-queue))
178 ;; @@: This seems to be the same as srfi-18's seconds->time procedure?
179 ;; Maybe double check and switch to that? (Thanks amz3!)
181 (define (time-from-float-or-fraction time)
182 "Produce a (sec . usec) pair from TIME, a float or fraction"
183 (let* ((mixed-whole (floor time))
184 (mixed-rest (- time mixed-whole)) ; float or fraction component
186 (usec (floor (* 1000000 mixed-rest))))
187 (cons (inexact->exact sec) (inexact->exact usec))))
189 (define (time-segment-right-format time)
190 "Ensure TIME is in the right format.
192 The right format means (second . microsecond).
193 If an integer, will convert appropriately."
194 ;; TODO: add floating point / rational number support.
196 ;; time is already a cons of second and microsecnd
197 (((? integer? s) . (? integer? u)) time)
198 ;; time was just an integer (just the second)
199 ((? integer? _) (cons time 0))
200 ((or (? rational? _) (? inexact? _))
201 (time-from-float-or-fraction time))
202 (_ (throw 'invalid-time "Invalid time" time))))
204 (define* (make-time-segment time #:optional (queue (make-q)))
205 "Make a time segment of TIME and QUEUE
207 No automatic conversion is done, so you might have to
208 run (time-segment-right-format) first."
209 (make-time-segment-intern time queue))
211 (define (time< time1 time2)
212 "Check if TIME1 is less than TIME2"
213 (cond ((< (car time1)
223 (define (time= time1 time2)
224 "Check whether TIME1 and TIME2 are equivalent"
225 (and (= (car time1) (car time2))
226 (= (cdr time1) (cdr time2))))
228 (define (time<= time1 time2)
229 "Check if TIME1 is less than or equal to TIME2"
230 (or (time< time1 time2)
231 (time= time1 time2)))
234 (define-record-type <time-delta>
235 (make-time-delta-intern sec usec)
238 (usec time-delta-usec))
240 (define* (make-time-delta time)
241 "Make a <time-delta> of SEC seconds and USEC microseconds.
243 This is used primarily so the agenda can recognize RUN-REQUEST objects
244 which are meant to delay computation"
245 (match (time-segment-right-format time)
247 (make-time-delta-intern sec usec))))
249 (define tdelta make-time-delta)
251 (define (time-carry-correct time)
252 "Corrects/handles time microsecond carry.
253 Will produce (0 . 0) instead of a negative number, if needed."
254 (cond ((>= (cdr time) 1000000)
257 (- (cdr time) 1000000)))
263 (+ (cdr time) 1000000))))
266 (define (time-delta+ time time-delta)
267 "Increment a TIME by the value of TIME-DELTA"
269 (cons (+ (car time) (time-delta-sec time-delta))
270 (+ (cdr time) (time-delta-usec time-delta)))))
272 (define (time-minus time1 time2)
273 "Subtract TIME2 from TIME1"
275 (cons (- (car time1) (car time2))
276 (- (cdr time1) (cdr time2)))))
278 (define (time-plus time1 time2)
279 "Add TIME1 and TIME2"
281 (cons (+ (car time1) (car time2))
282 (+ (cdr time1) (cdr time2)))))
285 (define-record-type <schedule>
286 (make-schedule-intern segments)
288 (segments schedule-segments set-schedule-segments!))
290 (define* (make-schedule #:optional segments)
291 "Make a schedule, optionally pre-composed of SEGMENTS"
292 (make-schedule-intern (or segments '())))
294 (define (schedule-soonest-time schedule)
295 "Return a cons of (sec . usec) for next time segement, or #f if none"
296 (let ((segments (schedule-segments schedule)))
297 (if (eq? segments '())
299 (time-segment-time (car segments)))))
301 ;; TODO: This code is reasonably easy to read but it
302 ;; mutates AND is worst case of O(n) in both space and time :(
303 ;; but at least it'll be reasonably easy to refactor to
304 ;; a more functional setup?
305 (define (schedule-add! schedule time proc)
306 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
307 (let ((time (time-segment-right-format time)))
308 (define (new-time-segment)
310 (make-time-segment time)))
311 (enq! (time-segment-queue new-segment) proc)
313 (define (loop segments)
314 (define (segment-equals-time? segment)
315 (time= time (time-segment-time segment)))
317 (define (segment-more-than-time? segment)
318 (time< time (time-segment-time segment)))
320 ;; We could switch this out to be more mutate'y
321 ;; and avoid the O(n) of space... is that over-optimizing?
323 ;; If we're at the end of the list, time to make a new
325 ('() (cons (new-time-segment) '()))
326 ;; If the segment's time is exactly our time, good news
327 ;; everyone! Let's append our stuff to its queue
328 (((? segment-equals-time? first) rest ...)
329 (enq! (time-segment-queue first) proc)
331 ;; If the first segment is more than our time,
332 ;; ours belongs before this one, so add it and
333 ;; start consing our way back
334 (((? segment-more-than-time? first) rest ...)
335 (cons (new-time-segment) segments))
336 ;; Otherwise, build up recursive result
338 (cons first (loop rest)))))
339 (set-schedule-segments!
341 (loop (schedule-segments schedule)))))
343 (define (schedule-empty? schedule)
344 "Check if the SCHEDULE is currently empty"
345 (eq? (schedule-segments schedule) '()))
347 (define (schedule-segments-split schedule time)
348 "Does a multiple value return of time segments before/at and after TIME"
349 (let ((time (time-segment-right-format time)))
350 (define (segment-is-now? segment)
351 (time= (time-segment-time segment) time))
352 (define (segment-is-before-now? segment)
353 (time< (time-segment-time segment) time))
355 (let loop ((segments-before '())
356 (segments-left (schedule-segments schedule)))
358 ;; end of the line, return
360 (values (reverse segments-before) '()))
362 ;; It's right now, so time to stop, but include this one in before
363 ;; but otherwise return
364 (((? segment-is-now? first) rest ...)
365 (values (reverse (cons first segments-before)) rest))
367 ;; This is prior or at now, so add it and keep going
368 (((? segment-is-before-now? first) rest ...)
369 (loop (cons first segments-before) rest))
371 ;; Otherwise it's past now, just return what we have
373 (values segments-before segments-after))))))
375 (define (schedule-extract-until! schedule time)
376 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
377 (receive (segments-before segments-after)
378 (schedule-segments-split schedule time)
379 (set-schedule-segments! schedule segments-after)
382 (define (add-segments-contents-to-queue! segments queue)
385 (let ((seg-queue (time-segment-queue segment)))
386 (while (not (q-empty? seg-queue))
387 (enq! queue (deq! seg-queue)))))
392 ;;; Request to run stuff
393 ;;; ====================
395 (define-record-type <run-request>
396 (make-run-request proc when)
398 (proc run-request-proc)
399 (when run-request-when))
401 (define* (run-it proc #:optional when)
402 "Make a request to run PROC (possibly at WHEN)"
403 (make-run-request proc when))
405 (define-syntax-rule (wrap body ...)
406 "Wrap contents in a procedure"
410 (define-syntax-rule (wrap-apply body)
411 "Wrap possibly multi-value function in a procedure, applies all arguments"
416 ;; @@: Do we really want `body ...' here?
417 ;; what about just `body'?
418 (define-syntax-rule (run body ...)
419 "Run everything in BODY but wrap in a convenient procedure"
420 (make-run-request (wrap body ...) #f))
422 (define-syntax-rule (run-at body ... when)
424 (make-run-request (wrap body ...) when))
426 ;; @@: Is it okay to overload the term "delay" like this?
427 ;; Would `run-in' be better?
428 (define-syntax-rule (run-delay body ... delay-time)
429 "Run BODY at DELAY-TIME time from now"
430 (make-run-request (wrap body ...) (tdelta delay-time)))
434 ;;; Asynchronous escape to run things
435 ;;; =================================
437 (define-syntax-rule (8sync-abort-to-prompt async-request)
438 (abort-to-prompt (current-agenda-prompt)
441 ;; Async port request and run-request meta-requests
442 (define (make-async-request proc)
443 "Wrap PROC in an async-request
445 The purpose of this is to make sure that users don't accidentally
446 return the wrong thing via (8sync) and trip themselves up."
447 (cons '*async-request* proc))
449 (define (setup-async-request resume-kont async-request)
450 "Complete an async request for agenda-run-once's continuation handling"
452 (('*async-request* . async-setup-proc)
453 (async-setup-proc resume-kont))
454 ;; TODO: deliver more helpful errors depending on what the user
456 (_ (throw 'invalid-async-request
457 "Invalid request passed back via an (8sync) procedure."
460 (define-syntax-rule (8sync body ...)
461 "Run body asynchronously but ignore its result...
462 forge ahead in our current function!"
463 (8sync-abort-to-prompt
466 (list (make-run-request
467 ;; What's with returning #f to kont?
468 ;; Otherwise we sometimes get errors like
469 ;; "Zero values returned to single-valued continuation""
471 (make-run-request (lambda () body ...) #f))))))
473 ;; TODO: Rewrite when we move to this being just `sleep'.
474 (define (8sleep time)
475 (8sync-abort-to-prompt
478 (make-run-request (lambda () (kont #f)) (tdelta time))))))
480 ;; Voluntarily yield execution
481 (define (yield) ; @@: should this be define-inlinable?
482 "Voluntarily yield execution to the scheduler."
483 (8sync-abort-to-prompt
486 (make-run-request (lambda () (kont #f)) #f)))))
489 ;;; Execution of agenda, and current agenda
490 ;;; =======================================
492 (define %current-agenda (make-parameter #f))
494 (define (update-agenda-from-select! agenda)
495 "Potentially (select) on ports specified in agenda, adding items to queue.
497 Also handles sleeping when all we have to do is wait on the schedule."
498 (define (hash-keys hash)
499 (hash-map->list (lambda (k v) k) hash))
500 (define (get-wait-time)
501 ;; TODO: we need to figure this out based on whether there's anything
502 ;; in the queue, and if not, how long till the next scheduled item
503 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
505 ((not (q-empty? (agenda-queue agenda)))
507 (soonest-time ; ie, the agenda is non-empty
508 (let* ((current-time (agenda-time agenda)))
509 (if (time<= soonest-time current-time)
510 ;; Well there's something due so let's select
511 ;; (this avoids a (possible?) race condition chance)
513 (time-minus soonest-time current-time))))
517 ;; TODO: support usecond wait time too
518 (match (get-wait-time)
522 (select (hash-keys (agenda-read-port-map agenda))
523 (hash-keys (agenda-write-port-map agenda))
526 (lambda (key . rest-args)
530 (_ (error "Unhandled error in select!" key rest-args))))))))
531 (define (get-procs-to-run)
532 (define (ports->procs ports port-map)
533 (lambda (initial-procs)
536 (define proc (hashq-ref port-map port))
537 ;; Now that we've selected on this port, it can be removed
538 (hashq-remove! port-map port)
543 ((read-ports write-ports except-ports) ; except-ports not used
544 ((compose (ports->procs
546 (agenda-read-port-map agenda))
549 (agenda-write-port-map agenda)))
551 (define (update-agenda)
552 (let ((procs-to-run (get-procs-to-run))
553 (q (agenda-queue agenda)))
559 (define (ports-to-select?)
560 (define (has-items? selector)
562 ;; ... we could use hash-for-each and a continuation to jump
563 ;; out with a #t at first indication of an item
564 (not (= (hash-count (const #t)
567 (or (has-items? agenda-read-port-map)
568 (has-items? agenda-write-port-map)))
570 (if (or (ports-to-select?)
571 ;; select doubles as sleep...
572 (not (schedule-empty? (agenda-schedule agenda))))
576 (define-record-type <read-request>
577 (make-read-request port proc)
579 (port read-request-port)
580 (proc read-request-proc))
582 (define-record-type <write-request>
583 (make-write-request port proc)
585 (port write-request-port)
586 (proc write-request-proc))
588 (define (agenda-handle-read-request! agenda read-request)
589 "Handle <read-request>, which is a request to add this port to the poll/select
590 on suspendable ports."
591 (hashq-set! (agenda-read-port-map agenda)
592 (read-request-port read-request)
593 (read-request-proc read-request)))
595 (define (agenda-handle-write-request! agenda write-request)
596 (hashq-set! (agenda-write-port-map agenda)
597 (write-request-port write-request)
598 (write-request-proc write-request)))
600 (define (stop-on-nothing-to-do agenda)
601 (and (q-empty? (agenda-queue agenda))
602 (schedule-empty? (agenda-schedule agenda))
603 (= 0 (hash-count (const #t) (agenda-read-port-map agenda)))
604 (= 0 (hash-count (const #t) (agenda-write-port-map agenda)))))
607 (define* (start-agenda agenda
609 ;; @@: Should we make stop-on-nothing-to-do
610 ;; the default stop-condition?
611 (stop-condition stop-on-nothing-to-do)
612 (get-time gettimeofday)
613 (handle-ports update-agenda-from-select!)
614 ;; For live hacking madness, etc
616 ;; TODO: Document fields
617 "Start up the AGENDA"
618 (install-suspendable-ports!)
619 (let loop ((agenda agenda))
621 ;; @@: Hm, maybe here would be a great place to handle
622 ;; select'ing on ports.
623 ;; We could compose over agenda-run-once and agenda-read-ports
624 (agenda-run-once agenda)))
625 ;; @@: This relies on mutation at present on the queue, in the rare
626 ;; event it's used. If we ever switch to something more immutable,
627 ;; it should return a new modified agenda instead.
629 (post-run-hook agenda))
630 (if (and stop-condition (stop-condition agenda))
633 ;; We have to update the time after ports handled, too
634 ;; because it may have changed after a select
637 ;; Adjust the agenda's time just in time
638 ;; We do this here rather than in agenda-run-once to make
639 ;; agenda-run-once's behavior fairly predictable
640 (set-field agenda (agenda-time) (get-time)))
641 (agenda-time) (get-time))))
642 ;; Update the agenda's current queue based on
643 ;; currently applicable time segments
644 (add-segments-contents-to-queue!
645 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
646 (agenda-queue agenda))
650 (define (print-error-and-continue key . args)
651 "Frequently used as pre-unwind-handler for agenda"
653 ((eq? key '8sync-caught-error)
655 ((orig-key orig-args stacks)
656 (display "\n*** Caught async exception. ***\n")
657 (format (current-error-port)
658 "* Original key '~s and arguments: ~s *\n"
660 (display "* Caught stacks below (ending with original) *\n\n")
663 (display-backtrace s (current-error-port))
664 (newline (current-error-port)))
667 (format (current-error-port)
668 "\n*** Caught exception with key '~s and arguments: ~s ***\n"
670 (display-backtrace (make-stack #t 1 0)
671 (current-error-port))
672 (newline (current-error-port)))))
674 (define-syntax-rule (maybe-catch-all (catch-handler pre-unwind-handler)
676 (if (or catch-handler pre-unwind-handler)
681 (or catch-handler (lambda _ #f))
682 (or pre-unwind-handler (lambda _ #f)))
685 (define (wait-for-readable port)
686 (8sync-abort-to-prompt
689 (make-read-request port (wrap (kont #f)))))))
691 (define (wait-for-writable port)
692 (8sync-abort-to-prompt
695 (make-write-request port (wrap (kont #f)))))))
697 (define (agenda-run-once agenda)
698 "Run once through the agenda, and produce a new agenda
699 based on the results"
700 (define (call-proc proc)
702 (agenda-prompt-tag agenda)
704 (parameterize ((%current-agenda agenda)
705 ;; @@: Couldn't we just parameterize this at the start of
707 (current-read-waiter wait-for-readable)
708 (current-write-waiter wait-for-writable))
710 ((agenda-catch-handler agenda)
711 (agenda-pre-unwind-handler agenda))
713 (lambda (kont async-request)
714 (setup-async-request kont async-request))))
716 (let ((queue (agenda-queue agenda))
717 (next-queue (make-q)))
718 (while (not (q-empty? queue))
719 (let* ((proc (q-pop! queue))
720 (proc-result (call-proc proc))
722 (lambda (run-request)
723 (define (schedule-at! time proc)
724 (schedule-add! (agenda-schedule agenda) time proc))
725 (let ((request-time (run-request-when run-request)))
727 ((? time-delta? time-delta)
728 (let ((time (time-delta+ (agenda-time agenda)
730 (schedule-at! time (run-request-proc run-request))))
732 (let ((time (cons sec 0)))
733 (schedule-at! time (run-request-proc run-request))))
734 (((? integer? sec) . (? integer? usec))
735 (schedule-at! request-time (run-request-proc run-request)))
737 (enq! next-queue (run-request-proc run-request))))))))
738 (define (handle-individual result)
739 ;; @@: Could maybe optimize by switching to an explicit cond...
741 ((? run-request? new-proc)
743 ((? read-request? read-request)
744 (agenda-handle-read-request! agenda read-request))
745 ((? write-request? write-request)
746 (agenda-handle-write-request! agenda write-request))
748 ;; Remember, we don't throw an error here because procedures can
749 ;; return a run request, eg with run-it, at the end of their
750 ;; evaluation to keep looping.
751 ;; @@: Though is this really a useful feature?
753 ;; @@: We might support delay-wrapped procedures here
756 (for-each handle-individual results))
757 (one-result (handle-individual one-result)))))
758 ;; TODO: Alternately, we could return the next-queue
759 ;; along with changes to be added to the schedule here?
760 ;; Return new agenda, with next queue set
761 (set-field agenda (agenda-queue) next-queue)))