Unkey

Populating Logs

When testing locally or on vercel previews, /logs and /ratelimit/logs page, we need some data to test the functionality. Here is the script we use temporarily.

We're currently working on making this easier by seeding the data for you.

Logs

Make sure you have an API Key with ratelimit enabled.

#!/bin/bash
 
# Check if terminal supports colors
if [ -t 1 ] && command -v tput >/dev/null 2>&1 && [ "$(tput colors)" -ge 8 ]; then
  RED=$(tput setaf 1)
  GREEN=$(tput setaf 2)
  YELLOW=$(tput setaf 3)
  BLUE=$(tput setaf 4)
  CYAN=$(tput setaf 6)
  GRAY=$(tput setaf 8)
  BOLD=$(tput bold)
  NC=$(tput sgr0)
else
  # No color support - use empty strings
  RED=""
  GREEN=""
  YELLOW=""
  BLUE=""
  CYAN=""
  GRAY=""
  BOLD=""
  NC=""
fi
 
# Logging functions
log_header() {
  printf "\n${BOLD}${BLUE}=== %s ===${NC}\n" "$1"
}
 
log_success() {
  printf "${GREEN}✔ %s${NC}\n" "$1"
}
 
log_error() {
  printf "${RED}✖ %s${NC}\n" "$1"
}
 
log_warning() {
  printf "${YELLOW}⚠ %s${NC}\n" "$1"
}
 
log_info() {
  printf "${CYAN}ℹ %s${NC}\n" "$1"
}
 
log_debug() {
  printf "${GRAY}➜ %s${NC}\n" "$1"
}
 
