MCPcopy Create free account
hub / github.com/Effect-TS/effect / throttleEnforceEffect

Function throttleEnforceEffect

packages/effect/src/internal/stream.ts:6851–6892  ·  view source on GitHub ↗
(
  self: Stream.Stream<A, E, R>,
  cost: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>,
  units: number,
  duration: Duration.DurationInput,
  burst: number
)

Source from the content-addressed store, hash-verified

6849)
6850
6851const throttleEnforceEffect = <A, E, R, E2, R2>(
6852 self: Stream.Stream<A, E, R>,
6853 cost: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>,
6854 units: number,
6855 duration: Duration.DurationInput,
6856 burst: number
6857): Stream.Stream<A, E | E2, R | R2> => {
6858 const loop = (
6859 tokens: number,
6860 timestampMillis: number
6861 ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, void, unknown, R2> =>
6862 core.readWithCause({
6863 onInput: (input: Chunk.Chunk<A>) =>
6864 pipe(
6865 cost(input),
6866 Effect.zip(Clock.currentTimeMillis),
6867 Effect.map(([weight, currentTimeMillis]) => {
6868 const elapsed = currentTimeMillis - timestampMillis
6869 const cycles = elapsed / Duration.toMillis(duration)
6870 const sum = tokens + (cycles * units)
6871 const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst
6872 const available = sum < 0 ? max : Math.min(sum, max)
6873 if (weight <= available) {
6874 return pipe(
6875 core.write(input),
6876 core.flatMap(() => loop(available - weight, currentTimeMillis))
6877 )
6878 }
6879 return loop(tokens, timestampMillis)
6880 }),
6881 channel.unwrap
6882 ),
6883 onFailure: core.failCause,
6884 onDone: () => core.void
6885 })
6886 const throttled = pipe(
6887 Clock.currentTimeMillis,
6888 Effect.map((currentTimeMillis) => loop(units, currentTimeMillis)),
6889 channel.unwrap
6890 )
6891 return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(throttled)))
6892}
6893
6894const throttleShapeEffect = <A, E, R, E2, R2>(
6895 self: Stream.Stream<A, E, R>,

Callers 1

stream.tsFile · 0.85

Calls 4

pipeFunction · 0.70
loopFunction · 0.70
toChannelFunction · 0.70
mapMethod · 0.65

Tested by

no test coverage detected