1 (define-module (eightsync 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!
36 %sync 8sync %sync-at 8sync-at %sync-delay 8sync-delay
39 make-run-request run-request?
40 run-request-proc run-request-when
42 run-it wrap run run-at run-delay
45 start-agenda agenda-run-once))
47 ;; @@: Using immutable agendas here, so wouldn't it make sense to
48 ;; replace this queue stuff with using pfds based immutable queues?
54 ;;; The agenda consists of:
55 ;;; - a queue of immediate items to handle
56 ;;; - sheduled future events to be added to a future queue
57 ;;; - a tag by which running processes can escape for some asynchronous
58 ;;; operation (from which they can be returned later)
59 ;;; - a mapping of ports to various handler procedures
61 ;;; The goal, eventually, is for this all to be immutable and functional.
62 ;;; However, we aren't there yet. Some tricky things:
63 ;;; - The schedule needs to be immutable, yet reasonably efficient.
64 ;;; - Need to use immutable queues (ijp's pfds library?)
65 ;;; - Modeling reading from ports as something repeatable,
66 ;;; and with reasonable separation from functional components?
68 (define-immutable-record-type <agenda>
69 (make-agenda-intern queue prompt-tag
70 read-port-map write-port-map except-port-map
74 (prompt-tag agenda-prompt-tag)
75 (read-port-map agenda-read-port-map)
76 (write-port-map agenda-write-port-map)
77 (except-port-map agenda-except-port-map)
78 (schedule agenda-schedule)
81 (define (make-async-prompt-tag)
82 "Make an async prompt tag for an agenda.
84 Generally done automatically for the user through (make-agenda)."
85 (make-prompt-tag "prompt"))
87 (define* (make-agenda #:key
89 (prompt (make-prompt-tag))
90 (read-port-map (make-hash-table))
91 (write-port-map (make-hash-table))
92 (except-port-map (make-hash-table))
93 (schedule (make-schedule))
94 (time (gettimeofday)))
95 ;; TODO: document arguments
96 "Make a fresh agenda."
97 (make-agenda-intern queue prompt
98 read-port-map write-port-map except-port-map
101 (define (current-agenda-prompt)
102 "Get the prompt for the current agenda; signal an error if there isn't one."
103 (let ((current-agenda (%current-agenda)))
104 (if (not current-agenda)
107 "Can't get current agenda prompt if there's no current agenda!")
108 (agenda-prompt-tag current-agenda))))
115 ;;; This is where we handle timed events for the future
117 ;; This section totally borrows from the ideas in SICP
120 ;; NOTE: time is a cons of (seconds . microseconds)
122 (define-record-type <time-segment>
123 (make-time-segment-intern time queue)
125 (time time-segment-time)
126 (queue time-segment-queue))
128 (define (time-segment-right-format time)
129 "Ensure TIME is in the right format.
131 The right format means (second . microsecond).
132 If an integer, will convert appropriately."
133 ;; TODO: add floating point / rational number support.
135 ;; time is already a cons of second and microsecnd
136 (((? integer? s) . (? integer? u)) time)
137 ;; time was just an integer (just the second)
138 ((? integer? _) (cons time 0))
139 (_ (throw 'invalid-time "Invalid time" time))))
141 (define* (make-time-segment time #:optional (queue (make-q)))
142 "Make a time segment of TIME and QUEUE
144 No automatic conversion is done, so you might have to
145 run (time-segment-right-format) first."
146 (make-time-segment-intern time queue))
148 (define (time< time1 time2)
149 "Check if TIME1 is less than TIME2"
150 (cond ((< (car time1)
160 (define (time= time1 time2)
161 "Check whether TIME1 and TIME2 are equivalent"
162 (and (= (car time1) (car time2))
163 (= (cdr time1) (cdr time2))))
165 (define (time<= time1 time2)
166 "Check if TIME1 is less than or equal to TIME2"
167 (or (time< time1 time2)
168 (time= time1 time2)))
171 (define-record-type <time-delta>
172 (make-time-delta-intern sec usec)
175 (usec time-delta-usec))
177 (define* (make-time-delta sec #:optional (usec 0))
178 "Make a <time-delta> of SEC seconds and USEC microseconds.
180 This is used primarily so the agenda can recognize RUN-REQUEST objects
182 (make-time-delta-intern sec usec))
184 (define tdelta make-time-delta)
186 (define (time-carry-correct time)
187 "Corrects/handles time microsecond carry.
188 Will produce (0 . 0) instead of a negative number, if needed."
189 (cond ((>= (cdr time) 1000000)
192 (- (cdr time) 1000000)))
198 (+ (cdr time) 1000000))))
201 (define (time-delta+ time time-delta)
202 "Increment a TIME by the value of TIME-DELTA"
204 (cons (+ (car time) (time-delta-sec time-delta))
205 (+ (cdr time) (time-delta-usec time-delta)))))
207 (define (time-minus time1 time2)
208 "Subtract TIME2 from TIME1"
210 (cons (- (car time1) (car time2))
211 (- (cdr time2) (cdr time2)))))
213 (define (time-plus time1 time2)
214 "Add TIME1 and TIME2"
216 (cons (+ (car time1) (car time2))
217 (+ (cdr time2) (cdr time2)))))
220 (define-record-type <schedule>
221 (make-schedule-intern segments)
223 (segments schedule-segments set-schedule-segments!))
225 (define* (make-schedule #:optional segments)
226 "Make a schedule, optionally pre-composed of SEGMENTS"
227 (make-schedule-intern (or segments '())))
229 (define (schedule-soonest-time schedule)
230 "Return a cons of (sec . usec) for next time segement, or #f if none"
231 (let ((segments (schedule-segments schedule)))
232 (if (eq? segments '())
234 (time-segment-time (car segments)))))
236 ;; TODO: This code is reasonably easy to read but it
237 ;; mutates AND is worst case of O(n) in both space and time :(
238 ;; but at least it'll be reasonably easy to refactor to
239 ;; a more functional setup?
240 (define (schedule-add! schedule time proc)
241 "Mutate SCHEDULE, adding PROC at an appropriate time segment for TIME"
242 (let ((time (time-segment-right-format time)))
243 (define (new-time-segment)
245 (make-time-segment time)))
246 (enq! (time-segment-queue new-segment) proc)
248 (define (loop segments)
249 (define (segment-equals-time? segment)
250 (time= time (time-segment-time segment)))
252 (define (segment-more-than-time? segment)
253 (time< time (time-segment-time segment)))
255 ;; We could switch this out to be more mutate'y
256 ;; and avoid the O(n) of space... is that over-optimizing?
258 ;; If we're at the end of the list, time to make a new
260 ('() (cons (new-time-segment) '()))
261 ;; If the segment's time is exactly our time, good news
262 ;; everyone! Let's append our stuff to its queue
263 (((? segment-equals-time? first) rest ...)
264 (enq! (time-segment-queue first) proc)
266 ;; If the first segment is more than our time,
267 ;; ours belongs before this one, so add it and
268 ;; start consing our way back
269 (((? segment-more-than-time? first) rest ...)
270 (cons (new-time-segment) segments))
271 ;; Otherwise, build up recursive result
273 (cons first (loop rest)))))
274 (set-schedule-segments!
276 (loop (schedule-segments schedule)))))
278 (define (schedule-empty? schedule)
279 "Check if the SCHEDULE is currently empty"
280 (eq? (schedule-segments schedule) '()))
282 (define (schedule-segments-split schedule time)
283 "Does a multiple value return of time segments before/at and after TIME"
284 (let ((time (time-segment-right-format time)))
285 (define (segment-is-now? segment)
286 (time= (time-segment-time segment) time))
287 (define (segment-is-before-now? segment)
288 (time< (time-segment-time segment) time))
290 (let loop ((segments-before '())
291 (segments-left (schedule-segments schedule)))
293 ;; end of the line, return
295 (values (reverse segments-before) '()))
297 ;; It's right now, so time to stop, but include this one in before
298 ;; but otherwise return
299 (((? segment-is-now? first) rest ...)
300 (values (reverse (cons first segments-before)) rest))
302 ;; This is prior or at now, so add it and keep going
303 (((? segment-is-before-now? first) rest ...)
304 (loop (cons first segments-before) rest))
306 ;; Otherwise it's past now, just return what we have
308 (values segments-before segments-after))))))
310 (define (schedule-extract-until! schedule time)
311 "Extract all segments until TIME from SCHEDULE, and pop old segments off"
312 (receive (segments-before segments-after)
313 (schedule-segments-split schedule time)
314 (set-schedule-segments! schedule segments-after)
317 (define (add-segments-contents-to-queue! segments queue)
320 (let ((seg-queue (time-segment-queue segment)))
321 (while (not (q-empty? seg-queue))
322 (enq! queue (deq! seg-queue)))))
327 ;;; Request to run stuff
328 ;;; ====================
330 (define-record-type <run-request>
331 (make-run-request proc when)
333 (proc run-request-proc)
334 (when run-request-when))
336 (define* (run-it proc #:optional when)
337 "Make a request to run PROC (possibly at WHEN)"
338 (make-run-request proc when))
340 (define-syntax-rule (wrap body ...)
341 "Wrap contents in a procedure"
345 ;; @@: Do we really want `body ...' here?
346 ;; what about just `body'?
347 (define-syntax-rule (run body ...)
348 "Run everything in BODY but wrap in a convenient procedure"
349 (make-run-request (wrap body ...) #f))
351 (define-syntax-rule (run-at body ... when)
353 (make-run-request (wrap body ...) when))
355 ;; @@: Is it okay to overload the term "delay" like this?
356 ;; Would `run-in' be better?
357 (define-syntax-rule (run-delay body ... delay-time)
358 "Run BODY at DELAY-TIME time from now"
359 (make-run-request (wrap body ...) (tdelta delay-time)))
362 ;; A request to set up a port with at least one of read, write, except
363 ;; handling processes
365 (define-record-type <port-request>
366 (make-port-request-intern port read write except)
368 (port port-request-port)
369 (read port-request-read)
370 (write port-request-write)
371 (except port-request-except))
373 (define* (make-port-request port #:key read write except)
374 (if (not (or read write except))
375 (throw 'no-port-handler-given "No port handler given.\n"))
376 (make-port-request-intern port read write except))
378 (define port-request make-port-request)
382 ;;; Asynchronous escape to run things
383 ;;; =================================
385 ;; The future's in futures
387 (define (make-future call-first on-success on-fail on-error)
388 ;; TODO: add error stuff here
390 (let ((call-result (call-first)))
391 ;; queue up calling the
392 (run (on-success call-result)))))
394 (define (agenda-on-error agenda)
397 (define (agenda-on-fail agenda)
400 (define* (request-future call-first on-success
402 (agenda (%current-agenda))
403 (on-fail (agenda-on-fail agenda))
404 (on-error (agenda-on-error agenda))
406 ;; TODO: error handling
407 ;; do we need some distinction between expected, catchable errors,
408 ;; and unexpected, uncatchable ones? Probably...?
410 (make-future call-first on-success on-fail on-error)
413 (define-syntax-rule (%sync body args ...)
414 "Run BODY asynchronously at a prompt, passing args to make-future.
416 Pronounced `async' despite the spelling.
418 %sync was chosen because (async) was already taken and could lead to
419 errors, and this version of asynchronous code uses a prompt, so the `a'
420 character becomes a `%' prompt! :)
422 The % and 8 characters kind of look similar... hence this library's
423 name! (There are 8sync aliases if you prefer that name.)"
424 (abort-to-prompt (current-agenda-prompt)
428 (define-syntax-rule (%sync-at body when args ...)
429 (abort-to-prompt (current-agenda-prompt)
434 (define-syntax-rule (%sync-delay body delay-time args ...)
435 (abort-to-prompt (current-agenda-prompt)
437 #:when (tdelta delay-time)
440 (define-syntax-rule (8sync args ...)
444 (define-syntax-rule (8sync-at args ...)
448 (define-syntax-rule (8sync-delay args ...)
449 "Alias for %sync-delay"
450 (8sync-delay args ...))
454 ;;; Execution of agenda, and current agenda
455 ;;; =======================================
457 (define %current-agenda (make-parameter #f))
459 (define (update-agenda-from-select! agenda)
460 "Potentially (select) on ports specified in agenda, adding items to queue"
461 (define (hash-keys hash)
462 (hash-map->list (lambda (k v) k) hash))
463 (define (get-wait-time)
464 ;; TODO: we need to figure this out based on whether there's anything
465 ;; in the queue, and if not, how long till the next scheduled item
466 (let ((soonest-time (schedule-soonest-time (agenda-schedule agenda))))
468 ((not (q-empty? (agenda-queue agenda)))
470 (soonest-time ; ie, the agenda is non-empty
471 (let* ((current-time (agenda-time agenda)))
472 (if (time<= soonest-time current-time)
473 ;; Well there's something due so let's select
474 ;; (this avoids a (possible?) race condition chance)
476 (time-minus soonest-time current-time))))
480 ;; TODO: support usecond wait time too
481 (match (get-wait-time)
483 (select (hash-keys (agenda-read-port-map agenda))
484 (hash-keys (agenda-write-port-map agenda))
485 (hash-keys (agenda-except-port-map agenda))
487 (define (get-procs-to-run)
488 (define (ports->procs ports port-map)
489 (lambda (initial-procs)
493 ((hash-ref port-map port) port))
498 ((read-ports write-ports except-ports)
499 ;; @@: Come on, we can do better than append ;P
500 ((compose (ports->procs
502 (agenda-read-port-map agenda))
505 (agenda-write-port-map agenda))
508 (agenda-except-port-map agenda)))
510 (define (update-agenda)
511 (let ((procs-to-run (get-procs-to-run))
512 (q (agenda-queue agenda)))
518 (define (ports-to-select?)
519 (define (has-items? selector)
521 ;; ... we could use hash-for-each and a continuation to jump
522 ;; out with a #t at first indication of an item
523 (not (= (hash-count (const #t)
526 (or (has-items? agenda-read-port-map)
527 (has-items? agenda-write-port-map)
528 (has-items? agenda-except-port-map)))
530 (if (ports-to-select?)
534 (define (agenda-handle-port-request! agenda port-request)
535 "Update an agenda for a port-request"
536 (define (handle-selector request-selector port-map-selector)
537 (if (request-selector port-request)
538 (hash-set! (port-map-selector agenda)
539 (port-request-port port-request)
540 (request-selector port-request))))
541 (handle-selector port-request-read agenda-read-port-map)
542 (handle-selector port-request-write agenda-write-port-map)
543 (handle-selector port-request-except agenda-except-port-map))
546 (define* (start-agenda agenda
548 (get-time gettimeofday)
549 (handle-ports update-agenda-from-select!))
550 ;; TODO: Document fields
551 "Start up the AGENDA"
552 (let loop ((agenda agenda))
554 ;; @@: Hm, maybe here would be a great place to handle
555 ;; select'ing on ports.
556 ;; We could compose over agenda-run-once and agenda-read-ports
557 (parameterize ((%current-agenda agenda))
558 (agenda-run-once agenda))))
559 (if (and stop-condition (stop-condition agenda))
562 ;; We have to update the time after ports handled, too
563 ;; because it may have changed after a select
566 ;; Adjust the agenda's time just in time
567 ;; We do this here rather than in agenda-run-once to make
568 ;; agenda-run-once's behavior fairly predictable
569 (set-field agenda (agenda-time) (get-time)))
570 (agenda-time) (get-time))))
571 ;; Update the agenda's current queue based on
572 ;; currently applicable time segments
573 (add-segments-contents-to-queue!
574 (schedule-extract-until! (agenda-schedule agenda) (agenda-time agenda))
575 (agenda-queue agenda))
578 (define (agenda-run-once agenda)
579 "Run once through the agenda, and produce a new agenda
580 based on the results"
581 (define (call-proc proc)
583 (agenda-prompt-tag agenda)
586 (lambda* (resume-with please-run-this . args)
587 (apply request-future please-run-this resume-with
590 (let ((queue (agenda-queue agenda))
591 (next-queue (make-q)))
592 (while (not (q-empty? queue))
593 (let* ((proc (q-pop! queue))
594 (proc-result (call-proc proc))
596 (lambda (run-request)
597 (define (schedule-at! time proc)
598 (schedule-add! (agenda-schedule agenda) time proc))
599 (let ((request-time (run-request-when run-request)))
601 ((? time-delta? time-delta)
602 (let ((time (time-delta+ (agenda-time agenda)
604 (schedule-at! time (run-request-proc run-request))))
606 (let ((time (cons sec 0)))
607 (schedule-at! time (run-request-proc run-request))))
608 (((? integer? sec) . (? integer? usec))
609 (schedule-at! request-time (run-request-proc run-request)))
611 (enq! next-queue (run-request-proc run-request))))))))
612 (define (handle-individual result)
614 ((? run-request? new-proc)
616 ((? port-request? port-request)
617 (agenda-handle-port-request! agenda port-request))
620 ;; @@: We might support delay-wrapped procedures here
622 ;; TODO: replace procedure with something that indicates
623 ;; intent to run. Use a (run foo) procedure
625 (for-each handle-individual results))
626 (one-result (handle-individual one-result)))))
627 ;; TODO: Alternately, we could return the next-queue
628 ;; along with changes to be added to the schedule here?
629 ;; Return new agenda, with next queue set
630 (set-field agenda (agenda-queue) next-queue)))