1 (define-module (eightsync agenda)
2 #:use-module (srfi srfi-1)
3 #:use-module (srfi srfi-9)
4 #:use-module (srfi srfi-9 gnu)
6 #:use-module (ice-9 match)
7 #:use-module (ice-9 receive)
10 agenda-queue agenda-prompt-tag
11 agenda-read-port-map agenda-write-port-map agenda-except-port-map
17 make-time-segment time-segment?
18 time-segment-time time-segment-queue
20 time< time= time<= time-delta+
24 make-time-delta tdelta time-delta?
25 time-delta-sec time-delta-usec
28 make-schedule schedule?
29 schedule-add! schedule-empty?
33 schedule-segments-split schedule-extract-until!
34 add-segments-contents-to-queue!
39 make-run-request run-request?
40 run-request-proc run-request-when
43 make-port-request port-request port-request?
45 port-request-read port-request-write port-request-except
47 run-it wrap run run-at run-delay
49 %port-request %run %run-at %run-delay
50 8port-request 8run 8run-at 8run-delay
53 start-agenda agenda-run-once))
55 ;; @@: Using immutable agendas here, so wouldn't it make sense to
56 ;; replace this queue stuff with using pfds based immutable queues?
62 ;;; The agenda consists of:
63 ;;; - a queue of immediate items to handle
64 ;;; - sheduled future events to be added to a future queue
65 ;;; - a tag by which running processes can escape for some asynchronous
66 ;;; operation (from which they can be returned later)
67 ;;; - a mapping of ports to various handler procedures
69 ;;; The goal, eventually, is for this all to be immutable and functional.
70 ;;; However, we aren't there yet. Some tricky things:
71 ;;; - The schedule needs to be immutable, yet reasonably efficient.
72 ;;; - Need to use immutable queues (ijp's pfds library?)
73 ;;; - Modeling reading from ports as something repeatable,
74 ;;; and with reasonable separation from functional components?
76 (define-immutable-record-type <agenda>
77 (make-agenda-intern queue prompt-tag
78 read-port-map write-port-map except-port-map
82 (prompt-tag agenda-prompt-tag)
83 (read-port-map agenda-read-port-map)
84 (write-port-map agenda-write-port-map)
85 (except-port-map agenda-except-port-map)
86 (schedule agenda-schedule)
89 (define (make-async-prompt-tag)
90 "Make an async prompt tag for an agenda.
92 Generally done automatically for the user through (make-agenda)."
93 (make-prompt-tag "prompt"))
95 (define* (make-agenda #:key
97 (prompt (make-prompt-tag))
98 (read-port-map (make-hash-table))
99 (write-port-map (make-hash-table))
100 (except-port-map (make-hash-table))
101 (schedule (make-schedule))
102 (time (gettimeofday)))
103 ;; TODO: document arguments
104 "Make a fresh agenda."
105 (make-agenda-intern queue prompt
106 read-port-map write-port-map except-port-map
109 (define (current-agenda-prompt)
110 "Get the prompt for the current agenda; signal an error if there isn't one."
111 (let ((current-agenda (%current-agenda)))
112 (if (not current-agenda)
115 "Can't get current agenda prompt if there's no current agenda!")
116 (agenda-prompt-tag current-agenda))))
123 ;;; This is where we handle timed events for the future
125 ;; This section totally borrows from the ideas in SICP
128 ;; NOTE: time is a cons of (seconds . microseconds)
130 (define-record-type <time-segment>
131 (make-time-segment-intern time queue)
133 (time time-segment-time)
134 (queue time-segment-queue))
136 (define (time-segment-right-format time)
137 "Ensure TIME is in the right format.
139 The right format means (second . microsecond).
140 If an integer, will convert appropriately."
141 ;; TODO: add floating point / rational number support.
143 ;; time is already a cons of second and microsecnd
144 (((? integer? s) . (? integer? u)) time)
145 ;; time was just an integer (just the second)
146 ((? integer? _) (cons time 0))
147 (_ (throw 'invalid-time "Invalid time" time))))
149 (define* (make-time-segment time #:optional (queue (make-q)))
150 "Make a time segment of TIME and QUEUE
152 No automatic conversion is done, so you might have to
153 run (time-segment-right-format) first."
154 (make-time-segment-intern time queue))
156 (define (time< time1 time2)
157 "Check if TIME1 is less than TIME2"
158 (cond ((< (car time1)
168 (define (time= time1 time2)
169 "Check whether TIME1 and TIME2 are equivalent"
170 (and (= (car time1) (car time2))
171 (= (cdr time1) (cdr time2))))
173 (define (time<= time1 time2)
174 "Check if TIME1 is less than or equal to TIME2"
175 (or (time< time1 time2)
176 (time= time1 time2)))
179 (define-record-type <time-delta>
180 (make-time-delta-intern sec usec)
183 (usec time-delta-usec))
185 (define* (make-time-delta sec #:optional (usec 0))
186 "Make a <time-delta> of SEC seconds and USEC microseconds.
188 This is used primarily so the agenda can recognize RUN-REQUEST objects
190 (make-time-delta-intern sec usec))
192 (define tdelta make-time-delta)
194 (define (time-carry-correct time)
195 "Corrects/handles time microsecond carry.
196 Will produce (0 . 0) instead of a negative number, if needed."
197 (cond ((>= (cdr time) 1000000)
200 (- (cdr time) 1000000)))
206 (+ (cdr time) 1000000))))
209 (define (time-delta+ time time-delta)
210 "Increment a TIME by the value of TIME-DELTA"
212 (cons (+ (car time) (time-delta-sec time-delta))
213 (+ (cdr time) (time-delta-usec time-delta)))))
215 (define (time-minus time1 time2)
216 "Subtract TIME2 from TIME1"
218 (cons (- (car time1) (car time2))
219 (- (cdr time2) (cdr time2)))))
221 (define (time-plus time1 time2)
222 "Add TIME1 and TIME2"
224 (cons (+ (car time1) (car time2))
225 (+ (cdr time2) (cdr time2)))))
228 (define-record-type <schedule>
229 (make-schedule-intern segments)
231 (segments schedule-segments set-schedule-segments!))
233 (define* (make-schedule #:optional segments)
234 "Make a schedule, optionally pre-composed of SEGMENTS"
235 (make-schedule-intern (or segments '())))
237 (define (schedule-soonest-time schedule)
238 "Return a cons of (sec . usec) for next time segement, or #f if none"
239 (let ((segments (schedule-segments schedule)))
240 (if (eq? segments '())
242 (time-segment-time (car segments)))))
244 ;; TODO: This code is reasonably easy to read but it
245 ;; mutates AND is worst case of O(n) in both space and time :(
246 ;; but at least it'll be reasonably easy to refactor to
247 ;; a more functional setup?
248 (define (schedule-add! schedule time proc)
249 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
250 (let ((time (time-segment-right-format time)))
251 (define (new-time-segment)
253 (make-time-segment time)))
254 (enq! (time-segment-queue new-segment) proc)
256 (define (loop segments)
257 (define (segment-equals-time? segment)
258 (time= time (time-segment-time segment)))
260 (define (segment-more-than-time? segment)
261 (time< time (time-segment-time segment)))
263 ;; We could switch this out to be more mutate'y
264 ;; and avoid the O(n) of space... is that over-optimizing?
266 ;; If we're at the end of the list, time to make a new
268 ('() (cons (new-time-segment) '()))
269 ;; If the segment's time is exactly our time, good news
270 ;; everyone! Let's append our stuff to its queue
271 (((? segment-equals-time? first) rest ...)
272 (enq! (time-segment-queue first) proc)
274 ;; If the first segment is more than our time,
275 ;; ours belongs before this one, so add it and
276 ;; start consing our way back
277 (((? segment-more-than-time? first) rest ...)
278 (cons (new-time-segment) segments))
279 ;; Otherwise, build up recursive result
281 (cons first (loop rest)))))
282 (set-schedule-segments!
284 (loop (schedule-segments schedule)))))
286 (define (schedule-empty? schedule)
287 "Check if the SCHEDULE is currently empty"
288 (eq? (schedule-segments schedule) '()))
290 (define (schedule-segments-split schedule time)
291 "Does a multiple value return of time segments before/at and after TIME"
292 (let ((time (time-segment-right-format time)))
293 (define (segment-is-now? segment)
294 (time= (time-segment-time segment) time))
295 (define (segment-is-before-now? segment)
296 (time< (time-segment-time segment) time))
298 (let loop ((segments-before '())
299 (segments-left (schedule-segments schedule)))
301 ;; end of the line, return
303 (values (reverse segments-before) '()))
305 ;; It's right now, so time to stop, but include this one in before
306 ;; but otherwise return
307 (((? segment-is-now? first) rest ...)
308 (values (reverse (cons first segments-before)) rest))
310 ;; This is prior or at now, so add it and keep going
311 (((? segment-is-before-now? first) rest ...)
312 (loop (cons first segments-before) rest))
314 ;; Otherwise it's past now, just return what we have
316 (values segments-before segments-after))))))
318 (define (schedule-extract-until! schedule time)
319 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
320 (receive (segments-before segments-after)
321 (schedule-segments-split schedule time)
322 (set-schedule-segments! schedule segments-after)
325 (define (add-segments-contents-to-queue! segments queue)
328 (let ((seg-queue (time-segment-queue segment)))
329 (while (not (q-empty? seg-queue))
330 (enq! queue (deq! seg-queue)))))
335 ;;; Request to run stuff
336 ;;; ====================
338 (define-record-type <run-request>
339 (make-run-request proc when)
341 (proc run-request-proc)
342 (when run-request-when))
344 (define* (run-it proc #:optional when)
345 "Make a request to run PROC (possibly at WHEN)"
346 (make-run-request proc when))
348 (define-syntax-rule (wrap body ...)
349 "Wrap contents in a procedure"
353 ;; @@: Do we really want `body ...' here?
354 ;; what about just `body'?
355 (define-syntax-rule (run body ...)
356 "Run everything in BODY but wrap in a convenient procedure"
357 (make-run-request (wrap body ...) #f))
359 (define-syntax-rule (run-at body ... when)
361 (make-run-request (wrap body ...) when))
363 ;; @@: Is it okay to overload the term "delay" like this?
364 ;; Would `run-in' be better?
365 (define-syntax-rule (run-delay body ... delay-time)
366 "Run BODY at DELAY-TIME time from now"
367 (make-run-request (wrap body ...) (tdelta delay-time)))
370 ;; A request to set up a port with at least one of read, write, except
371 ;; handling processes
373 (define-record-type <port-request>
374 (make-port-request-intern port read write except)
376 (port port-request-port)
377 (read port-request-read)
378 (write port-request-write)
379 (except port-request-except))
381 (define* (make-port-request port #:key read write except)
382 (if (not (or read write except))
383 (throw 'no-port-handler-given "No port handler given.\n"))
384 (make-port-request-intern port read write except))
386 (define port-request make-port-request)
390 ;;; Asynchronous escape to run things
391 ;;; =================================
393 ;; The future's in futures
395 (define (make-future call-first on-success on-fail on-error)
396 ;; TODO: add error stuff here
398 (let ((call-result (call-first)))
399 ;; queue up calling the
400 (run (on-success call-result)))))
402 (define (agenda-on-error agenda)
405 (define (agenda-on-fail agenda)
408 (define* (request-future call-first on-success
410 (agenda (%current-agenda))
411 (on-fail (agenda-on-fail agenda))
412 (on-error (agenda-on-error agenda))
414 ;; TODO: error handling
415 ;; do we need some distinction between expected, catchable errors,
416 ;; and unexpected, uncatchable ones? Probably...?
418 (make-future call-first on-success on-fail on-error)
421 (define-syntax-rule (%sync async-request)
422 "Run BODY asynchronously at a prompt, passing args to make-future.
424 Pronounced `eight-sync' despite the spelling.
426 %sync was chosen because (async) was already taken and could lead to
427 errors, and this version of asynchronous code uses a prompt, so the `a'
428 character becomes a `%' prompt! :)
430 The % and 8 characters kind of look similar... hence this library's
431 name! (That, and the pun 'eight-synchronous' programming.)
432 There are 8sync aliases if you prefer that name."
433 (abort-to-prompt (current-agenda-prompt)
436 (define-syntax-rule (8sync args ...)
440 ;; Async port request and run-request meta-requests
441 (define (make-async-request proc)
442 "Wrap PROC in an async-request
444 The purpose of this is to make sure that users don't accidentally
445 return the wrong thing via (8sync) and trip themselves up."
446 (cons '*async-request* proc))
448 (define (setup-async-request resume-kont async-request)
449 "Complete an async request for agenda-run-once's continuation handling"
451 (('*async-request* . async-setup-proc)
452 (async-setup-proc resume-kont))
453 ;; TODO: deliver more helpful errors depending on what the user
455 (_ (throw 'invalid-async-request
456 "Invalid request passed back via an (%sync) procedure."
459 (define-syntax-rule (%run body ...)
460 (%run-at body ... #f))
462 (define-syntax-rule (%run-at body ... when)
471 (define-syntax-rule (%run-delay body ... delay-time)
472 (%run-at body ... (tdelta delay-time)))
474 (define-syntax-rule (%port-request add-this-port port-request-args ...)
477 (list (make-port-request port-request-args ...)
478 (make-run-request kont)))))
481 (define-syntax-rule (%run-with-return return body ...)
489 (define-syntax-rule (8run args ...) (%run args ...))
490 (define-syntax-rule (8run-at args ...) (%run-at args ...))
491 (define-syntax-rule (8run-delay args ...) (%run-delay args ...))
492 (define-syntax-rule (8port-request args ...) (%port-request args ...))
496 ;;; Execution of agenda, and current agenda
497 ;;; =======================================
499 (define %current-agenda (make-parameter #f))
501 (define (update-agenda-from-select! agenda)
502 "Potentially (select) on ports specified in agenda, adding items to queue"
503 (define (hash-keys hash)
504 (hash-map->list (lambda (k v) k) hash))
505 (define (get-wait-time)
506 ;; TODO: we need to figure this out based on whether there's anything
507 ;; in the queue, and if not, how long till the next scheduled item
508 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
510 ((not (q-empty? (agenda-queue agenda)))
512 (soonest-time ; ie, the agenda is non-empty
513 (let* ((current-time (agenda-time agenda)))
514 (if (time<= soonest-time current-time)
515 ;; Well there's something due so let's select
516 ;; (this avoids a (possible?) race condition chance)
518 (time-minus soonest-time current-time))))
522 ;; TODO: support usecond wait time too
523 (match (get-wait-time)
525 (select (hash-keys (agenda-read-port-map agenda))
526 (hash-keys (agenda-write-port-map agenda))
527 (hash-keys (agenda-except-port-map agenda))
529 (define (get-procs-to-run)
530 (define (ports->procs ports port-map)
531 (lambda (initial-procs)
535 ((hash-ref port-map port) port))
540 ((read-ports write-ports except-ports)
541 ;; @@: Come on, we can do better than append ;P
542 ((compose (ports->procs
544 (agenda-read-port-map agenda))
547 (agenda-write-port-map agenda))
550 (agenda-except-port-map agenda)))
552 (define (update-agenda)
553 (let ((procs-to-run (get-procs-to-run))
554 (q (agenda-queue agenda)))
560 (define (ports-to-select?)
561 (define (has-items? selector)
563 ;; ... we could use hash-for-each and a continuation to jump
564 ;; out with a #t at first indication of an item
565 (not (= (hash-count (const #t)
568 (or (has-items? agenda-read-port-map)
569 (has-items? agenda-write-port-map)
570 (has-items? agenda-except-port-map)))
572 (if (ports-to-select?)
576 (define (agenda-handle-port-request! agenda port-request)
577 "Update an agenda for a port-request"
578 (define (handle-selector request-selector port-map-selector)
579 (if (request-selector port-request)
580 (hash-set! (port-map-selector agenda)
581 (port-request-port port-request)
582 (request-selector port-request))))
583 (handle-selector port-request-read agenda-read-port-map)
584 (handle-selector port-request-write agenda-write-port-map)
585 (handle-selector port-request-except agenda-except-port-map))
588 (define* (start-agenda agenda
590 (get-time gettimeofday)
591 (handle-ports update-agenda-from-select!))
592 ;; TODO: Document fields
593 "Start up the AGENDA"
594 (let loop ((agenda agenda))
596 ;; @@: Hm, maybe here would be a great place to handle
597 ;; select'ing on ports.
598 ;; We could compose over agenda-run-once and agenda-read-ports
599 (agenda-run-once agenda)))
600 (if (and stop-condition (stop-condition agenda))
603 ;; We have to update the time after ports handled, too
604 ;; because it may have changed after a select
607 ;; Adjust the agenda's time just in time
608 ;; We do this here rather than in agenda-run-once to make
609 ;; agenda-run-once's behavior fairly predictable
610 (set-field agenda (agenda-time) (get-time)))
611 (agenda-time) (get-time))))
612 ;; Update the agenda's current queue based on
613 ;; currently applicable time segments
614 (add-segments-contents-to-queue!
615 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
616 (agenda-queue agenda))
619 (define (agenda-run-once agenda)
620 "Run once through the agenda, and produce a new agenda
621 based on the results"
622 (define (call-proc proc)
624 (agenda-prompt-tag agenda)
626 (parameterize ((%current-agenda agenda))
628 (lambda (kont async-request)
629 (setup-async-request kont async-request))))
631 (let ((queue (agenda-queue agenda))
632 (next-queue (make-q)))
633 (while (not (q-empty? queue))
634 (let* ((proc (q-pop! queue))
635 (proc-result (call-proc proc))
637 (lambda (run-request)
638 (define (schedule-at! time proc)
639 (schedule-add! (agenda-schedule agenda) time proc))
640 (let ((request-time (run-request-when run-request)))
642 ((? time-delta? time-delta)
643 (let ((time (time-delta+ (agenda-time agenda)
645 (schedule-at! time (run-request-proc run-request))))
647 (let ((time (cons sec 0)))
648 (schedule-at! time (run-request-proc run-request))))
649 (((? integer? sec) . (? integer? usec))
650 (schedule-at! request-time (run-request-proc run-request)))
652 (enq! next-queue (run-request-proc run-request))))))))
653 (define (handle-individual result)
655 ((? run-request? new-proc)
657 ((? port-request? port-request)
658 (agenda-handle-port-request! agenda port-request))
661 ;; @@: We might support delay-wrapped procedures here
664 (for-each handle-individual results))
665 (one-result (handle-individual one-result)))))
666 ;; TODO: Alternately, we could return the next-queue
667 ;; along with changes to be added to the schedule here?
668 ;; Return new agenda, with next queue set
669 (set-field agenda (agenda-queue) next-queue)))