#!/usr/bin/env bash
# check-kms-request-quota.sh
# Read-only. Reports your KMS symmetric crypto-op request-rate quota and recent peak usage
# so you can see how close you are to throttling BEFORE a batch job trips ThrottlingException.
#
# Requires: awscli v2, jq. Uses Service Quotas + CloudWatch. No write operations.
# Usage: AWS_REGION=us-east-1 ./check-kms-request-quota.sh
set -euo pipefail

REGION="${AWS_REGION:-us-east-1}"
# Service Quotas code for "Cryptographic operations (symmetric) request rate" is L-9E107071.
QUOTA_CODE="${QUOTA_CODE:-L-9E107071}"

echo "Region: ${REGION}"
echo "== Symmetric cryptographic-operations request-rate quota =="
aws service-quotas get-service-quota \
  --service-code kms \
  --quota-code "${QUOTA_CODE}" \
  --region "${REGION}" \
  --query '{Quota:Quota.QuotaName, Limit:Quota.Value, Adjustable:Quota.Adjustable}' \
  --output table 2>/dev/null || echo "  (quota not published in this Region via Service Quotas; open a Support case)"

echo
echo "== Peak KMS request rate over the last 7 days (CloudWatch, 1-min granularity) =="
END=$(date -u +%Y-%m-%dT%H:%M:%SZ)
START=$(date -u -d '7 days ago' +%Y-%m-%dT%H:%M:%SZ 2>/dev/null || date -u -v-7d +%Y-%m-%dT%H:%M:%SZ)

# AWS/Usage shows per-API call volume; divide the 1-min Sum by 60 for an approximate req/s peak.
aws cloudwatch get-metric-statistics \
  --namespace "AWS/Usage" \
  --metric-name "CallCount" \
  --dimensions Name=Type,Value=API Name=Resource,Value=GenerateDataKey Name=Service,Value=KMS Name=Class,Value=None \
  --start-time "${START}" --end-time "${END}" \
  --period 60 --statistics Sum \
  --region "${REGION}" \
  --query 'sort_by(Datapoints,&Sum)[-5:].{Time:Timestamp, CallsPerMin:Sum}' \
  --output table 2>/dev/null || echo "  (no AWS/Usage CallCount data; enable the KMS usage metric or check CloudTrail)"

echo
echo "Rule of thumb: if peak (CallsPerMin / 60) is within ~70% of the quota Limit, add data key"
echo "caching (AWS Encryption SDK) and/or S3 Bucket Keys before requesting a quota increase."