# Check if API key is provided
if [ $# -eq 0 ]; then
  log_error "API key is required"
  log_info "Usage: $0 <api_key>"
  log_info "Example: $0 3ZZcemoaSsXp5YeHc8789yH4"
  exit 1
fi
 
API_KEY="$1"  # Get API key from first command line argument
ROOT_KEY="$2" # Get API key from first command line argument
 
# API endpoints
VERIFY_ENDPOINT="http://localhost:8787/v1/keys.verifyKey"
RATELIMIT_ENDPOINT="http://localhost:8787/v1/ratelimits"
 
# Rate limit settings
RATE_LIMIT_INTERVAL=1000 # milliseconds (1 second)
RATE_LIMIT_TOKENS=15     # max requests per interval
TOTAL_USES_LIMIT=100     # total number of allowed uses
 
# Counter for total requests made
total_requests=0
 
# Function to generate huge random numbers
generate_huge_number() {
  local length=$((RANDOM % 50 + 50)) # Random length between 50-100 digits
  local result=""
 
  # First digit shouldn't be 0
  result+=$((RANDOM % 9 + 1))
 
  # Generate remaining random digits
  for ((i = 1; i < length; i++)); do
    result+=$((RANDOM % 10))
  done
 
  echo "$result"
}
 
# Function to make a malformed request to trigger 500 error
trigger_500_error() {
  log_error "🚨 Triggering 500 error..."
 
  # Generate random huge numbers for limit and duration
  local huge_limit=$(generate_huge_number)
  local huge_duration=$(generate_huge_number)
 
  # Using large number payload with random values
  payload="{\"namespace\":\"\",\"identifier\":\"user_123\",\"limit\":$huge_limit,\"duration\":$huge_duration}"
 
  log_debug "Sending overflow payload..."
 
  # Make the request to the rate limit endpoint
  if response=$(curl -s -X POST "$RATELIMIT_ENDPOINT.limit" \
    -H "Content-Type: application/json" \
    -H "Authorization: Bearer $ROOT_KEY" \
    -d "$payload"); then
    log_error "Error response: $response"
  else
    log_error "500 error triggered (curl exit code: $?)"
  fi
}
 
# Function to trigger warning (400 error)
trigger_warning() {
  log_warning "⚠️ Triggering warning..."
 
  # Random invalid namespace ID
  local random_str="asdasdsad"
 
  if response=$(curl -s -X GET \
    "$RATELIMIT_ENDPOINT.listOverrides?namespaceId=$random_str" \
    -H "Authorization: Bearer $ROOT_KEY"); then
    log_warning "Warning response: $response"
  else
    log_warning "Warning triggered (curl exit code: $?)"
  fi
}
 
# Function to make API call
make_api_call() {
  # Generate random number 0-99 for percentage distribution
  random_num=$((RANDOM % 100))
 
  if [ $random_num -lt 25 ]; then
    # 0-24: Error (25%)
    trigger_500_error
  elif [ $random_num -lt 50 ]; then
    # 25-49: Warning (25%)
    trigger_warning
  else
    # 50-99: Regular request (50%)
    if ! response=$(curl -s -X POST "$VERIFY_ENDPOINT" \
      -H "Content-Type: application/json" \
      -d "{\"key\": \"$API_KEY\"}"); then
      log_error "Failed to make API call"
      return 1
    fi
    log_success "Regular API call successful"
    log_debug "Response: $response"
 
    # Extract remaining calls from response if available
    if echo "$response" | jq -e '.ratelimit.remaining' >/dev/null 2>&1; then
      remaining=$(echo "$response" | jq -r '.ratelimit.remaining')
      log_info "Remaining calls: ${remaining}"
    fi
  fi
 
  # Increment total requests counter
  ((total_requests++))
  progress=$((total_requests * 100 / TOTAL_USES_LIMIT))
  printf "${GRAY}Progress: [${GREEN}%3d%%${GRAY}] %d/%d requests${NC}\n" "$progress" "$total_requests" "$TOTAL_USES_LIMIT"
 
  # Check if we've hit the total usage limit
  if [ "$total_requests" -ge "$TOTAL_USES_LIMIT" ]; then
    log_warning "Total usage limit reached ($TOTAL_USES_LIMIT requests). Exiting..."
    exit 0
  fi
  return 0
}
 
# Script initialization
log_header "API Testing Script Initialization"
log_info "API Key: ${API_KEY:0:4}...${API_KEY: -4}"
log_info "Rate Limit: $RATE_LIMIT_TOKENS requests per $RATE_LIMIT_INTERVAL ms"
log_info "Total Usage Limit: $TOTAL_USES_LIMIT requests"
 
# Initial rate limit configuration
log_header "Initial Setup"
set_rate_limit
 
# Counter for tracking intervals
interval_counter=0
 
while :; do
  requests_this_interval=0
  ((interval_counter++))
 
  log_header "Interval #$interval_counter"
 
  # Every 5 intervals, update rate limit configuration
  if [ $((interval_counter % 5)) -eq 0 ]; then
    log_info "Updating rate limit configuration..."
    set_rate_limit
  fi
 
  # Randomly decide if we'll do a "burst" of requests
  if [ "$((RANDOM % 3))" -eq 0 ]; then
    log_warning "🚀 Initiating burst mode..."
    request_delay=0.01
    burst_requests=$((RATE_LIMIT_TOKENS + 3))
  else
    request_delay=0.1
    burst_requests=$RATE_LIMIT_TOKENS
  fi
 
  # Make API calls until we hit the rate limit or interval ends
  for ((i = 1; i <= burst_requests; i++)); do
    if ! make_api_call; then
      log_error "API call failed, waiting before retry..."
      sleep 1
      continue
    fi
    ((requests_this_interval++))
 
    # Check if we've hit the rate limit
    if [ "$requests_this_interval" -ge "$RATE_LIMIT_TOKENS" ]; then
      log_warning "Rate limit reached. Waiting for next interval..."
      sleep 1
      break
    fi
 
    # Add delay between requests
    sleep "$request_delay"
  done
 
  # Interval summary
  log_success "Made $requests_this_interval requests in interval #$interval_counter"
  log_info "Waiting for next interval..."
  sleep 1
done

Ratelimit Logs

#!/bin/bash
 
# Check for API key in command line args
UNKEY_ROOT_KEY=""
 
while [[ $# -gt 0 ]]; do
  case $1 in
  --key | -k)
    UNKEY_ROOT_KEY="$2"
    shift 2
    ;;
  *)
    break
    ;;
  esac
done
 
# Verify we have a key one way or another
if [ -z "$UNKEY_ROOT_KEY" ]; then
  echo "Error: No API key provided"
  echo "Usage: $0 --key YOUR_KEY"
  echo "   or: UNKEY_ROOT_KEY=your_key $0"
  exit 1
fi
 
# Array of funny identifiers - mix of short and long names
IDENTIFIERS=(
  "tiny_tim"
  "mr_noodles"
  "the_incredible_coding_hamster_9000"
  "bob"
  "sir_types_a_lot_but_mostly_wrong"
  "caffeine_powered_developer"
  "bug_master_flash"
  "404_sleep_not_found"
  "ye"
  "the_developer_formerly_known_as_printer_fixer"
  "zzzz"
  "quantum_bug_generator"
  "git_lord_of_the_commits"
  "ctrl_alt_defeated"
  "vim_escape_artist"
)
 
# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color
 
# Function to make the API call
make_request() {
  local identifier=$1
  local request_number=$2
  local total_requests=$3
 
  echo -e "${YELLOW}Request $request_number/$total_requests for identifier: ${NC}$identifier"
 
  response=$(curl -s --request POST \
    --url 'http://localhost:8787/v1/ratelimits.limit' \
    --header "Authorization: Bearer $UNKEY_ROOT_KEY" \
    --header 'Content-Type: application/json' \
    --data "{
           \"namespace\": \"funny.test\",
           \"identifier\": \"$identifier\",
           \"limit\": 5,
           \"duration\": 10000,
           \"cost\": 1,
           \"async\": false,
           \"meta\": {
             \"mood\": \"playful\",
             \"coffee_level\": \"high\"
           },
           \"resources\": [
             {
               \"type\": \"project\",
               \"id\": \"p_123\",
               \"name\": \"fun_testing\"
             }
           ]
         }")
 
  # Check if request was successful or blocked
  if echo "$response" | grep -q "\"success\":true"; then
    echo -e "${GREEN}✓ Request allowed${NC}"
  else
    echo -e "${RED}✗ Request blocked${NC}"
  fi
  echo "$response" | jq '.' 2>/dev/null || echo "$response"
  echo "-------------------"
}
 
# Number of requests to make for each identifier
REQUESTS_PER_ID=7
 
# Loop through each identifier and make multiple requests
for identifier in "${IDENTIFIERS[@]}"; do
  echo -e "\n${YELLOW}=== Testing identifier: $identifier ===${NC}"
  for ((i = 1; i <= $REQUESTS_PER_ID; i++)); do
    make_request "$identifier" "$i" "$REQUESTS_PER_ID"
    sleep 0.5 # Small delay between requests
  done
  echo -e "\n${YELLOW}=== Finished testing $identifier ===${NC}"
  sleep 2 # Pause between different identifiers
done
 
echo -e "\n${GREEN}Testing completed!${NC}"

Last updated on

On this page