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