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