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