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 wrap-apply run run-at run-delay
66 %port-request %run %run-at %run-delay
67 8port-request 8run 8run-at 8run-delay
69 print-error-and-continue
72 start-agenda agenda-run-once))
74 ;; @@: Using immutable agendas here, so wouldn't it make sense to
75 ;; replace this queue stuff with using pfds based immutable queues?
81 ;;; The agenda consists of:
82 ;;; - a queue of immediate items to handle
83 ;;; - sheduled future events to be added to a future queue
84 ;;; - a tag by which running processes can escape for some asynchronous
85 ;;; operation (from which they can be returned later)
86 ;;; - a mapping of ports to various handler procedures
88 ;;; The goal, eventually, is for this all to be immutable and functional.
89 ;;; However, we aren't there yet. Some tricky things:
90 ;;; - The schedule needs to be immutable, yet reasonably efficient.
91 ;;; - Need to use immutable queues (ijp's pfds library?)
92 ;;; - Modeling reading from ports as something repeatable,
93 ;;; and with reasonable separation from functional components?
95 (define-immutable-record-type <agenda>
96 (make-agenda-intern queue prompt-tag
97 read-port-map write-port-map except-port-map
98 schedule time catch-handler pre-unwind-handler)
101 (prompt-tag agenda-prompt-tag)
102 (read-port-map agenda-read-port-map)
103 (write-port-map agenda-write-port-map)
104 (except-port-map agenda-except-port-map)
105 (schedule agenda-schedule)
107 (catch-handler agenda-catch-handler)
108 (pre-unwind-handler agenda-pre-unwind-handler))
110 (define (make-async-prompt-tag)
111 "Make an async prompt tag for an agenda.
113 Generally done automatically for the user through (make-agenda)."
114 (make-prompt-tag "prompt"))
116 (define* (make-agenda #:key
118 (prompt (make-prompt-tag))
119 (read-port-map (make-hash-table))
120 (write-port-map (make-hash-table))
121 (except-port-map (make-hash-table))
122 (schedule (make-schedule))
123 (time (gettimeofday))
125 (pre-unwind-handler #f))
126 ;; TODO: document arguments
127 "Make a fresh agenda."
128 (make-agenda-intern queue prompt
129 read-port-map write-port-map except-port-map
131 catch-handler pre-unwind-handler))
133 (define (current-agenda-prompt)
134 "Get the prompt for the current agenda; signal an error if there isn't one."
135 (let ((current-agenda (%current-agenda)))
136 (if (not current-agenda)
139 "Can't get current agenda prompt if there's no current agenda!")
140 (agenda-prompt-tag current-agenda))))
147 ;;; This is where we handle timed events for the future
149 ;; This section totally borrows from the ideas in SICP
152 ;; NOTE: time is a cons of (seconds . microseconds)
154 (define-record-type <time-segment>
155 (make-time-segment-intern time queue)
157 (time time-segment-time)
158 (queue time-segment-queue))
160 ;; @@: This seems to be the same as srfi-18's seconds->time procedure?
161 ;; Maybe double check and switch to that? (Thanks amz3!)
163 (define (time-from-float-or-fraction time)
164 "Produce a (sec . usec) pair from TIME, a float or fraction"
165 (let* ((mixed-whole (floor time))
166 (mixed-rest (- time mixed-whole)) ; float or fraction component
168 (usec (floor (* 1000000 mixed-rest))))
169 (cons (inexact->exact sec) (inexact->exact usec))))
171 (define (time-segment-right-format time)
172 "Ensure TIME is in the right format.
174 The right format means (second . microsecond).
175 If an integer, will convert appropriately."
176 ;; TODO: add floating point / rational number support.
178 ;; time is already a cons of second and microsecnd
179 (((? integer? s) . (? integer? u)) time)
180 ;; time was just an integer (just the second)
181 ((? integer? _) (cons time 0))
182 ((or (? rational? _) (? inexact? _))
183 (time-from-float-or-fraction time))
184 (_ (throw 'invalid-time "Invalid time" time))))
186 (define* (make-time-segment time #:optional (queue (make-q)))
187 "Make a time segment of TIME and QUEUE
189 No automatic conversion is done, so you might have to
190 run (time-segment-right-format) first."
191 (make-time-segment-intern time queue))
193 (define (time< time1 time2)
194 "Check if TIME1 is less than TIME2"
195 (cond ((< (car time1)
205 (define (time= time1 time2)
206 "Check whether TIME1 and TIME2 are equivalent"
207 (and (= (car time1) (car time2))
208 (= (cdr time1) (cdr time2))))
210 (define (time<= time1 time2)
211 "Check if TIME1 is less than or equal to TIME2"
212 (or (time< time1 time2)
213 (time= time1 time2)))
216 (define-record-type <time-delta>
217 (make-time-delta-intern sec usec)
220 (usec time-delta-usec))
222 (define* (make-time-delta time)
223 "Make a <time-delta> of SEC seconds and USEC microseconds.
225 This is used primarily so the agenda can recognize RUN-REQUEST objects
226 which are meant to delay computation"
227 (match (time-segment-right-format time)
229 (make-time-delta-intern sec usec))))
231 (define tdelta make-time-delta)
233 (define (time-carry-correct time)
234 "Corrects/handles time microsecond carry.
235 Will produce (0 . 0) instead of a negative number, if needed."
236 (cond ((>= (cdr time) 1000000)
239 (- (cdr time) 1000000)))
245 (+ (cdr time) 1000000))))
248 (define (time-delta+ time time-delta)
249 "Increment a TIME by the value of TIME-DELTA"
251 (cons (+ (car time) (time-delta-sec time-delta))
252 (+ (cdr time) (time-delta-usec time-delta)))))
254 (define (time-minus time1 time2)
255 "Subtract TIME2 from TIME1"
257 (cons (- (car time1) (car time2))
258 (- (cdr time1) (cdr time2)))))
260 (define (time-plus time1 time2)
261 "Add TIME1 and TIME2"
263 (cons (+ (car time1) (car time2))
264 (+ (cdr time1) (cdr time2)))))
267 (define-record-type <schedule>
268 (make-schedule-intern segments)
270 (segments schedule-segments set-schedule-segments!))
272 (define* (make-schedule #:optional segments)
273 "Make a schedule, optionally pre-composed of SEGMENTS"
274 (make-schedule-intern (or segments '())))
276 (define (schedule-soonest-time schedule)
277 "Return a cons of (sec . usec) for next time segement, or #f if none"
278 (let ((segments (schedule-segments schedule)))
279 (if (eq? segments '())
281 (time-segment-time (car segments)))))
283 ;; TODO: This code is reasonably easy to read but it
284 ;; mutates AND is worst case of O(n) in both space and time :(
285 ;; but at least it'll be reasonably easy to refactor to
286 ;; a more functional setup?
287 (define (schedule-add! schedule time proc)
288 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
289 (let ((time (time-segment-right-format time)))
290 (define (new-time-segment)
292 (make-time-segment time)))
293 (enq! (time-segment-queue new-segment) proc)
295 (define (loop segments)
296 (define (segment-equals-time? segment)
297 (time= time (time-segment-time segment)))
299 (define (segment-more-than-time? segment)
300 (time< time (time-segment-time segment)))
302 ;; We could switch this out to be more mutate'y
303 ;; and avoid the O(n) of space... is that over-optimizing?
305 ;; If we're at the end of the list, time to make a new
307 ('() (cons (new-time-segment) '()))
308 ;; If the segment's time is exactly our time, good news
309 ;; everyone! Let's append our stuff to its queue
310 (((? segment-equals-time? first) rest ...)
311 (enq! (time-segment-queue first) proc)
313 ;; If the first segment is more than our time,
314 ;; ours belongs before this one, so add it and
315 ;; start consing our way back
316 (((? segment-more-than-time? first) rest ...)
317 (cons (new-time-segment) segments))
318 ;; Otherwise, build up recursive result
320 (cons first (loop rest)))))
321 (set-schedule-segments!
323 (loop (schedule-segments schedule)))))
325 (define (schedule-empty? schedule)
326 "Check if the SCHEDULE is currently empty"
327 (eq? (schedule-segments schedule) '()))
329 (define (schedule-segments-split schedule time)
330 "Does a multiple value return of time segments before/at and after TIME"
331 (let ((time (time-segment-right-format time)))
332 (define (segment-is-now? segment)
333 (time= (time-segment-time segment) time))
334 (define (segment-is-before-now? segment)
335 (time< (time-segment-time segment) time))
337 (let loop ((segments-before '())
338 (segments-left (schedule-segments schedule)))
340 ;; end of the line, return
342 (values (reverse segments-before) '()))
344 ;; It's right now, so time to stop, but include this one in before
345 ;; but otherwise return
346 (((? segment-is-now? first) rest ...)
347 (values (reverse (cons first segments-before)) rest))
349 ;; This is prior or at now, so add it and keep going
350 (((? segment-is-before-now? first) rest ...)
351 (loop (cons first segments-before) rest))
353 ;; Otherwise it's past now, just return what we have
355 (values segments-before segments-after))))))
357 (define (schedule-extract-until! schedule time)
358 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
359 (receive (segments-before segments-after)
360 (schedule-segments-split schedule time)
361 (set-schedule-segments! schedule segments-after)
364 (define (add-segments-contents-to-queue! segments queue)
367 (let ((seg-queue (time-segment-queue segment)))
368 (while (not (q-empty? seg-queue))
369 (enq! queue (deq! seg-queue)))))
374 ;;; Request to run stuff
375 ;;; ====================
377 (define-record-type <run-request>
378 (make-run-request proc when)
380 (proc run-request-proc)
381 (when run-request-when))
383 (define* (run-it proc #:optional when)
384 "Make a request to run PROC (possibly at WHEN)"
385 (make-run-request proc when))
387 (define-syntax-rule (wrap body ...)
388 "Wrap contents in a procedure"
392 (define-syntax-rule (wrap-apply body)
393 "Wrap possibly multi-value function in a procedure, applies all arguments"
398 ;; @@: Do we really want `body ...' here?
399 ;; what about just `body'?
400 (define-syntax-rule (run body ...)
401 "Run everything in BODY but wrap in a convenient procedure"
402 (make-run-request (wrap body ...) #f))
404 (define-syntax-rule (run-at body ... when)
406 (make-run-request (wrap body ...) when))
408 ;; @@: Is it okay to overload the term "delay" like this?
409 ;; Would `run-in' be better?
410 (define-syntax-rule (run-delay body ... delay-time)
411 "Run BODY at DELAY-TIME time from now"
412 (make-run-request (wrap body ...) (tdelta delay-time)))
415 ;; A request to set up a port with at least one of read, write, except
416 ;; handling processes
418 (define-record-type <port-request>
419 (make-port-request-intern port read write except)
421 (port port-request-port)
422 (read port-request-read)
423 (write port-request-write)
424 (except port-request-except))
426 (define* (make-port-request port #:key read write except)
427 (if (not (or read write except))
428 (throw 'no-port-handler-given "No port handler given.\n"))
429 (make-port-request-intern port read write except))
431 (define port-request make-port-request)
435 ;;; Asynchronous escape to run things
436 ;;; =================================
438 ;; The future's in futures
440 (define (make-future call-first on-success on-fail on-error)
441 ;; TODO: add error stuff here
443 (let ((call-result (call-first)))
444 ;; queue up calling the
445 (run (on-success call-result)))))
447 (define (agenda-on-error agenda)
450 (define (agenda-on-fail agenda)
453 (define* (request-future call-first on-success
455 (agenda (%current-agenda))
456 (on-fail (agenda-on-fail agenda))
457 (on-error (agenda-on-error agenda))
459 ;; TODO: error handling
460 ;; do we need some distinction between expected, catchable errors,
461 ;; and unexpected, uncatchable ones? Probably...?
463 (make-future call-first on-success on-fail on-error)
466 (define-syntax-rule (%8sync async-request)
467 "Run BODY asynchronously at a prompt, passing args to make-future.
469 Runs things asynchronously (8synchronously?)"
470 (abort-to-prompt (current-agenda-prompt)
473 ;; Async port request and run-request meta-requests
474 (define (make-async-request proc)
475 "Wrap PROC in an async-request
477 The purpose of this is to make sure that users don't accidentally
478 return the wrong thing via (%8sync) and trip themselves up."
479 (cons '*async-request* proc))
481 (define (setup-async-request resume-kont async-request)
482 "Complete an async request for agenda-run-once's continuation handling"
484 (('*async-request* . async-setup-proc)
485 (async-setup-proc resume-kont))
486 ;; TODO: deliver more helpful errors depending on what the user
488 (_ (throw 'invalid-async-request
489 "Invalid request passed back via an (%8sync) procedure."
492 (define-syntax-rule (%run body ...)
493 (%run-at body ... #f))
495 (define-syntax-rule (%run-at body ... when)
504 (define-syntax-rule (%run-delay body ... delay-time)
505 (%run-at body ... (tdelta delay-time)))
507 (define-syntax-rule (%port-request add-this-port port-request-args ...)
510 (list (make-port-request port-request-args ...)
511 (make-run-request kont)))))
514 (define-syntax-rule (%run-with-return return body ...)
522 (define-syntax-rule (8run args ...) (%run args ...))
523 (define-syntax-rule (8run-at args ...) (%run-at args ...))
524 (define-syntax-rule (8run-delay args ...) (%run-delay args ...))
525 (define-syntax-rule (8port-request args ...) (%port-request args ...))
529 ;;; Execution of agenda, and current agenda
530 ;;; =======================================
532 (define %current-agenda (make-parameter #f))
534 (define (update-agenda-from-select! agenda)
535 "Potentially (select) on ports specified in agenda, adding items to queue"
536 (define (hash-keys hash)
537 (hash-map->list (lambda (k v) k) hash))
538 (define (get-wait-time)
539 ;; TODO: we need to figure this out based on whether there's anything
540 ;; in the queue, and if not, how long till the next scheduled item
541 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
543 ((not (q-empty? (agenda-queue agenda)))
545 (soonest-time ; ie, the agenda is non-empty
546 (let* ((current-time (agenda-time agenda)))
547 (if (time<= soonest-time current-time)
548 ;; Well there's something due so let's select
549 ;; (this avoids a (possible?) race condition chance)
551 (time-minus soonest-time current-time))))
555 ;; TODO: support usecond wait time too
556 (match (get-wait-time)
560 (select (hash-keys (agenda-read-port-map agenda))
561 (hash-keys (agenda-write-port-map agenda))
562 (hash-keys (agenda-except-port-map agenda))
564 (lambda (key . rest-args)
568 (_ (error "Unhandled error in select!" key rest-args))))))))
569 (define (get-procs-to-run)
570 (define (ports->procs ports port-map)
571 (lambda (initial-procs)
575 ((hash-ref port-map port) port))
580 ((read-ports write-ports except-ports)
581 ;; @@: Come on, we can do better than append ;P
582 ((compose (ports->procs
584 (agenda-read-port-map agenda))
587 (agenda-write-port-map agenda))
590 (agenda-except-port-map agenda)))
592 (define (update-agenda)
593 (let ((procs-to-run (get-procs-to-run))
594 (q (agenda-queue agenda)))
600 (define (ports-to-select?)
601 (define (has-items? selector)
603 ;; ... we could use hash-for-each and a continuation to jump
604 ;; out with a #t at first indication of an item
605 (not (= (hash-count (const #t)
608 (or (has-items? agenda-read-port-map)
609 (has-items? agenda-write-port-map)
610 (has-items? agenda-except-port-map)))
612 (if (ports-to-select?)
616 (define (agenda-handle-port-request! agenda port-request)
617 "Update an agenda for a port-request"
618 (define (handle-selector request-selector port-map-selector)
619 (if (request-selector port-request)
620 (hash-set! (port-map-selector agenda)
621 (port-request-port port-request)
622 (request-selector port-request))))
623 (handle-selector port-request-read agenda-read-port-map)
624 (handle-selector port-request-write agenda-write-port-map)
625 (handle-selector port-request-except agenda-except-port-map))
628 (define* (start-agenda agenda
630 (get-time gettimeofday)
631 (handle-ports update-agenda-from-select!))
632 ;; TODO: Document fields
633 "Start up the AGENDA"
634 (let loop ((agenda agenda))
636 ;; @@: Hm, maybe here would be a great place to handle
637 ;; select'ing on ports.
638 ;; We could compose over agenda-run-once and agenda-read-ports
639 (agenda-run-once agenda)))
640 (if (and stop-condition (stop-condition agenda))
643 ;; We have to update the time after ports handled, too
644 ;; because it may have changed after a select
647 ;; Adjust the agenda's time just in time
648 ;; We do this here rather than in agenda-run-once to make
649 ;; agenda-run-once's behavior fairly predictable
650 (set-field agenda (agenda-time) (get-time)))
651 (agenda-time) (get-time))))
652 ;; Update the agenda's current queue based on
653 ;; currently applicable time segments
654 (add-segments-contents-to-queue!
655 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
656 (agenda-queue agenda))
659 (define (print-error-and-continue . args)
660 "Frequently used as pre-unwind-handler for agenda"
661 (format (current-error-port) "\n*** Caught exception with arguments: ~s ***\n"
663 (display-backtrace (make-stack #t 1 0)
664 (current-error-port))
665 (newline (current-error-port)))
667 (define-syntax-rule (maybe-catch-all (catch-handler pre-unwind-handler)
669 (if (or catch-handler pre-unwind-handler)
674 (or catch-handler (lambda _ #f))
675 (or pre-unwind-handler (lambda _ #f)))
678 (define (agenda-run-once agenda)
679 "Run once through the agenda, and produce a new agenda
680 based on the results"
681 (define (call-proc proc)
683 (agenda-prompt-tag agenda)
685 (parameterize ((%current-agenda agenda))
687 ((agenda-catch-handler agenda)
688 (agenda-pre-unwind-handler agenda))
690 (lambda (kont async-request)
691 (setup-async-request kont async-request))))
693 (let ((queue (agenda-queue agenda))
694 (next-queue (make-q)))
695 (while (not (q-empty? queue))
696 (let* ((proc (q-pop! queue))
697 (proc-result (call-proc proc))
699 (lambda (run-request)
700 (define (schedule-at! time proc)
701 (schedule-add! (agenda-schedule agenda) time proc))
702 (let ((request-time (run-request-when run-request)))
704 ((? time-delta? time-delta)
705 (let ((time (time-delta+ (agenda-time agenda)
707 (schedule-at! time (run-request-proc run-request))))
709 (let ((time (cons sec 0)))
710 (schedule-at! time (run-request-proc run-request))))
711 (((? integer? sec) . (? integer? usec))
712 (schedule-at! request-time (run-request-proc run-request)))
714 (enq! next-queue (run-request-proc run-request))))))))
715 (define (handle-individual result)
717 ((? run-request? new-proc)
719 ((? port-request? port-request)
720 (agenda-handle-port-request! agenda port-request))
723 ;; @@: We might support delay-wrapped procedures here
726 (for-each handle-individual results))
727 (one-result (handle-individual one-result)))))
728 ;; TODO: Alternately, we could return the next-queue
729 ;; along with changes to be added to the schedule here?
730 ;; Return new agenda, with next queue set
731 (set-field agenda (agenda-queue) next-queue)))