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 ;; TODO: document arguments
91 "Make a fresh agenda."
92 (make-agenda-intern queue prompt
93 read-port-map write-port-map except-port-map
101 ;;; This is where we handle timed events for the future
103 ;; This section totally borrows from the ideas in SICP
106 ;; NOTE: time is a cons of (seconds . microseconds)
108 (define-record-type <time-segment>
109 (make-time-segment-intern time queue)
111 (time time-segment-time)
112 (queue time-segment-queue))
114 (define (time-segment-right-format time)
115 "Ensure TIME is in the right format.
117 The right format means (second . microsecond).
118 If an integer, will convert appropriately."
119 ;; TODO: add floating point / rational number support.
121 ;; time is already a cons of second and microsecnd
122 (((? integer? s) . (? integer? u)) time)
123 ;; time was just an integer (just the second)
124 ((? integer? _) (cons time 0))
125 (_ (throw 'invalid-time "Invalid time" time))))
127 (define* (make-time-segment time #:optional (queue (make-q)))
128 "Make a time segment of TIME and QUEUE
130 No automatic conversion is done, so you might have to
131 run (time-segment-right-format) first."
132 (make-time-segment-intern time queue))
134 (define (time< time1 time2)
135 "Check if TIME1 is less than TIME2"
136 (cond ((< (car time1)
146 (define (time= time1 time2)
147 "Check whether TIME1 and TIME2 are equivalent"
148 (and (= (car time1) (car time2))
149 (= (cdr time1) (cdr time2))))
151 (define (time<= time1 time2)
152 "Check if TIME1 is less than or equal to TIME2"
153 (or (time< time1 time2)
154 (time= time1 time2)))
157 (define-record-type <time-delta>
158 (make-time-delta-intern sec usec)
161 (usec time-delta-usec))
163 (define* (make-time-delta sec #:optional (usec 0))
164 "Make a <time-delta> of SEC seconds and USEC microseconds.
166 This is used primarily so the agenda can recognize RUN-REQUEST objects
168 (make-time-delta-intern sec usec))
170 (define tdelta make-time-delta)
172 (define (time-carry-correct time)
173 "Corrects/handles time microsecond carry.
174 Will produce (0 . 0) instead of a negative number, if needed."
175 (cond ((>= (cdr time) 1000000)
178 (- (cdr time) 1000000)))
184 (+ (cdr time) 1000000))))
187 (define (time-delta+ time time-delta)
188 "Increment a TIME by the value of TIME-DELTA"
190 (cons (+ (car time) (time-delta-sec time-delta))
191 (+ (cdr time) (time-delta-usec time-delta)))))
193 (define (time-minus time1 time2)
194 "Subtract TIME2 from TIME1"
196 (cons (- (car time1) (car time2))
197 (- (cdr time2) (cdr time2)))))
199 (define (time-plus time1 time2)
200 "Add TIME1 and TIME2"
202 (cons (+ (car time1) (car time2))
203 (+ (cdr time2) (cdr time2)))))
206 (define-record-type <schedule>
207 (make-schedule-intern segments)
209 (segments schedule-segments set-schedule-segments!))
211 (define* (make-schedule #:optional segments)
212 "Make a schedule, optionally pre-composed of SEGMENTS"
213 (make-schedule-intern (or segments '())))
215 (define (schedule-soonest-time schedule)
216 "Return a cons of (sec . usec) for next time segement, or #f if none"
217 (let ((segments (schedule-segments schedule)))
218 (if (eq? segments '())
220 (time-segment-time (car segments)))))
222 ;; TODO: This code is reasonably easy to read but it
223 ;; mutates AND is worst case of O(n) in both space and time :(
224 ;; but at least it'll be reasonably easy to refactor to
225 ;; a more functional setup?
226 (define (schedule-add! schedule time proc)
227 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
228 (let ((time (time-segment-right-format time)))
229 (define (new-time-segment)
231 (make-time-segment time)))
232 (enq! (time-segment-queue new-segment) proc)
234 (define (loop segments)
235 (define (segment-equals-time? segment)
236 (time= time (time-segment-time segment)))
238 (define (segment-more-than-time? segment)
239 (time< time (time-segment-time segment)))
241 ;; We could switch this out to be more mutate'y
242 ;; and avoid the O(n) of space... is that over-optimizing?
244 ;; If we're at the end of the list, time to make a new
246 ('() (cons (new-time-segment) '()))
247 ;; If the segment's time is exactly our time, good news
248 ;; everyone! Let's append our stuff to its queue
249 (((? segment-equals-time? first) rest ...)
250 (enq! (time-segment-queue first) proc)
252 ;; If the first segment is more than our time,
253 ;; ours belongs before this one, so add it and
254 ;; start consing our way back
255 (((? segment-more-than-time? first) rest ...)
256 (cons (new-time-segment) segments))
257 ;; Otherwise, build up recursive result
259 (cons first (loop rest)))))
260 (set-schedule-segments!
262 (loop (schedule-segments schedule)))))
264 (define (schedule-empty? schedule)
265 "Check if the SCHEDULE is currently empty"
266 (eq? (schedule-segments schedule) '()))
268 (define (schedule-segments-split schedule time)
269 "Does a multiple value return of time segments before/at and after TIME"
270 (let ((time (time-segment-right-format time)))
271 (define (segment-is-now? segment)
272 (time= (time-segment-time segment) time))
273 (define (segment-is-before-now? segment)
274 (time< (time-segment-time segment) time))
276 (let loop ((segments-before '())
277 (segments-left (schedule-segments schedule)))
279 ;; end of the line, return
281 (values (reverse segments-before) '()))
283 ;; It's right now, so time to stop, but include this one in before
284 ;; but otherwise return
285 (((? segment-is-now? first) rest ...)
286 (values (reverse (cons first segments-before)) rest))
288 ;; This is prior or at now, so add it and keep going
289 (((? segment-is-before-now? first) rest ...)
290 (loop (cons first segments-before) rest))
292 ;; Otherwise it's past now, just return what we have
294 (values segments-before segments-after))))))
296 (define (schedule-extract-until! schedule time)
297 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
298 (receive (segments-before segments-after)
299 (schedule-segments-split schedule time)
300 (set-schedule-segments! schedule segments-after)
303 (define (add-segments-contents-to-queue! segments queue)
306 (let ((seg-queue (time-segment-queue segment)))
307 (while (not (q-empty? seg-queue))
308 (enq! queue (deq! seg-queue)))))
313 ;;; Request to run stuff
314 ;;; ====================
316 (define-immutable-record-type <run-request>
317 (make-run-request proc when)
319 (proc run-request-proc)
320 (when run-request-when))
322 (define* (run-it proc #:optional when)
323 "Make a request to run PROC (possibly at WHEN)"
324 (make-run-request proc when))
326 (define-syntax-rule (wrap body ...)
327 "Wrap contents in a procedure"
331 (define-syntax-rule (run body ...)
332 "Run everything in BODY but wrap in a convenient procedure"
333 (make-run-request (wrap body ...) #f))
335 (define-syntax-rule (run-at body ... when)
337 (make-run-request (wrap body ...) when))
339 (define-syntax-rule (run-delay body ... delay-time)
340 "Run BODY at DELAY-TIME time from now"
341 (make-run-request (wrap body ...) (tdelta delay-time)))
343 (define (delay run-request delay-time)
344 "Delay a RUN-REQUEST by DELAY-TIME"
345 (set-field run-request
347 (tdelta delay-time)))
350 ;;; Execution of agenda, and current agenda
351 ;;; =======================================
353 (define %current-agenda (make-parameter #f))
355 (define (update-agenda-from-select! agenda)
356 "Potentially (select) on ports specified in agenda, adding items to queue"
357 (define (hash-keys hash)
358 (hash-map->list (lambda (k v) k) hash))
359 (define (get-wait-time)
360 ;; TODO: we need to figure this out based on whether there's anything
361 ;; in the queue, and if not, how long till the next scheduled item
362 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
364 ((not (q-empty? (agenda-queue agenda)))
366 (soonest-time ; ie, the agenda is non-empty
367 (let* ((current-time (agenda-time agenda)))
368 (if (time<= soonest-time current-time)
369 ;; Well there's something due so let's select
370 ;; (this avoids a (possible?) race condition chance)
372 (time-minus soonest-time current-time))))
376 ;; TODO: support usecond wait time too
377 (match (get-wait-time)
379 (select (hash-keys (agenda-read-port-map agenda))
380 (hash-keys (agenda-write-port-map agenda))
381 (hash-keys (agenda-except-port-map agenda))
383 (define (get-procs-to-run)
384 (define (ports->procs ports port-map)
385 (lambda (initial-procs)
389 ((hash-ref port-map port) port))
394 ((read-ports write-ports except-ports)
395 ;; @@: Come on, we can do better than append ;P
396 ((compose (ports->procs
398 (agenda-read-port-map agenda))
401 (agenda-write-port-map agenda))
404 (agenda-except-port-map agenda)))
406 (define (update-agenda)
407 (let ((procs-to-run (get-procs-to-run))
408 (q (agenda-queue agenda)))
414 (define (ports-to-select?)
415 (define (has-items? selector)
417 ;; ... we could use hash-for-each and a continuation to jump
418 ;; out with a #t at first indication of an item
419 (not (= (hash-count (const #t)
422 (or (has-items? agenda-read-port-map)
423 (has-items? agenda-write-port-map)
424 (has-items? agenda-except-port-map)))
426 (if (ports-to-select?)
431 (define* (start-agenda agenda
433 (get-time gettimeofday)
434 (handle-ports update-agenda-from-select!))
435 ;; TODO: Document fields
436 "Start up the AGENDA"
437 (let loop ((agenda agenda))
439 ;; @@: Hm, maybe here would be a great place to handle
440 ;; select'ing on ports.
441 ;; We could compose over agenda-run-once and agenda-read-ports
442 (parameterize ((%current-agenda agenda))
443 (agenda-run-once agenda))))
444 (if (and stop-condition (stop-condition agenda))
447 ;; We have to update the time after ports handled, too
448 ;; because it may have changed after a select
451 ;; Adjust the agenda's time just in time
452 ;; We do this here rather than in agenda-run-once to make
453 ;; agenda-run-once's behavior fairly predictable
454 (set-field agenda (agenda-time) (get-time)))
455 (agenda-time) (get-time))))
456 ;; Update the agenda's current queue based on
457 ;; currently applicable time segments
458 (add-segments-contents-to-queue!
459 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
460 (agenda-queue agenda))
463 (define (agenda-run-once agenda)
464 "Run once through the agenda, and produce a new agenda
465 based on the results"
466 (define (call-proc proc)
468 (agenda-prompt-tag agenda)
474 (let ((queue (agenda-queue agenda))
475 (next-queue (make-q)))
476 (while (not (q-empty? queue))
477 (let* ((proc (q-pop! queue))
478 (proc-result (call-proc proc))
480 (lambda (run-request)
481 (define (schedule-at! time proc)
482 (schedule-add! (agenda-schedule agenda) time proc))
483 (let ((request-time (run-request-when run-request)))
485 ((? time-delta? time-delta)
486 (let ((time (time-delta+ (agenda-time agenda)
488 (schedule-at! time (run-request-proc run-request))))
490 (let ((time (cons sec 0)))
491 (schedule-at! time (run-request-proc run-request))))
492 (((? integer? sec) . (? integer? usec))
493 (schedule-at! request-time (run-request-proc run-request)))
495 (enq! next-queue (run-request-proc run-request))))))))
496 ;; @@: We might support delay-wrapped procedures here
498 ;; TODO: replace procedure with something that indicates
499 ;; intent to run. Use a (run foo) procedure
500 ((? run-request? new-proc)
502 (((? run-request? new-procs) ...)
509 ;; TODO: Alternately, we could return the next-queue
510 ;; along with changes to be added to the schedule here?
511 ;; Return new agenda, with next queue set
512 (set-field agenda (agenda-queue) next-queue)))