1 ;; Copyright (C) 2015 Christopher Allan Webber <cwebber@dustycloud.org>
3 ;; This library is free software; you can redistribute it and/or
4 ;; modify it under the terms of the GNU Lesser General Public
5 ;; License as published by the Free Software Foundation; either
6 ;; version 3 of the License, or (at your option) any later version.
8 ;; This library is distributed in the hope that it will be useful,
9 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
10 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 ;; Lesser General Public License for more details.
13 ;; You should have received a copy of the GNU Lesser General Public
14 ;; License along with this library; if not, write to the Free Software
15 ;; Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18 (define-module (eightsync agenda)
19 #:use-module (srfi srfi-1)
20 #:use-module (srfi srfi-9)
21 #:use-module (srfi srfi-9 gnu)
22 #:use-module (ice-9 q)
23 #:use-module (ice-9 match)
24 #:use-module (ice-9 receive)
27 agenda-queue agenda-prompt-tag
28 agenda-read-port-map agenda-write-port-map agenda-except-port-map
36 make-time-segment time-segment?
37 time-segment-time time-segment-queue
39 time< time= time<= time-delta+
43 make-time-delta tdelta time-delta?
44 time-delta-sec time-delta-usec
47 make-schedule schedule?
48 schedule-add! schedule-empty?
52 schedule-segments-split schedule-extract-until!
53 add-segments-contents-to-queue!
58 make-run-request run-request?
59 run-request-proc run-request-when
62 make-port-request port-request port-request?
64 port-request-read port-request-write port-request-except
66 run-it wrap wrap-apply run run-at run-delay
68 %port-request %run %run-at %run-delay
70 catch-8sync catch-%8sync
72 ;; used for introspecting the error, but a method for making
75 wrapped-exception-key wrapped-exception-args
76 wrapped-exception-stacks
78 print-error-and-continue
81 start-agenda agenda-run-once))
83 ;; @@: Using immutable agendas here, so wouldn't it make sense to
84 ;; replace this queue stuff with using pfds based immutable queues?
90 ;;; The agenda consists of:
91 ;;; - a queue of immediate items to handle
92 ;;; - sheduled future events to be added to a future queue
93 ;;; - a tag by which running processes can escape for some asynchronous
94 ;;; operation (from which they can be returned later)
95 ;;; - a mapping of ports to various handler procedures
97 ;;; The goal, eventually, is for this all to be immutable and functional.
98 ;;; However, we aren't there yet. Some tricky things:
99 ;;; - The schedule needs to be immutable, yet reasonably efficient.
100 ;;; - Need to use immutable queues (ijp's pfds library?)
101 ;;; - Modeling reading from ports as something repeatable,
102 ;;; and with reasonable separation from functional components?
104 (define-immutable-record-type <agenda>
105 (make-agenda-intern queue prompt-tag
106 read-port-map write-port-map except-port-map
107 schedule time catch-handler pre-unwind-handler)
110 (prompt-tag agenda-prompt-tag)
111 (read-port-map agenda-read-port-map)
112 (write-port-map agenda-write-port-map)
113 (except-port-map agenda-except-port-map)
114 (schedule agenda-schedule)
116 (catch-handler agenda-catch-handler)
117 (pre-unwind-handler agenda-pre-unwind-handler))
119 (define (make-async-prompt-tag)
120 "Make an async prompt tag for an agenda.
122 Generally done automatically for the user through (make-agenda)."
123 (make-prompt-tag "prompt"))
125 (define* (make-agenda #:key
127 (prompt (make-prompt-tag))
128 (read-port-map (make-hash-table))
129 (write-port-map (make-hash-table))
130 (except-port-map (make-hash-table))
131 (schedule (make-schedule))
132 (time (gettimeofday))
134 (pre-unwind-handler #f))
135 ;; TODO: document arguments
136 "Make a fresh agenda."
137 (make-agenda-intern queue prompt
138 read-port-map write-port-map except-port-map
140 catch-handler pre-unwind-handler))
142 (define (current-agenda-prompt)
143 "Get the prompt for the current agenda; signal an error if there isn't one."
144 (let ((current-agenda (%current-agenda)))
145 (if (not current-agenda)
148 "Can't get current agenda prompt if there's no current agenda!")
149 (agenda-prompt-tag current-agenda))))
151 ;; helper for making queues for an agenda
152 (define (list->q lst)
153 "Makes a queue composed of LST items"
161 (define (make-q* . args)
162 "Makes a queue and populates it with this invocation's ARGS"
169 ;;; This is where we handle timed events for the future
171 ;; This section totally borrows from the ideas in SICP
174 ;; NOTE: time is a cons of (seconds . microseconds)
176 (define-record-type <time-segment>
177 (make-time-segment-intern time queue)
179 (time time-segment-time)
180 (queue time-segment-queue))
182 ;; @@: This seems to be the same as srfi-18's seconds->time procedure?
183 ;; Maybe double check and switch to that? (Thanks amz3!)
185 (define (time-from-float-or-fraction time)
186 "Produce a (sec . usec) pair from TIME, a float or fraction"
187 (let* ((mixed-whole (floor time))
188 (mixed-rest (- time mixed-whole)) ; float or fraction component
190 (usec (floor (* 1000000 mixed-rest))))
191 (cons (inexact->exact sec) (inexact->exact usec))))
193 (define (time-segment-right-format time)
194 "Ensure TIME is in the right format.
196 The right format means (second . microsecond).
197 If an integer, will convert appropriately."
198 ;; TODO: add floating point / rational number support.
200 ;; time is already a cons of second and microsecnd
201 (((? integer? s) . (? integer? u)) time)
202 ;; time was just an integer (just the second)
203 ((? integer? _) (cons time 0))
204 ((or (? rational? _) (? inexact? _))
205 (time-from-float-or-fraction time))
206 (_ (throw 'invalid-time "Invalid time" time))))
208 (define* (make-time-segment time #:optional (queue (make-q)))
209 "Make a time segment of TIME and QUEUE
211 No automatic conversion is done, so you might have to
212 run (time-segment-right-format) first."
213 (make-time-segment-intern time queue))
215 (define (time< time1 time2)
216 "Check if TIME1 is less than TIME2"
217 (cond ((< (car time1)
227 (define (time= time1 time2)
228 "Check whether TIME1 and TIME2 are equivalent"
229 (and (= (car time1) (car time2))
230 (= (cdr time1) (cdr time2))))
232 (define (time<= time1 time2)
233 "Check if TIME1 is less than or equal to TIME2"
234 (or (time< time1 time2)
235 (time= time1 time2)))
238 (define-record-type <time-delta>
239 (make-time-delta-intern sec usec)
242 (usec time-delta-usec))
244 (define* (make-time-delta time)
245 "Make a <time-delta> of SEC seconds and USEC microseconds.
247 This is used primarily so the agenda can recognize RUN-REQUEST objects
248 which are meant to delay computation"
249 (match (time-segment-right-format time)
251 (make-time-delta-intern sec usec))))
253 (define tdelta make-time-delta)
255 (define (time-carry-correct time)
256 "Corrects/handles time microsecond carry.
257 Will produce (0 . 0) instead of a negative number, if needed."
258 (cond ((>= (cdr time) 1000000)
261 (- (cdr time) 1000000)))
267 (+ (cdr time) 1000000))))
270 (define (time-delta+ time time-delta)
271 "Increment a TIME by the value of TIME-DELTA"
273 (cons (+ (car time) (time-delta-sec time-delta))
274 (+ (cdr time) (time-delta-usec time-delta)))))
276 (define (time-minus time1 time2)
277 "Subtract TIME2 from TIME1"
279 (cons (- (car time1) (car time2))
280 (- (cdr time1) (cdr time2)))))
282 (define (time-plus time1 time2)
283 "Add TIME1 and TIME2"
285 (cons (+ (car time1) (car time2))
286 (+ (cdr time1) (cdr time2)))))
289 (define-record-type <schedule>
290 (make-schedule-intern segments)
292 (segments schedule-segments set-schedule-segments!))
294 (define* (make-schedule #:optional segments)
295 "Make a schedule, optionally pre-composed of SEGMENTS"
296 (make-schedule-intern (or segments '())))
298 (define (schedule-soonest-time schedule)
299 "Return a cons of (sec . usec) for next time segement, or #f if none"
300 (let ((segments (schedule-segments schedule)))
301 (if (eq? segments '())
303 (time-segment-time (car segments)))))
305 ;; TODO: This code is reasonably easy to read but it
306 ;; mutates AND is worst case of O(n) in both space and time :(
307 ;; but at least it'll be reasonably easy to refactor to
308 ;; a more functional setup?
309 (define (schedule-add! schedule time proc)
310 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
311 (let ((time (time-segment-right-format time)))
312 (define (new-time-segment)
314 (make-time-segment time)))
315 (enq! (time-segment-queue new-segment) proc)
317 (define (loop segments)
318 (define (segment-equals-time? segment)
319 (time= time (time-segment-time segment)))
321 (define (segment-more-than-time? segment)
322 (time< time (time-segment-time segment)))
324 ;; We could switch this out to be more mutate'y
325 ;; and avoid the O(n) of space... is that over-optimizing?
327 ;; If we're at the end of the list, time to make a new
329 ('() (cons (new-time-segment) '()))
330 ;; If the segment's time is exactly our time, good news
331 ;; everyone! Let's append our stuff to its queue
332 (((? segment-equals-time? first) rest ...)
333 (enq! (time-segment-queue first) proc)
335 ;; If the first segment is more than our time,
336 ;; ours belongs before this one, so add it and
337 ;; start consing our way back
338 (((? segment-more-than-time? first) rest ...)
339 (cons (new-time-segment) segments))
340 ;; Otherwise, build up recursive result
342 (cons first (loop rest)))))
343 (set-schedule-segments!
345 (loop (schedule-segments schedule)))))
347 (define (schedule-empty? schedule)
348 "Check if the SCHEDULE is currently empty"
349 (eq? (schedule-segments schedule) '()))
351 (define (schedule-segments-split schedule time)
352 "Does a multiple value return of time segments before/at and after TIME"
353 (let ((time (time-segment-right-format time)))
354 (define (segment-is-now? segment)
355 (time= (time-segment-time segment) time))
356 (define (segment-is-before-now? segment)
357 (time< (time-segment-time segment) time))
359 (let loop ((segments-before '())
360 (segments-left (schedule-segments schedule)))
362 ;; end of the line, return
364 (values (reverse segments-before) '()))
366 ;; It's right now, so time to stop, but include this one in before
367 ;; but otherwise return
368 (((? segment-is-now? first) rest ...)
369 (values (reverse (cons first segments-before)) rest))
371 ;; This is prior or at now, so add it and keep going
372 (((? segment-is-before-now? first) rest ...)
373 (loop (cons first segments-before) rest))
375 ;; Otherwise it's past now, just return what we have
377 (values segments-before segments-after))))))
379 (define (schedule-extract-until! schedule time)
380 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
381 (receive (segments-before segments-after)
382 (schedule-segments-split schedule time)
383 (set-schedule-segments! schedule segments-after)
386 (define (add-segments-contents-to-queue! segments queue)
389 (let ((seg-queue (time-segment-queue segment)))
390 (while (not (q-empty? seg-queue))
391 (enq! queue (deq! seg-queue)))))
396 ;;; Request to run stuff
397 ;;; ====================
399 (define-record-type <run-request>
400 (make-run-request proc when)
402 (proc run-request-proc)
403 (when run-request-when))
405 (define* (run-it proc #:optional when)
406 "Make a request to run PROC (possibly at WHEN)"
407 (make-run-request proc when))
409 (define-syntax-rule (wrap body ...)
410 "Wrap contents in a procedure"
414 (define-syntax-rule (wrap-apply body)
415 "Wrap possibly multi-value function in a procedure, applies all arguments"
420 ;; @@: Do we really want `body ...' here?
421 ;; what about just `body'?
422 (define-syntax-rule (run body ...)
423 "Run everything in BODY but wrap in a convenient procedure"
424 (make-run-request (wrap body ...) #f))
426 (define-syntax-rule (run-at body ... when)
428 (make-run-request (wrap body ...) when))
430 ;; @@: Is it okay to overload the term "delay" like this?
431 ;; Would `run-in' be better?
432 (define-syntax-rule (run-delay body ... delay-time)
433 "Run BODY at DELAY-TIME time from now"
434 (make-run-request (wrap body ...) (tdelta delay-time)))
437 ;; A request to set up a port with at least one of read, write, except
438 ;; handling processes
440 (define-record-type <port-request>
441 (make-port-request-intern port read write except)
443 (port port-request-port)
444 (read port-request-read)
445 (write port-request-write)
446 (except port-request-except))
448 (define* (make-port-request port #:key read write except)
449 (if (not (or read write except))
450 (throw 'no-port-handler-given "No port handler given.\n"))
451 (make-port-request-intern port read write except))
453 (define port-request make-port-request)
457 ;;; Asynchronous escape to run things
458 ;;; =================================
460 (define-syntax-rule (%8sync async-request)
461 "Run BODY asynchronously at a prompt, passing args to make-future.
463 Runs things asynchronously (8synchronously?)"
464 (propagate-%async-exceptions
465 (abort-to-prompt (current-agenda-prompt)
468 ;; Async port request and run-request meta-requests
469 (define (make-async-request proc)
470 "Wrap PROC in an async-request
472 The purpose of this is to make sure that users don't accidentally
473 return the wrong thing via (%8sync) and trip themselves up."
474 (cons '*async-request* proc))
476 (define (setup-async-request resume-kont async-request)
477 "Complete an async request for agenda-run-once's continuation handling"
479 (('*async-request* . async-setup-proc)
480 (async-setup-proc resume-kont))
481 ;; TODO: deliver more helpful errors depending on what the user
483 (_ (throw 'invalid-async-request
484 "Invalid request passed back via an (%8sync) procedure."
487 (define-record-type <wrapped-exception>
488 (make-wrapped-exception key args stacks)
490 (key wrapped-exception-key)
491 (args wrapped-exception-args)
492 (stacks wrapped-exception-stacks))
494 (define-syntax-rule (propagate-%async-exceptions body)
495 (let ((body-result body))
496 (if (wrapped-exception? body-result)
497 (throw '8sync-caught-error
498 (wrapped-exception-key body-result)
499 (wrapped-exception-args body-result)
500 (wrapped-exception-stacks body-result))
503 (define-syntax-rule (%run body ...)
504 (%run-at body ... #f))
506 (define-syntax-rule (%run-at body ... when)
507 ;; Send an asynchronous request to apply a continuation to the
508 ;; following function, then handle that as a request to the agenda
511 ;; We're making a run request
513 ;; Wrapping the following execution to run...
515 ;; Once we get the result from the inner part, we'll resume
516 ;; this continuation, but first
517 ;; @@: Is this running immediately, or queueing the result
518 ;; after evaluation for the next agenda tick? It looks
519 ;; like evaluating immediately. Is that what we want?
521 ;; Any unhandled errors are caught
522 (let ((exception-stack #f))
524 ;; Run the actual code the user requested
527 ;; If something bad happened and we didn't catch it,
528 ;; we'll wrap it up in such a way that the continuation
532 ((eq? key '8sync-caught-error)
534 ((orig-key orig-args orig-stacks)
535 (make-wrapped-exception
537 (cons exception-stack orig-stacks)))))
539 (make-wrapped-exception key args
540 (list exception-stack)))))
542 (set! exception-stack (make-stack #t 1 0)))))))
545 (define-syntax-rule (%run-delay body ... delay-time)
546 (%run-at body ... (tdelta delay-time)))
548 (define-syntax-rule (%port-request add-this-port port-request-args ...)
551 (list (make-port-request port-request-args ...)
552 (make-run-request kont)))))
555 (define-syntax-rule (%run-with-return return body ...)
562 (define-syntax-rule (catch-8sync exp (handler-key handler) ...)
563 (catch '8sync-caught-error
566 (lambda (_ orig-key orig-args orig-stacks)
568 ((or (eq? handler-key #t)
569 (eq? orig-key handler-key))
570 (apply handler orig-stacks orig-args)) ...
571 (else (raise '8sync-caught-error
572 orig-key orig-args orig-stacks))))))
575 (define-syntax-rule (catch-%8sync rest ...)
576 (catch-8sync rest ...))
580 ;;; Execution of agenda, and current agenda
581 ;;; =======================================
583 (define %current-agenda (make-parameter #f))
585 (define (update-agenda-from-select! agenda)
586 "Potentially (select) on ports specified in agenda, adding items to queue"
587 (define (hash-keys hash)
588 (hash-map->list (lambda (k v) k) hash))
589 (define (get-wait-time)
590 ;; TODO: we need to figure this out based on whether there's anything
591 ;; in the queue, and if not, how long till the next scheduled item
592 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
594 ((not (q-empty? (agenda-queue agenda)))
596 (soonest-time ; ie, the agenda is non-empty
597 (let* ((current-time (agenda-time agenda)))
598 (if (time<= soonest-time current-time)
599 ;; Well there's something due so let's select
600 ;; (this avoids a (possible?) race condition chance)
602 (time-minus soonest-time current-time))))
606 ;; TODO: support usecond wait time too
607 (match (get-wait-time)
611 (select (hash-keys (agenda-read-port-map agenda))
612 (hash-keys (agenda-write-port-map agenda))
613 (hash-keys (agenda-except-port-map agenda))
615 (lambda (key . rest-args)
619 (_ (error "Unhandled error in select!" key rest-args))))))))
620 (define (get-procs-to-run)
621 (define (ports->procs ports port-map)
622 (lambda (initial-procs)
626 ((hash-ref port-map port) port))
631 ((read-ports write-ports except-ports)
632 ;; @@: Come on, we can do better than append ;P
633 ((compose (ports->procs
635 (agenda-read-port-map agenda))
638 (agenda-write-port-map agenda))
641 (agenda-except-port-map agenda)))
643 (define (update-agenda)
644 (let ((procs-to-run (get-procs-to-run))
645 (q (agenda-queue agenda)))
651 (define (ports-to-select?)
652 (define (has-items? selector)
654 ;; ... we could use hash-for-each and a continuation to jump
655 ;; out with a #t at first indication of an item
656 (not (= (hash-count (const #t)
659 (or (has-items? agenda-read-port-map)
660 (has-items? agenda-write-port-map)
661 (has-items? agenda-except-port-map)))
663 (if (ports-to-select?)
667 (define (agenda-handle-port-request! agenda port-request)
668 "Update an agenda for a port-request"
669 (define (handle-selector request-selector port-map-selector)
670 (if (request-selector port-request)
671 (hash-set! (port-map-selector agenda)
672 (port-request-port port-request)
673 (request-selector port-request))))
674 (handle-selector port-request-read agenda-read-port-map)
675 (handle-selector port-request-write agenda-write-port-map)
676 (handle-selector port-request-except agenda-except-port-map))
679 (define* (start-agenda agenda
681 (get-time gettimeofday)
682 (handle-ports update-agenda-from-select!))
683 ;; TODO: Document fields
684 "Start up the AGENDA"
685 (let loop ((agenda agenda))
687 ;; @@: Hm, maybe here would be a great place to handle
688 ;; select'ing on ports.
689 ;; We could compose over agenda-run-once and agenda-read-ports
690 (agenda-run-once agenda)))
691 (if (and stop-condition (stop-condition agenda))
694 ;; We have to update the time after ports handled, too
695 ;; because it may have changed after a select
698 ;; Adjust the agenda's time just in time
699 ;; We do this here rather than in agenda-run-once to make
700 ;; agenda-run-once's behavior fairly predictable
701 (set-field agenda (agenda-time) (get-time)))
702 (agenda-time) (get-time))))
703 ;; Update the agenda's current queue based on
704 ;; currently applicable time segments
705 (add-segments-contents-to-queue!
706 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
707 (agenda-queue agenda))
710 (define (print-error-and-continue key . args)
711 "Frequently used as pre-unwind-handler for agenda"
713 ((eq? key '8sync-caught-error)
715 ((orig-key orig-args stacks)
716 (display "\n*** Caught async exception. ***\n")
717 (format (current-error-port)
718 "* Original key '~s and arguments: ~s *\n"
720 (display "* Caught stacks below (ending with original) *\n\n")
723 (display-backtrace s (current-error-port))
724 (newline (current-error-port)))
727 (format (current-error-port)
728 "\n*** Caught exception with key '~s and arguments: ~s ***\n"
730 (display-backtrace (make-stack #t 1 0)
731 (current-error-port))
732 (newline (current-error-port)))))
734 (define-syntax-rule (maybe-catch-all (catch-handler pre-unwind-handler)
736 (if (or catch-handler pre-unwind-handler)
741 (or catch-handler (lambda _ #f))
742 (or pre-unwind-handler (lambda _ #f)))
745 (define (agenda-run-once agenda)
746 "Run once through the agenda, and produce a new agenda
747 based on the results"
748 (define (call-proc proc)
750 (agenda-prompt-tag agenda)
752 (parameterize ((%current-agenda agenda))
754 ((agenda-catch-handler agenda)
755 (agenda-pre-unwind-handler agenda))
757 (lambda (kont async-request)
758 (setup-async-request kont async-request))))
760 (let ((queue (agenda-queue agenda))
761 (next-queue (make-q)))
762 (while (not (q-empty? queue))
763 (let* ((proc (q-pop! queue))
764 (proc-result (call-proc proc))
766 (lambda (run-request)
767 (define (schedule-at! time proc)
768 (schedule-add! (agenda-schedule agenda) time proc))
769 (let ((request-time (run-request-when run-request)))
771 ((? time-delta? time-delta)
772 (let ((time (time-delta+ (agenda-time agenda)
774 (schedule-at! time (run-request-proc run-request))))
776 (let ((time (cons sec 0)))
777 (schedule-at! time (run-request-proc run-request))))
778 (((? integer? sec) . (? integer? usec))
779 (schedule-at! request-time (run-request-proc run-request)))
781 (enq! next-queue (run-request-proc run-request))))))))
782 (define (handle-individual result)
784 ((? run-request? new-proc)
786 ((? port-request? port-request)
787 (agenda-handle-port-request! agenda port-request))
790 ;; @@: We might support delay-wrapped procedures here
793 (for-each handle-individual results))
794 (one-result (handle-individual one-result)))))
795 ;; TODO: Alternately, we could return the next-queue
796 ;; along with changes to be added to the schedule here?
797 ;; Return new agenda, with next queue set
798 (set-field agenda (agenda-queue) next-queue)))