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