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