feat: Complete v1.1.1 Phases 2 & 3 - Enhancements and Polish
Phase 2 - Enhancements: - Add performance monitoring infrastructure with MetricsBuffer - Implement three-tier health checks (/health, /health?detailed, /admin/health) - Enhance search with FTS5 fallback and XSS-safe highlighting - Add Unicode slug generation with timestamp fallback - Expose database pool statistics via /admin/metrics - Create missing error templates (400, 401, 403, 405, 503) Phase 3 - Polish: - Implement RSS streaming optimization (memory O(n) → O(1)) - Add admin metrics dashboard with htmx and Chart.js - Fix flaky migration race condition tests - Create comprehensive operational documentation - Add upgrade guide and troubleshooting guide Testing: 632 tests passing, zero flaky tests Documentation: Complete operational guides Security: All security reviews passed 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
1 parent
93d2398c1d
commit
07fff01fab
25 files changed
+4371
-142
No files matched your search
+92
-23
@@ -3,11 +3,22 @@ Slug validation and sanitization utilities for StarPunk
|
||||
|
||||
This module provides functions for validating, sanitizing, and ensuring uniqueness
|
||||
of note slugs. Supports custom slugs via Micropub's mp-slug property.
|
||||
|
||||
Per developer Q&A Q8:
|
||||
- Unicode normalization for slug generation
|
||||
- Timestamp-based fallback (YYYYMMDD-HHMMSS) when normalization fails
|
||||
- Log warnings with original text
|
||||
- Never fail Micropub request
|
||||
"""
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Optional, Set
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Reserved slugs that cannot be used for notes
|
||||
# These correspond to application routes and special pages
|
||||
RESERVED_SLUGS = frozenset([
|
||||
@@ -62,18 +73,25 @@ def is_reserved_slug(slug: str) -> bool:
|
||||
return slug.lower() in RESERVED_SLUGS
|
||||
|
||||
|
||||
def sanitize_slug(slug: str) -> str:
|
||||
def sanitize_slug(slug: str, allow_timestamp_fallback: bool = False) -> str:
|
||||
"""
|
||||
Sanitize a custom slug
|
||||
Sanitize a custom slug with Unicode normalization
|
||||
|
||||
Per developer Q&A Q8:
|
||||
- Unicode normalization (NFKD) for international characters
|
||||
- Timestamp-based fallback (YYYYMMDD-HHMMSS) when normalization fails
|
||||
- Log warnings with original text
|
||||
- Never fail (always returns a valid slug)
|
||||
|
||||
Converts to lowercase, replaces invalid characters with hyphens,
|
||||
removes consecutive hyphens, and trims to max length.
|
||||
|
||||
Args:
|
||||
slug: Raw slug input
|
||||
allow_timestamp_fallback: If True, use timestamp fallback for empty slugs
|
||||
|
||||
Returns:
|
||||
Sanitized slug string
|
||||
Sanitized slug string (never empty if allow_timestamp_fallback=True)
|
||||
|
||||
Examples:
|
||||
>>> sanitize_slug("Hello World!")
|
||||
@@ -84,7 +102,26 @@ def sanitize_slug(slug: str) -> str:
|
||||
|
||||
>>> sanitize_slug(" leading-spaces ")
|
||||
'leading-spaces'
|
||||
|
||||
>>> sanitize_slug("Café")
|
||||
'cafe'
|
||||
|
||||
>>> sanitize_slug("日本語", allow_timestamp_fallback=True)
|
||||
# Returns timestamp-based slug like '20231125-143022'
|
||||
|
||||
>>> sanitize_slug("😀🎉✨", allow_timestamp_fallback=True)
|
||||
# Returns timestamp-based slug
|
||||
"""
|
||||
original_slug = slug
|
||||
|
||||
# Unicode normalization (NFKD) - decomposes characters
|
||||
# e.g., "é" becomes "e" + combining accent
|
||||
slug = unicodedata.normalize('NFKD', slug)
|
||||
|
||||
# Remove combining characters (accents, etc.)
|
||||
# This converts accented characters to their ASCII equivalents
|
||||
slug = slug.encode('ascii', 'ignore').decode('ascii')
|
||||
|
||||
# Convert to lowercase
|
||||
slug = slug.lower()
|
||||
|
||||
@@ -98,6 +135,17 @@ def sanitize_slug(slug: str) -> str:
|
||||
# Trim leading/trailing hyphens
|
||||
slug = slug.strip('-')
|
||||
|
||||
# Check if normalization resulted in empty slug
|
||||
if not slug and allow_timestamp_fallback:
|
||||
# Per Q8: Use timestamp-based fallback
|
||||
timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
|
||||
slug = timestamp
|
||||
logger.warning(
|
||||
f"Slug normalization failed for input '{original_slug}' "
|
||||
f"(all characters removed during normalization). "
|
||||
f"Using timestamp fallback: {slug}"
|
||||
)
|
||||
|
||||
# Trim to max length
|
||||
if len(slug) > MAX_SLUG_LENGTH:
|
||||
slug = slug[:MAX_SLUG_LENGTH].rstrip('-')
|
||||
@@ -197,8 +245,13 @@ def validate_and_sanitize_custom_slug(custom_slug: str, existing_slugs: Set[str]
|
||||
"""
|
||||
Validate and sanitize a custom slug from Micropub
|
||||
|
||||
Per developer Q&A Q8:
|
||||
- Never fail Micropub request due to slug issues
|
||||
- Use timestamp fallback if normalization fails
|
||||
- Log warnings for debugging
|
||||
|
||||
Performs full validation pipeline:
|
||||
1. Sanitize the input
|
||||
1. Sanitize the input (with timestamp fallback)
|
||||
2. Check if it's reserved
|
||||
3. Validate format
|
||||
4. Make unique if needed
|
||||
@@ -219,6 +272,9 @@ def validate_and_sanitize_custom_slug(custom_slug: str, existing_slugs: Set[str]
|
||||
|
||||
>>> validate_and_sanitize_custom_slug("/invalid/slug", set())
|
||||
(False, None, 'Slug "/invalid/slug" contains hierarchical paths which are not supported')
|
||||
|
||||
>>> validate_and_sanitize_custom_slug("😀🎉", set())
|
||||
# Returns (True, '20231125-143022', None) - timestamp fallback
|
||||
"""
|
||||
# Check for hierarchical paths (not supported in v1.1.0)
|
||||
if '/' in custom_slug:
|
||||
@@ -228,40 +284,53 @@ def validate_and_sanitize_custom_slug(custom_slug: str, existing_slugs: Set[str]
|
||||
f'Slug "{custom_slug}" contains hierarchical paths which are not supported'
|
||||
)
|
||||
|
||||
# Sanitize
|
||||
sanitized = sanitize_slug(custom_slug)
|
||||
# Sanitize with timestamp fallback enabled
|
||||
# Per Q8: Never fail Micropub request
|
||||
sanitized = sanitize_slug(custom_slug, allow_timestamp_fallback=True)
|
||||
|
||||
# Check if sanitization resulted in empty slug
|
||||
# After timestamp fallback, slug should never be empty
|
||||
# But check anyway for safety
|
||||
if not sanitized:
|
||||
return (
|
||||
False,
|
||||
None,
|
||||
f'Slug "{custom_slug}" could not be sanitized to valid format'
|
||||
# This should never happen with allow_timestamp_fallback=True
|
||||
# but handle it just in case
|
||||
timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
|
||||
sanitized = timestamp
|
||||
logger.error(
|
||||
f"Unexpected empty slug after sanitization with fallback. "
|
||||
f"Original: '{custom_slug}'. Using timestamp: {sanitized}"
|
||||
)
|
||||
|
||||
# Check if reserved
|
||||
if is_reserved_slug(sanitized):
|
||||
return (
|
||||
False,
|
||||
None,
|
||||
f'Slug "{sanitized}" is reserved and cannot be used'
|
||||
# Per Q8: Never fail - add suffix to reserved slug
|
||||
logger.warning(
|
||||
f"Slug '{sanitized}' (from '{custom_slug}') is reserved. "
|
||||
f"Adding numeric suffix."
|
||||
)
|
||||
# Add a suffix to make it non-reserved
|
||||
sanitized = f"{sanitized}-note"
|
||||
|
||||
# Validate format
|
||||
if not validate_slug(sanitized):
|
||||
return (
|
||||
False,
|
||||
None,
|
||||
f'Slug "{sanitized}" does not match required format (lowercase letters, numbers, hyphens only)'
|
||||
# This should rarely happen after sanitization
|
||||
# but if it does, use timestamp fallback
|
||||
timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
|
||||
logger.warning(
|
||||
f"Slug '{sanitized}' (from '{custom_slug}') failed validation. "
|
||||
f"Using timestamp fallback: {timestamp}"
|
||||
)
|
||||
sanitized = timestamp
|
||||
|
||||
# Make unique if needed
|
||||
try:
|
||||
unique_slug = make_slug_unique_with_suffix(sanitized, existing_slugs)
|
||||
return (True, unique_slug, None)
|
||||
except ValueError as e:
|
||||
return (
|
||||
False,
|
||||
None,
|
||||
str(e)
|
||||
# This should rarely happen, but if it does, use timestamp
|
||||
# Per Q8: Never fail Micropub request
|
||||
timestamp = datetime.utcnow().strftime('%Y%m%d-%H%M%S')
|
||||
logger.error(
|
||||
f"Could not create unique slug from '{custom_slug}'. "
|
||||
f"Using timestamp: {timestamp}. Error: {e}"
|
||||
)
|
||||
return (True, timestamp, None)
|
||||
Reference in new issue
Block a user