102 lines
3.8 KiB
Markdown
102 lines
3.8 KiB
Markdown
# Subtask: Short Code Generation with Collision Handling
|
|
|
|
**Parent Task**: Decomp/001
|
|
**Subtask ID**: Decomp/001-03
|
|
**Dependencies**: Decomp/001-01 (Database Schema), Decomp/001-02 (Base62 Encoding)
|
|
|
|
## Description
|
|
Implement unique short code generation using database sequence IDs with Base62 encoding. Handle hash collisions gracefully when generating codes from URL hashes.
|
|
|
|
## Requirements
|
|
- Generate 6-8 character short codes
|
|
- Handle collisions gracefully (retry with different encoding)
|
|
- Support custom alias validation
|
|
- Detect duplicate URLs using checksum
|
|
- Ensure uniqueness at scale (10M URLs)
|
|
|
|
## Technical Specifications
|
|
|
|
### Code Generation Strategies
|
|
|
|
#### Strategy 1: Sequential ID-based (Primary)
|
|
```python
|
|
def generate_short_code(url_id: int) -> str:
|
|
"""Generate short code from sequential database ID."""
|
|
return base62_encode(url_id)
|
|
```
|
|
- **Pros**: Guaranteed unique, simple, collision-free
|
|
- **Cons**: Predictable (sequential), requires database roundtrip
|
|
|
|
#### Strategy 2: Hash-based with Collision Handling (Fallback)
|
|
```python
|
|
def generate_from_url_hash(url: str, attempt: int = 0) -> str:
|
|
"""Generate short code from URL hash with collision handling."""
|
|
# SHA-256 hash + salt for collision resolution
|
|
salt = f"_{attempt}" if attempt > 0 else ""
|
|
hash_val = hashlib.sha256(f"{url}{salt}".encode()).digest()
|
|
# Take first 6 bytes and encode
|
|
num = int.from_bytes(hash_val[:6], 'big')
|
|
return base62_encode(num)[:8]
|
|
```
|
|
|
|
### Collision Handling Logic
|
|
|
|
```python
|
|
def create_short_code(original_url: str, custom_alias: str = None) -> str:
|
|
"""Create unique short code with collision handling."""
|
|
|
|
# 1. Check for duplicate URL
|
|
checksum = hashlib.sha256(original_url.encode()).hexdigest()
|
|
existing = db.query("SELECT short_code FROM urls WHERE checksum = %s", checksum)
|
|
if existing:
|
|
return existing[0]['short_code'] # Return existing code
|
|
|
|
# 2. Handle custom alias
|
|
if custom_alias:
|
|
if not is_valid_alias(custom_alias):
|
|
raise ValueError("Invalid custom alias")
|
|
if db.exists("SELECT 1 FROM urls WHERE short_code = %s", custom_alias):
|
|
raise ValueError("Alias already taken")
|
|
return custom_alias
|
|
|
|
# 3. Generate ID-based code (primary strategy)
|
|
url_id = db.insert("INSERT INTO urls (original_url, checksum) VALUES (%s, %s) RETURNING id",
|
|
original_url, checksum)
|
|
return base62_encode(url_id)
|
|
```
|
|
|
|
### Custom Alias Validation
|
|
```python
|
|
def is_valid_alias(alias: str) -> bool:
|
|
"""Validate custom alias format."""
|
|
return bool(re.match(r'^[a-zA-Z0-9]{4,20}$', alias))
|
|
```
|
|
|
|
## Data Structures
|
|
- **checksum**: SHA-256 hash of URL for duplicate detection
|
|
- **collision_retry_count**: Track collision attempts for monitoring
|
|
|
|
## Acceptance Criteria
|
|
- [ ] Generated codes are 6-8 characters
|
|
- [ ] No duplicate short codes in database (verified by UNIQUE constraint)
|
|
- [ ] Duplicate URLs return existing short code
|
|
- [ ] Custom aliases validated for format and uniqueness
|
|
- [ ] Collision handling retries up to 3 times with different salts
|
|
- [ ] Unit tests cover: normal case, duplicate URL, custom alias, collision
|
|
|
|
## Notes
|
|
- **Why sequential ID as primary**: Simpler, predictable length, no collisions
|
|
- **Hash-based as alternative**: For future distributed generation needs
|
|
- **Trade-off**: Sequential IDs are guessable but acceptable for public URLs
|
|
|
|
## Edge Cases
|
|
- URL longer than database limit → truncate before hashing
|
|
- Special characters in custom alias → regex validation
|
|
- Database connection failure during insert → retry logic
|
|
- Concurrent duplicate URL inserts → UNIQUE constraint + application retry
|
|
|
|
## Performance
|
|
- Duplicate check: O(1) with checksum index
|
|
- Insert: <10ms with proper connection pooling
|
|
- Custom alias check: O(1) with short_code index
|