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