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