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 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
104 ;;; This is where we handle timed events for the future
106 ;; This section totally borrows from the ideas in SICP
109 ;; NOTE: time is a cons of (seconds . microseconds)
111 (define-record-type <time-segment>
112 (make-time-segment-intern time queue)
114 (time time-segment-time)
115 (queue time-segment-queue))
117 (define (time-segment-right-format time)
118 "Ensure TIME is in the right format.
120 The right format means (second . microsecond).
121 If an integer, will convert appropriately."
122 ;; TODO: add floating point / rational number support.
124 ;; time is already a cons of second and microsecnd
125 (((? integer? s) . (? integer? u)) time)
126 ;; time was just an integer (just the second)
127 ((? integer? _) (cons time 0))
128 (_ (throw 'invalid-time "Invalid time" time))))
130 (define* (make-time-segment time #:optional (queue (make-q)))
131 "Make a time segment of TIME and QUEUE
133 No automatic conversion is done, so you might have to
134 run (time-segment-right-format) first."
135 (make-time-segment-intern time queue))
137 (define (time< time1 time2)
138 "Check if TIME1 is less than TIME2"
139 (cond ((< (car time1)
149 (define (time= time1 time2)
150 "Check whether TIME1 and TIME2 are equivalent"
151 (and (= (car time1) (car time2))
152 (= (cdr time1) (cdr time2))))
154 (define (time<= time1 time2)
155 "Check if TIME1 is less than or equal to TIME2"
156 (or (time< time1 time2)
157 (time= time1 time2)))
160 (define-record-type <time-delta>
161 (make-time-delta-intern sec usec)
164 (usec time-delta-usec))
166 (define* (make-time-delta sec #:optional (usec 0))
167 "Make a <time-delta> of SEC seconds and USEC microseconds.
169 This is used primarily so the agenda can recognize RUN-REQUEST objects
171 (make-time-delta-intern sec usec))
173 (define tdelta make-time-delta)
175 (define (time-carry-correct time)
176 "Corrects/handles time microsecond carry.
177 Will produce (0 . 0) instead of a negative number, if needed."
178 (cond ((>= (cdr time) 1000000)
181 (- (cdr time) 1000000)))
187 (+ (cdr time) 1000000))))
190 (define (time-delta+ time time-delta)
191 "Increment a TIME by the value of TIME-DELTA"
193 (cons (+ (car time) (time-delta-sec time-delta))
194 (+ (cdr time) (time-delta-usec time-delta)))))
196 (define (time-minus time1 time2)
197 "Subtract TIME2 from TIME1"
199 (cons (- (car time1) (car time2))
200 (- (cdr time2) (cdr time2)))))
202 (define (time-plus time1 time2)
203 "Add TIME1 and TIME2"
205 (cons (+ (car time1) (car time2))
206 (+ (cdr time2) (cdr time2)))))
209 (define-record-type <schedule>
210 (make-schedule-intern segments)
212 (segments schedule-segments set-schedule-segments!))
214 (define* (make-schedule #:optional segments)
215 "Make a schedule, optionally pre-composed of SEGMENTS"
216 (make-schedule-intern (or segments '())))
218 (define (schedule-soonest-time schedule)
219 "Return a cons of (sec . usec) for next time segement, or #f if none"
220 (let ((segments (schedule-segments schedule)))
221 (if (eq? segments '())
223 (time-segment-time (car segments)))))
225 ;; TODO: This code is reasonably easy to read but it
226 ;; mutates AND is worst case of O(n) in both space and time :(
227 ;; but at least it'll be reasonably easy to refactor to
228 ;; a more functional setup?
229 (define (schedule-add! schedule time proc)
230 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
231 (let ((time (time-segment-right-format time)))
232 (define (new-time-segment)
234 (make-time-segment time)))
235 (enq! (time-segment-queue new-segment) proc)
237 (define (loop segments)
238 (define (segment-equals-time? segment)
239 (time= time (time-segment-time segment)))
241 (define (segment-more-than-time? segment)
242 (time< time (time-segment-time segment)))
244 ;; We could switch this out to be more mutate'y
245 ;; and avoid the O(n) of space... is that over-optimizing?
247 ;; If we're at the end of the list, time to make a new
249 ('() (cons (new-time-segment) '()))
250 ;; If the segment's time is exactly our time, good news
251 ;; everyone! Let's append our stuff to its queue
252 (((? segment-equals-time? first) rest ...)
253 (enq! (time-segment-queue first) proc)
255 ;; If the first segment is more than our time,
256 ;; ours belongs before this one, so add it and
257 ;; start consing our way back
258 (((? segment-more-than-time? first) rest ...)
259 (cons (new-time-segment) segments))
260 ;; Otherwise, build up recursive result
262 (cons first (loop rest)))))
263 (set-schedule-segments!
265 (loop (schedule-segments schedule)))))
267 (define (schedule-empty? schedule)
268 "Check if the SCHEDULE is currently empty"
269 (eq? (schedule-segments schedule) '()))
271 (define (schedule-segments-split schedule time)
272 "Does a multiple value return of time segments before/at and after TIME"
273 (let ((time (time-segment-right-format time)))
274 (define (segment-is-now? segment)
275 (time= (time-segment-time segment) time))
276 (define (segment-is-before-now? segment)
277 (time< (time-segment-time segment) time))
279 (let loop ((segments-before '())
280 (segments-left (schedule-segments schedule)))
282 ;; end of the line, return
284 (values (reverse segments-before) '()))
286 ;; It's right now, so time to stop, but include this one in before
287 ;; but otherwise return
288 (((? segment-is-now? first) rest ...)
289 (values (reverse (cons first segments-before)) rest))
291 ;; This is prior or at now, so add it and keep going
292 (((? segment-is-before-now? first) rest ...)
293 (loop (cons first segments-before) rest))
295 ;; Otherwise it's past now, just return what we have
297 (values segments-before segments-after))))))
299 (define (schedule-extract-until! schedule time)
300 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
301 (receive (segments-before segments-after)
302 (schedule-segments-split schedule time)
303 (set-schedule-segments! schedule segments-after)
306 (define (add-segments-contents-to-queue! segments queue)
309 (let ((seg-queue (time-segment-queue segment)))
310 (while (not (q-empty? seg-queue))
311 (enq! queue (deq! seg-queue)))))
316 ;;; Request to run stuff
317 ;;; ====================
319 (define-immutable-record-type <run-request>
320 (make-run-request proc when)
322 (proc run-request-proc)
323 (when run-request-when))
325 (define* (run-it proc #:optional when)
326 "Make a request to run PROC (possibly at WHEN)"
327 (make-run-request proc when))
329 (define-syntax-rule (wrap body ...)
330 "Wrap contents in a procedure"
334 (define-syntax-rule (run body ...)
335 "Run everything in BODY but wrap in a convenient procedure"
336 (make-run-request (wrap body ...) #f))
338 (define-syntax-rule (run-at body ... when)
340 (make-run-request (wrap body ...) when))
342 (define-syntax-rule (run-delay body ... delay-time)
343 "Run BODY at DELAY-TIME time from now"
344 (make-run-request (wrap body ...) (tdelta delay-time)))
346 (define (delay run-request delay-time)
347 "Delay a RUN-REQUEST by DELAY-TIME"
348 (set-field run-request
350 (tdelta delay-time)))
353 ;;; Execution of agenda, and current agenda
354 ;;; =======================================
356 (define %current-agenda (make-parameter #f))
358 (define (update-agenda-from-select! agenda)
359 "Potentially (select) on ports specified in agenda, adding items to queue"
360 (define (hash-keys hash)
361 (hash-map->list (lambda (k v) k) hash))
362 (define (get-wait-time)
363 ;; TODO: we need to figure this out based on whether there's anything
364 ;; in the queue, and if not, how long till the next scheduled item
365 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
367 ((not (q-empty? (agenda-queue agenda)))
369 (soonest-time ; ie, the agenda is non-empty
370 (let* ((current-time (agenda-time agenda)))
371 (if (time<= soonest-time current-time)
372 ;; Well there's something due so let's select
373 ;; (this avoids a (possible?) race condition chance)
375 (time-minus soonest-time current-time))))
379 ;; TODO: support usecond wait time too
380 (match (get-wait-time)
382 (select (hash-keys (agenda-read-port-map agenda))
383 (hash-keys (agenda-write-port-map agenda))
384 (hash-keys (agenda-except-port-map agenda))
386 (define (get-procs-to-run)
387 (define (ports->procs ports port-map)
388 (lambda (initial-procs)
392 ((hash-ref port-map port) port))
397 ((read-ports write-ports except-ports)
398 ;; @@: Come on, we can do better than append ;P
399 ((compose (ports->procs
401 (agenda-read-port-map agenda))
404 (agenda-write-port-map agenda))
407 (agenda-except-port-map agenda)))
409 (define (update-agenda)
410 (let ((procs-to-run (get-procs-to-run))
411 (q (agenda-queue agenda)))
417 (define (ports-to-select?)
418 (define (has-items? selector)
420 ;; ... we could use hash-for-each and a continuation to jump
421 ;; out with a #t at first indication of an item
422 (not (= (hash-count (const #t)
425 (or (has-items? agenda-read-port-map)
426 (has-items? agenda-write-port-map)
427 (has-items? agenda-except-port-map)))
429 (if (ports-to-select?)
434 (define* (start-agenda agenda
436 (get-time gettimeofday)
437 (handle-ports update-agenda-from-select!))
438 ;; TODO: Document fields
439 "Start up the AGENDA"
440 (let loop ((agenda agenda))
442 ;; @@: Hm, maybe here would be a great place to handle
443 ;; select'ing on ports.
444 ;; We could compose over agenda-run-once and agenda-read-ports
445 (parameterize ((%current-agenda agenda))
446 (agenda-run-once agenda))))
447 (if (and stop-condition (stop-condition agenda))
450 ;; We have to update the time after ports handled, too
451 ;; because it may have changed after a select
454 ;; Adjust the agenda's time just in time
455 ;; We do this here rather than in agenda-run-once to make
456 ;; agenda-run-once's behavior fairly predictable
457 (set-field agenda (agenda-time) (get-time)))
458 (agenda-time) (get-time))))
459 ;; Update the agenda's current queue based on
460 ;; currently applicable time segments
461 (add-segments-contents-to-queue!
462 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
463 (agenda-queue agenda))
466 (define (agenda-run-once agenda)
467 "Run once through the agenda, and produce a new agenda
468 based on the results"
469 (define (call-proc proc)
471 (agenda-prompt-tag agenda)
477 (let ((queue (agenda-queue agenda))
478 (next-queue (make-q)))
479 (while (not (q-empty? queue))
480 (let* ((proc (q-pop! queue))
481 (proc-result (call-proc proc))
483 (lambda (run-request)
484 (define (schedule-at! time proc)
485 (schedule-add! (agenda-schedule agenda) time proc))
486 (let ((request-time (run-request-when run-request)))
488 ((? time-delta? time-delta)
489 (let ((time (time-delta+ (agenda-time agenda)
491 (schedule-at! time (run-request-proc run-request))))
493 (let ((time (cons sec 0)))
494 (schedule-at! time (run-request-proc run-request))))
495 (((? integer? sec) . (? integer? usec))
496 (schedule-at! request-time (run-request-proc run-request)))
498 (enq! next-queue (run-request-proc run-request))))))))
499 ;; @@: We might support delay-wrapped procedures here
501 ;; TODO: replace procedure with something that indicates
502 ;; intent to run. Use a (run foo) procedure
503 ((? run-request? new-proc)
505 (((? run-request? new-procs) ...)
512 ;; TODO: Alternately, we could return the next-queue
513 ;; along with changes to be added to the schedule here?
514 ;; Return new agenda, with next queue set
515 (set-field agenda (agenda-queue) next-queue)))