chore: Recover v1.6.0-rc.2 source from production image
The v1.6.0 work (webmentions, reply contexts, rate limiter, migration 010) was built and deployed as git.thesatelliteoflove.com/phil/starpunk:v1.6.0-rc.2 but never committed. This restores the application code from /app in the running container so later work builds on what production runs. Tests and docs for v1.6.0 were not in the image and are not recovered. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
06a8aabc01
commit
d3fa5b7a2a
24 files changed
+3982
-78
No files matched your search
+141
-56
@@ -14,15 +14,21 @@ Debug file management (v1.5.0 Phase 2):
|
||||
- Debug file saving disabled by default
|
||||
- Automatic cleanup of old debug files
|
||||
- Size limit enforcement
|
||||
|
||||
Memory-safe image processing (v1.5.1):
|
||||
- Early downscale for large images (>4096px) to prevent OOM
|
||||
- PIL Image passed through pipeline (not bytes) to avoid memory copies
|
||||
- Explicit memory cleanup after processing steps
|
||||
"""
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
from pathlib import Path
|
||||
from datetime import datetime, timedelta
|
||||
import time
|
||||
import uuid
|
||||
import io
|
||||
import shutil
|
||||
from typing import Optional, List, Dict, Tuple
|
||||
from typing import Optional, List, Dict, Tuple, Union
|
||||
from flask import current_app
|
||||
|
||||
# HEIC/HEIF support - import registers with Pillow automatically
|
||||
@@ -50,6 +56,11 @@ MIN_QUALITY = 70 # Minimum JPEG quality before rejection (v1.4.
|
||||
MIN_DIMENSION = 640 # Minimum dimension before rejection (v1.4.0)
|
||||
MAX_IMAGES_PER_NOTE = 4
|
||||
|
||||
# Memory safety limits (v1.5.1 - fix for OOM on large phone images)
|
||||
# Early downscale very large images to prevent memory exhaustion
|
||||
# A 4096x4096 image = 50MB uncompressed, manageable per worker
|
||||
MEMORY_SAFE_DIMENSION = 4096 # Downscale to this before heavy processing
|
||||
|
||||
# Variant specifications (v1.4.0 Phase 2)
|
||||
VARIANT_SPECS = {
|
||||
'thumb': {'size': (150, 150), 'crop': True},
|
||||
@@ -82,21 +93,22 @@ def get_optimization_params(file_size: int) -> Tuple[int, int]:
|
||||
return (1280, 85)
|
||||
|
||||
|
||||
def validate_image(file_data: bytes, filename: str) -> Tuple[bytes, str, int, int]:
|
||||
def validate_image(file_data: bytes, filename: str) -> Tuple[Image.Image, str, int, int]:
|
||||
"""
|
||||
Validate image file
|
||||
Validate image file and return PIL Image for memory-efficient processing
|
||||
|
||||
Per Q11: Validate MIME type using Pillow
|
||||
Per Q6: Reject if >50MB or >4096px (updated v1.4.0)
|
||||
Per Q6: Reject if >50MB or >12000px
|
||||
Per v1.4.2: Convert HEIC to JPEG (browsers cannot display HEIC)
|
||||
Per v1.5.1: Return PIL Image (not bytes) to avoid memory copies
|
||||
|
||||
Args:
|
||||
file_data: Raw file bytes
|
||||
filename: Original filename
|
||||
|
||||
Returns:
|
||||
Tuple of (file_data, mime_type, width, height)
|
||||
Note: file_data may be converted (e.g., HEIC to JPEG)
|
||||
Tuple of (pil_image, mime_type, original_width, original_height)
|
||||
Note: Image may be downscaled for memory safety but original dimensions returned
|
||||
|
||||
Raises:
|
||||
ValueError: If file is invalid
|
||||
@@ -150,40 +162,34 @@ def validate_image(file_data: bytes, filename: str) -> Tuple[bytes, str, int, in
|
||||
else:
|
||||
raise ValueError(f"Invalid or corrupted image: {e}")
|
||||
|
||||
# Store original format before any conversions
|
||||
original_format = img.format
|
||||
|
||||
# HEIC/HEIF conversion (v1.4.2)
|
||||
# HEIC cannot be displayed in browsers, convert to JPEG
|
||||
if img.format in ('HEIF', 'HEIC'):
|
||||
if original_format in ('HEIF', 'HEIC'):
|
||||
if not HEIC_SUPPORTED:
|
||||
raise ValueError(
|
||||
"HEIC/HEIF images require pillow-heif library. "
|
||||
"Please convert to JPEG before uploading."
|
||||
)
|
||||
# Convert HEIC to JPEG in memory
|
||||
output = io.BytesIO()
|
||||
# Convert to RGB if needed (HEIC may have alpha channel)
|
||||
if img.mode in ('RGBA', 'P'):
|
||||
img = img.convert('RGB')
|
||||
img.save(output, format='JPEG', quality=95)
|
||||
output.seek(0)
|
||||
# Re-open as JPEG for further processing
|
||||
file_data = output.getvalue()
|
||||
img = Image.open(io.BytesIO(file_data))
|
||||
# Mark format as JPEG for later processing
|
||||
original_format = 'JPEG'
|
||||
|
||||
# MPO (Multi-Picture Object) conversion (v1.4.2)
|
||||
# MPO is used by iPhones for depth/portrait photos - extract primary image as JPEG
|
||||
if img.format == 'MPO':
|
||||
output = io.BytesIO()
|
||||
# MPO is used by iPhones for depth/portrait photos - extract primary image
|
||||
if original_format == 'MPO':
|
||||
# Convert to RGB if needed
|
||||
if img.mode in ('RGBA', 'P'):
|
||||
img = img.convert('RGB')
|
||||
img.save(output, format='JPEG', quality=95)
|
||||
output.seek(0)
|
||||
file_data = output.getvalue()
|
||||
img = Image.open(io.BytesIO(file_data))
|
||||
original_format = 'JPEG'
|
||||
|
||||
# Check format is allowed
|
||||
if img.format:
|
||||
format_lower = img.format.lower()
|
||||
if original_format:
|
||||
format_lower = original_format.lower()
|
||||
mime_type = f'image/{format_lower}'
|
||||
|
||||
# Special case: JPEG format can be reported as 'jpeg'
|
||||
@@ -195,26 +201,29 @@ def validate_image(file_data: bytes, filename: str) -> Tuple[bytes, str, int, in
|
||||
try:
|
||||
current_app.logger.warning(
|
||||
f'Media upload rejected format: filename="{filename}", '
|
||||
f'detected_format="{img.format}", mime_type="{mime_type}"'
|
||||
f'detected_format="{original_format}", mime_type="{mime_type}"'
|
||||
)
|
||||
except RuntimeError:
|
||||
pass # Outside app context
|
||||
raise ValueError(f"Invalid image format '{img.format}'. Accepted: JPEG, PNG, GIF, WebP")
|
||||
raise ValueError(f"Invalid image format '{original_format}'. Accepted: JPEG, PNG, GIF, WebP")
|
||||
else:
|
||||
raise ValueError("Could not determine image format")
|
||||
|
||||
# Store original dimensions before any resizing
|
||||
orig_width, orig_height = img.size
|
||||
|
||||
# Check dimensions (v1.4.2: increased to 12000px to support modern phone cameras)
|
||||
# Images will be resized by optimize_image() anyway
|
||||
width, height = img.size
|
||||
if max(width, height) > MAX_DIMENSION:
|
||||
if max(orig_width, orig_height) > MAX_DIMENSION:
|
||||
raise ValueError(f"Image dimensions too large. Maximum is {MAX_DIMENSION}x{MAX_DIMENSION} pixels")
|
||||
|
||||
# Check for animated GIF (v1.4.0)
|
||||
# Animated GIFs cannot be resized, so reject if >10MB
|
||||
if img.format == 'GIF':
|
||||
is_animated_gif = False
|
||||
if original_format == 'GIF':
|
||||
try:
|
||||
img.seek(1) # Try to seek to second frame
|
||||
# If successful, it's animated
|
||||
is_animated_gif = True
|
||||
if file_size > MAX_OUTPUT_SIZE:
|
||||
raise ValueError(
|
||||
"Animated GIF too large. Maximum size for animated GIFs is 10MB. "
|
||||
@@ -225,10 +234,38 @@ def validate_image(file_data: bytes, filename: str) -> Tuple[bytes, str, int, in
|
||||
# Not animated, continue normally
|
||||
pass
|
||||
|
||||
return file_data, mime_type, width, height
|
||||
# v1.5.1: Early downscale for memory safety
|
||||
# Large phone images (48MP+) can use 500MB+ per copy in memory
|
||||
# Downscale early to MEMORY_SAFE_DIMENSION to reduce memory footprint
|
||||
# This happens BEFORE optimize_image to prevent OOM during processing
|
||||
if not is_animated_gif and max(orig_width, orig_height) > MEMORY_SAFE_DIMENSION:
|
||||
try:
|
||||
current_app.logger.info(
|
||||
f'Memory safety downscale: {orig_width}x{orig_height} -> '
|
||||
f'{MEMORY_SAFE_DIMENSION}x{MEMORY_SAFE_DIMENSION} max'
|
||||
)
|
||||
except RuntimeError:
|
||||
pass # Outside app context
|
||||
|
||||
# Apply EXIF orientation before resize
|
||||
img = ImageOps.exif_transpose(img)
|
||||
|
||||
# Use thumbnail() for memory-efficient in-place resize
|
||||
img.thumbnail((MEMORY_SAFE_DIMENSION, MEMORY_SAFE_DIMENSION), Image.Resampling.LANCZOS)
|
||||
|
||||
# Store the format on the image object for later use
|
||||
img.format = original_format
|
||||
|
||||
# Clear file_data reference to allow garbage collection
|
||||
del file_data
|
||||
|
||||
return img, mime_type, orig_width, orig_height
|
||||
|
||||
|
||||
def optimize_image(image_data: bytes, original_size: int = None) -> Tuple[Image.Image, int, int, bytes]:
|
||||
def optimize_image(
|
||||
image_input: Union[Image.Image, bytes],
|
||||
original_size: int = None
|
||||
) -> Tuple[Image.Image, int, int, bytes]:
|
||||
"""
|
||||
Optimize image for web display with size-aware strategy
|
||||
|
||||
@@ -237,8 +274,12 @@ def optimize_image(image_data: bytes, original_size: int = None) -> Tuple[Image.
|
||||
- Iterative quality reduction if needed
|
||||
- Target output <=10MB
|
||||
|
||||
Per v1.5.1:
|
||||
- Accept PIL Image directly to avoid memory copies
|
||||
- Image may already be downscaled for memory safety
|
||||
|
||||
Args:
|
||||
image_data: Raw image bytes
|
||||
image_input: PIL Image object or raw image bytes
|
||||
original_size: Original file size (for tiered optimization)
|
||||
|
||||
Returns:
|
||||
@@ -247,24 +288,35 @@ def optimize_image(image_data: bytes, original_size: int = None) -> Tuple[Image.
|
||||
Raises:
|
||||
ValueError: If image cannot be optimized to target size
|
||||
"""
|
||||
if original_size is None:
|
||||
original_size = len(image_data)
|
||||
# Handle both PIL Image and bytes input (v1.5.1)
|
||||
if isinstance(image_input, Image.Image):
|
||||
img = image_input
|
||||
# For PIL input, use provided size or estimate from current dimensions
|
||||
if original_size is None:
|
||||
# Estimate: assume worst case of uncompressed RGB
|
||||
original_size = img.width * img.height * 3
|
||||
else:
|
||||
# Legacy bytes input path
|
||||
if original_size is None:
|
||||
original_size = len(image_input)
|
||||
img = Image.open(io.BytesIO(image_input))
|
||||
|
||||
# Get initial optimization parameters based on input size
|
||||
max_dim, quality = get_optimization_params(original_size)
|
||||
|
||||
img = Image.open(io.BytesIO(image_data))
|
||||
|
||||
# Save original format before any processing (copy() loses this)
|
||||
original_format = img.format
|
||||
original_format = img.format or 'JPEG'
|
||||
|
||||
# Correct EXIF orientation (per ADR-058), except for GIFs
|
||||
img = ImageOps.exif_transpose(img) if img.format != 'GIF' else img
|
||||
# Note: For v1.5.1, this may already be done in validate_image for large images
|
||||
if original_format != 'GIF':
|
||||
img = ImageOps.exif_transpose(img)
|
||||
|
||||
# For animated GIFs, return as-is (already validated in validate_image)
|
||||
if img.format == 'GIF' and getattr(img, 'is_animated', False):
|
||||
# Already checked size in validate_image, just return original
|
||||
return img, img.size[0], img.size[1], image_data
|
||||
# For animated GIFs, serialize and return (already validated in validate_image)
|
||||
if original_format == 'GIF' and getattr(img, 'is_animated', False):
|
||||
output = io.BytesIO()
|
||||
img.save(output, format='GIF')
|
||||
return img, img.size[0], img.size[1], output.getvalue()
|
||||
|
||||
# Iterative optimization loop
|
||||
while True:
|
||||
@@ -277,8 +329,7 @@ def optimize_image(image_data: bytes, original_size: int = None) -> Tuple[Image.
|
||||
|
||||
# Save to bytes to check size
|
||||
output = io.BytesIO()
|
||||
# Use original format (copy() loses the format attribute)
|
||||
save_format = original_format or 'JPEG'
|
||||
save_format = original_format
|
||||
save_kwargs = {'optimize': True}
|
||||
|
||||
if save_format in ['JPEG', 'JPG']:
|
||||
@@ -528,6 +579,7 @@ def save_media(file_data: bytes, filename: str) -> Dict:
|
||||
Per Q2: Date-organized path: /media/YYYY/MM/uuid.ext
|
||||
Per Q6: Validate, optimize, then save
|
||||
Per v1.4.0: Size-aware optimization with iterative quality reduction
|
||||
Per v1.6.0 Phase 0: Timing logs for performance monitoring
|
||||
|
||||
Args:
|
||||
file_data: Raw file bytes
|
||||
@@ -544,24 +596,42 @@ def save_media(file_data: bytes, filename: str) -> Dict:
|
||||
# Capture file size for logging
|
||||
file_size = len(file_data)
|
||||
|
||||
# Timing instrumentation (v1.6.0 Phase 0)
|
||||
timing_start = time.monotonic()
|
||||
timing_validation = 0.0
|
||||
timing_optimization = 0.0
|
||||
timing_variants = 0.0
|
||||
timing_save = 0.0
|
||||
|
||||
try:
|
||||
# Validate image (returns 4-tuple with potentially converted bytes)
|
||||
# Validate image (v1.5.1: returns PIL Image to avoid memory copies)
|
||||
try:
|
||||
file_data, mime_type, orig_width, orig_height = validate_image(file_data, filename)
|
||||
t_start = time.monotonic()
|
||||
validated_img, mime_type, orig_width, orig_height = validate_image(file_data, filename)
|
||||
timing_validation = time.monotonic() - t_start
|
||||
# Clear file_data early to reduce memory pressure
|
||||
del file_data
|
||||
except ValueError as e:
|
||||
timing_validation = time.monotonic() - timing_start
|
||||
current_app.logger.warning(
|
||||
f'Media upload validation failed: filename="{filename}", '
|
||||
f'size={file_size}b, error="{e}"'
|
||||
f'size={file_size}b, error="{e}", timing: validation={timing_validation:.1f}s'
|
||||
)
|
||||
raise
|
||||
|
||||
# Optimize image with size-aware strategy (now returns 4-tuple with bytes)
|
||||
# Optimize image with size-aware strategy (v1.5.1: accepts PIL Image)
|
||||
try:
|
||||
optimized_img, width, height, optimized_bytes = optimize_image(file_data, file_size)
|
||||
t_start = time.monotonic()
|
||||
optimized_img, width, height, optimized_bytes = optimize_image(validated_img, file_size)
|
||||
timing_optimization = time.monotonic() - t_start
|
||||
# Clear validated_img reference (optimized_img is the result now)
|
||||
del validated_img
|
||||
except ValueError as e:
|
||||
timing_optimization = time.monotonic() - t_start
|
||||
current_app.logger.warning(
|
||||
f'Media upload optimization failed: filename="{filename}", '
|
||||
f'size={file_size}b, error="{e}"'
|
||||
f'size={file_size}b, error="{e}", '
|
||||
f'timing: validation={timing_validation:.1f}s, optimization={timing_optimization:.1f}s'
|
||||
)
|
||||
raise
|
||||
|
||||
@@ -601,7 +671,8 @@ def save_media(file_data: bytes, filename: str) -> Dict:
|
||||
temp_subdir = None
|
||||
|
||||
try:
|
||||
# Step 1: Save original to temp directory
|
||||
# Step 1: Generate variants to temp directory
|
||||
t_start = time.monotonic()
|
||||
media_dir = Path(current_app.config.get('DATA_PATH', 'data')) / 'media'
|
||||
temp_dir = media_dir / '.tmp'
|
||||
temp_dir.mkdir(parents=True, exist_ok=True)
|
||||
@@ -623,8 +694,10 @@ def save_media(file_data: bytes, filename: str) -> Dict:
|
||||
optimized_bytes,
|
||||
db
|
||||
)
|
||||
timing_variants = time.monotonic() - t_start
|
||||
|
||||
# Step 3: Begin transaction
|
||||
# Step 3: Begin transaction and save to database
|
||||
t_start = time.monotonic()
|
||||
db.execute("BEGIN TRANSACTION")
|
||||
|
||||
# Step 4: Insert media record
|
||||
@@ -667,6 +740,7 @@ def save_media(file_data: bytes, filename: str) -> Dict:
|
||||
|
||||
# Step 7: Commit transaction (after files are moved successfully)
|
||||
db.commit()
|
||||
timing_save = time.monotonic() - t_start
|
||||
|
||||
# Step 8: Clean up temp directory
|
||||
try:
|
||||
@@ -679,6 +753,9 @@ def save_media(file_data: bytes, filename: str) -> Dict:
|
||||
variants = [v for v in variant_metadata if v['variant_type'] != 'original']
|
||||
|
||||
except Exception as e:
|
||||
# Capture timing for failed save operation
|
||||
timing_save = time.monotonic() - t_start if 't_start' in locals() else 0.0
|
||||
|
||||
# Rollback database on any failure (best effort)
|
||||
try:
|
||||
db.rollback()
|
||||
@@ -722,19 +799,27 @@ def save_media(file_data: bytes, filename: str) -> Dict:
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# Log and re-raise
|
||||
# Calculate total timing
|
||||
timing_total = time.monotonic() - timing_start
|
||||
|
||||
# Log and re-raise (with timing data)
|
||||
current_app.logger.warning(
|
||||
f'Media upload atomic operation failed: filename="{filename}", '
|
||||
f'error="{e}"'
|
||||
f'error="{e}", timing: validation={timing_validation:.1f}s, '
|
||||
f'optimization={timing_optimization:.1f}s, variants={timing_variants:.1f}s, '
|
||||
f'save={timing_save:.1f}s, total={timing_total:.1f}s'
|
||||
)
|
||||
raise
|
||||
|
||||
# Log success
|
||||
# Log success with timing data (v1.6.0 Phase 0)
|
||||
timing_total = time.monotonic() - timing_start
|
||||
was_optimized = len(optimized_bytes) < file_size
|
||||
current_app.logger.info(
|
||||
f'Media upload successful: filename="{filename}", '
|
||||
f'stored="{stored_filename}", size={len(optimized_bytes)}b, '
|
||||
f'optimized={was_optimized}, variants={len(variants)}'
|
||||
f'optimized={was_optimized}, variants={len(variants)}, '
|
||||
f'timing: validation={timing_validation:.1f}s, optimization={timing_optimization:.1f}s, '
|
||||
f'variants={timing_variants:.1f}s, save={timing_save:.1f}s, total={timing_total:.1f}s'
|
||||
)
|
||||
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user