3c4270fa1ab99a1fe66c0d9e1801e2584755cc19
[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: Write (%run-immediately)
556
557 ;; TODO
558 (define-syntax-rule (%run-with-return return body ...)
559   (make-async-request
560    (lambda (kont)
561      (let ((return kont))
562        (lambda ()
563          body ...)))))
564
565 (define-syntax-rule (catch-8sync exp (handler-key handler) ...)
566   (catch '8sync-caught-error
567     (lambda ()
568       exp)
569     (lambda (_ orig-key orig-args orig-stacks)
570       (cond
571        ((or (eq? handler-key #t)
572             (eq? orig-key handler-key))
573         (apply handler orig-stacks orig-args)) ...
574        (else (raise '8sync-caught-error
575                     orig-key orig-args orig-stacks))))))
576
577 ;; Alias...?
578 (define-syntax-rule (catch-%8sync rest ...)
579   (catch-8sync rest ...))
580
581
582 \f
583 ;;; Execution of agenda, and current agenda
584 ;;; =======================================
585
586 (define %current-agenda (make-parameter #f))
587
588 (define (update-agenda-from-select! agenda)
589   "Potentially (select) on ports specified in agenda, adding items to queue"
590   (define (hash-keys hash)
591     (hash-map->list (lambda (k v) k) hash))
592   (define (get-wait-time)
593     ;; TODO: we need to figure this out based on whether there's anything
594     ;;   in the queue, and if not, how long till the next scheduled item
595     (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
596       (cond 
597        ((not (q-empty? (agenda-queue agenda)))
598         (cons 0 0))
599        (soonest-time    ; ie, the agenda is non-empty
600         (let* ((current-time (agenda-time agenda)))
601           (if (time<= soonest-time current-time)
602               ;; Well there's something due so let's select
603               ;; (this avoids a (possible?) race condition chance)
604               (cons 0 0)
605               (time-minus soonest-time current-time))))
606        (else
607         (cons #f #f)))))
608   (define (do-select)
609     ;; TODO: support usecond wait time too
610     (match (get-wait-time)
611       ((sec . usec)
612        (catch 'system-error
613          (lambda ()
614            (select (hash-keys (agenda-read-port-map agenda))
615                    (hash-keys (agenda-write-port-map agenda))
616                    (hash-keys (agenda-except-port-map agenda))
617                    sec usec))
618          (lambda (key . rest-args)
619            (match rest-args
620              ((_ _ _ (EINTR))
621               '(() () ()))
622              (_ (error "Unhandled error in select!" key rest-args))))))))
623   (define (get-procs-to-run)
624     (define (ports->procs ports port-map)
625       (lambda (initial-procs)
626         (fold
627          (lambda (port prev)
628            (cons (lambda ()
629                    ((hash-ref port-map port) port))
630                  prev))
631          initial-procs
632          ports)))
633     (match (do-select)
634       ((read-ports write-ports except-ports)
635        ;; @@: Come on, we can do better than append ;P
636        ((compose (ports->procs
637                   read-ports
638                   (agenda-read-port-map agenda))
639                  (ports->procs
640                   write-ports
641                   (agenda-write-port-map agenda))
642                  (ports->procs
643                   except-ports
644                   (agenda-except-port-map agenda)))
645         '()))))
646   (define (update-agenda)
647     (let ((procs-to-run (get-procs-to-run))
648           (q (agenda-queue agenda)))
649       (for-each
650        (lambda (proc)
651          (enq! q proc))
652        procs-to-run))
653     agenda)
654   (define (ports-to-select?)
655     (define (has-items? selector)
656       ;; @@: O(n)
657       ;;    ... we could use hash-for-each and a continuation to jump
658       ;;    out with a #t at first indication of an item
659       (not (= (hash-count (const #t)
660                           (selector agenda))
661               0)))
662     (or (has-items? agenda-read-port-map)
663         (has-items? agenda-write-port-map)
664         (has-items? agenda-except-port-map)))
665
666   (if (ports-to-select?)
667       (update-agenda)
668       agenda))
669
670 (define (agenda-handle-port-request! agenda port-request)
671   "Update an agenda for a port-request"
672   (define (handle-selector request-selector port-map-selector)
673     (if (request-selector port-request)
674         (hash-set! (port-map-selector agenda)
675                    (port-request-port port-request)
676                    (request-selector port-request))))
677   (handle-selector port-request-read agenda-read-port-map)
678   (handle-selector port-request-write agenda-write-port-map)
679   (handle-selector port-request-except agenda-except-port-map))
680
681
682 (define* (start-agenda agenda
683                        #:key stop-condition
684                        (get-time gettimeofday)
685                        (handle-ports update-agenda-from-select!))
686   ;; TODO: Document fields
687   "Start up the AGENDA"
688   (let loop ((agenda agenda))
689     (let ((agenda   
690            ;; @@: Hm, maybe here would be a great place to handle
691            ;;   select'ing on ports.
692            ;;   We could compose over agenda-run-once and agenda-read-ports
693            (agenda-run-once agenda)))
694       (if (and stop-condition (stop-condition agenda))
695           'done
696           (let* ((agenda
697                   ;; We have to update the time after ports handled, too
698                   ;; because it may have changed after a select
699                   (set-field
700                    (handle-ports
701                     ;; Adjust the agenda's time just in time
702                     ;; We do this here rather than in agenda-run-once to make
703                     ;; agenda-run-once's behavior fairly predictable
704                     (set-field agenda (agenda-time) (get-time)))
705                    (agenda-time) (get-time))))
706             ;; Update the agenda's current queue based on
707             ;; currently applicable time segments
708             (add-segments-contents-to-queue!
709              (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
710              (agenda-queue agenda))
711             (loop agenda))))))
712
713 (define (print-error-and-continue key . args)
714   "Frequently used as pre-unwind-handler for agenda"
715   (cond
716    ((eq? key '8sync-caught-error)
717     (match args
718       ((orig-key orig-args stacks)
719        (display "\n*** Caught async exception. ***\n")
720        (format (current-error-port)
721                "* Original key '~s and arguments: ~s *\n"
722                orig-key orig-args)
723        (display "* Caught stacks below (ending with original) *\n\n")
724        (for-each
725         (lambda (s)
726           (display-backtrace s (current-error-port))
727           (newline (current-error-port)))
728         stacks))))
729    (else
730     (format (current-error-port)
731             "\n*** Caught exception with key '~s and arguments: ~s ***\n"
732             key args)
733     (display-backtrace (make-stack #t 1 0)
734                        (current-error-port))
735     (newline (current-error-port)))))
736
737 (define-syntax-rule (maybe-catch-all (catch-handler pre-unwind-handler)
738                                      body ...)
739   (if (or catch-handler pre-unwind-handler)
740       (catch
741         #t
742         (lambda ()
743           body ...)
744         (or catch-handler (lambda _ #f))
745         (or pre-unwind-handler (lambda _ #f)))
746       (begin body ...)))
747
748 (define (agenda-run-once agenda)
749   "Run once through the agenda, and produce a new agenda
750 based on the results"
751   (define (call-proc proc)
752     (call-with-prompt
753      (agenda-prompt-tag agenda)
754      (lambda ()
755        (parameterize ((%current-agenda agenda))
756          (maybe-catch-all
757           ((agenda-catch-handler agenda)
758            (agenda-pre-unwind-handler agenda))
759           (proc))))
760      (lambda (kont async-request)
761        (setup-async-request kont async-request))))
762
763   (let ((queue (agenda-queue agenda))
764         (next-queue (make-q)))
765     (while (not (q-empty? queue))
766       (let* ((proc (q-pop! queue))
767              (proc-result (call-proc proc))
768              (enqueue
769               (lambda (run-request)
770                 (define (schedule-at! time proc)
771                   (schedule-add! (agenda-schedule agenda) time proc))
772                 (let ((request-time (run-request-when run-request)))
773                   (match request-time
774                     ((? time-delta? time-delta)
775                      (let ((time (time-delta+ (agenda-time agenda)
776                                               time-delta)))
777                        (schedule-at! time (run-request-proc run-request))))
778                     ((? integer? sec)
779                      (let ((time (cons sec 0)))
780                        (schedule-at! time (run-request-proc run-request))))
781                     (((? integer? sec) . (? integer? usec))
782                      (schedule-at! request-time (run-request-proc run-request)))
783                     (#f
784                      (enq! next-queue (run-request-proc run-request))))))))
785         (define (handle-individual result)
786           (match result
787             ((? run-request? new-proc)
788              (enqueue new-proc))
789             ((? port-request? port-request)
790              (agenda-handle-port-request! agenda port-request))
791             ;; do nothing
792             (_ #f)))
793         ;; @@: We might support delay-wrapped procedures here
794         (match proc-result
795           ((results ...)
796            (for-each handle-individual results))
797           (one-result (handle-individual one-result)))))
798     ;; TODO: Alternately, we could return the next-queue
799     ;;   along with changes to be added to the schedule here?
800     ;; Return new agenda, with next queue set
801     (set-field agenda (agenda-queue) next-queue)))