1 ;;; 8sync --- Asynchronous programming for Guile
2 ;;; Copyright (C) 2015 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 (eightsync 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)
28 agenda-queue agenda-prompt-tag
29 agenda-read-port-map agenda-write-port-map agenda-except-port-map
37 make-time-segment time-segment?
38 time-segment-time time-segment-queue
40 time< time= time<= time-delta+
44 make-time-delta tdelta time-delta?
45 time-delta-sec time-delta-usec
48 make-schedule schedule?
49 schedule-add! schedule-empty?
53 schedule-segments-split schedule-extract-until!
54 add-segments-contents-to-queue!
59 make-run-request run-request?
60 run-request-proc run-request-when
63 make-port-request port-request port-request?
65 port-request-read port-request-write port-request-except
67 run-it wrap wrap-apply run run-at run-delay
69 %port-request %run %run-at %run-delay
71 catch-8sync catch-%8sync
73 ;; used for introspecting the error, but a method for making
76 wrapped-exception-key wrapped-exception-args
77 wrapped-exception-stacks
79 print-error-and-continue
82 start-agenda agenda-run-once))
84 ;; @@: Using immutable agendas here, so wouldn't it make sense to
85 ;; replace this queue stuff with using pfds based immutable queues?
91 ;;; The agenda consists of:
92 ;;; - a queue of immediate items to handle
93 ;;; - sheduled future events to be added to a future queue
94 ;;; - a tag by which running processes can escape for some asynchronous
95 ;;; operation (from which they can be returned later)
96 ;;; - a mapping of ports to various handler procedures
98 ;;; The goal, eventually, is for this all to be immutable and functional.
99 ;;; However, we aren't there yet. Some tricky things:
100 ;;; - The schedule needs to be immutable, yet reasonably efficient.
101 ;;; - Need to use immutable queues (ijp's pfds library?)
102 ;;; - Modeling reading from ports as something repeatable,
103 ;;; and with reasonable separation from functional components?
105 (define-immutable-record-type <agenda>
106 (make-agenda-intern queue prompt-tag
107 read-port-map write-port-map except-port-map
108 schedule time catch-handler pre-unwind-handler)
111 (prompt-tag agenda-prompt-tag)
112 (read-port-map agenda-read-port-map)
113 (write-port-map agenda-write-port-map)
114 (except-port-map agenda-except-port-map)
115 (schedule agenda-schedule)
117 (catch-handler agenda-catch-handler)
118 (pre-unwind-handler agenda-pre-unwind-handler))
120 (define (make-async-prompt-tag)
121 "Make an async prompt tag for an agenda.
123 Generally done automatically for the user through (make-agenda)."
124 (make-prompt-tag "prompt"))
126 (define* (make-agenda #:key
128 (prompt (make-prompt-tag))
129 (read-port-map (make-hash-table))
130 (write-port-map (make-hash-table))
131 (except-port-map (make-hash-table))
132 (schedule (make-schedule))
133 (time (gettimeofday))
135 (pre-unwind-handler #f))
136 ;; TODO: document arguments
137 "Make a fresh agenda."
138 (make-agenda-intern queue prompt
139 read-port-map write-port-map except-port-map
141 catch-handler pre-unwind-handler))
143 (define (current-agenda-prompt)
144 "Get the prompt for the current agenda; signal an error if there isn't one."
145 (let ((current-agenda (%current-agenda)))
146 (if (not current-agenda)
149 "Can't get current agenda prompt if there's no current agenda!")
150 (agenda-prompt-tag current-agenda))))
152 ;; helper for making queues for an agenda
153 (define (list->q lst)
154 "Makes a queue composed of LST items"
162 (define (make-q* . args)
163 "Makes a queue and populates it with this invocation's ARGS"
170 ;;; This is where we handle timed events for the future
172 ;; This section totally borrows from the ideas in SICP
175 ;; NOTE: time is a cons of (seconds . microseconds)
177 (define-record-type <time-segment>
178 (make-time-segment-intern time queue)
180 (time time-segment-time)
181 (queue time-segment-queue))
183 ;; @@: This seems to be the same as srfi-18's seconds->time procedure?
184 ;; Maybe double check and switch to that? (Thanks amz3!)
186 (define (time-from-float-or-fraction time)
187 "Produce a (sec . usec) pair from TIME, a float or fraction"
188 (let* ((mixed-whole (floor time))
189 (mixed-rest (- time mixed-whole)) ; float or fraction component
191 (usec (floor (* 1000000 mixed-rest))))
192 (cons (inexact->exact sec) (inexact->exact usec))))
194 (define (time-segment-right-format time)
195 "Ensure TIME is in the right format.
197 The right format means (second . microsecond).
198 If an integer, will convert appropriately."
199 ;; TODO: add floating point / rational number support.
201 ;; time is already a cons of second and microsecnd
202 (((? integer? s) . (? integer? u)) time)
203 ;; time was just an integer (just the second)
204 ((? integer? _) (cons time 0))
205 ((or (? rational? _) (? inexact? _))
206 (time-from-float-or-fraction time))
207 (_ (throw 'invalid-time "Invalid time" time))))
209 (define* (make-time-segment time #:optional (queue (make-q)))
210 "Make a time segment of TIME and QUEUE
212 No automatic conversion is done, so you might have to
213 run (time-segment-right-format) first."
214 (make-time-segment-intern time queue))
216 (define (time< time1 time2)
217 "Check if TIME1 is less than TIME2"
218 (cond ((< (car time1)
228 (define (time= time1 time2)
229 "Check whether TIME1 and TIME2 are equivalent"
230 (and (= (car time1) (car time2))
231 (= (cdr time1) (cdr time2))))
233 (define (time<= time1 time2)
234 "Check if TIME1 is less than or equal to TIME2"
235 (or (time< time1 time2)
236 (time= time1 time2)))
239 (define-record-type <time-delta>
240 (make-time-delta-intern sec usec)
243 (usec time-delta-usec))
245 (define* (make-time-delta time)
246 "Make a <time-delta> of SEC seconds and USEC microseconds.
248 This is used primarily so the agenda can recognize RUN-REQUEST objects
249 which are meant to delay computation"
250 (match (time-segment-right-format time)
252 (make-time-delta-intern sec usec))))
254 (define tdelta make-time-delta)
256 (define (time-carry-correct time)
257 "Corrects/handles time microsecond carry.
258 Will produce (0 . 0) instead of a negative number, if needed."
259 (cond ((>= (cdr time) 1000000)
262 (- (cdr time) 1000000)))
268 (+ (cdr time) 1000000))))
271 (define (time-delta+ time time-delta)
272 "Increment a TIME by the value of TIME-DELTA"
274 (cons (+ (car time) (time-delta-sec time-delta))
275 (+ (cdr time) (time-delta-usec time-delta)))))
277 (define (time-minus time1 time2)
278 "Subtract TIME2 from TIME1"
280 (cons (- (car time1) (car time2))
281 (- (cdr time1) (cdr time2)))))
283 (define (time-plus time1 time2)
284 "Add TIME1 and TIME2"
286 (cons (+ (car time1) (car time2))
287 (+ (cdr time1) (cdr time2)))))
290 (define-record-type <schedule>
291 (make-schedule-intern segments)
293 (segments schedule-segments set-schedule-segments!))
295 (define* (make-schedule #:optional segments)
296 "Make a schedule, optionally pre-composed of SEGMENTS"
297 (make-schedule-intern (or segments '())))
299 (define (schedule-soonest-time schedule)
300 "Return a cons of (sec . usec) for next time segement, or #f if none"
301 (let ((segments (schedule-segments schedule)))
302 (if (eq? segments '())
304 (time-segment-time (car segments)))))
306 ;; TODO: This code is reasonably easy to read but it
307 ;; mutates AND is worst case of O(n) in both space and time :(
308 ;; but at least it'll be reasonably easy to refactor to
309 ;; a more functional setup?
310 (define (schedule-add! schedule time proc)
311 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
312 (let ((time (time-segment-right-format time)))
313 (define (new-time-segment)
315 (make-time-segment time)))
316 (enq! (time-segment-queue new-segment) proc)
318 (define (loop segments)
319 (define (segment-equals-time? segment)
320 (time= time (time-segment-time segment)))
322 (define (segment-more-than-time? segment)
323 (time< time (time-segment-time segment)))
325 ;; We could switch this out to be more mutate'y
326 ;; and avoid the O(n) of space... is that over-optimizing?
328 ;; If we're at the end of the list, time to make a new
330 ('() (cons (new-time-segment) '()))
331 ;; If the segment's time is exactly our time, good news
332 ;; everyone! Let's append our stuff to its queue
333 (((? segment-equals-time? first) rest ...)
334 (enq! (time-segment-queue first) proc)
336 ;; If the first segment is more than our time,
337 ;; ours belongs before this one, so add it and
338 ;; start consing our way back
339 (((? segment-more-than-time? first) rest ...)
340 (cons (new-time-segment) segments))
341 ;; Otherwise, build up recursive result
343 (cons first (loop rest)))))
344 (set-schedule-segments!
346 (loop (schedule-segments schedule)))))
348 (define (schedule-empty? schedule)
349 "Check if the SCHEDULE is currently empty"
350 (eq? (schedule-segments schedule) '()))
352 (define (schedule-segments-split schedule time)
353 "Does a multiple value return of time segments before/at and after TIME"
354 (let ((time (time-segment-right-format time)))
355 (define (segment-is-now? segment)
356 (time= (time-segment-time segment) time))
357 (define (segment-is-before-now? segment)
358 (time< (time-segment-time segment) time))
360 (let loop ((segments-before '())
361 (segments-left (schedule-segments schedule)))
363 ;; end of the line, return
365 (values (reverse segments-before) '()))
367 ;; It's right now, so time to stop, but include this one in before
368 ;; but otherwise return
369 (((? segment-is-now? first) rest ...)
370 (values (reverse (cons first segments-before)) rest))
372 ;; This is prior or at now, so add it and keep going
373 (((? segment-is-before-now? first) rest ...)
374 (loop (cons first segments-before) rest))
376 ;; Otherwise it's past now, just return what we have
378 (values segments-before segments-after))))))
380 (define (schedule-extract-until! schedule time)
381 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
382 (receive (segments-before segments-after)
383 (schedule-segments-split schedule time)
384 (set-schedule-segments! schedule segments-after)
387 (define (add-segments-contents-to-queue! segments queue)
390 (let ((seg-queue (time-segment-queue segment)))
391 (while (not (q-empty? seg-queue))
392 (enq! queue (deq! seg-queue)))))
397 ;;; Request to run stuff
398 ;;; ====================
400 (define-record-type <run-request>
401 (make-run-request proc when)
403 (proc run-request-proc)
404 (when run-request-when))
406 (define* (run-it proc #:optional when)
407 "Make a request to run PROC (possibly at WHEN)"
408 (make-run-request proc when))
410 (define-syntax-rule (wrap body ...)
411 "Wrap contents in a procedure"
415 (define-syntax-rule (wrap-apply body)
416 "Wrap possibly multi-value function in a procedure, applies all arguments"
421 ;; @@: Do we really want `body ...' here?
422 ;; what about just `body'?
423 (define-syntax-rule (run body ...)
424 "Run everything in BODY but wrap in a convenient procedure"
425 (make-run-request (wrap body ...) #f))
427 (define-syntax-rule (run-at body ... when)
429 (make-run-request (wrap body ...) when))
431 ;; @@: Is it okay to overload the term "delay" like this?
432 ;; Would `run-in' be better?
433 (define-syntax-rule (run-delay body ... delay-time)
434 "Run BODY at DELAY-TIME time from now"
435 (make-run-request (wrap body ...) (tdelta delay-time)))
438 ;; A request to set up a port with at least one of read, write, except
439 ;; handling processes
441 (define-record-type <port-request>
442 (make-port-request-intern port read write except)
444 (port port-request-port)
445 (read port-request-read)
446 (write port-request-write)
447 (except port-request-except))
449 (define* (make-port-request port #:key read write except)
450 (if (not (or read write except))
451 (throw 'no-port-handler-given "No port handler given.\n"))
452 (make-port-request-intern port read write except))
454 (define port-request make-port-request)
458 ;;; Asynchronous escape to run things
459 ;;; =================================
461 (define-syntax-rule (%8sync async-request)
462 "Run BODY asynchronously at a prompt, passing args to make-future.
464 Runs things asynchronously (8synchronously?)"
465 (propagate-%async-exceptions
466 (abort-to-prompt (current-agenda-prompt)
469 ;; Async port request and run-request meta-requests
470 (define (make-async-request proc)
471 "Wrap PROC in an async-request
473 The purpose of this is to make sure that users don't accidentally
474 return the wrong thing via (%8sync) and trip themselves up."
475 (cons '*async-request* proc))
477 (define (setup-async-request resume-kont async-request)
478 "Complete an async request for agenda-run-once's continuation handling"
480 (('*async-request* . async-setup-proc)
481 (async-setup-proc resume-kont))
482 ;; TODO: deliver more helpful errors depending on what the user
484 (_ (throw 'invalid-async-request
485 "Invalid request passed back via an (%8sync) procedure."
488 (define-record-type <wrapped-exception>
489 (make-wrapped-exception key args stacks)
491 (key wrapped-exception-key)
492 (args wrapped-exception-args)
493 (stacks wrapped-exception-stacks))
495 (define-syntax-rule (propagate-%async-exceptions body)
496 (let ((body-result body))
497 (if (wrapped-exception? body-result)
498 (throw '8sync-caught-error
499 (wrapped-exception-key body-result)
500 (wrapped-exception-args body-result)
501 (wrapped-exception-stacks body-result))
504 (define-syntax-rule (%run body ...)
505 (%run-at body ... #f))
507 (define-syntax-rule (%run-at body ... when)
508 ;; Send an asynchronous request to apply a continuation to the
509 ;; following function, then handle that as a request to the agenda
512 ;; We're making a run request
514 ;; Wrapping the following execution to run...
516 ;; Once we get the result from the inner part, we'll resume
517 ;; this continuation, but first
518 ;; @@: Is this running immediately, or queueing the result
519 ;; after evaluation for the next agenda tick? It looks
520 ;; like evaluating immediately. Is that what we want?
522 ;; Any unhandled errors are caught
523 (let ((exception-stack #f))
525 ;; Run the actual code the user requested
528 ;; If something bad happened and we didn't catch it,
529 ;; we'll wrap it up in such a way that the continuation
533 ((eq? key '8sync-caught-error)
535 ((orig-key orig-args orig-stacks)
536 (make-wrapped-exception
538 (cons exception-stack orig-stacks)))))
540 (make-wrapped-exception key args
541 (list exception-stack)))))
543 (set! exception-stack (make-stack #t 1 0)))))))
546 (define-syntax-rule (%run-delay body ... delay-time)
547 (%run-at body ... (tdelta delay-time)))
549 (define-syntax-rule (%port-request add-this-port port-request-args ...)
552 (list (make-port-request port-request-args ...)
553 (make-run-request kont)))))
556 (define-syntax-rule (%run-with-return return body ...)
563 (define-syntax-rule (catch-8sync exp (handler-key handler) ...)
564 (catch '8sync-caught-error
567 (lambda (_ orig-key orig-args orig-stacks)
569 ((or (eq? handler-key #t)
570 (eq? orig-key handler-key))
571 (apply handler orig-stacks orig-args)) ...
572 (else (raise '8sync-caught-error
573 orig-key orig-args orig-stacks))))))
576 (define-syntax-rule (catch-%8sync rest ...)
577 (catch-8sync rest ...))
581 ;;; Execution of agenda, and current agenda
582 ;;; =======================================
584 (define %current-agenda (make-parameter #f))
586 (define (update-agenda-from-select! agenda)
587 "Potentially (select) on ports specified in agenda, adding items to queue"
588 (define (hash-keys hash)
589 (hash-map->list (lambda (k v) k) hash))
590 (define (get-wait-time)
591 ;; TODO: we need to figure this out based on whether there's anything
592 ;; in the queue, and if not, how long till the next scheduled item
593 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
595 ((not (q-empty? (agenda-queue agenda)))
597 (soonest-time ; ie, the agenda is non-empty
598 (let* ((current-time (agenda-time agenda)))
599 (if (time<= soonest-time current-time)
600 ;; Well there's something due so let's select
601 ;; (this avoids a (possible?) race condition chance)
603 (time-minus soonest-time current-time))))
607 ;; TODO: support usecond wait time too
608 (match (get-wait-time)
612 (select (hash-keys (agenda-read-port-map agenda))
613 (hash-keys (agenda-write-port-map agenda))
614 (hash-keys (agenda-except-port-map agenda))
616 (lambda (key . rest-args)
620 (_ (error "Unhandled error in select!" key rest-args))))))))
621 (define (get-procs-to-run)
622 (define (ports->procs ports port-map)
623 (lambda (initial-procs)
627 ((hash-ref port-map port) port))
632 ((read-ports write-ports except-ports)
633 ;; @@: Come on, we can do better than append ;P
634 ((compose (ports->procs
636 (agenda-read-port-map agenda))
639 (agenda-write-port-map agenda))
642 (agenda-except-port-map agenda)))
644 (define (update-agenda)
645 (let ((procs-to-run (get-procs-to-run))
646 (q (agenda-queue agenda)))
652 (define (ports-to-select?)
653 (define (has-items? selector)
655 ;; ... we could use hash-for-each and a continuation to jump
656 ;; out with a #t at first indication of an item
657 (not (= (hash-count (const #t)
660 (or (has-items? agenda-read-port-map)
661 (has-items? agenda-write-port-map)
662 (has-items? agenda-except-port-map)))
664 (if (ports-to-select?)
668 (define (agenda-handle-port-request! agenda port-request)
669 "Update an agenda for a port-request"
670 (define (handle-selector request-selector port-map-selector)
671 (if (request-selector port-request)
672 (hash-set! (port-map-selector agenda)
673 (port-request-port port-request)
674 (request-selector port-request))))
675 (handle-selector port-request-read agenda-read-port-map)
676 (handle-selector port-request-write agenda-write-port-map)
677 (handle-selector port-request-except agenda-except-port-map))
680 (define* (start-agenda agenda
682 (get-time gettimeofday)
683 (handle-ports update-agenda-from-select!))
684 ;; TODO: Document fields
685 "Start up the AGENDA"
686 (let loop ((agenda agenda))
688 ;; @@: Hm, maybe here would be a great place to handle
689 ;; select'ing on ports.
690 ;; We could compose over agenda-run-once and agenda-read-ports
691 (agenda-run-once agenda)))
692 (if (and stop-condition (stop-condition agenda))
695 ;; We have to update the time after ports handled, too
696 ;; because it may have changed after a select
699 ;; Adjust the agenda's time just in time
700 ;; We do this here rather than in agenda-run-once to make
701 ;; agenda-run-once's behavior fairly predictable
702 (set-field agenda (agenda-time) (get-time)))
703 (agenda-time) (get-time))))
704 ;; Update the agenda's current queue based on
705 ;; currently applicable time segments
706 (add-segments-contents-to-queue!
707 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
708 (agenda-queue agenda))
711 (define (print-error-and-continue key . args)
712 "Frequently used as pre-unwind-handler for agenda"
714 ((eq? key '8sync-caught-error)
716 ((orig-key orig-args stacks)
717 (display "\n*** Caught async exception. ***\n")
718 (format (current-error-port)
719 "* Original key '~s and arguments: ~s *\n"
721 (display "* Caught stacks below (ending with original) *\n\n")
724 (display-backtrace s (current-error-port))
725 (newline (current-error-port)))
728 (format (current-error-port)
729 "\n*** Caught exception with key '~s and arguments: ~s ***\n"
731 (display-backtrace (make-stack #t 1 0)
732 (current-error-port))
733 (newline (current-error-port)))))
735 (define-syntax-rule (maybe-catch-all (catch-handler pre-unwind-handler)
737 (if (or catch-handler pre-unwind-handler)
742 (or catch-handler (lambda _ #f))
743 (or pre-unwind-handler (lambda _ #f)))
746 (define (agenda-run-once agenda)
747 "Run once through the agenda, and produce a new agenda
748 based on the results"
749 (define (call-proc proc)
751 (agenda-prompt-tag agenda)
753 (parameterize ((%current-agenda agenda))
755 ((agenda-catch-handler agenda)
756 (agenda-pre-unwind-handler agenda))
758 (lambda (kont async-request)
759 (setup-async-request kont async-request))))
761 (let ((queue (agenda-queue agenda))
762 (next-queue (make-q)))
763 (while (not (q-empty? queue))
764 (let* ((proc (q-pop! queue))
765 (proc-result (call-proc proc))
767 (lambda (run-request)
768 (define (schedule-at! time proc)
769 (schedule-add! (agenda-schedule agenda) time proc))
770 (let ((request-time (run-request-when run-request)))
772 ((? time-delta? time-delta)
773 (let ((time (time-delta+ (agenda-time agenda)
775 (schedule-at! time (run-request-proc run-request))))
777 (let ((time (cons sec 0)))
778 (schedule-at! time (run-request-proc run-request))))
779 (((? integer? sec) . (? integer? usec))
780 (schedule-at! request-time (run-request-proc run-request)))
782 (enq! next-queue (run-request-proc run-request))))))))
783 (define (handle-individual result)
785 ((? run-request? new-proc)
787 ((? port-request? port-request)
788 (agenda-handle-port-request! agenda port-request))
791 ;; @@: We might support delay-wrapped procedures here
794 (for-each handle-individual results))
795 (one-result (handle-individual one-result)))))
796 ;; TODO: Alternately, we could return the next-queue
797 ;; along with changes to be added to the schedule here?
798 ;; Return new agenda, with next queue set
799 (set-field agenda (agenda-queue) next-queue)))