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