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
34 make-time-segment time-segment?
35 time-segment-time time-segment-queue
37 time< time= time<= time-delta+
41 make-time-delta tdelta time-delta?
42 time-delta-sec time-delta-usec
45 make-schedule schedule?
46 schedule-add! schedule-empty?
50 schedule-segments-split schedule-extract-until!
51 add-segments-contents-to-queue!
56 make-run-request run-request?
57 run-request-proc run-request-when
60 make-port-request port-request port-request?
62 port-request-read port-request-write port-request-except
64 run-it wrap run run-at run-delay
66 %port-request %run %run-at %run-delay
67 8port-request 8run 8run-at 8run-delay
70 start-agenda agenda-run-once))
72 ;; @@: Using immutable agendas here, so wouldn't it make sense to
73 ;; replace this queue stuff with using pfds based immutable queues?
79 ;;; The agenda consists of:
80 ;;; - a queue of immediate items to handle
81 ;;; - sheduled future events to be added to a future queue
82 ;;; - a tag by which running processes can escape for some asynchronous
83 ;;; operation (from which they can be returned later)
84 ;;; - a mapping of ports to various handler procedures
86 ;;; The goal, eventually, is for this all to be immutable and functional.
87 ;;; However, we aren't there yet. Some tricky things:
88 ;;; - The schedule needs to be immutable, yet reasonably efficient.
89 ;;; - Need to use immutable queues (ijp's pfds library?)
90 ;;; - Modeling reading from ports as something repeatable,
91 ;;; and with reasonable separation from functional components?
93 (define-immutable-record-type <agenda>
94 (make-agenda-intern queue prompt-tag
95 read-port-map write-port-map except-port-map
99 (prompt-tag agenda-prompt-tag)
100 (read-port-map agenda-read-port-map)
101 (write-port-map agenda-write-port-map)
102 (except-port-map agenda-except-port-map)
103 (schedule agenda-schedule)
106 (define (make-async-prompt-tag)
107 "Make an async prompt tag for an agenda.
109 Generally done automatically for the user through (make-agenda)."
110 (make-prompt-tag "prompt"))
112 (define* (make-agenda #:key
114 (prompt (make-prompt-tag))
115 (read-port-map (make-hash-table))
116 (write-port-map (make-hash-table))
117 (except-port-map (make-hash-table))
118 (schedule (make-schedule))
119 (time (gettimeofday)))
120 ;; TODO: document arguments
121 "Make a fresh agenda."
122 (make-agenda-intern queue prompt
123 read-port-map write-port-map except-port-map
126 (define (current-agenda-prompt)
127 "Get the prompt for the current agenda; signal an error if there isn't one."
128 (let ((current-agenda (%current-agenda)))
129 (if (not current-agenda)
132 "Can't get current agenda prompt if there's no current agenda!")
133 (agenda-prompt-tag current-agenda))))
140 ;;; This is where we handle timed events for the future
142 ;; This section totally borrows from the ideas in SICP
145 ;; NOTE: time is a cons of (seconds . microseconds)
147 (define-record-type <time-segment>
148 (make-time-segment-intern time queue)
150 (time time-segment-time)
151 (queue time-segment-queue))
153 (define (time-from-float-or-fraction time)
154 "Produce a (sec . usec) pair from TIME, a float or fraction"
155 (let* ((mixed-whole (floor time))
156 (mixed-rest (- time mixed-whole)) ; float or fraction component
158 (usec (floor (* 1000000 mixed-rest))))
159 (cons (inexact->exact sec) (inexact->exact usec))))
161 (define (time-segment-right-format time)
162 "Ensure TIME is in the right format.
164 The right format means (second . microsecond).
165 If an integer, will convert appropriately."
166 ;; TODO: add floating point / rational number support.
168 ;; time is already a cons of second and microsecnd
169 (((? integer? s) . (? integer? u)) time)
170 ;; time was just an integer (just the second)
171 ((? integer? _) (cons time 0))
172 ((or (? rational? _) (? inexact? _))
173 (time-from-float-or-fraction time))
174 (_ (throw 'invalid-time "Invalid time" time))))
176 (define* (make-time-segment time #:optional (queue (make-q)))
177 "Make a time segment of TIME and QUEUE
179 No automatic conversion is done, so you might have to
180 run (time-segment-right-format) first."
181 (make-time-segment-intern time queue))
183 (define (time< time1 time2)
184 "Check if TIME1 is less than TIME2"
185 (cond ((< (car time1)
195 (define (time= time1 time2)
196 "Check whether TIME1 and TIME2 are equivalent"
197 (and (= (car time1) (car time2))
198 (= (cdr time1) (cdr time2))))
200 (define (time<= time1 time2)
201 "Check if TIME1 is less than or equal to TIME2"
202 (or (time< time1 time2)
203 (time= time1 time2)))
206 (define-record-type <time-delta>
207 (make-time-delta-intern sec usec)
210 (usec time-delta-usec))
212 (define* (make-time-delta time)
213 "Make a <time-delta> of SEC seconds and USEC microseconds.
215 This is used primarily so the agenda can recognize RUN-REQUEST objects
216 which are meant to delay computation"
217 (match (time-segment-right-format time)
219 (make-time-delta-intern sec usec))))
221 (define tdelta make-time-delta)
223 (define (time-carry-correct time)
224 "Corrects/handles time microsecond carry.
225 Will produce (0 . 0) instead of a negative number, if needed."
226 (cond ((>= (cdr time) 1000000)
229 (- (cdr time) 1000000)))
235 (+ (cdr time) 1000000))))
238 (define (time-delta+ time time-delta)
239 "Increment a TIME by the value of TIME-DELTA"
241 (cons (+ (car time) (time-delta-sec time-delta))
242 (+ (cdr time) (time-delta-usec time-delta)))))
244 (define (time-minus time1 time2)
245 "Subtract TIME2 from TIME1"
247 (cons (- (car time1) (car time2))
248 (- (cdr time2) (cdr time2)))))
250 (define (time-plus time1 time2)
251 "Add TIME1 and TIME2"
253 (cons (+ (car time1) (car time2))
254 (+ (cdr time2) (cdr time2)))))
257 (define-record-type <schedule>
258 (make-schedule-intern segments)
260 (segments schedule-segments set-schedule-segments!))
262 (define* (make-schedule #:optional segments)
263 "Make a schedule, optionally pre-composed of SEGMENTS"
264 (make-schedule-intern (or segments '())))
266 (define (schedule-soonest-time schedule)
267 "Return a cons of (sec . usec) for next time segement, or #f if none"
268 (let ((segments (schedule-segments schedule)))
269 (if (eq? segments '())
271 (time-segment-time (car segments)))))
273 ;; TODO: This code is reasonably easy to read but it
274 ;; mutates AND is worst case of O(n) in both space and time :(
275 ;; but at least it'll be reasonably easy to refactor to
276 ;; a more functional setup?
277 (define (schedule-add! schedule time proc)
278 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
279 (let ((time (time-segment-right-format time)))
280 (define (new-time-segment)
282 (make-time-segment time)))
283 (enq! (time-segment-queue new-segment) proc)
285 (define (loop segments)
286 (define (segment-equals-time? segment)
287 (time= time (time-segment-time segment)))
289 (define (segment-more-than-time? segment)
290 (time< time (time-segment-time segment)))
292 ;; We could switch this out to be more mutate'y
293 ;; and avoid the O(n) of space... is that over-optimizing?
295 ;; If we're at the end of the list, time to make a new
297 ('() (cons (new-time-segment) '()))
298 ;; If the segment's time is exactly our time, good news
299 ;; everyone! Let's append our stuff to its queue
300 (((? segment-equals-time? first) rest ...)
301 (enq! (time-segment-queue first) proc)
303 ;; If the first segment is more than our time,
304 ;; ours belongs before this one, so add it and
305 ;; start consing our way back
306 (((? segment-more-than-time? first) rest ...)
307 (cons (new-time-segment) segments))
308 ;; Otherwise, build up recursive result
310 (cons first (loop rest)))))
311 (set-schedule-segments!
313 (loop (schedule-segments schedule)))))
315 (define (schedule-empty? schedule)
316 "Check if the SCHEDULE is currently empty"
317 (eq? (schedule-segments schedule) '()))
319 (define (schedule-segments-split schedule time)
320 "Does a multiple value return of time segments before/at and after TIME"
321 (let ((time (time-segment-right-format time)))
322 (define (segment-is-now? segment)
323 (time= (time-segment-time segment) time))
324 (define (segment-is-before-now? segment)
325 (time< (time-segment-time segment) time))
327 (let loop ((segments-before '())
328 (segments-left (schedule-segments schedule)))
330 ;; end of the line, return
332 (values (reverse segments-before) '()))
334 ;; It's right now, so time to stop, but include this one in before
335 ;; but otherwise return
336 (((? segment-is-now? first) rest ...)
337 (values (reverse (cons first segments-before)) rest))
339 ;; This is prior or at now, so add it and keep going
340 (((? segment-is-before-now? first) rest ...)
341 (loop (cons first segments-before) rest))
343 ;; Otherwise it's past now, just return what we have
345 (values segments-before segments-after))))))
347 (define (schedule-extract-until! schedule time)
348 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
349 (receive (segments-before segments-after)
350 (schedule-segments-split schedule time)
351 (set-schedule-segments! schedule segments-after)
354 (define (add-segments-contents-to-queue! segments queue)
357 (let ((seg-queue (time-segment-queue segment)))
358 (while (not (q-empty? seg-queue))
359 (enq! queue (deq! seg-queue)))))
364 ;;; Request to run stuff
365 ;;; ====================
367 (define-record-type <run-request>
368 (make-run-request proc when)
370 (proc run-request-proc)
371 (when run-request-when))
373 (define* (run-it proc #:optional when)
374 "Make a request to run PROC (possibly at WHEN)"
375 (make-run-request proc when))
377 (define-syntax-rule (wrap body ...)
378 "Wrap contents in a procedure"
382 ;; @@: Do we really want `body ...' here?
383 ;; what about just `body'?
384 (define-syntax-rule (run body ...)
385 "Run everything in BODY but wrap in a convenient procedure"
386 (make-run-request (wrap body ...) #f))
388 (define-syntax-rule (run-at body ... when)
390 (make-run-request (wrap body ...) when))
392 ;; @@: Is it okay to overload the term "delay" like this?
393 ;; Would `run-in' be better?
394 (define-syntax-rule (run-delay body ... delay-time)
395 "Run BODY at DELAY-TIME time from now"
396 (make-run-request (wrap body ...) (tdelta delay-time)))
399 ;; A request to set up a port with at least one of read, write, except
400 ;; handling processes
402 (define-record-type <port-request>
403 (make-port-request-intern port read write except)
405 (port port-request-port)
406 (read port-request-read)
407 (write port-request-write)
408 (except port-request-except))
410 (define* (make-port-request port #:key read write except)
411 (if (not (or read write except))
412 (throw 'no-port-handler-given "No port handler given.\n"))
413 (make-port-request-intern port read write except))
415 (define port-request make-port-request)
419 ;;; Asynchronous escape to run things
420 ;;; =================================
422 ;; The future's in futures
424 (define (make-future call-first on-success on-fail on-error)
425 ;; TODO: add error stuff here
427 (let ((call-result (call-first)))
428 ;; queue up calling the
429 (run (on-success call-result)))))
431 (define (agenda-on-error agenda)
434 (define (agenda-on-fail agenda)
437 (define* (request-future call-first on-success
439 (agenda (%current-agenda))
440 (on-fail (agenda-on-fail agenda))
441 (on-error (agenda-on-error agenda))
443 ;; TODO: error handling
444 ;; do we need some distinction between expected, catchable errors,
445 ;; and unexpected, uncatchable ones? Probably...?
447 (make-future call-first on-success on-fail on-error)
450 (define-syntax-rule (%sync async-request)
451 "Run BODY asynchronously at a prompt, passing args to make-future.
453 Pronounced `eight-sync' despite the spelling.
455 %sync was chosen because (async) was already taken and could lead to
456 errors, and this version of asynchronous code uses a prompt, so the `a'
457 character becomes a `%' prompt! :)
459 The % and 8 characters kind of look similar... hence this library's
460 name! (That, and the pun 'eight-synchronous' programming.)
461 There are 8sync aliases if you prefer that name."
462 (abort-to-prompt (current-agenda-prompt)
465 (define-syntax-rule (8sync args ...)
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 (%sync) procedure."
488 (define-syntax-rule (%run body ...)
489 (%run-at body ... #f))
491 (define-syntax-rule (%run-at body ... when)
500 (define-syntax-rule (%run-delay body ... delay-time)
501 (%run-at body ... (tdelta delay-time)))
503 (define-syntax-rule (%port-request add-this-port port-request-args ...)
506 (list (make-port-request port-request-args ...)
507 (make-run-request kont)))))
510 (define-syntax-rule (%run-with-return return body ...)
518 (define-syntax-rule (8run args ...) (%run args ...))
519 (define-syntax-rule (8run-at args ...) (%run-at args ...))
520 (define-syntax-rule (8run-delay args ...) (%run-delay args ...))
521 (define-syntax-rule (8port-request args ...) (%port-request args ...))
525 ;;; Execution of agenda, and current agenda
526 ;;; =======================================
528 (define %current-agenda (make-parameter #f))
530 (define (update-agenda-from-select! agenda)
531 "Potentially (select) on ports specified in agenda, adding items to queue"
532 (define (hash-keys hash)
533 (hash-map->list (lambda (k v) k) hash))
534 (define (get-wait-time)
535 ;; TODO: we need to figure this out based on whether there's anything
536 ;; in the queue, and if not, how long till the next scheduled item
537 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
539 ((not (q-empty? (agenda-queue agenda)))
541 (soonest-time ; ie, the agenda is non-empty
542 (let* ((current-time (agenda-time agenda)))
543 (if (time<= soonest-time current-time)
544 ;; Well there's something due so let's select
545 ;; (this avoids a (possible?) race condition chance)
547 (time-minus soonest-time current-time))))
551 ;; TODO: support usecond wait time too
552 (match (get-wait-time)
554 (select (hash-keys (agenda-read-port-map agenda))
555 (hash-keys (agenda-write-port-map agenda))
556 (hash-keys (agenda-except-port-map agenda))
558 (define (get-procs-to-run)
559 (define (ports->procs ports port-map)
560 (lambda (initial-procs)
564 ((hash-ref port-map port) port))
569 ((read-ports write-ports except-ports)
570 ;; @@: Come on, we can do better than append ;P
571 ((compose (ports->procs
573 (agenda-read-port-map agenda))
576 (agenda-write-port-map agenda))
579 (agenda-except-port-map agenda)))
581 (define (update-agenda)
582 (let ((procs-to-run (get-procs-to-run))
583 (q (agenda-queue agenda)))
589 (define (ports-to-select?)
590 (define (has-items? selector)
592 ;; ... we could use hash-for-each and a continuation to jump
593 ;; out with a #t at first indication of an item
594 (not (= (hash-count (const #t)
597 (or (has-items? agenda-read-port-map)
598 (has-items? agenda-write-port-map)
599 (has-items? agenda-except-port-map)))
601 (if (ports-to-select?)
605 (define (agenda-handle-port-request! agenda port-request)
606 "Update an agenda for a port-request"
607 (define (handle-selector request-selector port-map-selector)
608 (if (request-selector port-request)
609 (hash-set! (port-map-selector agenda)
610 (port-request-port port-request)
611 (request-selector port-request))))
612 (handle-selector port-request-read agenda-read-port-map)
613 (handle-selector port-request-write agenda-write-port-map)
614 (handle-selector port-request-except agenda-except-port-map))
617 (define* (start-agenda agenda
619 (get-time gettimeofday)
620 (handle-ports update-agenda-from-select!))
621 ;; TODO: Document fields
622 "Start up the AGENDA"
623 (let loop ((agenda agenda))
625 ;; @@: Hm, maybe here would be a great place to handle
626 ;; select'ing on ports.
627 ;; We could compose over agenda-run-once and agenda-read-ports
628 (agenda-run-once agenda)))
629 (if (and stop-condition (stop-condition agenda))
632 ;; We have to update the time after ports handled, too
633 ;; because it may have changed after a select
636 ;; Adjust the agenda's time just in time
637 ;; We do this here rather than in agenda-run-once to make
638 ;; agenda-run-once's behavior fairly predictable
639 (set-field agenda (agenda-time) (get-time)))
640 (agenda-time) (get-time))))
641 ;; Update the agenda's current queue based on
642 ;; currently applicable time segments
643 (add-segments-contents-to-queue!
644 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
645 (agenda-queue agenda))
648 (define (agenda-run-once agenda)
649 "Run once through the agenda, and produce a new agenda
650 based on the results"
651 (define (call-proc proc)
653 (agenda-prompt-tag agenda)
655 (parameterize ((%current-agenda agenda))
657 (lambda (kont async-request)
658 (setup-async-request kont async-request))))
660 (let ((queue (agenda-queue agenda))
661 (next-queue (make-q)))
662 (while (not (q-empty? queue))
663 (let* ((proc (q-pop! queue))
664 (proc-result (call-proc proc))
666 (lambda (run-request)
667 (define (schedule-at! time proc)
668 (schedule-add! (agenda-schedule agenda) time proc))
669 (let ((request-time (run-request-when run-request)))
671 ((? time-delta? time-delta)
672 (let ((time (time-delta+ (agenda-time agenda)
674 (schedule-at! time (run-request-proc run-request))))
676 (let ((time (cons sec 0)))
677 (schedule-at! time (run-request-proc run-request))))
678 (((? integer? sec) . (? integer? usec))
679 (schedule-at! request-time (run-request-proc run-request)))
681 (enq! next-queue (run-request-proc run-request))))))))
682 (define (handle-individual result)
684 ((? run-request? new-proc)
686 ((? port-request? port-request)
687 (agenda-handle-port-request! agenda port-request))
690 ;; @@: We might support delay-wrapped procedures here
693 (for-each handle-individual results))
694 (one-result (handle-individual one-result)))))
695 ;; TODO: Alternately, we could return the next-queue
696 ;; along with changes to be added to the schedule here?
697 ;; Return new agenda, with next queue set
698 (set-field agenda (agenda-queue) next-queue)))