1 (define-module (loopy 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!
37 make-run-request run-request?
38 run-request-proc run-request-when
40 run-it wrap run run-at run-delay
43 start-agenda agenda-run-once))
45 ;; @@: Using immutable agendas here, so wouldn't it make sense to
46 ;; replace this queue stuff with using pfds based immutable queues?
52 ;;; The agenda consists of:
53 ;;; - a queue of immediate items to handle
54 ;;; - sheduled future events to be added to a future queue
55 ;;; - a tag by which running processes can escape for some asynchronous
56 ;;; operation (from which they can be returned later)
57 ;;; - a mapping of ports to various handler procedures
59 ;;; The goal, eventually, is for this all to be immutable and functional.
60 ;;; However, we aren't there yet. Some tricky things:
61 ;;; - The schedule needs to be immutable, yet reasonably efficient.
62 ;;; - Need to use immutable queues (ijp's pfds library?)
63 ;;; - Modeling reading from ports as something repeatable,
64 ;;; and with reasonable separation from functional components?
66 (define-immutable-record-type <agenda>
67 (make-agenda-intern queue prompt-tag
68 read-port-map write-port-map except-port-map
72 (prompt-tag agenda-prompt-tag)
73 (read-port-map agenda-read-port-map)
74 (write-port-map agenda-write-port-map)
75 (except-port-map agenda-except-port-map)
76 (schedule agenda-schedule)
79 (define (make-async-prompt-tag)
80 "Make an async prompt tag for an agenda.
82 Generally done automatically for the user through (make-agenda)."
83 (make-prompt-tag "prompt"))
85 (define* (make-agenda #:key
87 (prompt (make-prompt-tag))
88 (read-port-map (make-hash-table))
89 (write-port-map (make-hash-table))
90 (except-port-map (make-hash-table))
91 (schedule (make-schedule))
92 (time (gettimeofday)))
93 ;; TODO: document arguments
94 "Make a fresh agenda."
95 (make-agenda-intern queue prompt
96 read-port-map write-port-map except-port-map
99 (define (current-agenda-prompt)
100 "Get the prompt for the current agenda; signal an error if there isn't one."
101 (let ((current-agenda (%current-agenda)))
102 (if (not current-agenda)
105 "Can't get current agenda prompt if there's no current agenda!")
106 (agenda-prompt-tag current-agenda))))
113 ;;; This is where we handle timed events for the future
115 ;; This section totally borrows from the ideas in SICP
118 ;; NOTE: time is a cons of (seconds . microseconds)
120 (define-record-type <time-segment>
121 (make-time-segment-intern time queue)
123 (time time-segment-time)
124 (queue time-segment-queue))
126 (define (time-segment-right-format time)
127 "Ensure TIME is in the right format.
129 The right format means (second . microsecond).
130 If an integer, will convert appropriately."
131 ;; TODO: add floating point / rational number support.
133 ;; time is already a cons of second and microsecnd
134 (((? integer? s) . (? integer? u)) time)
135 ;; time was just an integer (just the second)
136 ((? integer? _) (cons time 0))
137 (_ (throw 'invalid-time "Invalid time" time))))
139 (define* (make-time-segment time #:optional (queue (make-q)))
140 "Make a time segment of TIME and QUEUE
142 No automatic conversion is done, so you might have to
143 run (time-segment-right-format) first."
144 (make-time-segment-intern time queue))
146 (define (time< time1 time2)
147 "Check if TIME1 is less than TIME2"
148 (cond ((< (car time1)
158 (define (time= time1 time2)
159 "Check whether TIME1 and TIME2 are equivalent"
160 (and (= (car time1) (car time2))
161 (= (cdr time1) (cdr time2))))
163 (define (time<= time1 time2)
164 "Check if TIME1 is less than or equal to TIME2"
165 (or (time< time1 time2)
166 (time= time1 time2)))
169 (define-record-type <time-delta>
170 (make-time-delta-intern sec usec)
173 (usec time-delta-usec))
175 (define* (make-time-delta sec #:optional (usec 0))
176 "Make a <time-delta> of SEC seconds and USEC microseconds.
178 This is used primarily so the agenda can recognize RUN-REQUEST objects
180 (make-time-delta-intern sec usec))
182 (define tdelta make-time-delta)
184 (define (time-carry-correct time)
185 "Corrects/handles time microsecond carry.
186 Will produce (0 . 0) instead of a negative number, if needed."
187 (cond ((>= (cdr time) 1000000)
190 (- (cdr time) 1000000)))
196 (+ (cdr time) 1000000))))
199 (define (time-delta+ time time-delta)
200 "Increment a TIME by the value of TIME-DELTA"
202 (cons (+ (car time) (time-delta-sec time-delta))
203 (+ (cdr time) (time-delta-usec time-delta)))))
205 (define (time-minus time1 time2)
206 "Subtract TIME2 from TIME1"
208 (cons (- (car time1) (car time2))
209 (- (cdr time2) (cdr time2)))))
211 (define (time-plus time1 time2)
212 "Add TIME1 and TIME2"
214 (cons (+ (car time1) (car time2))
215 (+ (cdr time2) (cdr time2)))))
218 (define-record-type <schedule>
219 (make-schedule-intern segments)
221 (segments schedule-segments set-schedule-segments!))
223 (define* (make-schedule #:optional segments)
224 "Make a schedule, optionally pre-composed of SEGMENTS"
225 (make-schedule-intern (or segments '())))
227 (define (schedule-soonest-time schedule)
228 "Return a cons of (sec . usec) for next time segement, or #f if none"
229 (let ((segments (schedule-segments schedule)))
230 (if (eq? segments '())
232 (time-segment-time (car segments)))))
234 ;; TODO: This code is reasonably easy to read but it
235 ;; mutates AND is worst case of O(n) in both space and time :(
236 ;; but at least it'll be reasonably easy to refactor to
237 ;; a more functional setup?
238 (define (schedule-add! schedule time proc)
239 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
240 (let ((time (time-segment-right-format time)))
241 (define (new-time-segment)
243 (make-time-segment time)))
244 (enq! (time-segment-queue new-segment) proc)
246 (define (loop segments)
247 (define (segment-equals-time? segment)
248 (time= time (time-segment-time segment)))
250 (define (segment-more-than-time? segment)
251 (time< time (time-segment-time segment)))
253 ;; We could switch this out to be more mutate'y
254 ;; and avoid the O(n) of space... is that over-optimizing?
256 ;; If we're at the end of the list, time to make a new
258 ('() (cons (new-time-segment) '()))
259 ;; If the segment's time is exactly our time, good news
260 ;; everyone! Let's append our stuff to its queue
261 (((? segment-equals-time? first) rest ...)
262 (enq! (time-segment-queue first) proc)
264 ;; If the first segment is more than our time,
265 ;; ours belongs before this one, so add it and
266 ;; start consing our way back
267 (((? segment-more-than-time? first) rest ...)
268 (cons (new-time-segment) segments))
269 ;; Otherwise, build up recursive result
271 (cons first (loop rest)))))
272 (set-schedule-segments!
274 (loop (schedule-segments schedule)))))
276 (define (schedule-empty? schedule)
277 "Check if the SCHEDULE is currently empty"
278 (eq? (schedule-segments schedule) '()))
280 (define (schedule-segments-split schedule time)
281 "Does a multiple value return of time segments before/at and after TIME"
282 (let ((time (time-segment-right-format time)))
283 (define (segment-is-now? segment)
284 (time= (time-segment-time segment) time))
285 (define (segment-is-before-now? segment)
286 (time< (time-segment-time segment) time))
288 (let loop ((segments-before '())
289 (segments-left (schedule-segments schedule)))
291 ;; end of the line, return
293 (values (reverse segments-before) '()))
295 ;; It's right now, so time to stop, but include this one in before
296 ;; but otherwise return
297 (((? segment-is-now? first) rest ...)
298 (values (reverse (cons first segments-before)) rest))
300 ;; This is prior or at now, so add it and keep going
301 (((? segment-is-before-now? first) rest ...)
302 (loop (cons first segments-before) rest))
304 ;; Otherwise it's past now, just return what we have
306 (values segments-before segments-after))))))
308 (define (schedule-extract-until! schedule time)
309 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
310 (receive (segments-before segments-after)
311 (schedule-segments-split schedule time)
312 (set-schedule-segments! schedule segments-after)
315 (define (add-segments-contents-to-queue! segments queue)
318 (let ((seg-queue (time-segment-queue segment)))
319 (while (not (q-empty? seg-queue))
320 (enq! queue (deq! seg-queue)))))
325 ;;; Request to run stuff
326 ;;; ====================
328 (define-immutable-record-type <run-request>
329 (make-run-request proc when)
331 (proc run-request-proc)
332 (when run-request-when))
334 (define* (run-it proc #:optional when)
335 "Make a request to run PROC (possibly at WHEN)"
336 (make-run-request proc when))
338 (define-syntax-rule (wrap body ...)
339 "Wrap contents in a procedure"
343 ;; @@: Do we really want `body ...' here?
344 ;; what about just `body'?
345 (define-syntax-rule (run body ...)
346 "Run everything in BODY but wrap in a convenient procedure"
347 (make-run-request (wrap body ...) #f))
349 (define-syntax-rule (run-at body ... when)
351 (make-run-request (wrap body ...) when))
353 ;; @@: Is it okay to overload the term "delay" like this?
354 ;; Would `run-in' be better?
355 (define-syntax-rule (run-delay body ... delay-time)
356 "Run BODY at DELAY-TIME time from now"
357 (make-run-request (wrap body ...) (tdelta delay-time)))
361 ;;; Asynchronous escape to run things
362 ;;; =================================
364 ;; The future's in futures
366 (define (make-future call-first on-success on-fail on-error)
367 ;; TODO: add error stuff here
369 (let ((call-result (call-first)))
370 ;; queue up calling the
371 (run (on-success call-result)))))
373 (define (agenda-on-error agenda)
376 (define (agenda-on-fail agenda)
379 (define* (request-future call-first on-success
381 (agenda (%current-agenda))
382 (on-fail (agenda-on-fail agenda))
383 (on-error (agenda-on-error agenda))
385 ;; TODO: error handling
386 ;; do we need some distinction between expected, catchable errors,
387 ;; and unexpected, uncatchable ones? Probably...?
389 (make-future call-first on-success on-fail on-error)
392 (define-syntax-rule (%sync body args ...)
393 "Run BODY asynchronously at a prompt, passing args to make-future.
395 Pronounced `async' despite the spelling.
397 8sync was chosen because (async) was already taken and could lead to
398 errors, and this version of asynchronous code uses a prompt, so the `a'
399 character becomes a `%' prompt :)"
400 (abort-to-prompt (current-agenda-prompt)
404 (define-syntax-rule (%sync-at body when args ...)
405 (abort-to-prompt (current-agenda-prompt)
410 (define-syntax-rule (%sync-delay body delay-time args ...)
411 (abort-to-prompt (current-agenda-prompt)
413 #:when (tdelta delay-time)
417 ;;; Execution of agenda, and current agenda
418 ;;; =======================================
420 (define %current-agenda (make-parameter #f))
422 (define (update-agenda-from-select! agenda)
423 "Potentially (select) on ports specified in agenda, adding items to queue"
424 (define (hash-keys hash)
425 (hash-map->list (lambda (k v) k) hash))
426 (define (get-wait-time)
427 ;; TODO: we need to figure this out based on whether there's anything
428 ;; in the queue, and if not, how long till the next scheduled item
429 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
431 ((not (q-empty? (agenda-queue agenda)))
433 (soonest-time ; ie, the agenda is non-empty
434 (let* ((current-time (agenda-time agenda)))
435 (if (time<= soonest-time current-time)
436 ;; Well there's something due so let's select
437 ;; (this avoids a (possible?) race condition chance)
439 (time-minus soonest-time current-time))))
443 ;; TODO: support usecond wait time too
444 (match (get-wait-time)
446 (select (hash-keys (agenda-read-port-map agenda))
447 (hash-keys (agenda-write-port-map agenda))
448 (hash-keys (agenda-except-port-map agenda))
450 (define (get-procs-to-run)
451 (define (ports->procs ports port-map)
452 (lambda (initial-procs)
456 ((hash-ref port-map port) port))
461 ((read-ports write-ports except-ports)
462 ;; @@: Come on, we can do better than append ;P
463 ((compose (ports->procs
465 (agenda-read-port-map agenda))
468 (agenda-write-port-map agenda))
471 (agenda-except-port-map agenda)))
473 (define (update-agenda)
474 (let ((procs-to-run (get-procs-to-run))
475 (q (agenda-queue agenda)))
481 (define (ports-to-select?)
482 (define (has-items? selector)
484 ;; ... we could use hash-for-each and a continuation to jump
485 ;; out with a #t at first indication of an item
486 (not (= (hash-count (const #t)
489 (or (has-items? agenda-read-port-map)
490 (has-items? agenda-write-port-map)
491 (has-items? agenda-except-port-map)))
493 (if (ports-to-select?)
498 (define* (start-agenda agenda
500 (get-time gettimeofday)
501 (handle-ports update-agenda-from-select!))
502 ;; TODO: Document fields
503 "Start up the AGENDA"
504 (let loop ((agenda agenda))
506 ;; @@: Hm, maybe here would be a great place to handle
507 ;; select'ing on ports.
508 ;; We could compose over agenda-run-once and agenda-read-ports
509 (parameterize ((%current-agenda agenda))
510 (agenda-run-once agenda))))
511 (if (and stop-condition (stop-condition agenda))
514 ;; We have to update the time after ports handled, too
515 ;; because it may have changed after a select
518 ;; Adjust the agenda's time just in time
519 ;; We do this here rather than in agenda-run-once to make
520 ;; agenda-run-once's behavior fairly predictable
521 (set-field agenda (agenda-time) (get-time)))
522 (agenda-time) (get-time))))
523 ;; Update the agenda's current queue based on
524 ;; currently applicable time segments
525 (add-segments-contents-to-queue!
526 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
527 (agenda-queue agenda))
530 (define (agenda-run-once agenda)
531 "Run once through the agenda, and produce a new agenda
532 based on the results"
533 (define (call-proc proc)
535 (agenda-prompt-tag agenda)
538 (lambda* (resume-with please-run-this . args)
539 (apply request-future please-run-this resume-with
542 (let ((queue (agenda-queue agenda))
543 (next-queue (make-q)))
544 (while (not (q-empty? queue))
545 (let* ((proc (q-pop! queue))
546 (proc-result (call-proc proc))
548 (lambda (run-request)
549 (define (schedule-at! time proc)
550 (schedule-add! (agenda-schedule agenda) time proc))
551 (let ((request-time (run-request-when run-request)))
553 ((? time-delta? time-delta)
554 (let ((time (time-delta+ (agenda-time agenda)
556 (schedule-at! time (run-request-proc run-request))))
558 (let ((time (cons sec 0)))
559 (schedule-at! time (run-request-proc run-request))))
560 (((? integer? sec) . (? integer? usec))
561 (schedule-at! request-time (run-request-proc run-request)))
563 (enq! next-queue (run-request-proc run-request))))))))
564 ;; @@: We might support delay-wrapped procedures here
566 ;; TODO: replace procedure with something that indicates
567 ;; intent to run. Use a (run foo) procedure
568 ((? run-request? new-proc)
570 (((? run-request? new-procs) ...)
577 ;; TODO: Alternately, we could return the next-queue
578 ;; along with changes to be added to the schedule here?
579 ;; Return new agenda, with next queue set
580 (set-field agenda (agenda-queue) next-queue)))