switch stop-condition to be a keyword argument
[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 tdelta 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 tdelta make-time-delta)
145
146 (define (time-+ time time-delta)
147   (cons (+ (car time) (time-delta-sec time-delta))
148         (+ (cdr time) (time-delta-usec time-delta))))
149
150
151 (define-record-type <schedule>
152   (make-schedule-intern segments)
153   schedule?
154   (segments schedule-segments set-schedule-segments!))
155
156 (define* (make-schedule #:optional segments)
157   (make-schedule-intern (or segments '())))
158
159 ;; TODO: This code is reasonably easy to read but it
160 ;;   mutates AND is worst case of O(n) in both space and time :(
161 ;;   but at least it'll be reasonably easy to refactor to
162 ;;   a more functional setup?
163 (define (schedule-add! schedule time proc)
164   (let ((time (time-segment-right-format time)))
165     (define (new-time-segment)
166       (let ((new-segment
167              (make-time-segment time)))
168         (enq! (time-segment-queue new-segment) proc)
169         new-segment))
170     (define (loop segments)
171       (define (segment-equals-time? segment)
172         (time-= time (time-segment-time segment)))
173
174       (define (segment-more-than-time? segment)
175         (time-< time (time-segment-time segment)))
176
177       ;; We could switch this out to be more mutate'y
178       ;; and avoid the O(n) of space... is that over-optimizing?
179       (match segments
180         ;; If we're at the end of the list, time to make a new
181         ;; segment...
182         ('() (cons (new-time-segment) '()))
183         ;; If the segment's time is exactly our time, good news
184         ;; everyone!  Let's append our stuff to its queue
185         (((? segment-equals-time? first) rest ...)
186          (enq! (time-segment-queue first) proc)
187          segments)
188         ;; If the first segment is more than our time,
189         ;; ours belongs before this one, so add it and
190         ;; start consing our way back
191         (((? segment-more-than-time? first) rest ...)
192          (cons (new-time-segment) segments))
193         ;; Otherwise, build up recursive result
194         ((first rest ... )
195          (cons first (loop rest)))))
196     (set-schedule-segments!
197      schedule
198      (loop (schedule-segments schedule)))))
199
200 (define (schedule-empty? schedule)
201   (eq? (schedule-segments schedule) '()))
202
203 (define (schedule-segments-split schedule time)
204   "Does a multiple value return of time segments before/at and after TIME"
205   (let ((time (time-segment-right-format time)))
206     (define (segment-is-now? segment)
207       (time-= (time-segment-time segment) time))
208     (define (segment-is-before-now? segment)
209       (time-< (time-segment-time segment) time))
210
211     (let loop ((segments-before '())
212                (segments-left (schedule-segments schedule)))
213       (match segments-left
214         ;; end of the line, return
215         ('()
216          (values (reverse segments-before) '()))
217
218         ;; It's right now, so time to stop, but include this one in before
219         ;; but otherwise return
220         (((? segment-is-now? first) rest ...)
221          (values (reverse (cons first segments-before)) rest))
222
223         ;; This is prior or at now, so add it and keep going
224         (((? segment-is-before-now? first) rest ...)
225          (loop (cons first segments-before) rest))
226
227         ;; Otherwise it's past now, just return what we have
228         (segments-after
229          (values segments-before segments-after))))))
230
231 (define (schedule-extract-until! schedule time)
232   "Extract all segments until TIME from SCHEDULE, and pop old segments off"
233   (receive (segments-before segments-after)
234       (schedule-segments-split schedule time)
235     (set-schedule-segments! schedule segments-after)
236     segments-before))
237
238 (define (add-segments-contents-to-queue! segments queue)
239   (for-each
240    (lambda (segment)
241      (let ((seg-queue (time-segment-queue segment)))
242        (while (not (q-empty? seg-queue))
243          (enq! queue (deq! seg-queue)))))
244    segments))
245
246
247 \f
248 ;;; Port handling
249 ;;; =============
250
251 (define (make-port-mapping)
252   (make-hash-table))
253
254 (define* (port-mapping-set! port-mapping port #:optional read write except)
255   "Sets port-mapping for reader / writer / exception handlers"
256   (if (not (or read write except))
257       (throw 'no-handlers-given "No handlers given for port" port))
258   (hashq-set! port-mapping port
259               `#(,read ,write ,except)))
260
261 (define (port-mapping-remove! port-mapping port)
262   (hashq-remove! port-mapping port))
263
264 ;; TODO: This is O(n), I'm pretty sure :\
265 ;; ... it might be worthwhile for us to have a
266 ;;   port-mapping record that keeps a count of how many
267 ;;   handlers (maybe via a promise?)
268 (define (port-mapping-empty? port-mapping)
269   "Is this port mapping empty?"
270   (eq? (hash-count (const #t) port-mapping) 0))
271
272 (define (port-mapping-non-empty? port-mapping)
273   "Whether this port-mapping contains any elements"
274   (not (port-mapping-empty? port-mapping)))
275
276
277 \f
278 ;;; Request to run stuff
279 ;;; ====================
280
281 (define-record-type <run-request>
282   (make-run-request proc when)
283   run-request?
284   (proc run-request-proc)
285   (when run-request-when))
286
287 (define* (run proc #:optional when)
288   (make-run-request proc when))
289
290 (define-syntax-rule (wrap body ...)
291   (lambda ()
292     body ...))
293
294 (define-syntax-rule (run-wrap body ...)
295   (run (wrap body ...)))
296
297 (define-syntax-rule (run-wrap-at body ... when)
298   (run (wrap body ...) when))
299
300 \f
301 ;;; Execution of agenda, and current agenda
302 ;;; =======================================
303
304 (define %current-agenda (make-parameter #f))
305
306 (define* (start-agenda agenda #:key stop-condition)
307   (let loop ((agenda agenda))
308     (let ((agenda   
309            ;; @@: Hm, maybe here would be a great place to handle
310            ;;   select'ing on ports.
311            ;;   We could compose over agenda-run-once and agenda-read-ports
312            (parameterize ((%current-agenda agenda))
313              (agenda-run-once agenda))))
314       (if (and stop-condition (stop-condition agenda))
315           'done
316           (let* ((new-time (gettimeofday))
317                  (agenda
318                   ;; Adjust the agenda's time just in time
319                   ;; We do this here rather than in agenda-run-once to make
320                   ;; agenda-run-once's behavior fairly predictable
321                   (set-field agenda (agenda-time) new-time)))
322             ;; Update the agenda's current queue based on
323             ;; currently applicable time segments
324             (add-segments-contents-to-queue!
325              (schedule-extract-until! (agenda-schedule agenda) new-time)
326              (agenda-queue agenda))
327             (loop agenda))))))
328
329 (define (agenda-run-once agenda)
330   "Run once through the agenda, and produce a new agenda
331 based on the results"
332   (define (call-proc proc)
333     (call-with-prompt
334         (agenda-prompt-tag agenda)
335       (lambda ()
336         (proc))
337       ;; TODO
338       (lambda (k) k)))
339
340   (let ((queue (agenda-queue agenda))
341         (next-queue (make-q)))
342     (while (not (q-empty? queue))
343       (let* ((proc (q-pop! queue))
344              (proc-result (call-proc proc))
345              (enqueue
346               (lambda (run-request)
347                 (define (schedule-at! time proc)
348                   (schedule-add! (agenda-schedule agenda) time proc))
349                 (let ((request-time (run-request-when run-request)))
350                   (match request-time
351                     ((? time-delta? time-delta)
352                      (let ((time (time-+ (agenda-time agenda)
353                                          time-delta)))
354                        (schedule-at! time (run-request-proc run-request))))
355                     ((? integer? sec)
356                      (let ((time (cons sec 0)))
357                        (schedule-at! time (run-request-proc run-request))))
358                     (((? integer? sec) . (? integer? usec))
359                      (schedule-at! request-time (run-request-proc run-request)))
360                     (#f
361                      (enq! next-queue (run-request-proc run-request))))))))
362         ;; @@: We might support delay-wrapped procedures here
363         (match proc-result
364           ;; TODO: replace procedure with something that indicates
365           ;;   intent to run.  Use a (run foo) procedure
366           ((? run-request? new-proc)
367            (enqueue new-proc))
368           (((? run-request? new-procs) ...)
369            (for-each
370             (lambda (new-proc)
371               (enqueue new-proc))
372             new-procs))
373           ;; do nothing
374           (_ #f))))
375     ;; TODO: Alternately, we could return the next-queue
376     ;;   along with changes to be added to the schedule here?
377     ;; Return new agenda, with next queue set
378     (set-field agenda (agenda-queue) next-queue)))