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!
36 %sync 8sync %sync-at 8sync-at %sync-delay 8sync-delay
39 make-run-request run-request?
40 run-request-proc run-request-when
43 make-port-request port-request?
45 port-request-read port-request-write port-request-except
47 run-it wrap run run-at run-delay
50 start-agenda agenda-run-once))
52 ;; @@: Using immutable agendas here, so wouldn't it make sense to
53 ;; replace this queue stuff with using pfds based immutable queues?
59 ;;; The agenda consists of:
60 ;;; - a queue of immediate items to handle
61 ;;; - sheduled future events to be added to a future queue
62 ;;; - a tag by which running processes can escape for some asynchronous
63 ;;; operation (from which they can be returned later)
64 ;;; - a mapping of ports to various handler procedures
66 ;;; The goal, eventually, is for this all to be immutable and functional.
67 ;;; However, we aren't there yet. Some tricky things:
68 ;;; - The schedule needs to be immutable, yet reasonably efficient.
69 ;;; - Need to use immutable queues (ijp's pfds library?)
70 ;;; - Modeling reading from ports as something repeatable,
71 ;;; and with reasonable separation from functional components?
73 (define-immutable-record-type <agenda>
74 (make-agenda-intern queue prompt-tag
75 read-port-map write-port-map except-port-map
79 (prompt-tag agenda-prompt-tag)
80 (read-port-map agenda-read-port-map)
81 (write-port-map agenda-write-port-map)
82 (except-port-map agenda-except-port-map)
83 (schedule agenda-schedule)
86 (define (make-async-prompt-tag)
87 "Make an async prompt tag for an agenda.
89 Generally done automatically for the user through (make-agenda)."
90 (make-prompt-tag "prompt"))
92 (define* (make-agenda #:key
94 (prompt (make-prompt-tag))
95 (read-port-map (make-hash-table))
96 (write-port-map (make-hash-table))
97 (except-port-map (make-hash-table))
98 (schedule (make-schedule))
99 (time (gettimeofday)))
100 ;; TODO: document arguments
101 "Make a fresh agenda."
102 (make-agenda-intern queue prompt
103 read-port-map write-port-map except-port-map
106 (define (current-agenda-prompt)
107 "Get the prompt for the current agenda; signal an error if there isn't one."
108 (let ((current-agenda (%current-agenda)))
109 (if (not current-agenda)
112 "Can't get current agenda prompt if there's no current agenda!")
113 (agenda-prompt-tag current-agenda))))
120 ;;; This is where we handle timed events for the future
122 ;; This section totally borrows from the ideas in SICP
125 ;; NOTE: time is a cons of (seconds . microseconds)
127 (define-record-type <time-segment>
128 (make-time-segment-intern time queue)
130 (time time-segment-time)
131 (queue time-segment-queue))
133 (define (time-segment-right-format time)
134 "Ensure TIME is in the right format.
136 The right format means (second . microsecond).
137 If an integer, will convert appropriately."
138 ;; TODO: add floating point / rational number support.
140 ;; time is already a cons of second and microsecnd
141 (((? integer? s) . (? integer? u)) time)
142 ;; time was just an integer (just the second)
143 ((? integer? _) (cons time 0))
144 (_ (throw 'invalid-time "Invalid time" time))))
146 (define* (make-time-segment time #:optional (queue (make-q)))
147 "Make a time segment of TIME and QUEUE
149 No automatic conversion is done, so you might have to
150 run (time-segment-right-format) first."
151 (make-time-segment-intern time queue))
153 (define (time< time1 time2)
154 "Check if TIME1 is less than TIME2"
155 (cond ((< (car time1)
165 (define (time= time1 time2)
166 "Check whether TIME1 and TIME2 are equivalent"
167 (and (= (car time1) (car time2))
168 (= (cdr time1) (cdr time2))))
170 (define (time<= time1 time2)
171 "Check if TIME1 is less than or equal to TIME2"
172 (or (time< time1 time2)
173 (time= time1 time2)))
176 (define-record-type <time-delta>
177 (make-time-delta-intern sec usec)
180 (usec time-delta-usec))
182 (define* (make-time-delta sec #:optional (usec 0))
183 "Make a <time-delta> of SEC seconds and USEC microseconds.
185 This is used primarily so the agenda can recognize RUN-REQUEST objects
187 (make-time-delta-intern sec usec))
189 (define tdelta make-time-delta)
191 (define (time-carry-correct time)
192 "Corrects/handles time microsecond carry.
193 Will produce (0 . 0) instead of a negative number, if needed."
194 (cond ((>= (cdr time) 1000000)
197 (- (cdr time) 1000000)))
203 (+ (cdr time) 1000000))))
206 (define (time-delta+ time time-delta)
207 "Increment a TIME by the value of TIME-DELTA"
209 (cons (+ (car time) (time-delta-sec time-delta))
210 (+ (cdr time) (time-delta-usec time-delta)))))
212 (define (time-minus time1 time2)
213 "Subtract TIME2 from TIME1"
215 (cons (- (car time1) (car time2))
216 (- (cdr time2) (cdr time2)))))
218 (define (time-plus time1 time2)
219 "Add TIME1 and TIME2"
221 (cons (+ (car time1) (car time2))
222 (+ (cdr time2) (cdr time2)))))
225 (define-record-type <schedule>
226 (make-schedule-intern segments)
228 (segments schedule-segments set-schedule-segments!))
230 (define* (make-schedule #:optional segments)
231 "Make a schedule, optionally pre-composed of SEGMENTS"
232 (make-schedule-intern (or segments '())))
234 (define (schedule-soonest-time schedule)
235 "Return a cons of (sec . usec) for next time segement, or #f if none"
236 (let ((segments (schedule-segments schedule)))
237 (if (eq? segments '())
239 (time-segment-time (car segments)))))
241 ;; TODO: This code is reasonably easy to read but it
242 ;; mutates AND is worst case of O(n) in both space and time :(
243 ;; but at least it'll be reasonably easy to refactor to
244 ;; a more functional setup?
245 (define (schedule-add! schedule time proc)
246 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
247 (let ((time (time-segment-right-format time)))
248 (define (new-time-segment)
250 (make-time-segment time)))
251 (enq! (time-segment-queue new-segment) proc)
253 (define (loop segments)
254 (define (segment-equals-time? segment)
255 (time= time (time-segment-time segment)))
257 (define (segment-more-than-time? segment)
258 (time< time (time-segment-time segment)))
260 ;; We could switch this out to be more mutate'y
261 ;; and avoid the O(n) of space... is that over-optimizing?
263 ;; If we're at the end of the list, time to make a new
265 ('() (cons (new-time-segment) '()))
266 ;; If the segment's time is exactly our time, good news
267 ;; everyone! Let's append our stuff to its queue
268 (((? segment-equals-time? first) rest ...)
269 (enq! (time-segment-queue first) proc)
271 ;; If the first segment is more than our time,
272 ;; ours belongs before this one, so add it and
273 ;; start consing our way back
274 (((? segment-more-than-time? first) rest ...)
275 (cons (new-time-segment) segments))
276 ;; Otherwise, build up recursive result
278 (cons first (loop rest)))))
279 (set-schedule-segments!
281 (loop (schedule-segments schedule)))))
283 (define (schedule-empty? schedule)
284 "Check if the SCHEDULE is currently empty"
285 (eq? (schedule-segments schedule) '()))
287 (define (schedule-segments-split schedule time)
288 "Does a multiple value return of time segments before/at and after TIME"
289 (let ((time (time-segment-right-format time)))
290 (define (segment-is-now? segment)
291 (time= (time-segment-time segment) time))
292 (define (segment-is-before-now? segment)
293 (time< (time-segment-time segment) time))
295 (let loop ((segments-before '())
296 (segments-left (schedule-segments schedule)))
298 ;; end of the line, return
300 (values (reverse segments-before) '()))
302 ;; It's right now, so time to stop, but include this one in before
303 ;; but otherwise return
304 (((? segment-is-now? first) rest ...)
305 (values (reverse (cons first segments-before)) rest))
307 ;; This is prior or at now, so add it and keep going
308 (((? segment-is-before-now? first) rest ...)
309 (loop (cons first segments-before) rest))
311 ;; Otherwise it's past now, just return what we have
313 (values segments-before segments-after))))))
315 (define (schedule-extract-until! schedule time)
316 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
317 (receive (segments-before segments-after)
318 (schedule-segments-split schedule time)
319 (set-schedule-segments! schedule segments-after)
322 (define (add-segments-contents-to-queue! segments queue)
325 (let ((seg-queue (time-segment-queue segment)))
326 (while (not (q-empty? seg-queue))
327 (enq! queue (deq! seg-queue)))))
332 ;;; Request to run stuff
333 ;;; ====================
335 (define-record-type <run-request>
336 (make-run-request proc when)
338 (proc run-request-proc)
339 (when run-request-when))
341 (define* (run-it proc #:optional when)
342 "Make a request to run PROC (possibly at WHEN)"
343 (make-run-request proc when))
345 (define-syntax-rule (wrap body ...)
346 "Wrap contents in a procedure"
350 ;; @@: Do we really want `body ...' here?
351 ;; what about just `body'?
352 (define-syntax-rule (run body ...)
353 "Run everything in BODY but wrap in a convenient procedure"
354 (make-run-request (wrap body ...) #f))
356 (define-syntax-rule (run-at body ... when)
358 (make-run-request (wrap body ...) when))
360 ;; @@: Is it okay to overload the term "delay" like this?
361 ;; Would `run-in' be better?
362 (define-syntax-rule (run-delay body ... delay-time)
363 "Run BODY at DELAY-TIME time from now"
364 (make-run-request (wrap body ...) (tdelta delay-time)))
367 ;; A request to set up a port with at least one of read, write, except
368 ;; handling processes
370 (define-record-type <port-request>
371 (make-port-request-intern port read write except)
373 (port port-request-port)
374 (read port-request-read)
375 (write port-request-write)
376 (except port-request-except))
378 (define* (make-port-request port #:key read write except)
379 (if (not (or read write except))
380 (throw 'no-port-handler-given "No port handler given.\n"))
381 (make-port-request-intern port read write except))
385 ;;; Asynchronous escape to run things
386 ;;; =================================
388 ;; The future's in futures
390 (define (make-future call-first on-success on-fail on-error)
391 ;; TODO: add error stuff here
393 (let ((call-result (call-first)))
394 ;; queue up calling the
395 (run (on-success call-result)))))
397 (define (agenda-on-error agenda)
400 (define (agenda-on-fail agenda)
403 (define* (request-future call-first on-success
405 (agenda (%current-agenda))
406 (on-fail (agenda-on-fail agenda))
407 (on-error (agenda-on-error agenda))
409 ;; TODO: error handling
410 ;; do we need some distinction between expected, catchable errors,
411 ;; and unexpected, uncatchable ones? Probably...?
413 (make-future call-first on-success on-fail on-error)
416 (define-syntax-rule (%sync body args ...)
417 "Run BODY asynchronously at a prompt, passing args to make-future.
419 Pronounced `eight-sync' despite the spelling.
421 %sync was chosen because (async) was already taken and could lead to
422 errors, and this version of asynchronous code uses a prompt, so the `a'
423 character becomes a `%' prompt! :)
425 The % and 8 characters kind of look similar... hence this library's
426 name! (That, and the pun 'eight-synchronous' programming.)
427 There are 8sync aliases if you prefer that name."
428 (abort-to-prompt (current-agenda-prompt)
432 (define-syntax-rule (%sync-at body when args ...)
433 (abort-to-prompt (current-agenda-prompt)
438 (define-syntax-rule (%sync-delay body delay-time args ...)
439 (abort-to-prompt (current-agenda-prompt)
441 #:when (tdelta delay-time)
444 (define-syntax-rule (8sync args ...)
448 (define-syntax-rule (8sync-at args ...)
452 (define-syntax-rule (8sync-delay args ...)
453 "Alias for %sync-delay"
454 (8sync-delay args ...))
458 ;;; Execution of agenda, and current agenda
459 ;;; =======================================
461 (define %current-agenda (make-parameter #f))
463 (define (update-agenda-from-select! agenda)
464 "Potentially (select) on ports specified in agenda, adding items to queue"
465 (define (hash-keys hash)
466 (hash-map->list (lambda (k v) k) hash))
467 (define (get-wait-time)
468 ;; TODO: we need to figure this out based on whether there's anything
469 ;; in the queue, and if not, how long till the next scheduled item
470 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
472 ((not (q-empty? (agenda-queue agenda)))
474 (soonest-time ; ie, the agenda is non-empty
475 (let* ((current-time (agenda-time agenda)))
476 (if (time<= soonest-time current-time)
477 ;; Well there's something due so let's select
478 ;; (this avoids a (possible?) race condition chance)
480 (time-minus soonest-time current-time))))
484 ;; TODO: support usecond wait time too
485 (match (get-wait-time)
487 (select (hash-keys (agenda-read-port-map agenda))
488 (hash-keys (agenda-write-port-map agenda))
489 (hash-keys (agenda-except-port-map agenda))
491 (define (get-procs-to-run)
492 (define (ports->procs ports port-map)
493 (lambda (initial-procs)
497 ((hash-ref port-map port) port))
502 ((read-ports write-ports except-ports)
503 ;; @@: Come on, we can do better than append ;P
504 ((compose (ports->procs
506 (agenda-read-port-map agenda))
509 (agenda-write-port-map agenda))
512 (agenda-except-port-map agenda)))
514 (define (update-agenda)
515 (let ((procs-to-run (get-procs-to-run))
516 (q (agenda-queue agenda)))
522 (define (ports-to-select?)
523 (define (has-items? selector)
525 ;; ... we could use hash-for-each and a continuation to jump
526 ;; out with a #t at first indication of an item
527 (not (= (hash-count (const #t)
530 (or (has-items? agenda-read-port-map)
531 (has-items? agenda-write-port-map)
532 (has-items? agenda-except-port-map)))
534 (if (ports-to-select?)
538 (define (agenda-handle-port-request! agenda port-request)
539 "Update an agenda for a port-request"
540 (define (handle-selector request-selector port-map-selector)
541 (if (request-selector port-request)
542 (hash-set! (port-map-selector agenda)
543 (port-request-port port-request)
544 (request-selector port-request))))
545 (handle-selector port-request-read agenda-read-port-map)
546 (handle-selector port-request-write agenda-write-port-map)
547 (handle-selector port-request-except agenda-except-port-map))
550 (define* (start-agenda agenda
552 (get-time gettimeofday)
553 (handle-ports update-agenda-from-select!))
554 ;; TODO: Document fields
555 "Start up the AGENDA"
556 (let loop ((agenda agenda))
558 ;; @@: Hm, maybe here would be a great place to handle
559 ;; select'ing on ports.
560 ;; We could compose over agenda-run-once and agenda-read-ports
561 (parameterize ((%current-agenda agenda))
562 (agenda-run-once agenda))))
563 (if (and stop-condition (stop-condition agenda))
566 ;; We have to update the time after ports handled, too
567 ;; because it may have changed after a select
570 ;; Adjust the agenda's time just in time
571 ;; We do this here rather than in agenda-run-once to make
572 ;; agenda-run-once's behavior fairly predictable
573 (set-field agenda (agenda-time) (get-time)))
574 (agenda-time) (get-time))))
575 ;; Update the agenda's current queue based on
576 ;; currently applicable time segments
577 (add-segments-contents-to-queue!
578 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
579 (agenda-queue agenda))
582 (define (agenda-run-once agenda)
583 "Run once through the agenda, and produce a new agenda
584 based on the results"
585 (define (call-proc proc)
587 (agenda-prompt-tag agenda)
590 (lambda* (resume-with please-run-this . args)
591 (apply request-future please-run-this resume-with
594 (let ((queue (agenda-queue agenda))
595 (next-queue (make-q)))
596 (while (not (q-empty? queue))
597 (let* ((proc (q-pop! queue))
598 (proc-result (call-proc proc))
600 (lambda (run-request)
601 (define (schedule-at! time proc)
602 (schedule-add! (agenda-schedule agenda) time proc))
603 (let ((request-time (run-request-when run-request)))
605 ((? time-delta? time-delta)
606 (let ((time (time-delta+ (agenda-time agenda)
608 (schedule-at! time (run-request-proc run-request))))
610 (let ((time (cons sec 0)))
611 (schedule-at! time (run-request-proc run-request))))
612 (((? integer? sec) . (? integer? usec))
613 (schedule-at! request-time (run-request-proc run-request)))
615 (enq! next-queue (run-request-proc run-request))))))))
616 (define (handle-individual result)
618 ((? run-request? new-proc)
620 ((? port-request? port-request)
621 (agenda-handle-port-request! agenda port-request))
624 ;; @@: We might support delay-wrapped procedures here
626 ;; TODO: replace procedure with something that indicates
627 ;; intent to run. Use a (run foo) procedure
629 (for-each handle-individual results))
630 (one-result (handle-individual one-result)))))
631 ;; TODO: Alternately, we could return the next-queue
632 ;; along with changes to be added to the schedule here?
633 ;; Return new agenda, with next queue set
634 (set-field agenda (agenda-queue) next-queue)))