Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposed doc change to show with-timeout using :interrupt? #66

Merged
merged 5 commits into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ execution if the open condition triggered.

A rate limiter protects your code block to run limited times per
second. It will block or throw exception depends on your
configuration.
configuration. (:rate is a floating point number, and can be less than 1.0.
Example: 0.5 is once every two seconds.)

```clojure
(require '[diehard.core :as dh])
Expand Down Expand Up @@ -80,7 +81,8 @@ Timeouts allow you to fail an execution with `TimeoutExceededException` if it ta
```clojure
(require '[diehard.core :as dh])

(dh/with-timeout {:timeout-ms 5000}
(dh/with-timeout {:timeout-ms 5000
:interrupt? true}
(fly-me-to-the-moon))
```

Expand Down
4 changes: 3 additions & 1 deletion src/diehard/spec.clj
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,9 @@
:timeout/on-failure]))

;; rate limiter
(s/def :rate-limiter/rate int?)
; allow floating point numbers, so that we can pass numbers such as 0.5, to signify 1 req / 2 seconds
;(s/def :rate-limiter/rate int?)
(s/def :rate-limiter/rate number?)
(s/def :rate-limiter/max-cached-tokens int?)

(s/def :rate-limiter/rate-limiter-new
Expand Down
21 changes: 20 additions & 1 deletion test/diehard/rate_limiter_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,23 @@
(.shutdown pool)
(t/is (< (Math/abs (- @counter (* rate time-secs)))
;; error tolerance 3%
(* 0.03 (* rate time-secs)))))))
(* 0.03 (* rate time-secs))))))

(t/testing "rate limits less than 1.0"
(let [rate 0.5
threads 1
pool (Executors/newFixedThreadPool threads)
rl (r/rate-limiter {:rate rate})
counter (atom 0)
time-secs 5]
(doseq [_ (range threads)]
(.submit pool (cast Runnable (fn []
(while true
(r/acquire! rl)
(swap! counter inc))))))
(Thread/sleep (* time-secs 1000))
(.shutdown pool)
(let [variance (Math/abs (- @counter (* rate time-secs)))]
(t/is (<= variance
;; error tolerance: 0.5 -- larger, because we are dealing with slower ticks
0.5))))))
Loading