Dynamic Time Restriction System - Developer Documentation
This component provides a robust, MongoDB-backed time restriction system that allows updating API availability (times, days, routes) without any code deployment. It uses a template-based approach to minimize duplication.
Key Features
- Zero Deployment Updates: Change settings via API or direct DB update (MongoDB).
- Template-Based: Define reusable time restriction templates and reference them across multiple routes.
- Distributed Caching (Redis): Uses Redis to share configuration across all server instances.
- Manual Refresh: Admin API to trigger an immediate update in Redis and all server instances.
Directory Structure
models.py: Pydantic models for data validation and structure.service.py: Core logic for caching (Redis), DB syncing (MongoDB), and template-based access checking. Includes a configurable in-memory local cache (Default: 10 minutes) for zero-latency lookups.middleware.py: FastAPI middleware for global enforcement of restrictions.api.py: Admin endpoints for configuration and template management.utils.py: Helper functions for JSON serialization.
API Usage
1. View Current Configuration
Endpoint: GET /api/v1/time-restrictions/
Returns the current active configuration (routes + resolved templates) currently loaded in memory.
2. Manage Templates (Reduced Duplication)
Templates are stored in the time_restriction_templates collection.
Endpoint: POST /api/v1/time-restrictions/templates
Body:
{
"name": "standard_school_hours",
"time_slots": [
{
"start_time": "08:00:00",
"end_time": "18:00:00",
"allowed_days": ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]
}
],
"enabled": true,
"message": "API available only during school hours (08:00 - 18:00)",
"status_code": 423,
"user_id": "60d5ecb8b391690015ef5c2a"
}
Endpoint: GET /api/v1/time-restrictions/templates - List all templates.
Endpoint: DELETE /api/v1/time-restrictions/templates/{name} - Delete a template.
3. Configure Routes
Routes are stored in the dynamic_time_restrictions collection. Routes can reference templates and override specific fields.
Endpoint: PUT /api/v1/time-restrictions/
Body:
{
"routes": {
"/api/teacher/app/create_student_assessment/": {
"template": "standard_school_hours",
"enabled": true,
"message": "Custom Message: Assessment not available now"
},
"/api/v2/admin/emergency-block/": {
"time_slots": [],
"enabled": true,
"force_block": true,
"message": "Emergency maintenance in progress"
}
},
"user_id": "60d5ecb8b391690015ef5c2a"
}
Updating via this API saves the config as the "active" record in the dynamic_time_restrictions collection and immediately refreshes the server instance's memory cache.
2.3 Partial Update (Merging)
Endpoint: PATCH /api/v1/time-restrictions/
Allows you to update specific routes without providing the full configuration. New routes are added, and existing ones are updated.
Body:
{
"routes": {
"/api/teacher/app/new-feature/": {
"template": "school_hours",
"enabled": true
}
},
"user_id": "60d5ecb8b391690015ef5c2a"
}
Detailed Model Attributes
Template & Route Common Attributes
| Attribute | Type | Description |
|---|---|---|
name | string | (Template Only) Unique identifier for the template. |
template | string | (Route Only) Reference to a template's name. The route will inherit the template's settings. |
time_slots | array | List of allowed time intervals. If defined at the route level, it overrides the template. |
enabled | boolean | If false, the restriction is disabled for this route/template (Default: true). |
force_block | boolean | If true, the API is blocked 24/7 regardless of time slots. If either route OR template has this true, it is blocked (Default: false). |
message | string | Custom error message shown when blocked. |
status_code | integer | HTTP status code returned when blocked (Default: 423). |
endpoint_detail | string | (Route Only) Optional description of what the API does for documentation purposes. |
user_id | string | Required. Must be a valid 24-character hex MongoDB ObjectId. |
Time Slot Object
| Attribute | Type | Description |
|---|---|---|
start_time | string | Format "HH:MM:SS" (e.g., "08:00:00"). |
end_time | string | Format "HH:MM:SS" (e.g., "18:00:00"). |
allowed_days | array | List of days ("monday", "tuesday", etc.) when access is permitted. |
timezone | string | Timezone for calculations (Default: "Asia/Kolkata"). |
Overriding Logic
- Field Override: If a route provides its own
time_slots,message, orstatus_code, it completely overrides the values in the referencedtemplate. force_blockMerge: If a template saysforce_block: true, its routes are blocked unless they disable the restriction viaenabled: false.
4. Force Sync from Database
Endpoint: POST /api/v1/time-restrictions/refresh
Forces the server to sync with the latest MongoDB state (both templates and routes) immediately.
Integration Details
- This component is registered in
main.pyviaDynamicTimeRestrictionMiddleware. - The router is registered under the prefix
/api/v1/time-restrictions. - The original logic in
app/time_restrictionsis preserved but inactive as a backup.