Add %8sync-run sugar and friends
[8sync.git] / 8sync / agenda.scm
1 ;;; 8sync --- Asynchronous programming for Guile
2 ;;; Copyright (C) 2015 Christopher Allan Webber <cwebber@dustycloud.org>
3 ;;;
4 ;;; This file is part of 8sync.
5 ;;;
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.
10 ;;;
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.
15 ;;;
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/>.
18
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   #:export (<agenda>
27             make-agenda agenda?
28             agenda-queue agenda-prompt-tag
29             agenda-read-port-map agenda-write-port-map agenda-except-port-map
30             agenda-schedule
31             
32             make-async-prompt-tag
33
34             list->q make-q*
35
36             <time-segment>
37             make-time-segment time-segment?
38             time-segment-time time-segment-queue
39
40             time< time= time<= time-delta+
41             time-minus time-plus
42
43             <time-delta>
44             make-time-delta tdelta time-delta?
45             time-delta-sec time-delta-usec
46
47             <schedule>
48             make-schedule schedule?
49             schedule-add! schedule-empty?
50             schedule-segments
51             schedule-soonest-time
52
53             schedule-segments-split schedule-extract-until!
54             add-segments-contents-to-queue!
55
56             %8sync
57
58             <run-request>
59             make-run-request run-request?
60             run-request-proc run-request-when
61
62             <port-request>
63             make-port-request port-request port-request?
64             port-request-port
65             port-request-read port-request-write port-request-except
66
67             run-it wrap wrap-apply run run-at run-delay
68
69             %run %run-at %run-delay %port-request 
70             %8sync-run %8sync-run-at %8sync-run-delay %8sync-port
71             
72             catch-8sync catch-%8sync
73
74             ;; used for introspecting the error, but a method for making
75             ;; is not exposed
76             wrapped-exception?
77             wrapped-exception-key wrapped-exception-args
78             wrapped-exception-stacks
79
80             print-error-and-continue
81
82             %current-agenda
83             start-agenda agenda-run-once))
84
85 ;; @@: Using immutable agendas here, so wouldn't it make sense to
86 ;;   replace this queue stuff with using pfds based immutable queues?
87
88 \f
89 ;;; Agenda definition
90 ;;; =================
91
92 ;;; The agenda consists of:
93 ;;;  - a queue of immediate items to handle
94 ;;;  - sheduled future events to be added to a future queue
95 ;;;  - a tag by which running processes can escape for some asynchronous
96 ;;;    operation (from which they can be returned later)
97 ;;;  - a mapping of ports to various handler procedures
98 ;;;
99 ;;; The goal, eventually, is for this all to be immutable and functional.
100 ;;; However, we aren't there yet.  Some tricky things:
101 ;;;  - The schedule needs to be immutable, yet reasonably efficient.
102 ;;;  - Need to use immutable queues (ijp's pfds library?)
103 ;;;  - Modeling reading from ports as something repeatable,
104 ;;;    and with reasonable separation from functional components?
105
106 (define-immutable-record-type <agenda>
107   (make-agenda-intern queue prompt-tag
108                       read-port-map write-port-map except-port-map
109                       schedule time catch-handler pre-unwind-handler)
110   agenda?
111   (queue agenda-queue)
112   (prompt-tag agenda-prompt-tag)
113   (read-port-map agenda-read-port-map)
114   (write-port-map agenda-write-port-map)
115   (except-port-map agenda-except-port-map)
116   (schedule agenda-schedule)
117   (time agenda-time)
118   (catch-handler agenda-catch-handler)
119   (pre-unwind-handler agenda-pre-unwind-handler))
120
121 (define (make-async-prompt-tag)
122   "Make an async prompt tag for an agenda.
123
124 Generally done automatically for the user through (make-agenda)."
125   (make-prompt-tag "prompt"))
126
127 (define* (make-agenda #:key
128                       (queue (make-q))
129                       (prompt (make-prompt-tag))
130                       (read-port-map (make-hash-table))
131                       (write-port-map (make-hash-table))
132                       (except-port-map (make-hash-table))
133                       (schedule (make-schedule))
134                       (time (gettimeofday))
135                       (catch-handler #f)
136                       (pre-unwind-handler #f))
137   ;; TODO: document arguments
138   "Make a fresh agenda."
139   (make-agenda-intern queue prompt
140                       read-port-map write-port-map except-port-map
141                       schedule time
142                       catch-handler pre-unwind-handler))
143
144 (define (current-agenda-prompt)
145   "Get the prompt for the current agenda; signal an error if there isn't one."
146   (let ((current-agenda (%current-agenda)))
147     (if (not current-agenda)
148         (throw
149          'no-current-agenda
150          "Can't get current agenda prompt if there's no current agenda!")
151         (agenda-prompt-tag current-agenda))))
152
153 ;; helper for making queues for an agenda
154 (define (list->q lst)
155   "Makes a queue composed of LST items"
156   (let ((q (make-q)))
157     (for-each
158      (lambda (x)
159        (enq! q x))
160      lst)
161     q))
162
163 (define (make-q* . args)
164   "Makes a queue and populates it with this invocation's ARGS"
165   (list->q args))
166
167 \f
168 ;;; Schedule
169 ;;; ========
170
171 ;;; This is where we handle timed events for the future
172
173 ;; This section totally borrows from the ideas in SICP
174 ;; <3 <3 <3
175
176 ;; NOTE: time is a cons of (seconds . microseconds)
177
178 (define-record-type <time-segment>
179   (make-time-segment-intern time queue)
180   time-segment?
181   (time time-segment-time)
182   (queue time-segment-queue))
183
184 ;; @@: This seems to be the same as srfi-18's seconds->time procedure?
185 ;;   Maybe double check and switch to that?  (Thanks amz3!)
186
187 (define (time-from-float-or-fraction time)
188   "Produce a (sec . usec) pair from TIME, a float or fraction"
189   (let* ((mixed-whole (floor time))
190          (mixed-rest (- time mixed-whole))  ; float or fraction component
191          (sec mixed-whole)
192          (usec (floor (* 1000000 mixed-rest))))
193     (cons (inexact->exact sec) (inexact->exact usec))))
194
195 (define (time-segment-right-format time)
196   "Ensure TIME is in the right format.
197
198 The right format means (second . microsecond).
199 If an integer, will convert appropriately."
200   ;; TODO: add floating point / rational number support.
201   (match time
202     ;; time is already a cons of second and microsecnd
203     (((? integer? s) . (? integer? u)) time)
204     ;; time was just an integer (just the second)
205     ((? integer? _) (cons time 0))
206     ((or (? rational? _) (? inexact? _))
207      (time-from-float-or-fraction time))
208     (_ (throw 'invalid-time "Invalid time" time))))
209
210 (define* (make-time-segment time #:optional (queue (make-q)))
211   "Make a time segment of TIME and QUEUE
212
213 No automatic conversion is done, so you might have to
214 run (time-segment-right-format) first."
215   (make-time-segment-intern time queue))
216
217 (define (time< time1 time2)
218   "Check if TIME1 is less than TIME2"
219   (cond ((< (car time1)
220             (car time2))
221          #t)
222         ((and (= (car time1)
223                  (car time2))
224               (< (cdr time1)
225                  (cdr time2)))
226          #t)
227         (else #f)))
228
229 (define (time= time1 time2)
230   "Check whether TIME1 and TIME2 are equivalent"
231   (and (= (car time1) (car time2))
232        (= (cdr time1) (cdr time2))))
233
234 (define (time<= time1 time2)
235   "Check if TIME1 is less than or equal to TIME2"
236   (or (time< time1 time2)
237       (time= time1 time2)))
238
239
240 (define-record-type <time-delta>
241   (make-time-delta-intern sec usec)
242   time-delta?
243   (sec time-delta-sec)
244   (usec time-delta-usec))
245
246 (define* (make-time-delta time)
247   "Make a <time-delta> of SEC seconds and USEC microseconds.
248
249 This is used primarily so the agenda can recognize RUN-REQUEST objects
250 which are meant to delay computation"
251   (match (time-segment-right-format time)
252     ((sec . usec)
253      (make-time-delta-intern sec usec))))
254
255 (define tdelta make-time-delta)
256
257 (define (time-carry-correct time)
258   "Corrects/handles time microsecond carry.
259 Will produce (0 . 0) instead of a negative number, if needed."
260   (cond ((>= (cdr time) 1000000)
261          (cons
262           (+ (car time) 1)
263           (- (cdr time) 1000000)))
264         ((< (cdr time) 0)
265          (if (= (car time) 0)
266              '(0 0)
267              (cons
268               (- (car time) 1)
269               (+ (cdr time) 1000000))))
270         (else time)))
271
272 (define (time-delta+ time time-delta)
273   "Increment a TIME by the value of TIME-DELTA"
274   (time-carry-correct
275    (cons (+ (car time) (time-delta-sec time-delta))
276          (+ (cdr time) (time-delta-usec time-delta)))))
277
278 (define (time-minus time1 time2)
279   "Subtract TIME2 from TIME1"
280   (time-carry-correct
281    (cons (- (car time1) (car time2))
282          (- (cdr time1) (cdr time2)))))
283
284 (define (time-plus time1 time2)
285   "Add TIME1 and TIME2"
286   (time-carry-correct
287    (cons (+ (car time1) (car time2))
288          (+ (cdr time1) (cdr time2)))))
289
290
291 (define-record-type <schedule>
292   (make-schedule-intern segments)
293   schedule?
294   (segments schedule-segments set-schedule-segments!))
295
296 (define* (make-schedule #:optional segments)
297   "Make a schedule, optionally pre-composed of SEGMENTS"
298   (make-schedule-intern (or segments '())))
299
300 (define (schedule-soonest-time schedule)
301   "Return a cons of (sec . usec) for next time segement, or #f if none"
302   (let ((segments (schedule-segments schedule)))
303     (if (eq? segments '())
304         #f
305         (time-segment-time (car segments)))))
306
307 ;; TODO: This code is reasonably easy to read but it
308 ;;   mutates AND is worst case of O(n) in both space and time :(
309 ;;   but at least it'll be reasonably easy to refactor to
310 ;;   a more functional setup?
311 (define (schedule-add! schedule time proc)
312   "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
313   (let ((time (time-segment-right-format time)))
314     (define (new-time-segment)
315       (let ((new-segment
316              (make-time-segment time)))
317         (enq! (time-segment-queue new-segment) proc)
318         new-segment))
319     (define (loop segments)
320       (define (segment-equals-time? segment)
321         (time= time (time-segment-time segment)))
322
323       (define (segment-more-than-time? segment)
324         (time< time (time-segment-time segment)))
325
326       ;; We could switch this out to be more mutate'y
327       ;; and avoid the O(n) of space... is that over-optimizing?
328       (match segments
329         ;; If we're at the end of the list, time to make a new
330         ;; segment...
331         ('() (cons (new-time-segment) '()))
332         ;; If the segment's time is exactly our time, good news
333         ;; everyone!  Let's append our stuff to its queue
334         (((? segment-equals-time? first) rest ...)
335          (enq! (time-segment-queue first) proc)
336          segments)
337         ;; If the first segment is more than our time,
338         ;; ours belongs before this one, so add it and
339         ;; start consing our way back
340         (((? segment-more-than-time? first) rest ...)
341          (cons (new-time-segment) segments))
342         ;; Otherwise, build up recursive result
343         ((first rest ... )
344          (cons first (loop rest)))))
345     (set-schedule-segments!
346      schedule
347      (loop (schedule-segments schedule)))))
348
349 (define (schedule-empty? schedule)
350   "Check if the SCHEDULE is currently empty"
351   (eq? (schedule-segments schedule) '()))
352
353 (define (schedule-segments-split schedule time)
354   "Does a multiple value return of time segments before/at and after TIME"
355   (let ((time (time-segment-right-format time)))
356     (define (segment-is-now? segment)
357       (time= (time-segment-time segment) time))
358     (define (segment-is-before-now? segment)
359       (time< (time-segment-time segment) time))
360
361     (let loop ((segments-before '())
362                (segments-left (schedule-segments schedule)))
363       (match segments-left
364         ;; end of the line, return
365         ('()
366          (values (reverse segments-before) '()))
367
368         ;; It's right now, so time to stop, but include this one in before
369         ;; but otherwise return
370         (((? segment-is-now? first) rest ...)
371          (values (reverse (cons first segments-before)) rest))
372
373         ;; This is prior or at now, so add it and keep going
374         (((? segment-is-before-now? first) rest ...)
375          (loop (cons first segments-before) rest))
376
377         ;; Otherwise it's past now, just return what we have
378         (segments-after
379          (values segments-before segments-after))))))
380
381 (define (schedule-extract-until! schedule time)
382   "Extract all segments until TIME from SCHEDULE, and pop old segments off"
383   (receive (segments-before segments-after)
384       (schedule-segments-split schedule time)
385     (set-schedule-segments! schedule segments-after)
386     segments-before))
387
388 (define (add-segments-contents-to-queue! segments queue)
389   (for-each
390    (lambda (segment)
391      (let ((seg-queue (time-segment-queue segment)))
392        (while (not (q-empty? seg-queue))
393          (enq! queue (deq! seg-queue)))))
394    segments))
395
396
397 \f
398 ;;; Request to run stuff
399 ;;; ====================
400
401 (define-record-type <run-request>
402   (make-run-request proc when)
403   run-request?
404   (proc run-request-proc)
405   (when run-request-when))
406
407 (define* (run-it proc #:optional when)
408   "Make a request to run PROC (possibly at WHEN)"
409   (make-run-request proc when))
410
411 (define-syntax-rule (wrap body ...)
412   "Wrap contents in a procedure"
413   (lambda ()
414     body ...))
415
416 (define-syntax-rule (wrap-apply body)
417   "Wrap possibly multi-value function in a procedure, applies all arguments"
418   (lambda args
419     (apply body args)))
420
421
422 ;; @@: Do we really want `body ...' here?
423 ;;   what about just `body'?
424 (define-syntax-rule (run body ...)
425   "Run everything in BODY but wrap in a convenient procedure"
426   (make-run-request (wrap body ...) #f))
427
428 (define-syntax-rule (run-at body ... when)
429   "Run BODY at WHEN"
430   (make-run-request (wrap body ...) when))
431
432 ;; @@: Is it okay to overload the term "delay" like this?
433 ;;   Would `run-in' be better?
434 (define-syntax-rule (run-delay body ... delay-time)
435   "Run BODY at DELAY-TIME time from now"
436   (make-run-request (wrap body ...) (tdelta delay-time)))
437
438
439 ;; A request to set up a port with at least one of read, write, except
440 ;; handling processes
441
442 (define-record-type <port-request>
443   (make-port-request-intern port read write except)
444   port-request?
445   (port port-request-port)
446   (read port-request-read)
447   (write port-request-write)
448   (except port-request-except))
449
450 (define* (make-port-request port #:key read write except)
451   (if (not (or read write except))
452       (throw 'no-port-handler-given "No port handler given.\n"))
453   (make-port-request-intern port read write except))
454
455 (define port-request make-port-request)
456
457
458 \f
459 ;;; Asynchronous escape to run things
460 ;;; =================================
461
462 (define-syntax-rule (%8sync async-request)
463   "Run BODY asynchronously at a prompt, passing args to make-future.
464
465 Runs things asynchronously (8synchronously?)"
466   (propagate-%async-exceptions
467    (abort-to-prompt (current-agenda-prompt)
468                     async-request)))
469
470 ;; Async port request and run-request meta-requests
471 (define (make-async-request proc)
472   "Wrap PROC in an async-request
473
474 The purpose of this is to make sure that users don't accidentally
475 return the wrong thing via (%8sync) and trip themselves up."
476   (cons '*async-request* proc))
477
478 (define (setup-async-request resume-kont async-request)
479   "Complete an async request for agenda-run-once's continuation handling"
480   (match async-request
481     (('*async-request* . async-setup-proc)
482      (async-setup-proc resume-kont))
483     ;; TODO: deliver more helpful errors depending on what the user
484     ;;   returned
485     (_ (throw 'invalid-async-request
486               "Invalid request passed back via an (%8sync) procedure."
487               async-request))))
488
489 (define-record-type <wrapped-exception>
490   (make-wrapped-exception key args stacks)
491   wrapped-exception?
492   (key wrapped-exception-key)
493   (args wrapped-exception-args)
494   (stacks wrapped-exception-stacks))
495
496 (define-syntax-rule (propagate-%async-exceptions body)
497   (let ((body-result body))
498     (if (wrapped-exception? body-result)
499         (throw '8sync-caught-error
500                (wrapped-exception-key body-result)
501                (wrapped-exception-args body-result)
502                (wrapped-exception-stacks body-result))
503         body-result)))
504
505 (define-syntax-rule (%run body ...)
506   (%run-at body ... #f))
507
508 (define-syntax-rule (%run-at body ... when)
509   ;; Send an asynchronous request to apply a continuation to the
510   ;; following function, then handle that as a request to the agenda
511   (make-async-request
512    (lambda (kont)
513      ;; We're making a run request
514      (make-run-request
515       ;; Wrapping the following execution to run...
516       (wrap
517        ;; Once we get the result from the inner part, we'll resume
518        ;; this continuation, but first
519        ;; @@: Is this running immediately, or queueing the result
520        ;;   after evaluation for the next agenda tick?  It looks
521        ;;   like evaluating immediately.  Is that what we want?
522        (kont
523         ;; Any unhandled errors are caught
524         (let ((exception-stack #f))
525           (catch #t
526             ;; Run the actual code the user requested
527             (lambda ()
528               body ...)
529             ;; If something bad happened and we didn't catch it,
530             ;; we'll wrap it up in such a way that the continuation
531             ;; can address it
532             (lambda (key . args)
533               (cond
534                ((eq? key '8sync-caught-error)
535                 (match args
536                   ((orig-key orig-args orig-stacks)
537                    (make-wrapped-exception
538                     orig-key orig-args
539                     (cons exception-stack orig-stacks)))))
540                (else
541                 (make-wrapped-exception key args
542                                         (list exception-stack)))))
543             (lambda _
544               (set! exception-stack (make-stack #t 1 0)))))))
545       when))))
546
547 (define-syntax-rule (%run-delay body ... delay-time)
548   (%run-at body ... (tdelta delay-time)))
549
550 (define-syntax-rule (%port-request add-this-port port-request-args ...)
551   (make-async-request
552    (lambda (kont)
553      (list (make-port-request port-request-args ...)
554            (make-run-request kont)))))
555
556 ;; Sugar
557 (define-syntax-rule (%8sync-run rest ...)
558   "Sugar for (%8sync (%run ...))"
559   (%8sync (%run rest ...)))
560
561 (define-syntax-rule (%8sync-run-at rest ...)
562   "Sugar for (%8sync (%run-at ...))"
563   (%8sync (%run-at rest ...)))
564
565 (define-syntax-rule (%8sync-run-delay rest ...)
566   "Sugar for (%8sync (%run-delay ...))"
567   (%8sync (%run-delay rest ...)))
568
569 (define-syntax-rule (%8sync-port rest ...)
570   "Sugar for (%8sync (%port-request ...))"
571   (%8sync (%port-request rest ...)))
572
573
574 ;; TODO: Write (%run-immediately)
575
576 ;; TODO
577 (define-syntax-rule (%run-with-return return body ...)
578   (make-async-request
579    (lambda (kont)
580      (let ((return kont))
581        (lambda ()
582          body ...)))))
583
584 (define-syntax-rule (catch-8sync exp (handler-key handler) ...)
585   (catch '8sync-caught-error
586     (lambda ()
587       exp)
588     (lambda (_ orig-key orig-args orig-stacks)
589       (cond
590        ((or (eq? handler-key #t)
591             (eq? orig-key handler-key))
592         (apply handler orig-stacks orig-args)) ...
593        (else (raise '8sync-caught-error
594                     orig-key orig-args orig-stacks))))))
595
596 ;; Alias...?
597 (define-syntax-rule (catch-%8sync rest ...)
598   (catch-8sync rest ...))
599
600
601 \f
602 ;;; Execution of agenda, and current agenda
603 ;;; =======================================
604
605 (define %current-agenda (make-parameter #f))
606
607 (define (update-agenda-from-select! agenda)
608   "Potentially (select) on ports specified in agenda, adding items to queue"
609   (define (hash-keys hash)
610     (hash-map->list (lambda (k v) k) hash))
611   (define (get-wait-time)
612     ;; TODO: we need to figure this out based on whether there's anything
613     ;;   in the queue, and if not, how long till the next scheduled item
614     (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
615       (cond 
616        ((not (q-empty? (agenda-queue agenda)))
617         (cons 0 0))
618        (soonest-time    ; ie, the agenda is non-empty
619         (let* ((current-time (agenda-time agenda)))
620           (if (time<= soonest-time current-time)
621               ;; Well there's something due so let's select
622               ;; (this avoids a (possible?) race condition chance)
623               (cons 0 0)
624               (time-minus soonest-time current-time))))
625        (else
626         (cons #f #f)))))
627   (define (do-select)
628     ;; TODO: support usecond wait time too
629     (match (get-wait-time)
630       ((sec . usec)
631        (catch 'system-error
632          (lambda ()
633            (select (hash-keys (agenda-read-port-map agenda))
634                    (hash-keys (agenda-write-port-map agenda))
635                    (hash-keys (agenda-except-port-map agenda))
636                    sec usec))
637          (lambda (key . rest-args)
638            (match rest-args
639              ((_ _ _ (EINTR))
640               '(() () ()))
641              (_ (error "Unhandled error in select!" key rest-args))))))))
642   (define (get-procs-to-run)
643     (define (ports->procs ports port-map)
644       (lambda (initial-procs)
645         (fold
646          (lambda (port prev)
647            (cons (lambda ()
648                    ((hash-ref port-map port) port))
649                  prev))
650          initial-procs
651          ports)))
652     (match (do-select)
653       ((read-ports write-ports except-ports)
654        ;; @@: Come on, we can do better than append ;P
655        ((compose (ports->procs
656                   read-ports
657                   (agenda-read-port-map agenda))
658                  (ports->procs
659                   write-ports
660                   (agenda-write-port-map agenda))
661                  (ports->procs
662                   except-ports
663                   (agenda-except-port-map agenda)))
664         '()))))
665   (define (update-agenda)
666     (let ((procs-to-run (get-procs-to-run))
667           (q (agenda-queue agenda)))
668       (for-each
669        (lambda (proc)
670          (enq! q proc))
671        procs-to-run))
672     agenda)
673   (define (ports-to-select?)
674     (define (has-items? selector)
675       ;; @@: O(n)
676       ;;    ... we could use hash-for-each and a continuation to jump
677       ;;    out with a #t at first indication of an item
678       (not (= (hash-count (const #t)
679                           (selector agenda))
680               0)))
681     (or (has-items? agenda-read-port-map)
682         (has-items? agenda-write-port-map)
683         (has-items? agenda-except-port-map)))
684
685   (if (ports-to-select?)
686       (update-agenda)
687       agenda))
688
689 (define (agenda-handle-port-request! agenda port-request)
690   "Update an agenda for a port-request"
691   (define (handle-selector request-selector port-map-selector)
692     (if (request-selector port-request)
693         (hash-set! (port-map-selector agenda)
694                    (port-request-port port-request)
695                    (request-selector port-request))))
696   (handle-selector port-request-read agenda-read-port-map)
697   (handle-selector port-request-write agenda-write-port-map)
698   (handle-selector port-request-except agenda-except-port-map))
699
700
701 (define* (start-agenda agenda
702                        #:key stop-condition
703                        (get-time gettimeofday)
704                        (handle-ports update-agenda-from-select!))
705   ;; TODO: Document fields
706   "Start up the AGENDA"
707   (let loop ((agenda agenda))
708     (let ((agenda   
709            ;; @@: Hm, maybe here would be a great place to handle
710            ;;   select'ing on ports.
711            ;;   We could compose over agenda-run-once and agenda-read-ports
712            (agenda-run-once agenda)))
713       (if (and stop-condition (stop-condition agenda))
714           'done
715           (let* ((agenda
716                   ;; We have to update the time after ports handled, too
717                   ;; because it may have changed after a select
718                   (set-field
719                    (handle-ports
720                     ;; Adjust the agenda's time just in time
721                     ;; We do this here rather than in agenda-run-once to make
722                     ;; agenda-run-once's behavior fairly predictable
723                     (set-field agenda (agenda-time) (get-time)))
724                    (agenda-time) (get-time))))
725             ;; Update the agenda's current queue based on
726             ;; currently applicable time segments
727             (add-segments-contents-to-queue!
728              (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
729              (agenda-queue agenda))
730             (loop agenda))))))
731
732 (define (print-error-and-continue key . args)
733   "Frequently used as pre-unwind-handler for agenda"
734   (cond
735    ((eq? key '8sync-caught-error)
736     (match args
737       ((orig-key orig-args stacks)
738        (display "\n*** Caught async exception. ***\n")
739        (format (current-error-port)
740                "* Original key '~s and arguments: ~s *\n"
741                orig-key orig-args)
742        (display "* Caught stacks below (ending with original) *\n\n")
743        (for-each
744         (lambda (s)
745           (display-backtrace s (current-error-port))
746           (newline (current-error-port)))
747         stacks))))
748    (else
749     (format (current-error-port)
750             "\n*** Caught exception with key '~s and arguments: ~s ***\n"
751             key args)
752     (display-backtrace (make-stack #t 1 0)
753                        (current-error-port))
754     (newline (current-error-port)))))
755
756 (define-syntax-rule (maybe-catch-all (catch-handler pre-unwind-handler)
757                                      body ...)
758   (if (or catch-handler pre-unwind-handler)
759       (catch
760         #t
761         (lambda ()
762           body ...)
763         (or catch-handler (lambda _ #f))
764         (or pre-unwind-handler (lambda _ #f)))
765       (begin body ...)))
766
767 (define (agenda-run-once agenda)
768   "Run once through the agenda, and produce a new agenda
769 based on the results"
770   (define (call-proc proc)
771     (call-with-prompt
772      (agenda-prompt-tag agenda)
773      (lambda ()
774        (parameterize ((%current-agenda agenda))
775          (maybe-catch-all
776           ((agenda-catch-handler agenda)
777            (agenda-pre-unwind-handler agenda))
778           (proc))))
779      (lambda (kont async-request)
780        (setup-async-request kont async-request))))
781
782   (let ((queue (agenda-queue agenda))
783         (next-queue (make-q)))
784     (while (not (q-empty? queue))
785       (let* ((proc (q-pop! queue))
786              (proc-result (call-proc proc))
787              (enqueue
788               (lambda (run-request)
789                 (define (schedule-at! time proc)
790                   (schedule-add! (agenda-schedule agenda) time proc))
791                 (let ((request-time (run-request-when run-request)))
792                   (match request-time
793                     ((? time-delta? time-delta)
794                      (let ((time (time-delta+ (agenda-time agenda)
795                                               time-delta)))
796                        (schedule-at! time (run-request-proc run-request))))
797                     ((? integer? sec)
798                      (let ((time (cons sec 0)))
799                        (schedule-at! time (run-request-proc run-request))))
800                     (((? integer? sec) . (? integer? usec))
801                      (schedule-at! request-time (run-request-proc run-request)))
802                     (#f
803                      (enq! next-queue (run-request-proc run-request))))))))
804         (define (handle-individual result)
805           (match result
806             ((? run-request? new-proc)
807              (enqueue new-proc))
808             ((? port-request? port-request)
809              (agenda-handle-port-request! agenda port-request))
810             ;; do nothing
811             (_ #f)))
812         ;; @@: We might support delay-wrapped procedures here
813         (match proc-result
814           ((results ...)
815            (for-each handle-individual results))
816           (one-result (handle-individual one-result)))))
817     ;; TODO: Alternately, we could return the next-queue
818     ;;   along with changes to be added to the schedule here?
819     ;; Return new agenda, with next queue set
820     (set-field agenda (agenda-queue) next-queue)))