Skip to content

Add comprehensive rate limiting module with policy management#64

Merged
antosubash merged 9 commits intomainfrom
claude/add-rate-limiting-module-pjtmF
Apr 3, 2026
Merged

Add comprehensive rate limiting module with policy management#64
antosubash merged 9 commits intomainfrom
claude/add-rate-limiting-module-pjtmF

Conversation

@antosubash
Copy link
Copy Markdown
Owner

Summary

This PR introduces a complete rate limiting system for SimpleModule, including policy management, database persistence, admin UI, and ASP.NET Core integration. The implementation supports three rate limiting algorithms (Fixed Window, Sliding Window, Token Bucket) with flexible targeting options (IP, User, IP+User, Global).

Key Changes

Core Framework

  • Rate Limiting Abstractions: Added RateLimitPolicyType, RateLimitTarget, RateLimitPolicyDefinition, and registry interfaces to SimpleModule.Core
  • Policy Registry: Implemented RateLimitPolicyRegistry supporting fluent API for policy registration with case-insensitive lookups
  • Endpoint Extensions: Added RateLimit<TBuilder>() extension for declarative policy application to endpoints

Rate Limiting Module

  • Service Layer: RateLimitingService provides CRUD operations for rate limit rules with database persistence
  • Database: RateLimitingDbContext with RateLimitRule entity supporting all policy types and configurations
  • Contracts: Request/response DTOs (CreateRateLimitRuleRequest, UpdateRateLimitRuleRequest) with value object RateLimitRuleId
  • REST API: Full endpoint suite (Create, Read, Update, Delete, GetAll, GetActive) with validation
  • Admin UI: React component for managing stored rules and viewing active policies with real-time updates

ASP.NET Core Integration

  • Middleware: RateLimitHeaderMiddleware adds rate limit policy information to response headers
  • Setup: RateLimitingSetup configures ASP.NET Core's built-in rate limiting with three algorithm implementations:
    • Fixed Window: Simple permit-per-window model
    • Sliding Window: Segmented window for smoother rate limiting
    • Token Bucket: Continuous token replenishment model
  • Rejection Handling: Standardized 429 responses with RFC 7231 Retry-After headers

Built-in Policies

Module registers four default policies:

  • fixed-default: 60 requests/minute per IP
  • sliding-strict: 30 requests/minute per IP+User with 6 segments
  • token-bucket: 100 token capacity, 10 tokens/10 seconds per IP
  • auth-strict: 10 requests/minute for authentication endpoints

Testing

  • Comprehensive unit tests for service layer (CRUD operations, persistence)
  • Policy registry tests (registration, retrieval, case-insensitivity, chaining)
  • Module configuration tests validating built-in policies

Code Generation

  • Updated ModuleExtensionsEmitter to collect and register rate limit policies from modules
  • Enhanced discovery to track HasConfigureRateLimits capability
  • Integrated rate limiting setup into host configuration pipeline

Notable Implementation Details

  • Uses in-memory SQLite for testing with proper async/await patterns
  • Supports endpoint pattern matching for selective policy application
  • Partition keys resolved from HTTP context (IP address, user ID, or combination)
  • Fluent builder pattern for policy registration with method chaining
  • Structured logging with source-generated log methods
  • TypeScript type generation for frontend integration

https://claude.ai/code/session_01MR7ZSUPUM58TGcCZKXhCxn

claude and others added 3 commits April 3, 2026 07:13
- Add rate limiting abstractions to SimpleModule.Core: policy types (FixedWindow,
  SlidingWindow, TokenBucket), target modes (IP, User, IpAndUser, Global),
  IRateLimitBuilder, IRateLimitPolicyRegistry, and .RateLimit() endpoint extension
- Add ConfigureRateLimits() lifecycle hook to IModule interface
- Integrate ASP.NET Core RateLimiter middleware in SimpleModule.Hosting with
  automatic policy registration from module definitions
- Add X-RateLimit-* response headers via RateLimitHeaderMiddleware
- Update source generator to discover and wire ConfigureRateLimits on modules
- Create RateLimiting module with:
  - Contracts: RateLimitRule entity, CRUD DTOs, IRateLimitingContracts
  - Implementation: DbContext, CRUD service, REST endpoints, permissions
  - Admin UI: React/Inertia page for managing stored rules and viewing active policies
  - 4 built-in policies: fixed-default, sliding-strict, token-bucket, auth-strict
  - Navigation menu in admin sidebar
- Add 18 unit tests covering policy registry and CRUD service
- Register module in Host project, solution, and test infrastructure
- Use Dictionary<string, RateLimitPolicyDefinition> for O(1) policy lookup
  instead of linear List.Find on every rate-limited request
- Pre-build rate limiter options at registration time instead of allocating
  per-request in the partition factory
- Accept IRateLimitPolicyRegistry interface instead of concrete type in
  AddSimpleModuleRateLimiting to avoid leaking implementation details
- Extract CreateRequestValidator class following the codebase convention
  used by Products, Orders, and Tenants modules
- Extract API_BASE constant in Admin.tsx to eliminate hardcoded URL strings
- Fix handleToggle to send only UpdateRateLimitRuleRequest fields instead
  of spreading the full entity (which includes id, policyName, timestamps)
@antosubash antosubash marked this pull request as draft April 3, 2026 12:12
@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages Bot commented Apr 3, 2026

Deploying simplemodule-website with  Cloudflare Pages  Cloudflare Pages

Latest commit: 367bd3a
Status: ✅  Deploy successful!
Preview URL: https://71249f03.simplemodule-website.pages.dev
Branch Preview URL: https://claude-add-rate-limiting-mod.simplemodule-website.pages.dev

View logs

claude and others added 4 commits April 3, 2026 12:37
- Add page object (RateLimitingAdminPage) with selectors for heading,
  tabs, create dialog, rules table, and toggle/delete actions
- Add smoke tests: page loads, tabs visible, active policies table
- Add flow tests: full CRUD via API (create, read, update, delete),
  active policies endpoint verification, UI visibility after API create,
  create dialog opens from admin page
Resolve conflicts with Email module addition — keep both
RateLimiting and Email modules in solution, host project,
and test infrastructure.
@cloudflare-workers-and-pages
Copy link
Copy Markdown

cloudflare-workers-and-pages Bot commented Apr 3, 2026

Deploying simplemodule-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 0465f49
Status: ✅  Deploy successful!
Preview URL: https://037ff4c3.simplemodule.pages.dev
Branch Preview URL: https://claude-add-rate-limiting-mod.simplemodule.pages.dev

View logs

claude added 2 commits April 3, 2026 14:47
The RateLimiting admin page returned 500 because the database tables
were never created in the test infrastructure. Added the missing
EnsureTablesCreated<RateLimitingDbContext> call to the WebApplicationFactory
initialization alongside all other module contexts.

Also adds integration tests that verify the admin page and API endpoints
return 200 for authenticated admin users.
The E2E tests failed because the RateLimiting_Rules table didn't exist
in the SQLite database. The server uses MigrateAsync() on the HostDbContext
which requires an explicit migration to create new tables.

This migration creates the RateLimiting_Rules table with all columns,
the unique index on PolicyName, and also includes pending BackgroundJobs
and Email tables from the main branch merge.
@antosubash antosubash marked this pull request as ready for review April 3, 2026 15:03
@antosubash antosubash merged commit cd99418 into main Apr 3, 2026
4 checks passed
@antosubash antosubash deleted the claude/add-rate-limiting-module-pjtmF branch April 3, 2026 15:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants