add 8sync aliases and export 'em. Also, we're 8sync/eightsync now!
[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-immutable-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 \f
363 ;;; Asynchronous escape to run things
364 ;;; =================================
365
366 ;; The future's in futures
367
368 (define (make-future call-first on-success on-fail on-error)
369   ;; TODO: add error stuff here
370   (lambda ()
371     (let ((call-result (call-first)))
372       ;; queue up calling the 
373       (run (on-success call-result)))))
374
375 (define (agenda-on-error agenda)
376   (const #f))
377
378 (define (agenda-on-fail agenda)
379   (const #f))
380
381 (define* (request-future call-first on-success
382                          #:key
383                          (agenda (%current-agenda))
384                          (on-fail (agenda-on-fail agenda))
385                          (on-error (agenda-on-error agenda))  
386                          (when #f))
387   ;; TODO: error handling
388   ;; do we need some distinction between expected, catchable errors,
389   ;; and unexpected, uncatchable ones?  Probably...?
390   (make-run-request
391    (make-future call-first on-success on-fail on-error)
392    when))
393
394 (define-syntax-rule (%sync body args ...)
395   "Run BODY asynchronously at a prompt, passing args to make-future.
396
397 Pronounced `async' despite the spelling.
398
399 %sync was chosen because (async) was already taken and could lead to
400 errors, and this version of asynchronous code uses a prompt, so the `a'
401 character becomes a `%' prompt! :)
402
403 The % and 8 characters kind of look similar... hence this library's
404 name!  (There are 8sync aliases if you prefer that name.)"
405   (abort-to-prompt (current-agenda-prompt)
406                    (wrap body)
407                    args ...))
408
409 (define-syntax-rule (%sync-at body when args ...)
410   (abort-to-prompt (current-agenda-prompt)
411                    (wrap body)
412                    #:when when
413                    args ...))
414
415 (define-syntax-rule (%sync-delay body delay-time args ...)
416   (abort-to-prompt (current-agenda-prompt)
417                    (wrap body)
418                    #:when (tdelta delay-time)
419                    args ...))
420
421 (define-syntax-rule (8sync args ...)
422   "Alias for %sync"
423   (%sync args ...))
424
425 (define-syntax-rule (8sync-at args ...)
426   "Alias for %sync-at"
427   (%sync-at args ...))
428
429 (define-syntax-rule (8sync-delay args ...)
430   "Alias for %sync-delay"
431   (8sync-delay args ...))
432
433
434 \f
435 ;;; Execution of agenda, and current agenda
436 ;;; =======================================
437
438 (define %current-agenda (make-parameter #f))
439
440 (define (update-agenda-from-select! agenda)
441   "Potentially (select) on ports specified in agenda, adding items to queue"
442   (define (hash-keys hash)
443     (hash-map->list (lambda (k v) k) hash))
444   (define (get-wait-time)
445     ;; TODO: we need to figure this out based on whether there's anything
446     ;;   in the queue, and if not, how long till the next scheduled item
447     (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
448       (cond 
449        ((not (q-empty? (agenda-queue agenda)))
450         (cons 0 0))
451        (soonest-time    ; ie, the agenda is non-empty
452         (let* ((current-time (agenda-time agenda)))
453           (if (time<= soonest-time current-time)
454               ;; Well there's something due so let's select
455               ;; (this avoids a (possible?) race condition chance)
456               (cons 0 0)
457               (time-minus soonest-time current-time))))
458        (else
459         (cons #f #f)))))
460   (define (do-select)
461     ;; TODO: support usecond wait time too
462     (match (get-wait-time)
463       ((sec . usec)
464        (select (hash-keys (agenda-read-port-map agenda))
465                (hash-keys (agenda-write-port-map agenda))
466                (hash-keys (agenda-except-port-map agenda))
467                sec usec))))
468   (define (get-procs-to-run)
469     (define (ports->procs ports port-map)
470       (lambda (initial-procs)
471         (fold
472          (lambda (port prev)
473            (cons (lambda ()
474                    ((hash-ref port-map port) port))
475                  prev))
476          initial-procs
477          ports)))
478     (match (do-select)
479       ((read-ports write-ports except-ports)
480        ;; @@: Come on, we can do better than append ;P
481        ((compose (ports->procs
482                   read-ports
483                   (agenda-read-port-map agenda))
484                  (ports->procs
485                   write-ports
486                   (agenda-write-port-map agenda))
487                  (ports->procs
488                   except-ports
489                   (agenda-except-port-map agenda)))
490         '()))))
491   (define (update-agenda)
492     (let ((procs-to-run (get-procs-to-run))
493           (q (agenda-queue agenda)))
494       (for-each
495        (lambda (proc)
496          (enq! q proc))
497        procs-to-run))
498     agenda)
499   (define (ports-to-select?)
500     (define (has-items? selector)
501       ;; @@: O(n)
502       ;;    ... we could use hash-for-each and a continuation to jump
503       ;;    out with a #t at first indication of an item
504       (not (= (hash-count (const #t)
505                           (selector agenda))
506               0)))
507     (or (has-items? agenda-read-port-map)
508         (has-items? agenda-write-port-map)
509         (has-items? agenda-except-port-map)))
510
511   (if (ports-to-select?)
512       (update-agenda)
513       agenda))
514
515
516 (define* (start-agenda agenda
517                        #:key stop-condition
518                        (get-time gettimeofday)
519                        (handle-ports update-agenda-from-select!))
520   ;; TODO: Document fields
521   "Start up the AGENDA"
522   (let loop ((agenda agenda))
523     (let ((agenda   
524            ;; @@: Hm, maybe here would be a great place to handle
525            ;;   select'ing on ports.
526            ;;   We could compose over agenda-run-once and agenda-read-ports
527            (parameterize ((%current-agenda agenda))
528              (agenda-run-once agenda))))
529       (if (and stop-condition (stop-condition agenda))
530           'done
531           (let* ((agenda
532                   ;; We have to update the time after ports handled, too
533                   ;; because it may have changed after a select
534                   (set-field
535                    (handle-ports
536                     ;; Adjust the agenda's time just in time
537                     ;; We do this here rather than in agenda-run-once to make
538                     ;; agenda-run-once's behavior fairly predictable
539                     (set-field agenda (agenda-time) (get-time)))
540                    (agenda-time) (get-time))))
541             ;; Update the agenda's current queue based on
542             ;; currently applicable time segments
543             (add-segments-contents-to-queue!
544              (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
545              (agenda-queue agenda))
546             (loop agenda))))))
547
548 (define (agenda-run-once agenda)
549   "Run once through the agenda, and produce a new agenda
550 based on the results"
551   (define (call-proc proc)
552     (call-with-prompt
553         (agenda-prompt-tag agenda)
554       (lambda ()
555         (proc))
556       (lambda* (resume-with please-run-this . args)
557         (apply request-future please-run-this resume-with
558                args))))
559
560   (let ((queue (agenda-queue agenda))
561         (next-queue (make-q)))
562     (while (not (q-empty? queue))
563       (let* ((proc (q-pop! queue))
564              (proc-result (call-proc proc))
565              (enqueue
566               (lambda (run-request)
567                 (define (schedule-at! time proc)
568                   (schedule-add! (agenda-schedule agenda) time proc))
569                 (let ((request-time (run-request-when run-request)))
570                   (match request-time
571                     ((? time-delta? time-delta)
572                      (let ((time (time-delta+ (agenda-time agenda)
573                                               time-delta)))
574                        (schedule-at! time (run-request-proc run-request))))
575                     ((? integer? sec)
576                      (let ((time (cons sec 0)))
577                        (schedule-at! time (run-request-proc run-request))))
578                     (((? integer? sec) . (? integer? usec))
579                      (schedule-at! request-time (run-request-proc run-request)))
580                     (#f
581                      (enq! next-queue (run-request-proc run-request))))))))
582         ;; @@: We might support delay-wrapped procedures here
583         (match proc-result
584           ;; TODO: replace procedure with something that indicates
585           ;;   intent to run.  Use a (run foo) procedure
586           ((? run-request? new-proc)
587            (enqueue new-proc))
588           (((? run-request? new-procs) ...)
589            (for-each
590             (lambda (new-proc)
591               (enqueue new-proc))
592             new-procs))
593           ;; do nothing
594           (_ #f))))
595     ;; TODO: Alternately, we could return the next-queue
596     ;;   along with changes to be added to the schedule here?
597     ;; Return new agenda, with next queue set
598     (set-field agenda (agenda-queue) next-queue)))