European Parliament MCP Server API - v1.0.1
    Preparing search index...

    Token bucket rate limiter implementation

    Index

    Constructors

    Properties

    intervalMs: number
    lastRefill: number
    tokens: number
    tokensPerInterval: number

    Methods

    • Returns the number of tokens currently available in the bucket.

      Triggers a refill calculation based on elapsed time before returning the value, so the result reflects the current real-time availability.

      Returns number

      Current token count (may be fractional; floor before display)

      const tokens = rateLimiter.getAvailableTokens();
      console.log(`${tokens} / ${rateLimiter.getMaxTokens()} tokens available`);

      0.8.0

    • Returns the maximum token capacity of this bucket.

      Equal to the tokensPerInterval value passed at construction time. Does not trigger a refill calculation.

      Returns number

      Maximum number of tokens the bucket can hold

      const max = rateLimiter.getMaxTokens(); // e.g. 100
      

      0.8.0

    • Returns a typed status snapshot for health checks and monitoring.

      Triggers a refill calculation so the snapshot reflects real-time bucket state. Useful for /health endpoints and Prometheus exporters.

      Returns RateLimiterStatus

      Current RateLimiterStatus snapshot with availableTokens, maxTokens, and utilizationPercent (0–100)

      const status = rateLimiter.getStatus();
      console.log(`${status.utilizationPercent}% utilized`);
      // e.g. "45% utilized"

      0.8.0

    • Attempts to consume count tokens from the bucket, waiting asynchronously until tokens are available or the timeout expires.

      Refills the bucket based on elapsed time before each check. If sufficient tokens are available they are consumed immediately. Otherwise the method sleeps until the bucket has enough tokens and retries. If the required wait would exceed options.timeoutMs (default 5000 ms) the call returns immediately with allowed: false and a retryAfterMs hint. The timeout is enforced as a hard deadline: even if a sleep fires slightly late due to event-loop delay, tokens are never consumed after the deadline has elapsed.

      Parameters

      • count: number

        Number of tokens to consume (must be a finite integer ≥ 1 and ≤ tokensPerInterval); throws for invalid values

      • Optionaloptions: { timeoutMs?: number }
        • OptionaltimeoutMs?: number

          Maximum time to wait in milliseconds (default 5000); non-finite or negative values are coerced to 0, meaning the call never blocks and returns allowed: false immediately if tokens are unavailable

      Returns Promise<RateLimitResult>

      Promise resolving to a RateLimitResult. allowed is true when tokens were consumed, false when the timeout was reached. remainingTokens is always a non-negative integer (Math.floor of the internal fractional bucket state); it may differ from RateLimiter.getAvailableTokens which returns the raw fractional value.

      const result = await rateLimiter.removeTokens(1);
      if (!result.allowed) {
      console.warn(`Rate limited – retry after ${result.retryAfterMs}ms`);
      } else {
      const data = await fetchFromEPAPI('/meps');
      }

      Prevents abusive high-frequency requests to the EP API. Per ISMS Policy AC-003, rate limiting is a mandatory access control.

      0.8.0

    • Resets the bucket to full capacity and clears the refill timer.

      Useful in tests or after a planned maintenance window where queued demand should not be penalised by an already-depleted bucket.

      Returns void

      afterEach(() => {
      rateLimiter.reset();
      });

      0.8.0

    • Attempts to consume count tokens without throwing on failure.

      Synchronous alternative to removeTokens that returns false instead of waiting when the bucket lacks tokens. Useful in hot paths where callers want to branch on availability rather than await a refill.

      Note: This method still throws for invalid count arguments (non-integer, < 1, or exceeding bucket capacity). It only avoids throwing when there are insufficient tokens in the bucket at the time of the call.

      Parameters

      • count: number

        Number of tokens to consume (must be a finite integer ≥ 1 and ≤ tokensPerInterval); throws for invalid values

      Returns boolean

      true if tokens were successfully consumed, false if the bucket did not have enough tokens (bucket is left unchanged)

      if (!rateLimiter.tryRemoveTokens(1)) {
      return { error: 'Rate limit exceeded. Please try again later.' };
      }
      const data = await fetchFromEPAPI('/meps');

      0.8.0

    • Coerce an optional timeoutMs value to a safe finite number >= 0.

      Parameters

      • rawTimeoutMs: number | undefined

      Returns number