import hashlib
import json
import time
from datetime import datetime
from enum import Enum
from typing import Dict, Any, Optional, List
from sqlalchemy import create_engine, Column, String, Integer, BigInteger, DateTime, Text, Enum as SQLEnum
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from elasticsearch import Elasticsearch
from kafka import KafkaProducer, KafkaConsumer # For distributed backfill
import threading
Base = declarative_base()
class VersionStatus(Enum):
BUILDING = "building"
READY = "ready"
ACTIVE = "active"
DEPRECATED = "deprecated"
FAILED = "failed"
class Version(Base):
__tablename__ = 'versions'
id = Column(Integer, primary_key=True)
version = Column(String(50), unique=True, nullable=False)
status = Column(SQLEnum(VersionStatus), nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
activated_at = Column(DateTime)
deprecated_at = Column(DateTime)
index_name = Column(String(255), nullable=False)
alias_name = Column(String(255), default='prod')
checksum = Column(String(64))
error_msg = Column(Text)
class Checkpoint(Base):
__tablename__ = 'backfill_checkpoints'
id = Column(Integer, primary_key=True)
version_id = Column(Integer) # ForeignKey('versions.id')
batch_id = Column(BigInteger, nullable=False)
last_processed_id = Column(BigInteger)
processed_count = Column(BigInteger, default=0)
total_count = Column(BigInteger)
updated_at = Column(DateTime, default=datetime.utcnow)
class ReindexFramework:
def __init__(self, metadata_dsn: str, es_client: Elasticsearch, source_query_fn, index_mapping: Dict, batch_size: int = 1000):
self.engine = create_engine(metadata_dsn)
Base.metadata.create_all(self.engine)
self.Session = sessionmaker(bind=self.engine)
self.es = es_client
self.source_query_fn = source_query_fn # Callable: (start_id: int, batch_size: int) -> List[Dict]
self.index_mapping = index_mapping
self.batch_size = batch_size
self.alias = 'prod'
def create_version(self, version: str, index_name: str, config_checksum: str) -> Version:
"""Create a new version."""
session = self.Session()
try:
v = Version(version=version, status=VersionStatus.BUILDING, index_name=index_name, checksum=config_checksum)
session.add(v)
session.commit()
return v
finally:
session.close()
def build_version(self, version: str, max_workers: int = 10) -> None:
"""Asynchronous backfill with Kafka workers."""
session = self.Session()
v = session.query(Version).filter_by(version=version).one()
producer = KafkaProducer(bootstrap_servers=['localhost:9092'], value_serializer=lambda v: json.dumps(v).encode('utf-8'))
# Estimate total batches
total_count = self._estimate_total() # Implement based on source
num_batches = (total_count // self.batch_size) + 1
for batch_id in range(num_batches):
producer.send('backfill-topic', {
'version': version,
'batch_id': batch_id,
'version_id': v.id
})
producer.flush()
# Monitor completion (poll checkpoints)
self._await_completion(v.id, num_batches)
def _backfill_worker(self, consumer: KafkaConsumer):
"""Worker loop: Consume batches, query source, index docs."""
while True:
msg = consumer.poll(timeout_ms=1000)
for topic_partition, messages in msg.items():
for msg in messages:
data = json.loads(msg.value.decode('utf-8'))
self._process_batch(data['version_id'], data['batch_id'])
def _process_batch(self, version_id: int, batch_id: int) -> None:
"""Idempotent batch: Resume from checkpoint."""
session = self.Session()
checkpoint = session.query(Checkpoint).filter_by(version_id=version_id, batch_id=batch_id).first()
start_id = checkpoint.last_processed_id if checkpoint else 0
docs = self.source_query_fn(start=start_id, batch_size=self.batch_size)
if not docs:
return
# Index with retries
for attempt in range(3):
try:
self.es.bulk(body=[{"index": {"_index": f"index-{version_id}"}}, doc] for doc in docs)
break
except Exception as e:
if attempt == 2:
raise
# Update checkpoint
if not checkpoint:
checkpoint = Checkpoint(version_id=version_id, batch_id=batch_id, total_count=len(docs))
session.add(checkpoint)
checkpoint.last_processed_id = docs[-1]['id']
checkpoint.processed_count += len(docs)
session.commit()
session.close()
def _await_completion(self, version_id: int, expected_batches: int, timeout: int = 3600) -> None:
"""Wait for all batches, update status."""
start = time.time()
session = self.Session()
v = session.query(Version).get(version_id)
while time.time() - start < timeout:
completed = session.query(Checkpoint).filter_by(version_id=version_id).count()
if completed >= expected_batches:
v.status = VersionStatus.READY
session.commit()
return
time.sleep(10)
v.status = VersionStatus.FAILED
v.error_msg = "Timeout"
session.commit()
raise TimeoutError("Backfill timeout")
def activate_version(self, version: str) -> None:
"""Atomic swap: Point alias to new index."""
session = self.Session()
v = session.query(Version).filter_by(version=version).one()
if v.status != VersionStatus.READY:
raise ValueError("Version not ready")
# Atomic alias ops
self.es.indices.put_alias(index=v.index_name, name=self.alias)
old_active = self._get_active_version()
if old_active:
self.es.indices.delete_alias(index=old_active.index_name, name=self.alias)
old_active.status = VersionStatus.DEPRECATED
old_active.deprecated_at = datetime.utcnow()
v.status = VersionStatus.ACTIVE
v.activated_at = datetime.utcnow()
session.commit()
def rollback(self, target_version: str) -> None:
"""Atomic rollback to previous version."""
session = self.Session()
target = session.query(Version).filter_by(version=target_version).one()
if target.status != VersionStatus.ACTIVE and target.status != VersionStatus.READY:
raise ValueError("Can only rollback ready/active versions")
# Swap alias back
self.es.indices.put_alias(index=target.index_name, name=self.alias)
current = self._get_active_version()
if current and current.version != target_version:
self.es.indices.delete_alias(index=current.index_name, name=self.alias)
current.status = VersionStatus.DEPRECATED if current.status == VersionStatus.ACTIVE else current.status
session.close()
def _get_active_version(self) -> Optional[Version]:
session = self.Session()
alias_resp = self.es.indices.get_alias(name=self.alias)
if not alias_resp:
return None
index_name = list(alias_resp[self.alias]['aliases'].keys())[0]
version_id = int(index_name.split('-')[-1]) # Assumes index-vID
v = session.query(Version).get(version_id)
session.close()
return v
def list_versions(self) -> List[Dict]:
session = self.Session()
versions = session.query(Version).order_by(Version.created_at.desc()).all()
return [{c.name: getattr(v, c.name) for c in Version.__table__.columns} for v in versions]
# Hooks for monitoring/alerting
def health_check(version: str) -> Dict:
# Custom: Compare doc counts, query latency, etc.
pass