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