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-prompt-tag "prompt"))
82 (define* (make-agenda #:key
84 (prompt (make-prompt-tag))
85 (read-port-map (make-hash-table))
86 (write-port-map (make-hash-table))
87 (except-port-map (make-hash-table))
88 (schedule (make-schedule))
89 (time (gettimeofday)))
90 (make-agenda-intern queue prompt
91 read-port-map write-port-map except-port-map
99 ;;; This is where we handle timed events for the future
101 ;; This section totally borrows from the ideas in SICP
104 ;; NOTE: time is a cons of (seconds . microseconds)
106 (define-record-type <time-segment>
107 (make-time-segment-intern time queue)
109 (time time-segment-time)
110 (queue time-segment-queue))
112 (define (time-segment-right-format time)
113 "Ensure TIME is in the right format.
115 The right format means (second . microsecond).
116 If an integer, will convert appropriately."
117 ;; TODO: add floating point / rational number support.
119 ;; time is already a cons of second and microsecnd
120 (((? integer? s) . (? integer? u)) time)
121 ;; time was just an integer (just the second)
122 ((? integer? _) (cons time 0))
123 (_ (throw 'invalid-time "Invalid time" time))))
125 (define* (make-time-segment time #:optional (queue (make-q)))
126 "Make a time segment of TIME and QUEUE
128 No automatic conversion is done, so you might have to
129 run (time-segment-right-format) first."
130 (make-time-segment-intern time queue))
132 (define (time< time1 time2)
133 "Check if TIME1 is less than TIME2"
134 (cond ((< (car time1)
144 (define (time= time1 time2)
145 "Check whether TIME1 and TIME2 are equivalent"
146 (and (= (car time1) (car time2))
147 (= (cdr time1) (cdr time2))))
149 (define (time<= time1 time2)
150 "Check if TIME1 is less than or equal to TIME2"
151 (or (time< time1 time2)
152 (time= time1 time2)))
155 (define-record-type <time-delta>
156 (make-time-delta-intern sec usec)
159 (usec time-delta-usec))
161 (define* (make-time-delta sec #:optional (usec 0))
162 "Make a <time-delta> of SEC seconds and USEC microseconds.
164 This is used primarily so the agenda can recognize RUN-REQUEST objects
166 (make-time-delta-intern sec usec))
168 (define tdelta make-time-delta)
170 (define (time-carry-correct time)
171 "Corrects/handles time microsecond carry.
172 Will produce (0 . 0) instead of a negative number, if needed."
173 (cond ((>= (cdr time) 1000000)
176 (- (cdr time) 1000000)))
182 (+ (cdr time) 1000000))))
185 (define (time-delta+ time time-delta)
186 "Increment a TIME by the value of TIME-DELTA"
188 (cons (+ (car time) (time-delta-sec time-delta))
189 (+ (cdr time) (time-delta-usec time-delta)))))
191 (define (time-minus time1 time2)
192 "Subtract TIME2 from TIME1"
194 (cons (- (car time1) (car time2))
195 (- (cdr time2) (cdr time2)))))
197 (define (time-plus time1 time2)
198 "Add TIME1 and TIME2"
200 (cons (+ (car time1) (car time2))
201 (+ (cdr time2) (cdr time2)))))
204 (define-record-type <schedule>
205 (make-schedule-intern segments)
207 (segments schedule-segments set-schedule-segments!))
209 (define* (make-schedule #:optional segments)
210 "Make a schedule, optionally pre-composed of SEGMENTS"
211 (make-schedule-intern (or segments '())))
213 (define (schedule-soonest-time schedule)
214 "Return a cons of (sec . usec) for next time segement, or #f if none"
215 (let ((segments (schedule-segments schedule)))
216 (if (eq? segments '())
218 (time-segment-time (car segments)))))
220 ;; TODO: This code is reasonably easy to read but it
221 ;; mutates AND is worst case of O(n) in both space and time :(
222 ;; but at least it'll be reasonably easy to refactor to
223 ;; a more functional setup?
224 (define (schedule-add! schedule time proc)
225 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
226 (let ((time (time-segment-right-format time)))
227 (define (new-time-segment)
229 (make-time-segment time)))
230 (enq! (time-segment-queue new-segment) proc)
232 (define (loop segments)
233 (define (segment-equals-time? segment)
234 (time= time (time-segment-time segment)))
236 (define (segment-more-than-time? segment)
237 (time< time (time-segment-time segment)))
239 ;; We could switch this out to be more mutate'y
240 ;; and avoid the O(n) of space... is that over-optimizing?
242 ;; If we're at the end of the list, time to make a new
244 ('() (cons (new-time-segment) '()))
245 ;; If the segment's time is exactly our time, good news
246 ;; everyone! Let's append our stuff to its queue
247 (((? segment-equals-time? first) rest ...)
248 (enq! (time-segment-queue first) proc)
250 ;; If the first segment is more than our time,
251 ;; ours belongs before this one, so add it and
252 ;; start consing our way back
253 (((? segment-more-than-time? first) rest ...)
254 (cons (new-time-segment) segments))
255 ;; Otherwise, build up recursive result
257 (cons first (loop rest)))))
258 (set-schedule-segments!
260 (loop (schedule-segments schedule)))))
262 (define (schedule-empty? schedule)
263 "Check if the SCHEDULE is currently empty"
264 (eq? (schedule-segments schedule) '()))
266 (define (schedule-segments-split schedule time)
267 "Does a multiple value return of time segments before/at and after TIME"
268 (let ((time (time-segment-right-format time)))
269 (define (segment-is-now? segment)
270 (time= (time-segment-time segment) time))
271 (define (segment-is-before-now? segment)
272 (time< (time-segment-time segment) time))
274 (let loop ((segments-before '())
275 (segments-left (schedule-segments schedule)))
277 ;; end of the line, return
279 (values (reverse segments-before) '()))
281 ;; It's right now, so time to stop, but include this one in before
282 ;; but otherwise return
283 (((? segment-is-now? first) rest ...)
284 (values (reverse (cons first segments-before)) rest))
286 ;; This is prior or at now, so add it and keep going
287 (((? segment-is-before-now? first) rest ...)
288 (loop (cons first segments-before) rest))
290 ;; Otherwise it's past now, just return what we have
292 (values segments-before segments-after))))))
294 (define (schedule-extract-until! schedule time)
295 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
296 (receive (segments-before segments-after)
297 (schedule-segments-split schedule time)
298 (set-schedule-segments! schedule segments-after)
301 (define (add-segments-contents-to-queue! segments queue)
304 (let ((seg-queue (time-segment-queue segment)))
305 (while (not (q-empty? seg-queue))
306 (enq! queue (deq! seg-queue)))))
311 ;;; Request to run stuff
312 ;;; ====================
314 (define-immutable-record-type <run-request>
315 (make-run-request proc when)
317 (proc run-request-proc)
318 (when run-request-when))
320 (define* (run-it proc #:optional when)
321 "Make a request to run PROC (possibly at WHEN)"
322 (make-run-request proc when))
324 (define-syntax-rule (wrap body ...)
325 "Wrap contents in a procedure"
329 (define-syntax-rule (run body ...)
330 "Run everything in BODY but wrap in a convenient procedure"
331 (make-run-request (wrap body ...) #f))
333 (define-syntax-rule (run-at body ... when)
335 (make-run-request (wrap body ...) when))
337 (define-syntax-rule (run-delay body ... delay-time)
338 "Run BODY at DELAY-TIME time from now"
339 (make-run-request (wrap body ...) (tdelta delay-time)))
341 (define (delay run-request delay-time)
342 "Delay a RUN-REQUEST by DELAY-TIME"
343 (set-field run-request
345 (tdelta delay-time)))
348 ;;; Execution of agenda, and current agenda
349 ;;; =======================================
351 (define %current-agenda (make-parameter #f))
353 (define (update-agenda-from-select! agenda)
354 (define (hash-keys hash)
355 (hash-map->list (lambda (k v) k) hash))
356 (define (get-wait-time)
357 ;; TODO: we need to figure this out based on whether there's anything
358 ;; in the queue, and if not, how long till the next scheduled item
359 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
361 ((not (q-empty? (agenda-queue agenda)))
363 (soonest-time ; ie, the agenda is non-empty
364 (let* ((current-time (agenda-time agenda)))
365 (if (time<= soonest-time current-time)
366 ;; Well there's something due so let's select
367 ;; (this avoids a (possible?) race condition chance)
369 (time-minus soonest-time current-time))))
373 ;; TODO: support usecond wait time too
374 (match (get-wait-time)
376 (select (hash-keys (agenda-read-port-map agenda))
377 (hash-keys (agenda-write-port-map agenda))
378 (hash-keys (agenda-except-port-map agenda))
380 (define (get-procs-to-run)
381 (define (ports->procs ports port-map)
382 (lambda (initial-procs)
386 ((hash-ref port-map port) port))
391 ((read-ports write-ports except-ports)
392 ;; @@: Come on, we can do better than append ;P
393 ((compose (ports->procs
395 (agenda-read-port-map agenda))
398 (agenda-write-port-map agenda))
401 (agenda-except-port-map agenda)))
403 (define (update-agenda)
404 (let ((procs-to-run (get-procs-to-run))
405 (q (agenda-queue agenda)))
411 (define (ports-to-select?)
412 (define (has-items? selector)
414 ;; ... we could use hash-for-each and a continuation to jump
415 ;; out with a #t at first indication of an item
416 (not (= (hash-count (const #t)
419 (or (has-items? agenda-read-port-map)
420 (has-items? agenda-write-port-map)
421 (has-items? agenda-except-port-map)))
423 (if (ports-to-select?)
428 (define* (start-agenda agenda
430 (get-time gettimeofday)
431 (handle-ports update-agenda-from-select!))
432 (let loop ((agenda agenda))
434 ;; @@: Hm, maybe here would be a great place to handle
435 ;; select'ing on ports.
436 ;; We could compose over agenda-run-once and agenda-read-ports
437 (parameterize ((%current-agenda agenda))
438 (agenda-run-once agenda))))
439 (if (and stop-condition (stop-condition agenda))
442 ;; We have to update the time after ports handled, too
443 ;; because it may have changed after a select
446 ;; Adjust the agenda's time just in time
447 ;; We do this here rather than in agenda-run-once to make
448 ;; agenda-run-once's behavior fairly predictable
449 (set-field agenda (agenda-time) (get-time)))
450 (agenda-time) (get-time))))
451 ;; Update the agenda's current queue based on
452 ;; currently applicable time segments
453 (add-segments-contents-to-queue!
454 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
455 (agenda-queue agenda))
458 (define (agenda-run-once agenda)
459 "Run once through the agenda, and produce a new agenda
460 based on the results"
461 (define (call-proc proc)
463 (agenda-prompt-tag agenda)
469 (let ((queue (agenda-queue agenda))
470 (next-queue (make-q)))
471 (while (not (q-empty? queue))
472 (let* ((proc (q-pop! queue))
473 (proc-result (call-proc proc))
475 (lambda (run-request)
476 (define (schedule-at! time proc)
477 (schedule-add! (agenda-schedule agenda) time proc))
478 (let ((request-time (run-request-when run-request)))
480 ((? time-delta? time-delta)
481 (let ((time (time-delta+ (agenda-time agenda)
483 (schedule-at! time (run-request-proc run-request))))
485 (let ((time (cons sec 0)))
486 (schedule-at! time (run-request-proc run-request))))
487 (((? integer? sec) . (? integer? usec))
488 (schedule-at! request-time (run-request-proc run-request)))
490 (enq! next-queue (run-request-proc run-request))))))))
491 ;; @@: We might support delay-wrapped procedures here
493 ;; TODO: replace procedure with something that indicates
494 ;; intent to run. Use a (run foo) procedure
495 ((? run-request? new-proc)
497 (((? run-request? new-procs) ...)
504 ;; TODO: Alternately, we could return the next-queue
505 ;; along with changes to be added to the schedule here?
506 ;; Return new agenda, with next queue set
507 (set-field agenda (agenda-queue) next-queue)))