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

Function throttleShapeEffect

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

Source from the content-addressed store, hash-verified

6892}
6893
6894const throttleShapeEffect = <A, E, R, E2, R2>(
6895 self: Stream.Stream<A, E, R>,
6896 costFn: (chunk: Chunk.Chunk<A>) => Effect.Effect<number, E2, R2>,
6897 units: number,
6898 duration: Duration.DurationInput,
6899 burst: number
6900): Stream.Stream<A, E | E2, R | R2> => {
6901 const loop = (
6902 tokens: number,
6903 timestampMillis: number
6904 ): Channel.Channel<Chunk.Chunk<A>, Chunk.Chunk<A>, E | E2, E, void, unknown, R2> =>
6905 core.readWithCause({
6906 onInput: (input: Chunk.Chunk<A>) =>
6907 pipe(
6908 costFn(input),
6909 Effect.zip(Clock.currentTimeMillis),
6910 Effect.map(([weight, currentTimeMillis]) => {
6911 const elapsed = currentTimeMillis - timestampMillis
6912 const cycles = elapsed / Duration.toMillis(duration)
6913 const sum = tokens + (cycles * units)
6914 const max = units + burst < 0 ? Number.POSITIVE_INFINITY : units + burst
6915 const available = sum < 0 ? max : Math.min(sum, max)
6916 const remaining = available - weight
6917 const waitCycles = remaining >= 0 ? 0 : -remaining / units
6918 const delay = Duration.millis(Math.max(0, waitCycles * Duration.toMillis(duration)))
6919 if (Duration.greaterThan(delay, Duration.zero)) {
6920 return pipe(
6921 core.fromEffect(Clock.sleep(delay)),
6922 channel.zipRight(core.write(input)),
6923 core.flatMap(() => loop(remaining, currentTimeMillis))
6924 )
6925 }
6926 return core.flatMap(
6927 core.write(input),
6928 () => loop(remaining, currentTimeMillis)
6929 )
6930 }),
6931 channel.unwrap
6932 ),
6933 onFailure: core.failCause,
6934 onDone: () => core.void
6935 })
6936 const throttled = pipe(
6937 Clock.currentTimeMillis,
6938 Effect.map((currentTimeMillis) => loop(units, currentTimeMillis)),
6939 channel.unwrap
6940 )
6941 return new StreamImpl(pipe(toChannel(self), channel.pipeToOrFail(throttled)))
6942}
6943
6944/** @internal */
6945export const tick = (interval: Duration.DurationInput): Stream.Stream<void> =>

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