future -> futurists?????
[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 ;; @@: ... kinda conflicts with ice-9 futures.  Should we rename
440 ;;   to "futurists"? :)
441
442 (define (make-future call-first on-success on-fail on-error)
443   ;; TODO: add error stuff here
444   (lambda ()
445     (let ((call-result (call-first)))
446       ;; queue up calling the 
447       (run (on-success call-result)))))
448
449 (define (agenda-on-error agenda)
450   (const #f))
451
452 (define (agenda-on-fail agenda)
453   (const #f))
454
455 (define* (request-future call-first on-success
456                          #:key
457                          (agenda (%current-agenda))
458                          (on-fail (agenda-on-fail agenda))
459                          (on-error (agenda-on-error agenda))  
460                          (when #f))
461   ;; TODO: error handling
462   ;; do we need some distinction between expected, catchable errors,
463   ;; and unexpected, uncatchable ones?  Probably...?
464   (make-run-request
465    (make-future call-first on-success on-fail on-error)
466    when))
467
468 (define-syntax-rule (%8sync async-request)
469   "Run BODY asynchronously at a prompt, passing args to make-future.
470
471 Runs things asynchronously (8synchronously?)"
472   (abort-to-prompt (current-agenda-prompt)
473                    async-request))
474
475 ;; Async port request and run-request meta-requests
476 (define (make-async-request proc)
477   "Wrap PROC in an async-request
478
479 The purpose of this is to make sure that users don't accidentally
480 return the wrong thing via (%8sync) and trip themselves up."
481   (cons '*async-request* proc))
482
483 (define (setup-async-request resume-kont async-request)
484   "Complete an async request for agenda-run-once's continuation handling"
485   (match async-request
486     (('*async-request* . async-setup-proc)
487      (async-setup-proc resume-kont))
488     ;; TODO: deliver more helpful errors depending on what the user
489     ;;   returned
490     (_ (throw 'invalid-async-request
491               "Invalid request passed back via an (%8sync) procedure."
492               async-request))))
493
494 (define-syntax-rule (%run body ...)
495   (%run-at body ... #f))
496
497 (define-syntax-rule (%run-at body ... when)
498   (make-async-request
499    (lambda (kont)
500      (make-run-request
501       (wrap
502        (kont
503         (begin body ...)))
504       when))))
505
506 (define-syntax-rule (%run-delay body ... delay-time)
507   (%run-at body ... (tdelta delay-time)))
508
509 (define-syntax-rule (%port-request add-this-port port-request-args ...)
510   (make-async-request
511    (lambda (kont)
512      (list (make-port-request port-request-args ...)
513            (make-run-request kont)))))
514
515 ;; TODO
516 (define-syntax-rule (%run-with-return return body ...)
517   (make-async-request
518    (lambda (kont)
519      (let ((return kont))
520        (lambda ()
521          body ...)))))
522
523 ;; Aliases
524 (define-syntax-rule (8run args ...) (%run args ...))
525 (define-syntax-rule (8run-at args ...) (%run-at args ...))
526 (define-syntax-rule (8run-delay args ...) (%run-delay args ...))
527 (define-syntax-rule (8port-request args ...) (%port-request args ...))
528
529
530 \f
531 ;;; Execution of agenda, and current agenda
532 ;;; =======================================
533
534 (define %current-agenda (make-parameter #f))
535
536 (define (update-agenda-from-select! agenda)
537   "Potentially (select) on ports specified in agenda, adding items to queue"
538   (define (hash-keys hash)
539     (hash-map->list (lambda (k v) k) hash))
540   (define (get-wait-time)
541     ;; TODO: we need to figure this out based on whether there's anything
542     ;;   in the queue, and if not, how long till the next scheduled item
543     (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
544       (cond 
545        ((not (q-empty? (agenda-queue agenda)))
546         (cons 0 0))
547        (soonest-time    ; ie, the agenda is non-empty
548         (let* ((current-time (agenda-time agenda)))
549           (if (time<= soonest-time current-time)
550               ;; Well there's something due so let's select
551               ;; (this avoids a (possible?) race condition chance)
552               (cons 0 0)
553               (time-minus soonest-time current-time))))
554        (else
555         (cons #f #f)))))
556   (define (do-select)
557     ;; TODO: support usecond wait time too
558     (match (get-wait-time)
559       ((sec . usec)
560        (catch 'system-error
561          (lambda ()
562            (select (hash-keys (agenda-read-port-map agenda))
563                    (hash-keys (agenda-write-port-map agenda))
564                    (hash-keys (agenda-except-port-map agenda))
565                    sec usec))
566          (lambda (key . rest-args)
567            (match rest-args
568              ((_ _ _ (EINTR))
569               '(() () ()))
570              (_ (error "Unhandled error in select!" key rest-args))))))))
571   (define (get-procs-to-run)
572     (define (ports->procs ports port-map)
573       (lambda (initial-procs)
574         (fold
575          (lambda (port prev)
576            (cons (lambda ()
577                    ((hash-ref port-map port) port))
578                  prev))
579          initial-procs
580          ports)))
581     (match (do-select)
582       ((read-ports write-ports except-ports)
583        ;; @@: Come on, we can do better than append ;P
584        ((compose (ports->procs
585                   read-ports
586                   (agenda-read-port-map agenda))
587                  (ports->procs
588                   write-ports
589                   (agenda-write-port-map agenda))
590                  (ports->procs
591                   except-ports
592                   (agenda-except-port-map agenda)))
593         '()))))
594   (define (update-agenda)
595     (let ((procs-to-run (get-procs-to-run))
596           (q (agenda-queue agenda)))
597       (for-each
598        (lambda (proc)
599          (enq! q proc))
600        procs-to-run))
601     agenda)
602   (define (ports-to-select?)
603     (define (has-items? selector)
604       ;; @@: O(n)
605       ;;    ... we could use hash-for-each and a continuation to jump
606       ;;    out with a #t at first indication of an item
607       (not (= (hash-count (const #t)
608                           (selector agenda))
609               0)))
610     (or (has-items? agenda-read-port-map)
611         (has-items? agenda-write-port-map)
612         (has-items? agenda-except-port-map)))
613
614   (if (ports-to-select?)
615       (update-agenda)
616       agenda))
617
618 (define (agenda-handle-port-request! agenda port-request)
619   "Update an agenda for a port-request"
620   (define (handle-selector request-selector port-map-selector)
621     (if (request-selector port-request)
622         (hash-set! (port-map-selector agenda)
623                    (port-request-port port-request)
624                    (request-selector port-request))))
625   (handle-selector port-request-read agenda-read-port-map)
626   (handle-selector port-request-write agenda-write-port-map)
627   (handle-selector port-request-except agenda-except-port-map))
628
629
630 (define* (start-agenda agenda
631                        #:key stop-condition
632                        (get-time gettimeofday)
633                        (handle-ports update-agenda-from-select!))
634   ;; TODO: Document fields
635   "Start up the AGENDA"
636   (let loop ((agenda agenda))
637     (let ((agenda   
638            ;; @@: Hm, maybe here would be a great place to handle
639            ;;   select'ing on ports.
640            ;;   We could compose over agenda-run-once and agenda-read-ports
641            (agenda-run-once agenda)))
642       (if (and stop-condition (stop-condition agenda))
643           'done
644           (let* ((agenda
645                   ;; We have to update the time after ports handled, too
646                   ;; because it may have changed after a select
647                   (set-field
648                    (handle-ports
649                     ;; Adjust the agenda's time just in time
650                     ;; We do this here rather than in agenda-run-once to make
651                     ;; agenda-run-once's behavior fairly predictable
652                     (set-field agenda (agenda-time) (get-time)))
653                    (agenda-time) (get-time))))
654             ;; Update the agenda's current queue based on
655             ;; currently applicable time segments
656             (add-segments-contents-to-queue!
657              (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
658              (agenda-queue agenda))
659             (loop agenda))))))
660
661 (define (print-error-and-continue . args)
662   "Frequently used as pre-unwind-handler for agenda"
663   (format (current-error-port) "\n*** Caught exception with arguments: ~s ***\n"
664           args)
665   (display-backtrace (make-stack #t 1 0)
666                      (current-error-port))
667   (newline (current-error-port)))
668
669 (define-syntax-rule (maybe-catch-all (catch-handler pre-unwind-handler)
670                                      body ...)
671   (if (or catch-handler pre-unwind-handler)
672       (catch
673         #t
674         (lambda ()
675           body ...)
676         (or catch-handler (lambda _ #f))
677         (or pre-unwind-handler (lambda _ #f)))
678       (begin body ...)))
679
680 (define (agenda-run-once agenda)
681   "Run once through the agenda, and produce a new agenda
682 based on the results"
683   (define (call-proc proc)
684     (call-with-prompt
685      (agenda-prompt-tag agenda)
686      (lambda ()
687        (parameterize ((%current-agenda agenda))
688          (maybe-catch-all
689           ((agenda-catch-handler agenda)
690            (agenda-pre-unwind-handler agenda))
691           (proc))))
692      (lambda (kont async-request)
693        (setup-async-request kont async-request))))
694
695   (let ((queue (agenda-queue agenda))
696         (next-queue (make-q)))
697     (while (not (q-empty? queue))
698       (let* ((proc (q-pop! queue))
699              (proc-result (call-proc proc))
700              (enqueue
701               (lambda (run-request)
702                 (define (schedule-at! time proc)
703                   (schedule-add! (agenda-schedule agenda) time proc))
704                 (let ((request-time (run-request-when run-request)))
705                   (match request-time
706                     ((? time-delta? time-delta)
707                      (let ((time (time-delta+ (agenda-time agenda)
708                                               time-delta)))
709                        (schedule-at! time (run-request-proc run-request))))
710                     ((? integer? sec)
711                      (let ((time (cons sec 0)))
712                        (schedule-at! time (run-request-proc run-request))))
713                     (((? integer? sec) . (? integer? usec))
714                      (schedule-at! request-time (run-request-proc run-request)))
715                     (#f
716                      (enq! next-queue (run-request-proc run-request))))))))
717         (define (handle-individual result)
718           (match result
719             ((? run-request? new-proc)
720              (enqueue new-proc))
721             ((? port-request? port-request)
722              (agenda-handle-port-request! agenda port-request))
723             ;; do nothing
724             (_ #f)))
725         ;; @@: We might support delay-wrapped procedures here
726         (match proc-result
727           ((results ...)
728            (for-each handle-individual results))
729           (one-result (handle-individual one-result)))))
730     ;; TODO: Alternately, we could return the next-queue
731     ;;   along with changes to be added to the schedule here?
732     ;; Return new agenda, with next queue set
733     (set-field agenda (agenda-queue) next-queue)))