MCPcopy Index your code
hub / github.com/Effect-TS/effect / tokenBucket

Function tokenBucket

packages/effect/src/internal/rateLimiter.ts:30–58  ·  view source on GitHub ↗
(limit: number, window: DurationInput)

Source from the content-addressed store, hash-verified

28}
29
30const tokenBucket = (limit: number, window: DurationInput): Effect.Effect<
31 RateLimiter.RateLimiter,
32 never,
33 Scope.Scope
34> =>
35 Effect.gen(function*() {
36 const millisPerToken = Math.ceil(Duration.toMillis(window) / limit)
37 const semaphore = yield* Effect.makeSemaphore(limit)
38 const latch = yield* Effect.makeSemaphore(0)
39 const refill: Effect.Effect<void> = Effect.sleep(millisPerToken).pipe(
40 Effect.zipRight(latch.releaseAll),
41 Effect.zipRight(semaphore.release(1)),
42 Effect.flatMap((free) => free === limit ? Effect.void : refill)
43 )
44 yield* pipe(
45 latch.take(1),
46 Effect.zipRight(refill),
47 Effect.forever,
48 Effect.forkScoped,
49 Effect.interruptible
50 )
51 const take = Effect.uninterruptibleMask((restore) =>
52 Effect.flatMap(
53 FiberRef.get(currentCost),
54 (cost) => Effect.zipRight(restore(semaphore.take(cost)), latch.release(1))
55 )
56 )
57 return (effect) => Effect.zipRight(take, effect)
58 })
59
60const fixedWindow = (limit: number, window: DurationInput): Effect.Effect<
61 RateLimiter.RateLimiter,

Callers 1

makeFunction · 0.70

Calls 7

restoreFunction · 0.85
releaseMethod · 0.80
pipeFunction · 0.70
pipeMethod · 0.65
sleepMethod · 0.65
takeMethod · 0.65
getMethod · 0.65

Tested by

no test coverage detected