Files
test-glm47/ai_coder_1/subtasks/Decomp-001-08.md
T
2026-02-04 16:54:36 +10:00

4.1 KiB

Subtask: Link Expiration with TTL

Parent Task: Decomp/001 Subtask ID: Decomp/001-08 Dependencies: Decomp/001-01 (Database Schema), Decomp/001-04 (Redirect Endpoint)

Description

Implement time-to-live (TTL) functionality for shortened URLs. URLs can have an optional expiration time after which redirects return 410 Gone. Supports both absolute expiration timestamp and relative TTL.

Requirements

  • Optional expiration timestamp on URL creation
  • Support relative TTL (e.g., "expire in 24 hours")
  • Check expiration on every redirect
  • Return 410 Gone for expired URLs
  • API to extend URL expiration
  • Admin option to create permanent URLs (no expiration)
  • Background cleanup of expired URLs (optional)

Technical Specifications

Database schema update:

ALTER TABLE urls ADD COLUMN expires_at TIMESTAMP NULL;
ALTER TABLE urls ADD COLUMN is_permanent BOOLEAN DEFAULT FALSE;

CREATE INDEX idx_urls_expires_at ON urls(expires_at) WHERE expires_at IS NOT NULL;

API updates:

# URL Creation
POST /api/shorten
{
    "url": "https://example.com",
    "custom_alias": "mylink",  # optional
    "ttl_seconds": 86400,       # optional: 24 hours
    "expires_at": "2025-02-05T12:00:00Z",  # optional: absolute time
    "permanent": false          # optional: never expire
}

Expiration logic:

from datetime import datetime, timezone

def set_expiration(url_data: dict) -> datetime:
    """
    Calculate expiration timestamp from various input formats.
    Priority: permanent > expires_at > ttl_seconds > default

    Returns:
        UTC datetime or None (permanent)
    """
    if url_data.get('permanent'):
        return None

    if url_data.get('expires_at'):
        return datetime.fromisoformat(url_data['expires_at'])

    if url_data.get('ttl_seconds'):
        return datetime.now(timezone.utc) + timedelta(seconds=url_data['ttl_seconds'])

    # Default: no expiration (or configurable default TTL)
    return None

def is_url_expired(url_row: dict) -> bool:
    """
    Check if URL has expired.

    Returns:
        True if expired, False if valid or permanent
    """
    if url_row.get('is_permanent') or url_row.get('expires_at') is None:
        return False

    return datetime.now(timezone.utc) > url_row['expires_at']

Redirect endpoint update:

@app.route('/<short_code>')
def redirect(short_code: str):
    url = get_url_from_db(short_code)  # or cache

    if not url:
        return "Not found", 404

    if is_url_expired(url):
        return "This link has expired", 410  # HTTP 410 Gone

    return redirect(url['original_url'], code=301)

Cache key update (for Decomp/001-06):

# Include expiration in cached data
cache_data = {
    "url": "https://...",
    "expires_at": "2025-02-05T12:00:00Z",
    "is_permanent": False
}
# TTL is min(cache_ttl, time_until_expiration)

Acceptance Criteria

  • URL with past expiration returns 410 Gone
  • URL with future expiration redirects normally
  • Permanent URL (expires_at=NULL) never expires
  • ttl_seconds parameter works correctly
  • expires_at ISO 8601 format is parsed correctly
  • Cache respects expiration (TTL < remaining time)
  • 410 response includes helpful message

Notes

Trade-offs:

  • Hard delete vs soft delete (410): 410 chosen for better user feedback
  • Immediate cleanup vs background job: Background job optional
  • Default TTL: None (permanent) vs configurable default

Edge cases:

  • Timezone handling: All timestamps in UTC
  • Clock skew: Allow 5-second grace period
  • Very short TTLs: Minimum 60 seconds to prevent issues

Performance considerations:

  • Index on expires_at for efficient cleanup queries
  • Cache expiration: set Redis TTL = min(cache_ttl, url_ttl_remaining)

Cleanup query (for background job):

-- Delete URLs expired more than 30 days ago
DELETE FROM urls
WHERE expires_at < NOW() - INTERVAL '30 days'
  AND is_permanent = FALSE;

Alternatives considered:

  • Soft delete with deleted_at: rejected, 410 is sufficient
  • Immediate hard delete: rejected, loses analytics data
  • Cron-based cleanup: optional, can be manual initially