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