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