Oops, mixed up a car with a cdr, which is never wise :)
[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 wrap run-wrap run-wrap-at
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   (match time
114     ;; time is already a cons of second and microsecnd
115     (((? integer? s) . (? integer? u)) time)
116     ;; time was just an integer (just the second)
117     ((? integer? _) (cons time 0))
118     (_ (throw 'invalid-time "Invalid time" time))))
119
120 (define* (make-time-segment time #:optional (queue (make-q)))
121   (make-time-segment-intern time queue))
122
123 (define (time< time1 time2)
124   (cond ((< (car time1)
125             (car time2))
126          #t)
127         ((and (= (car time1)
128                  (car time2))
129               (< (cdr time1)
130                  (cdr time2)))
131          #t)
132         (else #f)))
133
134 (define (time= time1 time2)
135   (and (= (car time1) (car time2))
136        (= (cdr time1) (cdr time2))))
137
138 (define (time<= time1 time2)
139   (or (time< time1 time2)
140       (time= time1 time2)))
141
142
143 (define-record-type <time-delta>
144   (make-time-delta-intern sec usec)
145   time-delta?
146   (sec time-delta-sec)
147   (usec time-delta-usec))
148
149 (define* (make-time-delta sec #:optional usec)
150   (make-time-delta-intern sec (or usec 0)))
151
152 (define tdelta make-time-delta)
153
154 (define (time-carry-correct time)
155   "Corrects/handles time microsecond carry.
156 Will produce (0 . 0) instead of a negative number, if needed."
157   (cond ((>= (cdr time) 1000000)
158          (cons
159           (+ (car time) 1)
160           (- (cdr time) 1000000)))
161         ((< (cdr time) 0)
162          (if (= (car time) 0)
163              '(0 0)
164              (cons
165               (- (car time) 1)
166               (+ (cdr time) 1000000))))
167         (else time)))
168
169 (define (time-delta+ time time-delta)
170   (time-carry-correct
171    (cons (+ (car time) (time-delta-sec time-delta))
172          (+ (cdr time) (time-delta-usec time-delta)))))
173
174 (define (time-minus time1 time2)
175   (time-carry-correct
176    (cons (- (car time1) (car time2))
177          (- (cdr time2) (cdr time2)))))
178
179 (define (time-plus time1 time2)
180   (time-carry-correct
181    (cons (+ (car time1) (car time2))
182          (+ (cdr time2) (cdr time2)))))
183
184
185 (define-record-type <schedule>
186   (make-schedule-intern segments)
187   schedule?
188   (segments schedule-segments set-schedule-segments!))
189
190 (define* (make-schedule #:optional segments)
191   (make-schedule-intern (or segments '())))
192
193 (define (schedule-soonest-time schedule)
194   "Return a cons of (sec . usec) for next time segement, or #f if none"
195   (let ((segments (schedule-segments schedule)))
196     (if (eq? segments '())
197         #f
198         (time-segment-time (car segments)))))
199
200 ;; TODO: This code is reasonably easy to read but it
201 ;;   mutates AND is worst case of O(n) in both space and time :(
202 ;;   but at least it'll be reasonably easy to refactor to
203 ;;   a more functional setup?
204 (define (schedule-add! schedule time proc)
205   (let ((time (time-segment-right-format time)))
206     (define (new-time-segment)
207       (let ((new-segment
208              (make-time-segment time)))
209         (enq! (time-segment-queue new-segment) proc)
210         new-segment))
211     (define (loop segments)
212       (define (segment-equals-time? segment)
213         (time= time (time-segment-time segment)))
214
215       (define (segment-more-than-time? segment)
216         (time< time (time-segment-time segment)))
217
218       ;; We could switch this out to be more mutate'y
219       ;; and avoid the O(n) of space... is that over-optimizing?
220       (match segments
221         ;; If we're at the end of the list, time to make a new
222         ;; segment...
223         ('() (cons (new-time-segment) '()))
224         ;; If the segment's time is exactly our time, good news
225         ;; everyone!  Let's append our stuff to its queue
226         (((? segment-equals-time? first) rest ...)
227          (enq! (time-segment-queue first) proc)
228          segments)
229         ;; If the first segment is more than our time,
230         ;; ours belongs before this one, so add it and
231         ;; start consing our way back
232         (((? segment-more-than-time? first) rest ...)
233          (cons (new-time-segment) segments))
234         ;; Otherwise, build up recursive result
235         ((first rest ... )
236          (cons first (loop rest)))))
237     (set-schedule-segments!
238      schedule
239      (loop (schedule-segments schedule)))))
240
241 (define (schedule-empty? schedule)
242   (eq? (schedule-segments schedule) '()))
243
244 (define (schedule-segments-split schedule time)
245   "Does a multiple value return of time segments before/at and after TIME"
246   (let ((time (time-segment-right-format time)))
247     (define (segment-is-now? segment)
248       (time= (time-segment-time segment) time))
249     (define (segment-is-before-now? segment)
250       (time< (time-segment-time segment) time))
251
252     (let loop ((segments-before '())
253                (segments-left (schedule-segments schedule)))
254       (match segments-left
255         ;; end of the line, return
256         ('()
257          (values (reverse segments-before) '()))
258
259         ;; It's right now, so time to stop, but include this one in before
260         ;; but otherwise return
261         (((? segment-is-now? first) rest ...)
262          (values (reverse (cons first segments-before)) rest))
263
264         ;; This is prior or at now, so add it and keep going
265         (((? segment-is-before-now? first) rest ...)
266          (loop (cons first segments-before) rest))
267
268         ;; Otherwise it's past now, just return what we have
269         (segments-after
270          (values segments-before segments-after))))))
271
272 (define (schedule-extract-until! schedule time)
273   "Extract all segments until TIME from SCHEDULE, and pop old segments off"
274   (receive (segments-before segments-after)
275       (schedule-segments-split schedule time)
276     (set-schedule-segments! schedule segments-after)
277     segments-before))
278
279 (define (add-segments-contents-to-queue! segments queue)
280   (for-each
281    (lambda (segment)
282      (let ((seg-queue (time-segment-queue segment)))
283        (while (not (q-empty? seg-queue))
284          (enq! queue (deq! seg-queue)))))
285    segments))
286
287
288 \f
289 ;;; Port handling
290 ;;; =============
291
292 (define (make-port-mapping)
293   (make-hash-table))
294
295 (define* (port-mapping-set! port-mapping port #:optional read write except)
296   "Sets port-mapping for reader / writer / exception handlers"
297   (if (not (or read write except))
298       (throw 'no-handlers-given "No handlers given for port" port))
299   (hashq-set! port-mapping port
300               `#(,read ,write ,except)))
301
302 (define (port-mapping-remove! port-mapping port)
303   (hashq-remove! port-mapping port))
304
305 ;; TODO: This is O(n), I'm pretty sure :\
306 ;; ... it might be worthwhile for us to have a
307 ;;   port-mapping record that keeps a count of how many
308 ;;   handlers (maybe via a promise?)
309 (define (port-mapping-empty? port-mapping)
310   "Is this port mapping empty?"
311   (eq? (hash-count (const #t) port-mapping) 0))
312
313 (define (port-mapping-non-empty? port-mapping)
314   "Whether this port-mapping contains any elements"
315   (not (port-mapping-empty? port-mapping)))
316
317
318 \f
319 ;;; Request to run stuff
320 ;;; ====================
321
322 (define-record-type <run-request>
323   (make-run-request proc when)
324   run-request?
325   (proc run-request-proc)
326   (when run-request-when))
327
328 (define* (run proc #:optional when)
329   (make-run-request proc when))
330
331 (define-syntax-rule (wrap body ...)
332   (lambda ()
333     body ...))
334
335 (define-syntax-rule (run-wrap body ...)
336   (run (wrap body ...)))
337
338 (define-syntax-rule (run-wrap-at body ... when)
339   (run (wrap body ...) when))
340
341 \f
342 ;;; Execution of agenda, and current agenda
343 ;;; =======================================
344
345 (define %current-agenda (make-parameter #f))
346
347 (define (update-agenda-from-select! agenda)
348   (define (hash-keys hash)
349     (hash-map->list (lambda (k v) k) hash))
350   (define (get-wait-time)
351     ;; TODO: we need to figure this out based on whether there's anything
352     ;;   in the queue, and if not, how long till the next scheduled item
353     (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
354       (cond 
355        ((not (q-empty? (agenda-queue agenda)))
356         (cons 0 0))
357        (soonest-time    ; ie, the agenda is non-empty
358         (let* ((current-time (agenda-time agenda)))
359           (if (time<= soonest-time current-time)
360               ;; Well there's something due so let's select
361               ;; (this avoids a (possible?) race condition chance)
362               (cons 0 0)
363               (time-minus soonest-time current-time))))
364        (else
365         (cons #f #f)))))
366   (define (do-select)
367     ;; TODO: support usecond wait time too
368     (match (get-wait-time)
369       ((sec . usec)
370        (select (hash-keys (agenda-read-port-map agenda))
371                (hash-keys (agenda-write-port-map agenda))
372                (hash-keys (agenda-except-port-map agenda))
373                sec usec))))
374   (define (get-procs-to-run)
375     (define (ports->procs ports port-map)
376       (lambda (initial-procs)
377         (fold
378          (lambda (port prev)
379            (cons (lambda ()
380                    ((hash-ref port-map port) port))
381                  prev))
382          initial-procs
383          ports)))
384     (match (do-select)
385       ((read-ports write-ports except-ports)
386        ;; @@: Come on, we can do better than append ;P
387        ((compose (ports->procs
388                   read-ports
389                   (agenda-read-port-map agenda))
390                  (ports->procs
391                   write-ports
392                   (agenda-write-port-map agenda))
393                  (ports->procs
394                   except-ports
395                   (agenda-except-port-map agenda)))
396         '()))))
397   (define (update-agenda)
398     (let ((procs-to-run (get-procs-to-run))
399           (q (agenda-queue agenda)))
400       (for-each
401        (lambda (proc)
402          (enq! q proc))
403        procs-to-run))
404     agenda)
405   (define (ports-to-select?)
406     (define (has-items? selector)
407       ;; @@: O(n)
408       ;;    ... we could use hash-for-each and a continuation to jump
409       ;;    out with a #t at first indication of an item
410       (not (= (hash-count (const #t)
411                           (selector agenda))
412               0)))
413     (or (has-items? agenda-read-port-map)
414         (has-items? agenda-write-port-map)
415         (has-items? agenda-except-port-map)))
416
417   (if (ports-to-select?)
418       (update-agenda)
419       agenda))
420
421
422 (define* (start-agenda agenda
423                        #:key stop-condition
424                        (get-time gettimeofday)
425                        (handle-ports update-agenda-from-select!))
426   (let loop ((agenda agenda))
427     (let ((agenda   
428            ;; @@: Hm, maybe here would be a great place to handle
429            ;;   select'ing on ports.
430            ;;   We could compose over agenda-run-once and agenda-read-ports
431            (parameterize ((%current-agenda agenda))
432              (agenda-run-once agenda))))
433       (if (and stop-condition (stop-condition agenda))
434           'done
435           (let* ((new-time (get-time))
436                  (agenda
437                   (handle-ports
438                    ;; Adjust the agenda's time just in time
439                    ;; We do this here rather than in agenda-run-once to make
440                    ;; agenda-run-once's behavior fairly predictable
441                    (set-field agenda (agenda-time) new-time))))
442             ;; Update the agenda's current queue based on
443             ;; currently applicable time segments
444             (add-segments-contents-to-queue!
445              (schedule-extract-until! (agenda-schedule agenda) new-time)
446              (agenda-queue agenda))
447             (loop agenda))))))
448
449 (define (agenda-run-once agenda)
450   "Run once through the agenda, and produce a new agenda
451 based on the results"
452   (define (call-proc proc)
453     (call-with-prompt
454         (agenda-prompt-tag agenda)
455       (lambda ()
456         (proc))
457       ;; TODO
458       (lambda (k) k)))
459
460   (let ((queue (agenda-queue agenda))
461         (next-queue (make-q)))
462     (while (not (q-empty? queue))
463       (let* ((proc (q-pop! queue))
464              (proc-result (call-proc proc))
465              (enqueue
466               (lambda (run-request)
467                 (define (schedule-at! time proc)
468                   (schedule-add! (agenda-schedule agenda) time proc))
469                 (let ((request-time (run-request-when run-request)))
470                   (match request-time
471                     ((? time-delta? time-delta)
472                      (let ((time (time-delta+ (agenda-time agenda)
473                                               time-delta)))
474                        (schedule-at! time (run-request-proc run-request))))
475                     ((? integer? sec)
476                      (let ((time (cons sec 0)))
477                        (schedule-at! time (run-request-proc run-request))))
478                     (((? integer? sec) . (? integer? usec))
479                      (schedule-at! request-time (run-request-proc run-request)))
480                     (#f
481                      (enq! next-queue (run-request-proc run-request))))))))
482         ;; @@: We might support delay-wrapped procedures here
483         (match proc-result
484           ;; TODO: replace procedure with something that indicates
485           ;;   intent to run.  Use a (run foo) procedure
486           ((? run-request? new-proc)
487            (enqueue new-proc))
488           (((? run-request? new-procs) ...)
489            (for-each
490             (lambda (new-proc)
491               (enqueue new-proc))
492             new-procs))
493           ;; do nothing
494           (_ #f))))
495     ;; TODO: Alternately, we could return the next-queue
496     ;;   along with changes to be added to the schedule here?
497     ;; Return new agenda, with next queue set
498     (set-field agenda (agenda-queue) next-queue)))