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