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
42 run-it wrap run run-at run-delay
45 start-agenda agenda-run-once))
47 ;; @@: Using immutable agendas here, so wouldn't it make sense to
48 ;; replace this queue stuff with using pfds based immutable queues?
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
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?
68 (define-immutable-record-type <agenda>
69 (make-agenda-intern queue prompt-tag
70 read-port-map write-port-map except-port-map
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)
81 (define (make-async-prompt-tag)
82 "Make an async prompt tag for an agenda.
84 Generally done automatically for the user through (make-agenda)."
85 (make-prompt-tag "prompt"))
87 (define* (make-agenda #:key
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
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)
107 "Can't get current agenda prompt if there's no current agenda!")
108 (agenda-prompt-tag current-agenda))))
115 ;;; This is where we handle timed events for the future
117 ;; This section totally borrows from the ideas in SICP
120 ;; NOTE: time is a cons of (seconds . microseconds)
122 (define-record-type <time-segment>
123 (make-time-segment-intern time queue)
125 (time time-segment-time)
126 (queue time-segment-queue))
128 (define (time-segment-right-format time)
129 "Ensure TIME is in the right format.
131 The right format means (second . microsecond).
132 If an integer, will convert appropriately."
133 ;; TODO: add floating point / rational number support.
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))))
141 (define* (make-time-segment time #:optional (queue (make-q)))
142 "Make a time segment of TIME and QUEUE
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))
148 (define (time< time1 time2)
149 "Check if TIME1 is less than TIME2"
150 (cond ((< (car time1)
160 (define (time= time1 time2)
161 "Check whether TIME1 and TIME2 are equivalent"
162 (and (= (car time1) (car time2))
163 (= (cdr time1) (cdr time2))))
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)))
171 (define-record-type <time-delta>
172 (make-time-delta-intern sec usec)
175 (usec time-delta-usec))
177 (define* (make-time-delta sec #:optional (usec 0))
178 "Make a <time-delta> of SEC seconds and USEC microseconds.
180 This is used primarily so the agenda can recognize RUN-REQUEST objects
182 (make-time-delta-intern sec usec))
184 (define tdelta make-time-delta)
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)
192 (- (cdr time) 1000000)))
198 (+ (cdr time) 1000000))))
201 (define (time-delta+ time time-delta)
202 "Increment a TIME by the value of TIME-DELTA"
204 (cons (+ (car time) (time-delta-sec time-delta))
205 (+ (cdr time) (time-delta-usec time-delta)))))
207 (define (time-minus time1 time2)
208 "Subtract TIME2 from TIME1"
210 (cons (- (car time1) (car time2))
211 (- (cdr time2) (cdr time2)))))
213 (define (time-plus time1 time2)
214 "Add TIME1 and TIME2"
216 (cons (+ (car time1) (car time2))
217 (+ (cdr time2) (cdr time2)))))
220 (define-record-type <schedule>
221 (make-schedule-intern segments)
223 (segments schedule-segments set-schedule-segments!))
225 (define* (make-schedule #:optional segments)
226 "Make a schedule, optionally pre-composed of SEGMENTS"
227 (make-schedule-intern (or segments '())))
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 '())
234 (time-segment-time (car segments)))))
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)
245 (make-time-segment time)))
246 (enq! (time-segment-queue new-segment) proc)
248 (define (loop segments)
249 (define (segment-equals-time? segment)
250 (time= time (time-segment-time segment)))
252 (define (segment-more-than-time? segment)
253 (time< time (time-segment-time segment)))
255 ;; We could switch this out to be more mutate'y
256 ;; and avoid the O(n) of space... is that over-optimizing?
258 ;; If we're at the end of the list, time to make a new
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)
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
273 (cons first (loop rest)))))
274 (set-schedule-segments!
276 (loop (schedule-segments schedule)))))
278 (define (schedule-empty? schedule)
279 "Check if the SCHEDULE is currently empty"
280 (eq? (schedule-segments schedule) '()))
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))
290 (let loop ((segments-before '())
291 (segments-left (schedule-segments schedule)))
293 ;; end of the line, return
295 (values (reverse segments-before) '()))
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))
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))
306 ;; Otherwise it's past now, just return what we have
308 (values segments-before segments-after))))))
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)
317 (define (add-segments-contents-to-queue! segments queue)
320 (let ((seg-queue (time-segment-queue segment)))
321 (while (not (q-empty? seg-queue))
322 (enq! queue (deq! seg-queue)))))
327 ;;; Request to run stuff
328 ;;; ====================
330 (define-immutable-record-type <run-request>
331 (make-run-request proc when)
333 (proc run-request-proc)
334 (when run-request-when))
336 (define* (run-it proc #:optional when)
337 "Make a request to run PROC (possibly at WHEN)"
338 (make-run-request proc when))
340 (define-syntax-rule (wrap body ...)
341 "Wrap contents in a procedure"
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))
351 (define-syntax-rule (run-at body ... when)
353 (make-run-request (wrap body ...) when))
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)))
363 ;;; Asynchronous escape to run things
364 ;;; =================================
366 ;; The future's in futures
368 (define (make-future call-first on-success on-fail on-error)
369 ;; TODO: add error stuff here
371 (let ((call-result (call-first)))
372 ;; queue up calling the
373 (run (on-success call-result)))))
375 (define (agenda-on-error agenda)
378 (define (agenda-on-fail agenda)
381 (define* (request-future call-first on-success
383 (agenda (%current-agenda))
384 (on-fail (agenda-on-fail agenda))
385 (on-error (agenda-on-error agenda))
387 ;; TODO: error handling
388 ;; do we need some distinction between expected, catchable errors,
389 ;; and unexpected, uncatchable ones? Probably...?
391 (make-future call-first on-success on-fail on-error)
394 (define-syntax-rule (%sync body args ...)
395 "Run BODY asynchronously at a prompt, passing args to make-future.
397 Pronounced `async' despite the spelling.
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! :)
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)
409 (define-syntax-rule (%sync-at body when args ...)
410 (abort-to-prompt (current-agenda-prompt)
415 (define-syntax-rule (%sync-delay body delay-time args ...)
416 (abort-to-prompt (current-agenda-prompt)
418 #:when (tdelta delay-time)
421 (define-syntax-rule (8sync args ...)
425 (define-syntax-rule (8sync-at args ...)
429 (define-syntax-rule (8sync-delay args ...)
430 "Alias for %sync-delay"
431 (8sync-delay args ...))
435 ;;; Execution of agenda, and current agenda
436 ;;; =======================================
438 (define %current-agenda (make-parameter #f))
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))))
449 ((not (q-empty? (agenda-queue agenda)))
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)
457 (time-minus soonest-time current-time))))
461 ;; TODO: support usecond wait time too
462 (match (get-wait-time)
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))
468 (define (get-procs-to-run)
469 (define (ports->procs ports port-map)
470 (lambda (initial-procs)
474 ((hash-ref port-map port) port))
479 ((read-ports write-ports except-ports)
480 ;; @@: Come on, we can do better than append ;P
481 ((compose (ports->procs
483 (agenda-read-port-map agenda))
486 (agenda-write-port-map agenda))
489 (agenda-except-port-map agenda)))
491 (define (update-agenda)
492 (let ((procs-to-run (get-procs-to-run))
493 (q (agenda-queue agenda)))
499 (define (ports-to-select?)
500 (define (has-items? selector)
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)
507 (or (has-items? agenda-read-port-map)
508 (has-items? agenda-write-port-map)
509 (has-items? agenda-except-port-map)))
511 (if (ports-to-select?)
516 (define* (start-agenda agenda
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))
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))
532 ;; We have to update the time after ports handled, too
533 ;; because it may have changed after a select
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))
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)
553 (agenda-prompt-tag agenda)
556 (lambda* (resume-with please-run-this . args)
557 (apply request-future please-run-this resume-with
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))
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)))
571 ((? time-delta? time-delta)
572 (let ((time (time-delta+ (agenda-time agenda)
574 (schedule-at! time (run-request-proc run-request))))
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)))
581 (enq! next-queue (run-request-proc run-request))))))))
582 ;; @@: We might support delay-wrapped procedures here
584 ;; TODO: replace procedure with something that indicates
585 ;; intent to run. Use a (run foo) procedure
586 ((? run-request? new-proc)
588 (((? run-request? new-procs) ...)
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)))