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