Debian Codegraph @

lib/control/scheduler.scm

raw
1 ;;;
2 ;;; control.scheduler - scheduler
3 ;;;
4 ;;; Copyright (c) 2021-2024 Shiro Kawai <[email protected]>
5 ;;;
6 ;;; Redistribution and use in source and binary forms, with or without
7 ;;; modification, are permitted provided that the following conditions
8 ;;; are met:
9 ;;;
10 ;;; 1. Redistributions of source code must retain the above copyright
11 ;;; notice, this list of conditions and the following disclaimer.
12 ;;;
13 ;;; 2. Redistributions in binary form must reproduce the above copyright
14 ;;; notice, this list of conditions and the following disclaimer in the
15 ;;; documentation and/or other materials provided with the distribution.
16 ;;;
17 ;;; 3. Neither the name of the authors nor the names of its contributors
18 ;;; may be used to endorse or promote products derived from this
19 ;;; software without specific prior written permission.
20 ;;;
21 ;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
22 ;;; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
23 ;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
24 ;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
25 ;;; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
26 ;;; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
27 ;;; TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
28 ;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
29 ;;; LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
30 ;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
31 ;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 ;;;
33
34 (define-module control.scheduler
35 (use gauche.threads)
36 (use gauche.dictionary)
37 (use data.queue)
38 (use data.priority-map) ;id -> (thunk time)
39 (use srfi.19)
40 (use control.job)
41 (export <scheduler>
42 scheduler-schedule!
43 scheduler-reschedule!
44 scheduler-remove!
45 scheduler-exists?
46 scheduler-running?
47 scheduler-terminate!))
48 (select-module control.scheduler)
49
50 (define-class <scheduler> ()
51 ((error-handler :init-keyword :error-handler :init-value #f)
52 ;; The following slots are private. Only the scheduler's thread
53 ;; modifies those data structures. The client thread (the caller of
54 ;; API) just inserts request to the queue.
55 (request-queue :init-form (make-mtqueue :max-length 0))
56 (task-queue :init-form (make-priority-map :value-comparator task-comparator))
57 (next-task-id :init-value 0)
58 (exception :init-value (undefined))
59 (thread)))
60
61 (define-method initialize ((s <scheduler>) initargs)
62 (next-method)
63 (set! (~ s'thread) (make-scheduler-thread s)))
64
65 ;; Request queue is a queue of jobs (control.job).
66 ;; Public API actually sends a request to the scheduler's thread,
67 ;; and retrieves the result.
68 (define (request-response scheduler thunk :optional (end? #f))
69 (define job (make-job thunk :waitable #t))
70 (enqueue/wait! (~ scheduler'request-queue) job #f #f end?)
71 (job-wait job)
72 (let1 r (job-result job)
73 (if (is-a? r <condition>)
74 (raise r)
75 r)))
76
77 ;; Task queue is a queue of <task>s.
78 ;; For periodical tasks, time slot is updated to the next absolute time
79 ;; after the task is run.
80 (define-class <task> ()
81 ((id :init-keyword :id)
82 (thunk :init-keyword :thunk)
83 (time :init-keyword :time) ;absolute time to invoke thunk
84 (interval :init-keyword :interval))) ;#f for one-shot
85
86 (define (task-equal a b)
87 (and (eqv? (~ a'id) (~ b'id))
88 (eq? (~ a'thunk) (~ b'thunk))
89 (time=? (~ a'time) (~ b'time))
90 (equal? (~ a'time) (~ b'time))))
91
92 (define (task-compare a b)
93 (time<? (~ a'time) (~ b'time)))
94
95 (define task-comparator
96 (make-comparator (cut is-a? <> <task>) task-equal task-compare #f))
97
98 (define (make-task scheduler thunk time interval)
99 (rlet1 t (make <task> :id (~ scheduler'next-task-id)
100 :thunk thunk :time time :interval interval)
101 (inc! (~ scheduler'next-task-id))))
102
103 ;; Scheduler thread.
104 ;; Each scheduler runs an event processing loop with this thread.
105 ;; When a task throws an error and not handled by error-handler, we
106 ;; still keep running thread but no longer runs ready tasks.
107 (define (scheduler-thread-proc s)
108 (define (cancel-by-error e)
109 (set! (~ s'exception) e))
110 (define end? #f)
111 (^[]
112 (do () (end?)
113 (guard (e [(eq? e 'end) (set! end? #t)]
114 [else
115 (if-let1 eh (~ s'error-handler)
116 (guard (e [else (cancel-by-error e)])
117 (eh e))
118 (cancel-by-error e))])
119 (unless (slot-bound? s 'exception)
120 (run-ready-tasks! (~ s'task-queue)))
121 (and-let1 req (dequeue/wait! (~ s'request-queue)
122 (next-check-time (~ s'task-queue)))
123 (job-run! req))))))
124
125 (define (make-scheduler-thread s)
126 (thread-start! (make-thread (scheduler-thread-proc s))))
127
128 (define-constant *zero-duration* (make-time 'time-duration 0 0))
129
130 ;; Run tasks ready to execute
131 (define (run-ready-tasks! task-queue)
132 (and-let* ([p (priority-map-min task-queue)]
133 [id (car p)]
134 [task (cdr p)])
135 (when (time<=? (~ task'time) (current-time))
136 (dict-delete! task-queue id)
137 ((~ task'thunk))
138 (when (and (~ task'interval)
139 (not (eqv? (~ task'interval) 0))
140 (not (equal? (~ task'interval) *zero-duration*)))
141 (set! (~ task'time) (absolute-time (~ task'interval)))
142 (dict-put! task-queue id task))
143 (run-ready-tasks! task-queue))))
144
145 ;; Return next absolute time to check the task queue. #f if no need to check.
146 (define (next-check-time task-queue)
147 (and-let1 p (priority-map-min task-queue)
148 (~ (cdr p)'time)))
149
150 (define (validate-time when)
151 (or (and (real? when) (>= when 0))
152 (and (time? when) (memq (time-type when) '(time-duration time-utc)))
153 (error "Nonnegative real number or <time> is expected, but got:" when)))
154
155 (define (validate-duration dur)
156 (or (and (real? dur) (>= dur 0))
157 (and (time? dur) (eq? (time-type dur) 'time-duration))
158 (error "Nonnegative real number or <time> of time-duration is expected, but got:" when)))
159
160 (define (absolute-time when)
161 (cond [(real? when)
162 (receive (dfrac dsec) (modf when)
163 (let* ([now (current-time)]
164 [sec (+ (time-second now) (exact dsec))]
165 [nsec (+ (time-nanosecond now)
166 (round->exact (* dfrac 1e9)))])
167 (receive (sec nsec)
168 (if (>= nsec #e1e9)
169 (values (+ sec (exact (quotient nsec #e1e9)))
170 (modulo nsec #e1e9))
171 (values sec nsec))
172 (make-time time-utc nsec sec))))]
173 [(time? when)
174 (case (time-type when)
175 [(time-duration) (add-duration (current-time) when)]
176 [(time-utc time-tai) when]
177 [else (error "bad time object for 'when':" when)])]
178 [else (error "bad object for 'when':" when)]))
179
180 ;; API
181 ;; Returns task id
182 (define (scheduler-schedule! s thunk when :optional (interval #f))
183 (validate-time when)
184 (and interval (validate-duration interval))
185 ($ request-response s
186 (^[]
187 (let1 task (make-task s thunk (absolute-time when) interval)
188 (dict-put! (~ s'task-queue) (~ task'id) task)
189 (~ task'id)))))
190
191 ;; API
192 (define (scheduler-reschedule! s task-id when :optional (interval #f))
193 (or (eq? when 'unchanged)
194 (validate-time when))
195 (or (eq? interval 'unchanged)
196 (not interval)
197 (validate-duration interval))
198 ($ request-response s
199 (^[]
200 (if-let1 task (dict-get (~ s'task-queue) task-id #f)
201 (begin
202 (dict-delete! (~ s'task-queue) task-id)
203 (unless (eq? when 'unchanged)
204 (set! (~ task'time) (absolute-time when)))
205 (unless (eq? when 'unchanged)
206 (set! (~ task'interval) interval))
207 (dict-put! (~ s'task-queue) task-id task)
208 task-id)
209 (condition
210 (<error> (message (format "No task with id: ~s" task-id))))))))
211
212 ;; API
213 ;; Returns #t if task is removed, #f if not, for SRFI-120 specifies so.
214 ;; Relies on such behaivor of dict-delete!
215 (define (scheduler-remove! s task-id)
216 ($ request-response s
217 (^[] (dict-delete! (~ s'task-queue) task-id))))
218
219 ;; API
220 (define (scheduler-exists? s task-id)
221 ($ request-response s
222 (^[] (dict-exists? (~ s'task-queue) task-id))))
223
224 ;; API
225 (define (scheduler-running? s)
226 (not (~ s'request-queue'closed)))
227
228 ;; API
229 (define (scheduler-terminate! s :key (on-error :reraise))
230 (assume (memq on-error '(:reraise :return)))
231 ($ request-response s (^[] (raise 'end)) #t)
232 (if (and (slot-bound? s 'exception)
233 (eq? on-error :reraise))
234 (raise (~ s'exception))
235 #t))