Remove unused %sync-foo operators, shift parameterization to right before call
[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
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 async-request)
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                    async-request))
435
436 (define-syntax-rule (8sync args ...)
437   "Alias for %sync"
438   (%sync args ...))
439
440 ;; Async port request and run-request meta-requests
441 (define (make-async-request proc)
442   "Wrap PROC in an async-request
443
444 The purpose of this is to make sure that users don't accidentally
445 return the wrong thing via (8sync) and trip themselves up."
446   (cons '*async-request* proc))
447
448 (define (setup-async-request resume-kont async-request)
449   "Complete an async request for agenda-run-once's continuation handling"
450   (match async-request
451     (('*async-request* . async-setup-proc)
452      (async-setup-proc resume-kont))
453     ;; TODO: deliver more helpful errors depending on what the user
454     ;;   returned
455     (_ (throw 'invalid-async-request
456               "Invalid request passed back via an (%sync) procedure."
457               async-request))))
458
459 (define-syntax-rule (%run body ...)
460   (%run-at body ... #f))
461
462 (define-syntax-rule (%run-at body ... when)
463   (make-async-request
464    (lambda (kont)
465      (make-run-request
466       (wrap
467        (kont
468         (begin body ...)))
469       when))))
470
471 (define-syntax-rule (%run-delay body ... delay-time)
472   (%run-at body ... (tdelta delay-time)))
473
474 (define-syntax-rule (%port-request add-this-port port-request-args ...)
475   (make-async-request
476    (lambda (kont)
477      (list (make-port-request port-request-args ...)
478            (make-run-request kont)))))
479
480 ;; TODO
481 (define-syntax-rule (%run-with-return return body ...)
482   (make-async-request
483    (lambda (kont)
484      (let ((return kont))
485        (lambda ()
486          body ...)))))
487
488 ;; Aliases
489 (define-syntax-rule (8run args ...) (%run args ...))
490 (define-syntax-rule (8run-at args ...) (%run-at args ...))
491 (define-syntax-rule (8run-delay args ...) (%run-delay args ...))
492 (define-syntax-rule (8port-request args ...) (%port-request args ...))
493
494
495 \f
496 ;;; Execution of agenda, and current agenda
497 ;;; =======================================
498
499 (define %current-agenda (make-parameter #f))
500
501 (define (update-agenda-from-select! agenda)
502   "Potentially (select) on ports specified in agenda, adding items to queue"
503   (define (hash-keys hash)
504     (hash-map->list (lambda (k v) k) hash))
505   (define (get-wait-time)
506     ;; TODO: we need to figure this out based on whether there's anything
507     ;;   in the queue, and if not, how long till the next scheduled item
508     (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
509       (cond 
510        ((not (q-empty? (agenda-queue agenda)))
511         (cons 0 0))
512        (soonest-time    ; ie, the agenda is non-empty
513         (let* ((current-time (agenda-time agenda)))
514           (if (time<= soonest-time current-time)
515               ;; Well there's something due so let's select
516               ;; (this avoids a (possible?) race condition chance)
517               (cons 0 0)
518               (time-minus soonest-time current-time))))
519        (else
520         (cons #f #f)))))
521   (define (do-select)
522     ;; TODO: support usecond wait time too
523     (match (get-wait-time)
524       ((sec . usec)
525        (select (hash-keys (agenda-read-port-map agenda))
526                (hash-keys (agenda-write-port-map agenda))
527                (hash-keys (agenda-except-port-map agenda))
528                sec usec))))
529   (define (get-procs-to-run)
530     (define (ports->procs ports port-map)
531       (lambda (initial-procs)
532         (fold
533          (lambda (port prev)
534            (cons (lambda ()
535                    ((hash-ref port-map port) port))
536                  prev))
537          initial-procs
538          ports)))
539     (match (do-select)
540       ((read-ports write-ports except-ports)
541        ;; @@: Come on, we can do better than append ;P
542        ((compose (ports->procs
543                   read-ports
544                   (agenda-read-port-map agenda))
545                  (ports->procs
546                   write-ports
547                   (agenda-write-port-map agenda))
548                  (ports->procs
549                   except-ports
550                   (agenda-except-port-map agenda)))
551         '()))))
552   (define (update-agenda)
553     (let ((procs-to-run (get-procs-to-run))
554           (q (agenda-queue agenda)))
555       (for-each
556        (lambda (proc)
557          (enq! q proc))
558        procs-to-run))
559     agenda)
560   (define (ports-to-select?)
561     (define (has-items? selector)
562       ;; @@: O(n)
563       ;;    ... we could use hash-for-each and a continuation to jump
564       ;;    out with a #t at first indication of an item
565       (not (= (hash-count (const #t)
566                           (selector agenda))
567               0)))
568     (or (has-items? agenda-read-port-map)
569         (has-items? agenda-write-port-map)
570         (has-items? agenda-except-port-map)))
571
572   (if (ports-to-select?)
573       (update-agenda)
574       agenda))
575
576 (define (agenda-handle-port-request! agenda port-request)
577   "Update an agenda for a port-request"
578   (define (handle-selector request-selector port-map-selector)
579     (if (request-selector port-request)
580         (hash-set! (port-map-selector agenda)
581                    (port-request-port port-request)
582                    (request-selector port-request))))
583   (handle-selector port-request-read agenda-read-port-map)
584   (handle-selector port-request-write agenda-write-port-map)
585   (handle-selector port-request-except agenda-except-port-map))
586
587
588 (define* (start-agenda agenda
589                        #:key stop-condition
590                        (get-time gettimeofday)
591                        (handle-ports update-agenda-from-select!))
592   ;; TODO: Document fields
593   "Start up the AGENDA"
594   (let loop ((agenda agenda))
595     (let ((agenda   
596            ;; @@: Hm, maybe here would be a great place to handle
597            ;;   select'ing on ports.
598            ;;   We could compose over agenda-run-once and agenda-read-ports
599            (agenda-run-once agenda)))
600       (if (and stop-condition (stop-condition agenda))
601           'done
602           (let* ((agenda
603                   ;; We have to update the time after ports handled, too
604                   ;; because it may have changed after a select
605                   (set-field
606                    (handle-ports
607                     ;; Adjust the agenda's time just in time
608                     ;; We do this here rather than in agenda-run-once to make
609                     ;; agenda-run-once's behavior fairly predictable
610                     (set-field agenda (agenda-time) (get-time)))
611                    (agenda-time) (get-time))))
612             ;; Update the agenda's current queue based on
613             ;; currently applicable time segments
614             (add-segments-contents-to-queue!
615              (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
616              (agenda-queue agenda))
617             (loop agenda))))))
618
619 (define (agenda-run-once agenda)
620   "Run once through the agenda, and produce a new agenda
621 based on the results"
622   (define (call-proc proc)
623     (call-with-prompt
624      (agenda-prompt-tag agenda)
625      (lambda ()
626        (parameterize ((%current-agenda agenda))
627          (proc)))
628      (lambda (kont async-request)
629        (setup-async-request kont async-request))))
630
631   (let ((queue (agenda-queue agenda))
632         (next-queue (make-q)))
633     (while (not (q-empty? queue))
634       (let* ((proc (q-pop! queue))
635              (proc-result (call-proc proc))
636              (enqueue
637               (lambda (run-request)
638                 (define (schedule-at! time proc)
639                   (schedule-add! (agenda-schedule agenda) time proc))
640                 (let ((request-time (run-request-when run-request)))
641                   (match request-time
642                     ((? time-delta? time-delta)
643                      (let ((time (time-delta+ (agenda-time agenda)
644                                               time-delta)))
645                        (schedule-at! time (run-request-proc run-request))))
646                     ((? integer? sec)
647                      (let ((time (cons sec 0)))
648                        (schedule-at! time (run-request-proc run-request))))
649                     (((? integer? sec) . (? integer? usec))
650                      (schedule-at! request-time (run-request-proc run-request)))
651                     (#f
652                      (enq! next-queue (run-request-proc run-request))))))))
653         (define (handle-individual result)
654           (match result
655             ((? run-request? new-proc)
656              (enqueue new-proc))
657             ((? port-request? port-request)
658              (agenda-handle-port-request! agenda port-request))
659             ;; do nothing
660             (_ #f)))
661         ;; @@: We might support delay-wrapped procedures here
662         (match proc-result
663           ((results ...)
664            (for-each handle-individual results))
665           (one-result (handle-individual one-result)))))
666     ;; TODO: Alternately, we could return the next-queue
667     ;;   along with changes to be added to the schedule here?
668     ;; Return new agenda, with next queue set
669     (set-field agenda (agenda-queue) next-queue)))