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 wrap run-wrap run-wrap-at
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)
114 ;; time is already a cons of second and microsecnd
115 (((? integer? s) . (? integer? u)) time)
116 ;; time was just an integer (just the second)
117 ((? integer? _) (cons time 0))
118 (_ (throw 'invalid-time "Invalid time" time))))
120 (define* (make-time-segment time #:optional (queue (make-q)))
121 (make-time-segment-intern time queue))
123 (define (time< time1 time2)
124 (cond ((< (car time1)
134 (define (time= time1 time2)
135 (and (= (car time1) (car time2))
136 (= (cdr time1) (cdr time2))))
138 (define (time<= time1 time2)
139 (or (time< time1 time2)
140 (time= time1 time2)))
143 (define-record-type <time-delta>
144 (make-time-delta-intern sec usec)
147 (usec time-delta-usec))
149 (define* (make-time-delta sec #:optional usec)
150 (make-time-delta-intern sec (or usec 0)))
152 (define tdelta make-time-delta)
154 (define (time-carry-correct time)
155 "Corrects/handles time microsecond carry.
156 Will produce (0 . 0) instead of a negative number, if needed."
157 (cond ((>= (cdr time) 1000000)
160 (- (cdr time) 1000000)))
166 (+ (cdr time) 1000000))))
169 (define (time-delta+ time time-delta)
171 (cons (+ (car time) (time-delta-sec time-delta))
172 (+ (cdr time) (time-delta-usec time-delta)))))
174 (define (time-minus time1 time2)
176 (cons (- (car time1) (car time2))
177 (- (car time2) (cdr time2)))))
179 (define (time-plus time1 time2)
181 (cons (+ (car time1) (car time2))
182 (+ (car time2) (cdr time2)))))
185 (define-record-type <schedule>
186 (make-schedule-intern segments)
188 (segments schedule-segments set-schedule-segments!))
190 (define* (make-schedule #:optional segments)
191 (make-schedule-intern (or segments '())))
193 (define (schedule-soonest-time schedule)
194 "Return a cons of (sec . usec) for next time segement, or #f if none"
195 (let ((segments (schedule-segments schedule)))
196 (if (eq? segments '())
198 (time-segment-time (car segments)))))
200 ;; TODO: This code is reasonably easy to read but it
201 ;; mutates AND is worst case of O(n) in both space and time :(
202 ;; but at least it'll be reasonably easy to refactor to
203 ;; a more functional setup?
204 (define (schedule-add! schedule time proc)
205 (let ((time (time-segment-right-format time)))
206 (define (new-time-segment)
208 (make-time-segment time)))
209 (enq! (time-segment-queue new-segment) proc)
211 (define (loop segments)
212 (define (segment-equals-time? segment)
213 (time= time (time-segment-time segment)))
215 (define (segment-more-than-time? segment)
216 (time< time (time-segment-time segment)))
218 ;; We could switch this out to be more mutate'y
219 ;; and avoid the O(n) of space... is that over-optimizing?
221 ;; If we're at the end of the list, time to make a new
223 ('() (cons (new-time-segment) '()))
224 ;; If the segment's time is exactly our time, good news
225 ;; everyone! Let's append our stuff to its queue
226 (((? segment-equals-time? first) rest ...)
227 (enq! (time-segment-queue first) proc)
229 ;; If the first segment is more than our time,
230 ;; ours belongs before this one, so add it and
231 ;; start consing our way back
232 (((? segment-more-than-time? first) rest ...)
233 (cons (new-time-segment) segments))
234 ;; Otherwise, build up recursive result
236 (cons first (loop rest)))))
237 (set-schedule-segments!
239 (loop (schedule-segments schedule)))))
241 (define (schedule-empty? schedule)
242 (eq? (schedule-segments schedule) '()))
244 (define (schedule-segments-split schedule time)
245 "Does a multiple value return of time segments before/at and after TIME"
246 (let ((time (time-segment-right-format time)))
247 (define (segment-is-now? segment)
248 (time= (time-segment-time segment) time))
249 (define (segment-is-before-now? segment)
250 (time< (time-segment-time segment) time))
252 (let loop ((segments-before '())
253 (segments-left (schedule-segments schedule)))
255 ;; end of the line, return
257 (values (reverse segments-before) '()))
259 ;; It's right now, so time to stop, but include this one in before
260 ;; but otherwise return
261 (((? segment-is-now? first) rest ...)
262 (values (reverse (cons first segments-before)) rest))
264 ;; This is prior or at now, so add it and keep going
265 (((? segment-is-before-now? first) rest ...)
266 (loop (cons first segments-before) rest))
268 ;; Otherwise it's past now, just return what we have
270 (values segments-before segments-after))))))
272 (define (schedule-extract-until! schedule time)
273 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
274 (receive (segments-before segments-after)
275 (schedule-segments-split schedule time)
276 (set-schedule-segments! schedule segments-after)
279 (define (add-segments-contents-to-queue! segments queue)
282 (let ((seg-queue (time-segment-queue segment)))
283 (while (not (q-empty? seg-queue))
284 (enq! queue (deq! seg-queue)))))
292 (define (make-port-mapping)
295 (define* (port-mapping-set! port-mapping port #:optional read write except)
296 "Sets port-mapping for reader / writer / exception handlers"
297 (if (not (or read write except))
298 (throw 'no-handlers-given "No handlers given for port" port))
299 (hashq-set! port-mapping port
300 `#(,read ,write ,except)))
302 (define (port-mapping-remove! port-mapping port)
303 (hashq-remove! port-mapping port))
305 ;; TODO: This is O(n), I'm pretty sure :\
306 ;; ... it might be worthwhile for us to have a
307 ;; port-mapping record that keeps a count of how many
308 ;; handlers (maybe via a promise?)
309 (define (port-mapping-empty? port-mapping)
310 "Is this port mapping empty?"
311 (eq? (hash-count (const #t) port-mapping) 0))
313 (define (port-mapping-non-empty? port-mapping)
314 "Whether this port-mapping contains any elements"
315 (not (port-mapping-empty? port-mapping)))
319 ;;; Request to run stuff
320 ;;; ====================
322 (define-record-type <run-request>
323 (make-run-request proc when)
325 (proc run-request-proc)
326 (when run-request-when))
328 (define* (run proc #:optional when)
329 (make-run-request proc when))
331 (define-syntax-rule (wrap body ...)
335 (define-syntax-rule (run-wrap body ...)
336 (run (wrap body ...)))
338 (define-syntax-rule (run-wrap-at body ... when)
339 (run (wrap body ...) when))
342 ;;; Execution of agenda, and current agenda
343 ;;; =======================================
345 (define %current-agenda (make-parameter #f))
347 (define (update-agenda-from-select! agenda)
348 (define (hash-keys hash)
349 (hash-map->list (lambda (k v) k) hash))
350 (define (get-wait-time)
351 ;; TODO: we need to figure this out based on whether there's anything
352 ;; in the queue, and if not, how long till the next scheduled item
353 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
355 ((not (q-empty? (agenda-queue agenda)))
357 (soonest-time ; ie, the agenda is non-empty
358 (let* ((current-time (agenda-time agenda)))
359 (if (time<= (pk 'soonest-time soonest-time) (pk 'current-time current-time))
360 ;; Well there's something due so let's select
361 ;; (this avoids a (possible?) race condition chance)
363 (pk 'time-minus (time-minus soonest-time current-time)))))
367 ;; TODO: support usecond wait time too
368 (match (get-wait-time)
370 (select (hash-keys (agenda-read-port-map agenda))
371 (hash-keys (agenda-write-port-map agenda))
372 (hash-keys (agenda-except-port-map agenda))
374 (define (get-procs-to-run)
375 (define (ports->procs ports port-map)
376 (lambda (initial-procs)
380 ((hash-ref port-map port) port))
385 ((read-ports write-ports except-ports)
386 ;; @@: Come on, we can do better than append ;P
387 ((compose (ports->procs
389 (agenda-read-port-map agenda))
392 (agenda-write-port-map agenda))
395 (agenda-except-port-map agenda)))
397 (define (update-agenda)
398 (let ((procs-to-run (get-procs-to-run))
399 (q (agenda-queue agenda)))
405 (define (ports-to-select?)
406 (define (has-items? selector)
408 ;; ... we could use hash-for-each and a continuation to jump
409 ;; out with a #t at first indication of an item
410 (not (= (hash-count (const #t)
413 (or (has-items? agenda-read-port-map)
414 (has-items? agenda-write-port-map)
415 (has-items? agenda-except-port-map)))
417 (if (ports-to-select?)
422 (define* (start-agenda agenda
424 (get-time gettimeofday)
425 (handle-ports update-agenda-from-select!))
426 (let loop ((agenda agenda))
428 ;; @@: Hm, maybe here would be a great place to handle
429 ;; select'ing on ports.
430 ;; We could compose over agenda-run-once and agenda-read-ports
431 (parameterize ((%current-agenda agenda))
432 (agenda-run-once agenda))))
433 (if (and stop-condition (stop-condition agenda))
435 (let* ((new-time (get-time))
438 ;; Adjust the agenda's time just in time
439 ;; We do this here rather than in agenda-run-once to make
440 ;; agenda-run-once's behavior fairly predictable
441 (set-field agenda (agenda-time) new-time))))
442 ;; Update the agenda's current queue based on
443 ;; currently applicable time segments
444 (add-segments-contents-to-queue!
445 (schedule-extract-until! (agenda-schedule agenda) new-time)
446 (agenda-queue agenda))
449 (define (agenda-run-once agenda)
450 "Run once through the agenda, and produce a new agenda
451 based on the results"
452 (define (call-proc proc)
454 (agenda-prompt-tag agenda)
460 (let ((queue (agenda-queue agenda))
461 (next-queue (make-q)))
462 (while (not (q-empty? queue))
463 (let* ((proc (q-pop! queue))
464 (proc-result (call-proc proc))
466 (lambda (run-request)
467 (define (schedule-at! time proc)
468 (schedule-add! (agenda-schedule agenda) time proc))
469 (let ((request-time (run-request-when run-request)))
471 ((? time-delta? time-delta)
472 (let ((time (time-delta+ (agenda-time agenda)
474 (schedule-at! time (run-request-proc run-request))))
476 (let ((time (cons sec 0)))
477 (schedule-at! time (run-request-proc run-request))))
478 (((? integer? sec) . (? integer? usec))
479 (schedule-at! request-time (run-request-proc run-request)))
481 (enq! next-queue (run-request-proc run-request))))))))
482 ;; @@: We might support delay-wrapped procedures here
484 ;; TODO: replace procedure with something that indicates
485 ;; intent to run. Use a (run foo) procedure
486 ((? run-request? new-proc)
488 (((? run-request? new-procs) ...)
495 ;; TODO: Alternately, we could return the next-queue
496 ;; along with changes to be added to the schedule here?
497 ;; Return new agenda, with next queue set
498 (set-field agenda (agenda-queue) next-queue)))