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

3.3 KiB

Subtask: QR Code Generation

Parent Task: Decomp/001 Subtask ID: Decomp/001-07 Dependencies: Decomp/001-03 (Code Generation), Decomp/001-04 (Create API)

Description

Generate QR codes for short URLs. QR codes should be generated on-demand and cached.

Requirements

  • Generate QR code image (PNG format) for short URLs
  • Support configurable size (default 200x200px)
  • Cache generated QR codes
  • Serve via dedicated endpoint
  • Handle QR code with logo (optional enhancement)

Technical Specifications

API Endpoint

GET /api/v1/qr/{short_code}?size=200

Response 200 OK:
Content-Type: image/png

<binary PNG data>

Response 404 Not Found:
{
  "error": "Short URL not found"
}

QR Code Generation

import qrcode
from io import BytesIO

async def generate_qr_code(short_url: str, size: int = 200) -> bytes:
    """Generate QR code for URL."""

    # Validate size parameter
    if not 50 <= size <= 1000:
        raise ValueError("Size must be between 50 and 1000")

    # Create QR code
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=max(1, size // 25),  # Approximate scaling
        border=4,
    )
    qr.add_data(short_url)
    qr.make(fit=True)

    # Generate image
    img = qr.make_image(fill_color="black", back_color="white")

    # Resize to exact dimensions
    img = img.resize((size, size), resample=0)

    # Convert to bytes
    buffer = BytesIO()
    img.save(buffer, format='PNG')
    return buffer.getvalue()

Caching Strategy

async def get_qr_code(short_code: str, size: int = 200) -> bytes:
    """Get QR code from cache or generate new one."""

    cache_key = f"qr:{short_code}:{size}"

    # Check cache
    cached = await redis.get(cache_key)
    if cached:
        return cached

    # Verify short code exists
    url_data = await db.fetch_one(
        "SELECT short_code FROM urls WHERE short_code = $1",
        short_code
    )
    if not url_data:
        raise HTTPException(404, "Short URL not found")

    # Generate QR code
    short_url = f"{BASE_URL}/{short_code}"
    qr_data = await generate_qr_code(short_url, size)

    # Cache for 24 hours
    await redis.setex(cache_key, 86400, qr_data)

    return qr_data

Acceptance Criteria

  • GET /api/v1/qr/{short_code} returns PNG image
  • QR code scans to correct short URL
  • Size parameter validated (50-1000px)
  • QR codes cached in Redis (24 hour TTL)
  • Returns 404 for non-existent short codes
  • Unit tests for QR generation and caching

Notes

  • Library: qrcode (pip install qrcode[pil])
  • Cache duration: 24 hours (QR codes don't change)
  • Error correction: L (7%) for smallest size
  • Trade-off: Generate on-demand vs. pre-generate (on-demand chosen for flexibility)

Edge Cases

  • Invalid size parameter → 400 error
  • Short URL longer than QR capacity → use higher version QR
  • Concurrent generation → use cache lock or accept duplicate work
  • QR library failure → 500 error

Performance Targets

  • Generation time: <100ms
  • Cache hit: <10ms (Redis fetch)
  • Memory per QR: ~10KB (200x200 PNG)

Optional Enhancements

  • Logo in center (requires higher error correction)
  • Different colors
  • Vector format (SVG) for print
  • Bulk generation for analytics