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