695 lines
22 KiB
Markdown
695 lines
22 KiB
Markdown
# Subtask: Lifecycle Management
|
|
|
|
**Parent Task**: Decomp/005
|
|
**Subtask ID**: Decomp/005-08
|
|
**Dependencies**: Decomp-005-01 (Storage Architecture)
|
|
|
|
## Description
|
|
|
|
Implement lifecycle management for objects. Support automatic transitions between storage classes, expiration rules, and archival/deletion policies.
|
|
|
|
## Requirements
|
|
|
|
- Define lifecycle rules per bucket
|
|
- Auto-transition objects to cheaper storage
|
|
- Expire/delete old objects
|
|
- Support prefix-based rules
|
|
- Track lifecycle status
|
|
- Apply rules asynchronously
|
|
- Abort in-progress lifecycle operations
|
|
|
|
## Technical Specifications
|
|
|
|
**Lifecycle rule definitions**:
|
|
```python
|
|
from typing import List, Dict, Any, Optional
|
|
from dataclasses import dataclass
|
|
from datetime import datetime, timezone, timedelta
|
|
from enum import Enum
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
class StorageClass(Enum):
|
|
"""Storage class tiers."""
|
|
STANDARD = "standard"
|
|
INFREQUENT_ACCESS = "infrequent"
|
|
ARCHIVE = "archive"
|
|
DEEP_ARCHIVE = "deep_archive"
|
|
|
|
class LifecycleAction(Enum):
|
|
"""Types of lifecycle actions."""
|
|
TRANSITION = "transition"
|
|
EXPIRE = "expire"
|
|
|
|
@dataclass
|
|
class TransitionRule:
|
|
"""Rule for transitioning objects to a different storage class."""
|
|
days: int
|
|
target_storage_class: StorageClass
|
|
prefix: Optional[str] = None
|
|
|
|
@dataclass
|
|
class ExpirationRule:
|
|
"""Rule for expiring/deleting objects."""
|
|
days: int
|
|
prefix: Optional[str] = None
|
|
expired_object_delete_marker: bool = True
|
|
|
|
@dataclass
|
|
class LifecyclePolicy:
|
|
"""A lifecycle policy for a bucket."""
|
|
id: Optional[int]
|
|
bucket_id: int
|
|
name: str
|
|
transitions: List[TransitionRule]
|
|
expirations: List[ExpirationRule]
|
|
is_enabled: bool = True
|
|
created_at: datetime = None
|
|
updated_at: datetime = None
|
|
|
|
class LifecycleManager:
|
|
"""Service for managing object lifecycle policies."""
|
|
|
|
def __init__(self, db, storage_service):
|
|
self.db = db
|
|
self.storage = storage_service
|
|
|
|
async def create_policy(
|
|
self,
|
|
bucket_id: int,
|
|
name: str,
|
|
transitions: List[Dict[str, Any]] = None,
|
|
expirations: List[Dict[str, Any]] = None
|
|
) -> int:
|
|
"""
|
|
Create a lifecycle policy for a bucket.
|
|
|
|
Args:
|
|
bucket_id: Bucket ID
|
|
name: Policy name
|
|
transitions: List of transition rules
|
|
[{days: int, storage_class: str, prefix: str}]
|
|
expirations: List of expiration rules
|
|
[{days: int, prefix: str}]
|
|
|
|
Returns:
|
|
Policy ID
|
|
"""
|
|
# Convert dicts to rule objects
|
|
transition_rules = []
|
|
if transitions:
|
|
for t in transitions:
|
|
transition_rules.append(TransitionRule(
|
|
days=t["days"],
|
|
target_storage_class=StorageClass(t["storage_class"]),
|
|
prefix=t.get("prefix")
|
|
))
|
|
|
|
expiration_rules = []
|
|
if expirations:
|
|
for e in expirations:
|
|
expiration_rules.append(ExpirationRule(
|
|
days=e["days"],
|
|
prefix=e.get("prefix")
|
|
))
|
|
|
|
async with self.db.acquire() as conn:
|
|
policy_id = await conn.fetchval(
|
|
"""INSERT INTO lifecycle_policies
|
|
(bucket_id, name, rules, is_enabled)
|
|
VALUES ($1, $2, $3, TRUE)
|
|
RETURNING id""",
|
|
bucket_id,
|
|
name,
|
|
json.dumps({
|
|
"transitions": [
|
|
{
|
|
"days": t.days,
|
|
"storage_class": t.target_storage_class.value,
|
|
"prefix": t.prefix
|
|
}
|
|
for t in transition_rules
|
|
],
|
|
"expirations": [
|
|
{
|
|
"days": e.days,
|
|
"prefix": e.prefix
|
|
}
|
|
for e in expiration_rules
|
|
]
|
|
})
|
|
)
|
|
|
|
logger.info(f"Created lifecycle policy {policy_id} for bucket {bucket_id}")
|
|
return policy_id
|
|
|
|
async def update_policy(
|
|
self,
|
|
policy_id: int,
|
|
name: str = None,
|
|
transitions: List[Dict[str, Any]] = None,
|
|
expirations: List[Dict[str, Any]] = None,
|
|
is_enabled: bool = None
|
|
) -> bool:
|
|
"""Update an existing lifecycle policy."""
|
|
updates = []
|
|
params = []
|
|
|
|
if name is not None:
|
|
updates.append("name = $2")
|
|
params.append(name)
|
|
|
|
if is_enabled is not None:
|
|
updates.append("is_enabled = $2")
|
|
params.append(is_enabled)
|
|
|
|
if transitions is not None or expirations is not None:
|
|
# Rebuild rules
|
|
current_rules = await self.get_policy(policy_id)
|
|
if current_rules:
|
|
final_transitions = transitions if transitions is not None else current_rules.transitions
|
|
final_expirations = expirations if expirations is not None else current_rules.expirations
|
|
else:
|
|
final_transitions = transitions or []
|
|
final_expirations = expirations or []
|
|
|
|
updates.append("rules = $2")
|
|
params.append(json.dumps({
|
|
"transitions": final_transitions,
|
|
"expirations": final_expirations
|
|
}))
|
|
|
|
if updates:
|
|
params.append(policy_id)
|
|
query = f"UPDATE lifecycle_policies SET {', '.join(updates)} WHERE id = ${len(params)}"
|
|
|
|
async with self.db.acquire() as conn:
|
|
await conn.execute(query, *params)
|
|
await conn.execute(
|
|
"UPDATE lifecycle_policies SET updated_at = NOW() WHERE id = $1",
|
|
policy_id
|
|
)
|
|
|
|
return True
|
|
|
|
async def delete_policy(self, policy_id: int) -> bool:
|
|
"""Delete a lifecycle policy."""
|
|
async with self.db.acquire() as conn:
|
|
result = await conn.execute(
|
|
"DELETE FROM lifecycle_policies WHERE id = $1",
|
|
policy_id
|
|
)
|
|
return result != "DELETE 0"
|
|
|
|
async def get_policy(self, policy_id: int) -> Optional[LifecyclePolicy]:
|
|
"""Get a lifecycle policy by ID."""
|
|
async with self.db.acquire() as conn:
|
|
policy = await conn.fetchrow(
|
|
"""SELECT * FROM lifecycle_policies WHERE id = $1""",
|
|
policy_id
|
|
)
|
|
|
|
if not policy:
|
|
return None
|
|
|
|
rules = json.loads(policy["rules"])
|
|
|
|
return LifecyclePolicy(
|
|
id=policy["id"],
|
|
bucket_id=policy["bucket_id"],
|
|
name=policy["name"],
|
|
transitions=[
|
|
TransitionRule(
|
|
days=r["days"],
|
|
target_storage_class=StorageClass(r["storage_class"]),
|
|
prefix=r.get("prefix")
|
|
)
|
|
for r in rules.get("transitions", [])
|
|
],
|
|
expirations=[
|
|
ExpirationRule(
|
|
days=e["days"],
|
|
prefix=e.get("prefix")
|
|
)
|
|
for e in rules.get("expirations", [])
|
|
],
|
|
is_enabled=policy["is_enabled"],
|
|
created_at=policy["created_at"],
|
|
updated_at=policy["updated_at"]
|
|
)
|
|
|
|
async def list_policies(self, bucket_id: int) -> List[LifecyclePolicy]:
|
|
"""List all lifecycle policies for a bucket."""
|
|
async with self.db.acquire() as conn:
|
|
policies = await conn.fetch(
|
|
"""SELECT * FROM lifecycle_policies
|
|
WHERE bucket_id = $1
|
|
ORDER BY created_at DESC""",
|
|
bucket_id
|
|
)
|
|
|
|
result = []
|
|
for policy in policies:
|
|
rules = json.loads(policy["rules"])
|
|
result.append(
|
|
LifecyclePolicy(
|
|
id=policy["id"],
|
|
bucket_id=policy["bucket_id"],
|
|
name=policy["name"],
|
|
transitions=[
|
|
TransitionRule(
|
|
days=r["days"],
|
|
target_storage_class=StorageClass(r["storage_class"]),
|
|
prefix=r.get("prefix")
|
|
)
|
|
for r in rules.get("transitions", [])
|
|
],
|
|
expirations=[
|
|
ExpirationRule(
|
|
days=e["days"],
|
|
prefix=e.get("prefix")
|
|
)
|
|
for e in rules.get("expirations", [])
|
|
],
|
|
is_enabled=policy["is_enabled"],
|
|
created_at=policy["created_at"],
|
|
updated_at=policy["updated_at"]
|
|
)
|
|
)
|
|
|
|
return result
|
|
|
|
async def apply_lifecycle_rules(self, limit: int = 1000) -> Dict[str, int]:
|
|
"""
|
|
Apply lifecycle rules to eligible objects.
|
|
|
|
Should be run periodically (e.g., daily).
|
|
Processes transitions and expirations.
|
|
|
|
Returns:
|
|
Dictionary with counts of processed actions
|
|
"""
|
|
stats = {
|
|
"transitions": 0,
|
|
"expirations": 0,
|
|
"errors": 0
|
|
}
|
|
|
|
# Get all active policies
|
|
async with self.db.acquire() as conn:
|
|
policies = await conn.fetch(
|
|
"""SELECT lp.*, b.name as bucket_name
|
|
FROM lifecycle_policies lp
|
|
JOIN buckets b ON b.id = lp.bucket_id
|
|
WHERE lp.is_enabled = TRUE"""
|
|
)
|
|
|
|
for policy in policies:
|
|
rules = json.loads(policy["rules"])
|
|
|
|
# Process transitions
|
|
for rule in rules.get("transitions", []):
|
|
transitioned = await self._apply_transition_rule(
|
|
conn,
|
|
policy["bucket_id"],
|
|
policy["bucket_name"],
|
|
rule
|
|
)
|
|
stats["transitions"] += transitioned
|
|
|
|
# Process expirations
|
|
for rule in rules.get("expirations", []):
|
|
expired = await self._apply_expiration_rule(
|
|
conn,
|
|
policy["bucket_id"],
|
|
policy["bucket_name"],
|
|
rule
|
|
)
|
|
stats["expirations"] += expired
|
|
|
|
if stats["transitions"] > 0 or stats["expirations"] > 0:
|
|
logger.info(f"Lifecycle processing complete: {stats}")
|
|
|
|
return stats
|
|
|
|
async def _apply_transition_rule(
|
|
self,
|
|
conn,
|
|
bucket_id: int,
|
|
bucket_name: str,
|
|
rule: dict
|
|
) -> int:
|
|
"""Apply a transition rule to eligible objects."""
|
|
days = rule["days"]
|
|
target_class = rule["storage_class"]
|
|
prefix = rule.get("prefix")
|
|
|
|
# Find objects eligible for transition
|
|
query = """
|
|
UPDATE objects
|
|
SET storage_class = $1,
|
|
updated_at = NOW()
|
|
WHERE bucket_id = $2
|
|
AND storage_class != $1
|
|
AND modified_at < NOW() - INTERVAL '1 day' * $3
|
|
"""
|
|
params = [target_class, bucket_id, days]
|
|
|
|
if prefix:
|
|
query += " AND object_key LIKE $4"
|
|
params.append(f"{prefix}%")
|
|
|
|
query += f" LIMIT {10000}" # Batch limit
|
|
|
|
result = await conn.execute(query, *params)
|
|
count = int(result.split()[-1]) if result else 0
|
|
|
|
if count > 0:
|
|
logger.info(
|
|
f"Transitioned {count} objects in {bucket_name} "
|
|
f"to {target_class} (>{days} days, prefix: {prefix or '*'})"
|
|
)
|
|
|
|
return count
|
|
|
|
async def _apply_expiration_rule(
|
|
self,
|
|
conn,
|
|
bucket_id: int,
|
|
bucket_name: str,
|
|
rule: dict
|
|
) -> int:
|
|
"""Apply an expiration rule to eligible objects."""
|
|
days = rule["days"]
|
|
prefix = rule.get("prefix")
|
|
|
|
# If versioning is enabled, create delete markers
|
|
bucket = await conn.fetchrow(
|
|
"SELECT versioning_enabled FROM buckets WHERE id = $1",
|
|
bucket_id
|
|
)
|
|
|
|
if bucket and bucket["versioning_enabled"]:
|
|
# Create delete markers for old versions
|
|
# But only for non-latest versions that are old enough
|
|
query = """
|
|
INSERT INTO objects
|
|
(bucket_id, object_key, version_id, is_latest,
|
|
is_delete_marker, content_length, etag, modified_at)
|
|
SELECT bucket_id, object_key,
|
|
'v-delete-' || encode(gen_random_bytes(16), 'hex'),
|
|
TRUE, TRUE, 0, '', NOW()
|
|
FROM (
|
|
SELECT DISTINCT object_key
|
|
FROM objects
|
|
WHERE bucket_id = $1
|
|
AND is_delete_marker = FALSE
|
|
AND is_latest = TRUE
|
|
AND modified_at < NOW() - INTERVAL '1 day' * $2
|
|
"""
|
|
params = [bucket_id, days]
|
|
|
|
if prefix:
|
|
query += " AND object_key LIKE $3"
|
|
params.append(f"{prefix}%")
|
|
|
|
# Check if delete marker already exists
|
|
query += " EXCEPT SELECT object_key FROM objects WHERE is_delete_marker = TRUE"
|
|
|
|
result = await conn.execute(query, *params)
|
|
count = int(result.split()[-1]) if result else 0
|
|
|
|
if count > 0:
|
|
logger.info(f"Created {count} delete markers in {bucket_name} (>{days} days)")
|
|
else:
|
|
# Hard delete old objects
|
|
query = "DELETE FROM objects WHERE bucket_id = $1 AND modified_at < NOW() - INTERVAL '1 day' * $2"
|
|
params = [bucket_id, days]
|
|
|
|
if prefix:
|
|
query += " AND object_key LIKE $3"
|
|
params.append(f"{prefix}%")
|
|
|
|
query += f" LIMIT {10000}"
|
|
|
|
result = await conn.execute(query, *params)
|
|
count = int(result.split()[-1]) if result else 0
|
|
|
|
if count > 0:
|
|
logger.info(f"Deleted {count} objects from {bucket_name} (>{days} days)")
|
|
|
|
return count
|
|
|
|
async def get_object_lifecycle_status(
|
|
self,
|
|
object_id: int
|
|
) -> Dict[str, Any]:
|
|
"""Get lifecycle status for a specific object."""
|
|
async with self.db.acquire() as conn:
|
|
obj = await conn.fetchrow(
|
|
"""SELECT o.*, b.name as bucket_name, b.id as bucket_id
|
|
FROM objects o
|
|
JOIN buckets b ON b.id = o.bucket_id
|
|
WHERE o.id = $1""",
|
|
object_id
|
|
)
|
|
|
|
if not obj:
|
|
return None
|
|
|
|
# Find applicable policies
|
|
policies = await conn.fetch(
|
|
"""SELECT lp.* FROM lifecycle_policies lp
|
|
WHERE lp.bucket_id = $1 AND lp.is_enabled = TRUE""",
|
|
obj["bucket_id"]
|
|
)
|
|
|
|
applicable_actions = []
|
|
|
|
for policy in policies:
|
|
rules = json.loads(policy["rules"])
|
|
|
|
# Check transitions
|
|
for rule in rules.get("transitions", []):
|
|
prefix = rule.get("prefix")
|
|
if prefix and not obj["object_key"].startswith(prefix):
|
|
continue
|
|
|
|
days_old = (datetime.now(timezone.utc) - obj["modified_at"]).days
|
|
|
|
if days_old >= rule["days"]:
|
|
applicable_actions.append({
|
|
"action": LifecycleAction.TRANSITION.value,
|
|
"target_storage_class": rule["storage_class"],
|
|
"eligible_since": obj["modified_at"] + timedelta(days=rule["days"])
|
|
})
|
|
|
|
# Check expirations
|
|
for rule in rules.get("expirations", []):
|
|
prefix = rule.get("prefix")
|
|
if prefix and not obj["object_key"].startswith(prefix):
|
|
continue
|
|
|
|
days_old = (datetime.now(timezone.utc) - obj["modified_at"]).days
|
|
|
|
if days_old >= rule["days"]:
|
|
applicable_actions.append({
|
|
"action": LifecycleAction.EXPIRE.value,
|
|
"eligible_since": obj["modified_at"] + timedelta(days=rule["days"])
|
|
})
|
|
|
|
return {
|
|
"object_id": object_id,
|
|
"object_key": obj["object_key"],
|
|
"storage_class": obj["storage_class"],
|
|
"created_at": obj["created_at"].isoformat(),
|
|
"modified_at": obj["modified_at"].isoformat(),
|
|
"applicable_actions": applicable_actions
|
|
}
|
|
```
|
|
|
|
**Lifecycle API endpoints**:
|
|
```python
|
|
from fastapi import APIRouter, HTTPException, Query
|
|
from pydantic import BaseModel
|
|
from typing import List, Optional
|
|
|
|
router = APIRouter(prefix="/v1/lifecycle", tags=["lifecycle"])
|
|
|
|
class TransitionRuleModel(BaseModel):
|
|
days: int
|
|
storage_class: str
|
|
prefix: Optional[str] = None
|
|
|
|
class ExpirationRuleModel(BaseModel):
|
|
days: int
|
|
prefix: Optional[str] = None
|
|
|
|
class LifecyclePolicyModel(BaseModel):
|
|
name: str
|
|
transitions: List[TransitionRuleModel] = []
|
|
expirations: List[ExpirationRuleModel] = []
|
|
|
|
@router.post("/buckets/{bucket_id}/policies")
|
|
async def create_lifecycle_policy(
|
|
bucket_id: int,
|
|
policy: LifecyclePolicyModel
|
|
):
|
|
"""Create a lifecycle policy for a bucket."""
|
|
manager = get_lifecycle_manager()
|
|
|
|
policy_id = await manager.create_policy(
|
|
bucket_id=bucket_id,
|
|
name=policy.name,
|
|
transitions=[t.dict() for t in policy.transitions],
|
|
expirations=[e.dict() for e in policy.expirations]
|
|
)
|
|
|
|
return {"policy_id": policy_id, "message": "Policy created"}
|
|
|
|
@router.get("/buckets/{bucket_id}/policies")
|
|
async def list_lifecycle_policies(bucket_id: int):
|
|
"""List lifecycle policies for a bucket."""
|
|
manager = get_lifecycle_manager()
|
|
|
|
policies = await manager.list_policies(bucket_id)
|
|
|
|
return {
|
|
"bucket_id": bucket_id,
|
|
"policies": [
|
|
{
|
|
"id": p.id,
|
|
"name": p.name,
|
|
"transitions": [
|
|
{
|
|
"days": t.days,
|
|
"storage_class": t.target_storage_class.value,
|
|
"prefix": t.prefix
|
|
}
|
|
for t in p.transitions
|
|
],
|
|
"expirations": [
|
|
{
|
|
"days": e.days,
|
|
"prefix": e.prefix
|
|
}
|
|
for e in p.expirations
|
|
],
|
|
"is_enabled": p.is_enabled,
|
|
"created_at": p.created_at.isoformat() if p.created_at else None
|
|
}
|
|
for p in policies
|
|
]
|
|
}
|
|
|
|
@router.get("/policies/{policy_id}")
|
|
async def get_lifecycle_policy(policy_id: int):
|
|
"""Get a specific lifecycle policy."""
|
|
manager = get_lifecycle_manager()
|
|
|
|
policy = await manager.get_policy(policy_id)
|
|
|
|
if not policy:
|
|
raise HTTPException(status_code=404, detail="Policy not found")
|
|
|
|
return {
|
|
"id": policy.id,
|
|
"bucket_id": policy.bucket_id,
|
|
"name": policy.name,
|
|
"transitions": [
|
|
{
|
|
"days": t.days,
|
|
"storage_class": t.target_storage_class.value,
|
|
"prefix": t.prefix
|
|
}
|
|
for t in policy.transitions
|
|
],
|
|
"expirations": [
|
|
{
|
|
"days": e.days,
|
|
"prefix": e.prefix
|
|
}
|
|
for e in p.expirations
|
|
],
|
|
"is_enabled": policy.is_enabled
|
|
}
|
|
|
|
@router.put("/policies/{policy_id}")
|
|
async def update_lifecycle_policy(
|
|
policy_id: int,
|
|
policy: LifecyclePolicyModel
|
|
):
|
|
"""Update a lifecycle policy."""
|
|
manager = get_lifecycle_manager()
|
|
|
|
success = await manager.update_policy(
|
|
policy_id=policy_id,
|
|
name=policy.name,
|
|
transitions=[t.dict() for t in policy.transitions],
|
|
expirations=[e.dict() for e in policy.expirations]
|
|
)
|
|
|
|
return {"message": "Policy updated"}
|
|
|
|
@router.delete("/policies/{policy_id}")
|
|
async def delete_lifecycle_policy(policy_id: int):
|
|
"""Delete a lifecycle policy."""
|
|
manager = get_lifecycle_manager()
|
|
|
|
success = await manager.delete_policy(policy_id)
|
|
|
|
if not success:
|
|
raise HTTPException(status_code=404, detail="Policy not found")
|
|
|
|
return {"message": "Policy deleted"}
|
|
|
|
@router.post("/apply")
|
|
async def apply_lifecycle_policies(limit: int = Query(1000)):
|
|
"""Manually trigger lifecycle rule processing."""
|
|
manager = get_lifecycle_manager()
|
|
|
|
stats = await manager.apply_lifecycle_rules(limit=limit)
|
|
|
|
return {
|
|
"message": "Lifecycle rules applied",
|
|
"stats": stats
|
|
}
|
|
|
|
@router.get("/objects/{object_id}/lifecycle")
|
|
async def get_object_lifecycle_status(object_id: int):
|
|
"""Get lifecycle status for an object."""
|
|
manager = get_lifecycle_manager()
|
|
|
|
status = await manager.get_object_lifecycle_status(object_id)
|
|
|
|
if not status:
|
|
raise HTTPException(status_code=404, detail="Object not found")
|
|
|
|
return status
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
|
|
- [ ] Policies can be created per bucket
|
|
- [ ] Objects transition storage classes automatically
|
|
- [ ] Objects expire/delete according to rules
|
|
- [ ] Prefix-based rules work
|
|
- [ ] Policies can be enabled/disabled
|
|
- [ ] Lifecycle status is visible per object
|
|
- [ ] Manual rule application works
|
|
|
|
## Notes
|
|
|
|
**Trade-offs**:
|
|
- Immediate vs scheduled processing: Scheduled for batch efficiency
|
|
- Hard delete vs soft delete: Depends on bucket versioning
|
|
|
|
**Performance**:
|
|
- Process rules in batches
|
|
- Index on modified_at for efficient querying
|
|
|
|
**Alternatives considered**:
|
|
- S3 lifecycle rules: Similar approach adopted
|
|
- Custom tags for rules: More flexible but more complex
|