fixing the schedule-at! calls
[8sync.git] / loopy.scm
1 (define-module (loopy agenda)
2   #:use-module (srfi srfi-9)
3   #:use-module (srfi srfi-9 gnu)
4   #:use-module (ice-9 q)
5   #:use-module (ice-9 match)
6   #:use-module (ice-9 receive)
7   #:export (<agenda>
8             make-agenda agenda?
9             agenda-queue agenda-prompt-tag
10             agenda-port-pmapping agenda-schedule
11             
12             make-async-prompt-tag
13
14             <time-segment>
15             make-time-segment time-segment?
16             time-segment-time time-segment-queue
17
18             time-< time-= time-<= time-+
19
20             <time-delta>
21             make-time-delta time-delta?
22             time-delta-sec time-delta-usec
23
24             <schedule>
25             make-schedule schedule?
26             schedule-add! schedule-empty?
27             schedule-segments
28
29             schedule-segments-split schedule-extract-until!
30             add-segments-contents-to-queue!
31
32             make-port-mapping
33             port-mapping-set! port-mapping-remove!
34             port-mapping-empty? port-mapping-non-empty?
35
36             <run-request>
37             make-run-request run-request?
38             run-request-proc run-request-when
39
40             run wrap run-wrap run-wrap-at
41
42             %current-agenda
43             start-agenda agenda-run-once))
44
45 ;; @@: Using immutable agendas here, so wouldn't it make sense to
46 ;;   replace this queue stuff with using pfds based immutable queues?
47
48 \f
49 ;;; Agenda definition
50 ;;; =================
51
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
58 ;;;
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?
65
66 (define-immutable-record-type <agenda>
67   (make-agenda-intern queue prompt-tag port-mapping schedule time)
68   agenda?
69   (queue agenda-queue)
70   (prompt-tag agenda-prompt-tag)
71   (port-mapping agenda-port-mapping)
72   (schedule agenda-schedule)
73   (time agenda-time))
74
75 (define (make-async-prompt-tag)
76   (make-prompt-tag "prompt"))
77
78 (define* (make-agenda #:key
79                       (queue (make-q))
80                       (prompt (make-prompt-tag))
81                       (port-mapping (make-port-mapping))
82                       (schedule (make-schedule))
83                       (time (gettimeofday)))
84   (make-agenda-intern queue prompt port-mapping schedule time))
85
86
87 \f
88 ;;; Schedule
89 ;;; ========
90
91 ;;; This is where we handle timed events for the future
92
93 ;; This section totally borrows from the ideas in SICP
94 ;; <3 <3 <3
95
96 ;; NOTE: time is a cons of (seconds . microseconds)
97
98 (define-record-type <time-segment>
99   (make-time-segment-intern time queue)
100   time-segment?
101   (time time-segment-time)
102   (queue time-segment-queue))
103
104 (define (time-segment-right-format time)
105   (match time
106     ;; time is already a cons of second and microsecnd
107     (((? integer? s) . (? integer? u)) time)
108     ;; time was just an integer (just the second)
109     ((? integer? _) (cons time 0))
110     (_ (throw 'invalid-time "Invalid time" time))))
111
112 (define* (make-time-segment time #:optional (queue (make-q)))
113   (make-time-segment-intern time queue))
114
115 (define (time-< time1 time2)
116   (cond ((< (car time1)
117             (car time2))
118          #t)
119         ((and (= (car time1)
120                  (car time2))
121               (< (cdr time1)
122                  (cdr time2)))
123          #t)
124         (else #f)))
125
126 (define (time-= time1 time2)
127   (and (= (car time1) (car time2))
128        (= (cdr time1) (cdr time2))))
129
130 (define (time-<= time1 time2)
131   (or (time-< time1 time2)
132       (time-= time1 time2)))
133
134
135 (define-record-type <time-delta>
136   (make-time-delta-intern sec usec)
137   time-delta?
138   (sec time-delta-sec)
139   (usec time-delta-usec))
140
141 (define* (make-time-delta sec #:optional usec)
142   (make-time-delta-intern sec (or usec 0)))
143
144 (define (time-+ time time-delta)
145   (cons (+ (car time) (time-delta-sec time-delta))
146         (+ (cdr time) (time-delta-usec time-delta))))
147
148
149 (define-record-type <schedule>
150   (make-schedule-intern segments)
151   schedule?
152   (segments schedule-segments set-schedule-segments!))
153
154 (define* (make-schedule #:optional segments)
155   (make-schedule-intern (or segments '())))
156
157 ;; TODO: This code is reasonably easy to read but it
158 ;;   mutates AND is worst case of O(n) in both space and time :(
159 ;;   but at least it'll be reasonably easy to refactor to
160 ;;   a more functional setup?
161 (define (schedule-add! schedule time proc)
162   (let ((time (time-segment-right-format time)))
163     (define (new-time-segment)
164       (let ((new-segment
165              (make-time-segment time)))
166         (enq! (time-segment-queue new-segment) proc)
167         new-segment))
168     (define (loop segments)
169       (define (segment-equals-time? segment)
170         (time-= time (time-segment-time segment)))
171
172       (define (segment-more-than-time? segment)
173         (time-< time (time-segment-time segment)))
174
175       ;; We could switch this out to be more mutate'y
176       ;; and avoid the O(n) of space... is that over-optimizing?
177       (match segments
178         ;; If we're at the end of the list, time to make a new
179         ;; segment...
180         ('() (cons (new-time-segment) '()))
181         ;; If the segment's time is exactly our time, good news
182         ;; everyone!  Let's append our stuff to its queue
183         (((? segment-equals-time? first) rest ...)
184          (enq! (time-segment-queue first) proc)
185          segments)
186         ;; If the first segment is more than our time,
187         ;; ours belongs before this one, so add it and
188         ;; start consing our way back
189         (((? segment-more-than-time? first) rest ...)
190          (cons (new-time-segment) segments))
191         ;; Otherwise, build up recursive result
192         ((first rest ... )
193          (cons first (loop rest)))))
194     (set-schedule-segments!
195      schedule
196      (loop (schedule-segments schedule)))))
197
198 (define (schedule-empty? schedule)
199   (eq? (schedule-segments schedule) '()))
200
201 (define (schedule-segments-split schedule time)
202   "Does a multiple value return of time segments before/at and after TIME"
203   (let ((time (time-segment-right-format time)))
204     (define (segment-is-now? segment)
205       (time-= (time-segment-time segment) time))
206     (define (segment-is-before-now? segment)
207       (time-< (time-segment-time segment) time))
208
209     (let loop ((segments-before '())
210                (segments-left (schedule-segments schedule)))
211       (match segments-left
212         ;; end of the line, return
213         ('()
214          (values (reverse segments-before) '()))
215
216         ;; It's right now, so time to stop, but include this one in before
217         ;; but otherwise return
218         (((? segment-is-now? first) rest ...)
219          (values (reverse (cons first segments-before)) rest))
220
221         ;; This is prior or at now, so add it and keep going
222         (((? segment-is-before-now? first) rest ...)
223          (loop (cons first segments-before) rest))
224
225         ;; Otherwise it's past now, just return what we have
226         (segments-after
227          (values segments-before segments-after))))))
228
229 (define (schedule-extract-until! schedule time)
230   "Extract all segments until TIME from SCHEDULE, and pop old segments off"
231   (receive (segments-before segments-after)
232       (schedule-segments-split schedule time)
233     (set-schedule-segments! schedule segments-after)
234     segments-before))
235
236 (define (add-segments-contents-to-queue! segments queue)
237   (for-each
238    (lambda (segment)
239      (let ((seg-queue (time-segment-queue segment)))
240        (while (not (q-empty? seg-queue))
241          (enq! queue (deq! seg-queue)))))
242    segments))
243
244
245 \f
246 ;;; Port handling
247 ;;; =============
248
249 (define (make-port-mapping)
250   (make-hash-table))
251
252 (define* (port-mapping-set! port-mapping port #:optional read write except)
253   "Sets port-mapping for reader / writer / exception handlers"
254   (if (not (or read write except))
255       (throw 'no-handlers-given "No handlers given for port" port))
256   (hashq-set! port-mapping port
257               `#(,read ,write ,except)))
258
259 (define (port-mapping-remove! port-mapping port)
260   (hashq-remove! port-mapping port))
261
262 ;; TODO: This is O(n), I'm pretty sure :\
263 ;; ... it might be worthwhile for us to have a
264 ;;   port-mapping record that keeps a count of how many
265 ;;   handlers (maybe via a promise?)
266 (define (port-mapping-empty? port-mapping)
267   "Is this port mapping empty?"
268   (eq? (hash-count (const #t) port-mapping) 0))
269
270 (define (port-mapping-non-empty? port-mapping)
271   "Whether this port-mapping contains any elements"
272   (not (port-mapping-empty? port-mapping)))
273
274
275 \f
276 ;;; Request to run stuff
277 ;;; ====================
278
279 (define-record-type <run-request>
280   (make-run-request proc when)
281   run-request?
282   (proc run-request-proc)
283   (when run-request-when))
284
285 (define* (run proc #:optional when)
286   (make-run-request proc when))
287
288 (define-syntax-rule (wrap body ...)
289   (lambda ()
290     body ...))
291
292 (define-syntax-rule (run-wrap body ...)
293   (run (wrap body ...)))
294
295 (define-syntax-rule (run-wrap-at body ... when)
296   (run (wrap body ...) when))
297
298 \f
299 ;;; Execution of agenda, and current agenda
300 ;;; =======================================
301
302 (define %current-agenda (make-parameter #f))
303
304 (define* (start-agenda agenda #:optional stop-condition)
305   (let loop ((agenda agenda))
306     (let ((agenda   
307            ;; @@: Hm, maybe here would be a great place to handle
308            ;;   select'ing on ports.
309            ;;   We could compose over agenda-run-once and agenda-read-ports
310            (parameterize ((%current-agenda agenda))
311              (agenda-run-once agenda))))
312       (if (and stop-condition (stop-condition agenda))
313           'done
314           (let* ((new-time (gettimeofday))
315                  (agenda
316                   ;; Adjust the agenda's time just in time
317                   ;; We do this here rather than in agenda-run-once to make
318                   ;; agenda-run-once's behavior fairly predictable
319                   (set-field agenda (agenda-time) new-time)))
320             ;; Update the agenda's current queue based on
321             ;; currently applicable time segments
322             (add-segments-contents-to-queue!
323              (schedule-extract-until! (agenda-schedule agenda) new-time)
324              (agenda-queue agenda))
325             (loop agenda))))))
326
327 (define (agenda-run-once agenda)
328   "Run once through the agenda, and produce a new agenda
329 based on the results"
330   (define (call-proc proc)
331     (call-with-prompt
332         (agenda-prompt-tag agenda)
333       (lambda ()
334         (proc))
335       ;; TODO
336       (lambda (k) k)))
337
338   (let ((queue (agenda-queue agenda))
339         (next-queue (make-q)))
340     (while (not (q-empty? queue))
341       (let* ((proc (q-pop! queue))
342              (proc-result (call-proc proc))
343              (enqueue
344               (lambda (run-request)
345                 (define (schedule-at! time proc)
346                   (schedule-add! (agenda-schedule agenda) time proc))
347                 (let ((request-time (run-request-when run-request)))
348                   (match request-time
349                     ((? time-delta? time-delta)
350                      (let ((time (time-+ (agenda-time agenda)
351                                          time-delta)))
352                        (schedule-at! time (run-request-proc run-request))))
353                     ((? integer? sec)
354                      (let ((time (cons sec 0)))
355                        (schedule-at! time (run-request-proc run-request))))
356                     (((? integer? sec) . (? integer? usec))
357                      (schedule-at! request-time (run-request-proc run-request)))
358                     (#f
359                      (enq! next-queue (run-request-proc run-request))))))))
360         ;; @@: We might support delay-wrapped procedures here
361         (match proc-result
362           ;; TODO: replace procedure with something that indicates
363           ;;   intent to run.  Use a (run foo) procedure
364           ((? run-request? new-proc)
365            (enqueue new-proc))
366           (((? run-request? new-procs) ...)
367            (for-each
368             (lambda (new-proc)
369               (enqueue new-proc))
370             new-procs))
371           ;; do nothing
372           (_ #f))))
373     ;; TODO: Alternately, we could return the next-queue
374     ;;   along with changes to be added to the schedule here?
375     ;; Return new agenda, with next queue set
376     (set-field agenda (agenda-queue) next-queue)))