Fork me on GitHub
#missionary
<
2022-03-15
>
ribelo20:03:58

how to write a limiter idiomatically? i would like to limit the number of requests to the api in a unit of time but my functional thinking is not yet the best...

ribelo20:03:45

I have come up with something like this for now, but this internal state can probably be cut out somehow

(defn -limit
  [n ms >f]
  (mi/ap
   (let [start-time_ (volatile! (ex/-now-udt))
         [i x] (mi/?> (mi/eduction (map-indexed vector) >f))]
     (if (zero? (mod (inc i) n))
       (do (mi/? (mi/sleep (max 0 (- ms (- (ex/-now-udt) @start-time_))))) (vreset! start-time_ (ex/-now-udt)) x)
       x))))

Ben Sless04:03:17

E.g. a rate limiter?

ribelo07:03:15

the above works, but the volatility annoys me

leonoel07:03:05

mutable state is fine here, physical time is stateful anyways

leonoel07:03:53

it would even work with a non-volatile var because ap actions are HB ordered within a single evaluation context

Ben Sless10:03:20

You can try separating the rate calculation and rate limiting