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