16 KiB
16 KiB
Subtask: Storage Architecture and Metadata
Parent Task: Decomp/005 Subtask ID: Decomp/005-01 Dependencies: None
Description
Design storage architecture for distributed object storage system. Define metadata schema, bucket organization, data distribution strategy, and consistency guarantees.
Requirements
- Bucket-based file organization
- Metadata storage for files
- Data partitioning across nodes
- Consistent hashing for distribution
- Checksum-based integrity verification
- Support for large files (multi-part)
- Version tracking
- Access control metadata
Technical Specifications
Storage architecture overview:
┌─────────────────────────────────────────────────────────────┐
│ API Layer │
├─────────────────────────────────────────────────────────────┤
│ Metadata Service │
│ - PostgreSQL for metadata │
│ - Redis for hot metadata cache │
├─────────────────────────────────────────────────────────────┤
│ Storage Engine │
│ - Consistent Hash Ring │
│ - Replication Manager │
│ - Local Storage Adapter │
├─────────────────────────────────────────────────────────────┤
│ Storage Nodes (N replicas) │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Node 1 │ │ Node 2 │ │ Node 3 │ │ Node 4 │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────────────────────┘
Metadata schema (PostgreSQL):
-- Buckets (containers for files)
CREATE TABLE buckets (
id BIGSERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL UNIQUE,
owner_id BIGINT NOT NULL,
region VARCHAR(50) DEFAULT 'us-east-1',
storage_class VARCHAR(20) DEFAULT 'standard', -- standard, infrequent, archive
versioning_enabled BOOLEAN DEFAULT FALSE,
quota_bytes BIGINT,
used_bytes BIGINT DEFAULT 0,
object_count INTEGER DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
metadata JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX idx_buckets_owner ON buckets(owner_id);
CREATE INDEX idx_buckets_name ON buckets(name);
-- Objects (files)
CREATE TABLE objects (
id BIGSERIAL PRIMARY KEY,
bucket_id BIGINT NOT NULL REFERENCES buckets(id) ON DELETE CASCADE,
object_key VARCHAR(1024) NOT NULL, -- Full path including "folders"
version_id VARCHAR(100) UNIQUE, -- NULL if versioning disabled
is_latest BOOLEAN DEFAULT TRUE,
is_delete_marker BOOLEAN DEFAULT FALSE,
-- File metadata
content_type VARCHAR(255),
content_encoding VARCHAR(50),
content_language VARCHAR(50),
content_length BIGINT NOT NULL,
etag VARCHAR(100) NOT NULL, -- MD5 hash
checksum_sha256 VARCHAR(100),
-- Storage metadata
storage_class VARCHAR(20) DEFAULT 'standard',
storage_nodes JSONB, -- List of node IDs holding this object
-- Timestamps
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
modified_at TIMESTAMP NOT NULL DEFAULT NOW(),
accessed_at TIMESTAMP,
-- Additional metadata
user_metadata JSONB DEFAULT '{}'::jsonb,
custom_tags JSONB DEFAULT '{}'::jsonb,
UNIQUE(bucket_id, object_key, version_id)
);
CREATE INDEX idx_objects_bucket ON objects(bucket_id);
CREATE INDEX idx_objects_key ON objects(bucket_id, object_key);
CREATE INDEX idx_objects_version ON objects(bucket_id, object_key, version_id);
CREATE INDEX idx_objects_latest ON objects(bucket_id, object_key) WHERE is_latest = TRUE;
-- Multipart uploads
CREATE TABLE multipart_uploads (
id BIGSERIAL PRIMARY KEY,
upload_id VARCHAR(100) NOT NULL UNIQUE,
bucket_id BIGINT NOT NULL REFERENCES buckets(id),
object_key VARCHAR(1024) NOT NULL,
content_type VARCHAR(255),
owner_id BIGINT NOT NULL,
initiated_at TIMESTAMP NOT NULL DEFAULT NOW(),
expires_at TIMESTAMP NOT NULL,
parts_uploaded INTEGER DEFAULT 0,
total_parts INTEGER,
metadata JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX idx_multipart_uploads_id ON multipart_uploads(upload_id);
CREATE INDEX idx_multipart_uploads_expires ON multipart_uploads(expires_at)
WHERE expires_at > NOW();
-- Multipart upload parts
CREATE TABLE multipart_parts (
id BIGSERIAL PRIMARY KEY,
upload_id VARCHAR(100) NOT NULL REFERENCES multipart_uploads(upload_id) ON DELETE CASCADE,
part_number INTEGER NOT NULL,
object_id BIGINT NOT NULL REFERENCES objects(id),
size_bytes BIGINT NOT NULL,
etag VARCHAR(100) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
UNIQUE(upload_id, part_number)
);
CREATE INDEX idx_multipart_parts_upload ON multipart_parts(upload_id, part_number);
-- Access Control Lists
CREATE TABLE acls (
id BIGSERIAL PRIMARY KEY,
resource_type VARCHAR(20) NOT NULL, -- 'bucket' or 'object'
resource_id BIGINT NOT NULL,
grantee_type VARCHAR(20) NOT NULL, -- 'user', 'group', 'all'
grantee_id VARCHAR(255), -- User ID, group name, or NULL for 'all'
permission VARCHAR(20) NOT NULL, -- 'read', 'write', 'read_acl', 'write_acl', 'full_control'
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_acls_resource ON acls(resource_type, resource_id);
-- Presigned URLs
CREATE TABLE presigned_urls (
id BIGSERIAL PRIMARY KEY,
object_id BIGINT NOT NULL REFERENCES objects(id) ON DELETE CASCADE,
access_key VARCHAR(100) NOT NULL UNIQUE,
expires_at TIMESTAMP NOT NULL,
operation VARCHAR(10) NOT NULL, -- 'get', 'put', 'delete'
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_presigned_key ON presigned_urls(access_key);
CREATE INDEX idx_presigned_expires ON presigned_urls(expires_at) WHERE expires_at > NOW();
-- Storage nodes registration
CREATE TABLE storage_nodes (
id SERIAL PRIMARY KEY,
node_id VARCHAR(100) NOT NULL UNIQUE,
hostname VARCHAR(255) NOT NULL,
port INTEGER DEFAULT 8080,
storage_path VARCHAR(500) NOT NULL,
capacity_bytes BIGINT NOT NULL,
used_bytes BIGINT DEFAULT 0,
status VARCHAR(20) DEFAULT 'active', -- active, draining, maintenance, offline
region VARCHAR(50),
zone VARCHAR(50),
weight INTEGER DEFAULT 100, -- For weighted consistent hashing
last_heartbeat TIMESTAMP NOT NULL DEFAULT NOW(),
metadata JSONB DEFAULT '{}'::jsonb,
created_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_nodes_status ON storage_nodes(status);
CREATE INDEX idx_nodes_heartbeat ON storage_nodes(last_heartbeat);
-- Replication status
CREATE TABLE replication_status (
id BIGSERIAL PRIMARY KEY,
object_id BIGINT NOT NULL REFERENCES objects(id) ON DELETE CASCADE,
source_node VARCHAR(100),
target_node VARCHAR(100),
status VARCHAR(20) NOT NULL, -- pending, in_progress, completed, failed
started_at TIMESTAMP,
completed_at TIMESTAMP,
error_message TEXT
);
CREATE INDEX idx_replication_object ON replication_status(object_id);
CREATE INDEX idx_replication_status ON replication_status(status);
-- Lifecycle policies
CREATE TABLE lifecycle_policies (
id BIGSERIAL PRIMARY KEY,
bucket_id BIGINT NOT NULL REFERENCES buckets(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
rules JSONB NOT NULL, -- Transition/expiration rules
is_enabled BOOLEAN DEFAULT TRUE,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE INDEX idx_lifecycle_bucket ON lifecycle_policies(bucket_id);
-- Audit log
CREATE TABLE audit_log (
id BIGSERIAL PRIMARY KEY,
bucket_id BIGINT REFERENCES buckets(id),
object_id BIGINT REFERENCES objects(id),
operation VARCHAR(20) NOT NULL, -- GET, PUT, DELETE, HEAD, LIST
user_id VARCHAR(255),
access_key_id VARCHAR(100),
request_id VARCHAR(100),
source_ip VARCHAR(50),
user_agent TEXT,
http_status INTEGER,
error_code VARCHAR(50),
bytes_sent BIGINT,
bytes_received BIGINT,
operation_time TIMESTAMP NOT NULL DEFAULT NOW(),
details JSONB DEFAULT '{}'::jsonb
);
CREATE INDEX idx_audit_log_time ON audit_log(operation_time DESC);
CREATE INDEX idx_audit_log_bucket ON audit_log(bucket_id, operation_time DESC);
CREATE INDEX idx_audit_log_object ON audit_log(object_id, operation_time DESC);
-- Functions and triggers
CREATE OR REPLACE FUNCTION update_bucket_stats()
RETURNS TRIGGER AS $$
BEGIN
IF TG_OP = 'INSERT' THEN
UPDATE buckets
SET used_bytes = used_bytes + NEW.content_length,
object_count = object_count + 1,
updated_at = NOW()
WHERE id = NEW.bucket_id;
ELSIF TG_OP = 'DELETE' THEN
UPDATE buckets
SET used_bytes = used_bytes - OLD.content_length,
object_count = object_count - 1,
updated_at = NOW()
WHERE id = OLD.bucket_id;
END IF;
RETURN NULL;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER update_bucket_stats_trigger
AFTER INSERT OR DELETE ON objects
FOR EACH ROW
EXECUTE FUNCTION update_bucket_stats();
-- Function to generate version ID
CREATE OR REPLACE FUNCTION generate_version_id()
RETURNS TRIGGER AS $$
BEGIN
NEW.version_id := 'v-' || encode(gen_random_bytes(16), 'hex');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger for version ID (only when versioning enabled)
CREATE OR REPLACE FUNCTION check_versioning()
RETURNS TRIGGER AS $$
DECLARE
versioning_enabled BOOLEAN;
BEGIN
SELECT b.versioning_enabled INTO versioning_enabled
FROM buckets b WHERE b.id = NEW.bucket_id;
IF versioning_enabled THEN
PERFORM generate_version_id();
NEW.version_id := 'v-' || encode(gen_random_bytes(16), 'hex');
-- Mark previous versions as not latest
UPDATE objects
SET is_latest = FALSE
WHERE bucket_id = NEW.bucket_id
AND object_key = NEW.object_key
AND is_latest = TRUE;
ELSE
-- Delete previous object if exists
DELETE FROM objects
WHERE bucket_id = NEW.bucket_id
AND object_key = NEW.object_key
AND is_latest = TRUE;
NEW.version_id := 'v-' || encode(gen_random_bytes(16), 'hex');
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Storage allocation view
CREATE VIEW storage_usage AS
SELECT
sn.id,
sn.node_id,
sn.hostname,
sn.capacity_bytes,
sn.used_bytes,
sn.capacity_bytes - sn.used_bytes as available_bytes,
ROUND((sn.used_bytes::NUMERIC / sn.capacity_bytes) * 100, 2) as usage_percent,
sn.status,
COUNT(DISTINCT o.id) as object_count
FROM storage_nodes sn
LEFT JOIN objects o ON o.storage_nodes @> to_jsonb(sn.node_id)
GROUP BY sn.id, sn.node_id, sn.hostname, sn.capacity_bytes, sn.used_bytes, sn.status;
Consistent hashing configuration:
from dataclasses import dataclass
from typing import List, Dict, Optional
import hashlib
import bisect
@dataclass
class HashRingConfig:
"""Configuration for consistent hash ring."""
virtual_nodes: int = 150 # Virtual nodes per physical node
replication_factor: int = 3 # Number of replicas
hash_function: str = "md5" # md5, sha1, sha256
class HashRing:
"""Consistent hash ring for data distribution."""
def __init__(self, config: HashRingConfig):
self.config = config
self.ring: Dict[int, str] = {} # hash -> node_id
self.sorted_keys: List[int] = []
self.nodes: Dict[str, dict] = {}
def add_node(self, node_id: str, weight: int = 100):
"""Add a node to the ring."""
self.nodes[node_id] = {"weight": weight, "status": "active"}
# Add virtual nodes based on weight
virtual_count = self.config.virtual_nodes * weight // 100
for i in range(virtual_count):
key = self._hash(f"{node_id}:{i}")
self.ring[key] = node_id
bisect.insort(self.sorted_keys, key)
def remove_node(self, node_id: str):
"""Remove a node from the ring."""
self.nodes.pop(node_id, None)
# Remove all virtual nodes
keys_to_remove = [k for k, v in self.ring.items() if v == node_id]
for key in keys_to_remove:
self.ring.pop(key)
self.sorted_keys.remove(key)
def get_nodes(self, key: str) -> List[str]:
"""Get replication nodes for a key."""
if not self.sorted_keys:
return []
key_hash = self._hash(key)
idx = bisect.bisect_right(self.sorted_keys, key_hash)
nodes = []
# Get next N nodes
for _ in range(self.config.replication_factor * 10): # Limit iterations
if idx >= len(self.sorted_keys):
idx = 0
node_id = self.ring[self.sorted_keys[idx]]
if node_id not in nodes and self.nodes.get(node_id, {}).get("status") == "active":
nodes.append(node_id)
if len(nodes) >= self.config.replication_factor:
break
idx += 1
return nodes
def _hash(self, key: str) -> int:
"""Hash a key to an integer."""
if self.config.hash_function == "md5":
return int(hashlib.md5(key.encode()).hexdigest(), 16)
elif self.config.hash_function == "sha1":
return int(hashlib.sha1(key.encode()).hexdigest(), 16)
elif self.config.hash_function == "sha256":
return int(hashlib.sha256(key.encode()).hexdigest(), 16)
else:
return int(hashlib.md5(key.encode()).hexdigest(), 16)
Storage node configuration:
@dataclass
class StorageNodeConfig:
"""Configuration for a storage node."""
node_id: str
hostname: str
port: int = 8080
storage_path: str = "/data/storage"
capacity_bytes: int = 1_000_000_000_000 # 1TB default
region: str = "us-east-1"
zone: str = "a"
@dataclass
class StorageClass:
"""Storage class definitions."""
name: str # standard, infrequent, archive
durability: int # 9s (e.g., 11 for 99.999999999%)
availability: str # 99.99%
min_storage_size: int = 0
retrieval_time: str = "instant" # instant, minutes, hours
transition_days: int = None # Auto-transition after N days
Acceptance Criteria
- All tables created without errors
- Foreign key constraints enforced
- Hash ring distributes keys evenly
- Replication factor is respected
- Bucket stats update on object changes
- Version ID generation works
Notes
Trade-offs:
- PostgreSQL vs NoSQL for metadata: PostgreSQL for ACID
- Consistent hashing vs simple modulo: Consistent hashing for rebalancing
Scalability:
- Partition metadata by bucket_id for very large deployments
- Use read replicas for metadata queries
Alternatives considered:
- DynamoDB for metadata: More expensive, eventual consistency
- Ceph for storage: More complex, overkill for this use case