better variable names for the run procedures
[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   (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-immutable-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-it proc #:optional when)
329   "Make a request to run PROC (possibly at WHEN)"
330   (make-run-request proc when))
331
332 (define-syntax-rule (wrap body ...)
333   "Wrap contents in a procedure"
334   (lambda ()
335     body ...))
336
337 (define-syntax-rule (run body ...)
338   "Run everything in BODY but wrap in a convenient procedure"
339   (make-run-request (wrap body ...) #f))
340
341 (define-syntax-rule (run-at body ... when)
342   "Run BODY at WHEN"
343   (make-run-request (wrap body ...) when))
344
345 (define-syntax-rule (run-delay body ... delay-time)
346   (make-run-request (wrap body ...) (tdelta delay-time)))
347
348 (define (delay run-request delay-time)
349   "Delay a RUN-REQUEST by DELAY-TIME"
350   (set-field run-request
351              (run-request-when)
352              (tdelta delay-time)))
353
354 \f
355 ;;; Execution of agenda, and current agenda
356 ;;; =======================================
357
358 (define %current-agenda (make-parameter #f))
359
360 (define (update-agenda-from-select! agenda)
361   (define (hash-keys hash)
362     (hash-map->list (lambda (k v) k) hash))
363   (define (get-wait-time)
364     ;; TODO: we need to figure this out based on whether there's anything
365     ;;   in the queue, and if not, how long till the next scheduled item
366     (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
367       (cond 
368        ((not (q-empty? (agenda-queue agenda)))
369         (cons 0 0))
370        (soonest-time    ; ie, the agenda is non-empty
371         (let* ((current-time (agenda-time agenda)))
372           (if (time<= soonest-time current-time)
373               ;; Well there's something due so let's select
374               ;; (this avoids a (possible?) race condition chance)
375               (cons 0 0)
376               (time-minus soonest-time current-time))))
377        (else
378         (cons #f #f)))))
379   (define (do-select)
380     ;; TODO: support usecond wait time too
381     (match (get-wait-time)
382       ((sec . usec)
383        (select (hash-keys (agenda-read-port-map agenda))
384                (hash-keys (agenda-write-port-map agenda))
385                (hash-keys (agenda-except-port-map agenda))
386                sec usec))))
387   (define (get-procs-to-run)
388     (define (ports->procs ports port-map)
389       (lambda (initial-procs)
390         (fold
391          (lambda (port prev)
392            (cons (lambda ()
393                    ((hash-ref port-map port) port))
394                  prev))
395          initial-procs
396          ports)))
397     (match (do-select)
398       ((read-ports write-ports except-ports)
399        ;; @@: Come on, we can do better than append ;P
400        ((compose (ports->procs
401                   read-ports
402                   (agenda-read-port-map agenda))
403                  (ports->procs
404                   write-ports
405                   (agenda-write-port-map agenda))
406                  (ports->procs
407                   except-ports
408                   (agenda-except-port-map agenda)))
409         '()))))
410   (define (update-agenda)
411     (let ((procs-to-run (get-procs-to-run))
412           (q (agenda-queue agenda)))
413       (for-each
414        (lambda (proc)
415          (enq! q proc))
416        procs-to-run))
417     agenda)
418   (define (ports-to-select?)
419     (define (has-items? selector)
420       ;; @@: O(n)
421       ;;    ... we could use hash-for-each and a continuation to jump
422       ;;    out with a #t at first indication of an item
423       (not (= (hash-count (const #t)
424                           (selector agenda))
425               0)))
426     (or (has-items? agenda-read-port-map)
427         (has-items? agenda-write-port-map)
428         (has-items? agenda-except-port-map)))
429
430   (if (ports-to-select?)
431       (update-agenda)
432       agenda))
433
434
435 (define* (start-agenda agenda
436                        #:key stop-condition
437                        (get-time gettimeofday)
438                        (handle-ports update-agenda-from-select!))
439   (let loop ((agenda agenda))
440     (let ((agenda   
441            ;; @@: Hm, maybe here would be a great place to handle
442            ;;   select'ing on ports.
443            ;;   We could compose over agenda-run-once and agenda-read-ports
444            (parameterize ((%current-agenda agenda))
445              (agenda-run-once agenda))))
446       (if (and stop-condition (stop-condition agenda))
447           'done
448           (let* ((agenda
449                   ;; We have to update the time after ports handled, too
450                   ;; because it may have changed after a select
451                   (set-field
452                    (handle-ports
453                     ;; Adjust the agenda's time just in time
454                     ;; We do this here rather than in agenda-run-once to make
455                     ;; agenda-run-once's behavior fairly predictable
456                     (set-field agenda (agenda-time) (get-time)))
457                    (agenda-time) (get-time))))
458             ;; Update the agenda's current queue based on
459             ;; currently applicable time segments
460             (add-segments-contents-to-queue!
461              (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
462              (agenda-queue agenda))
463             (loop agenda))))))
464
465 (define (agenda-run-once agenda)
466   "Run once through the agenda, and produce a new agenda
467 based on the results"
468   (define (call-proc proc)
469     (call-with-prompt
470         (agenda-prompt-tag agenda)
471       (lambda ()
472         (proc))
473       ;; TODO
474       (lambda (k) k)))
475
476   (let ((queue (agenda-queue agenda))
477         (next-queue (make-q)))
478     (while (not (q-empty? queue))
479       (let* ((proc (q-pop! queue))
480              (proc-result (call-proc proc))
481              (enqueue
482               (lambda (run-request)
483                 (define (schedule-at! time proc)
484                   (schedule-add! (agenda-schedule agenda) time proc))
485                 (let ((request-time (run-request-when run-request)))
486                   (match request-time
487                     ((? time-delta? time-delta)
488                      (let ((time (time-delta+ (agenda-time agenda)
489                                               time-delta)))
490                        (schedule-at! time (run-request-proc run-request))))
491                     ((? integer? sec)
492                      (let ((time (cons sec 0)))
493                        (schedule-at! time (run-request-proc run-request))))
494                     (((? integer? sec) . (? integer? usec))
495                      (schedule-at! request-time (run-request-proc run-request)))
496                     (#f
497                      (enq! next-queue (run-request-proc run-request))))))))
498         ;; @@: We might support delay-wrapped procedures here
499         (match proc-result
500           ;; TODO: replace procedure with something that indicates
501           ;;   intent to run.  Use a (run foo) procedure
502           ((? run-request? new-proc)
503            (enqueue new-proc))
504           (((? run-request? new-procs) ...)
505            (for-each
506             (lambda (new-proc)
507               (enqueue new-proc))
508             new-procs))
509           ;; do nothing
510           (_ #f))))
511     ;; TODO: Alternately, we could return the next-queue
512     ;;   along with changes to be added to the schedule here?
513     ;; Return new agenda, with next queue set
514     (set-field agenda (agenda-queue) next-queue)))