"""
Suppression and Do-Not-Sell/Share Signals Orchestrator
This orchestration system processes incoming privacy signals (suppression lists, do-not-sell/share opt-outs)
from various sources (e.g., webhooks, APIs, files). It validates, normalizes, deduplicates, and applies signals
to downstream systems like databases, CDPs, ad platforms, and email service providers (ESPs).
Key Features:
- Supports CCPA/CPRA, GDPR, TCPA compliance.
- Handles batch and real-time signals.
- Idempotent operations (safe retries).
- Audit logging for compliance.
- Scalable with async processing (e.g., Celery, AWS Lambda).
Architecture:
1. Ingress: Webhook/Queue listener for signals.
2. Validation & Normalization: PII hashing, validation.
3. Deduplication & Merge: Upsert to central signal store (Redis + Postgres).
4. Propagation: Fan-out to effectors (DBs, APIs).
5. Monitoring: Metrics, alerts.
Dependencies:
- Python 3.10+
- Install: pip install fastapi uvicorn redis psycopg2-binary celery requests pydantic
- Config: Use .env for secrets (DB_URL, REDIS_URL, etc.)
"""
import os
import json
import hashlib
import uuid
from typing import Dict, List, Any, Optional
from datetime import datetime, timedelta
from enum import Enum
from dataclasses import dataclass
from pydantic import BaseModel, validator
from fastapi import FastAPI, BackgroundTasks, HTTPException
import redis
import psycopg2
from psycopg2.extras import RealDictCursor
import requests
from celery import Celery
# Config
app = FastAPI(title="Privacy Signals Orchestrator")
redis_client = redis.Redis.from_url(os.getenv("REDIS_URL", "redis://localhost:6379"))
celery_app = Celery("orchestrator", broker=os.getenv("CELERY_BROKER", "redis://localhost:6379"))
DB_URL = os.getenv("DB_URL", "postgresql://user:pass@localhost/privacy_signals")
# Enums
class SignalType(str, Enum):
SUPPRESSION = "suppression" # General opt-out (e.g., email, SMS)
DO_NOT_SELL = "do_not_sell"
DO_NOT_SHARE = "do_not_share"
GLOBAL_PRIVACY = "global_privacy" # Revoke all consent
class Source(str, Enum):
WEBHOOK = "webhook"
FILE_UPLOAD = "file_upload"
API = "api"
# Models
@dataclass
class Signal:
id: str
signal_type: SignalType
pii_hash: str # SHA-256 hash of normalized PII (email/phone)
source: Source
timestamp: datetime
expiry: Optional[datetime] = None # e.g., 10 years for legal signals
metadata: Dict[str, Any] = None
class SignalPayload(BaseModel):
signals: List[Dict[str, Any]]
source: str = "webhook"
@validator("signals")
def validate_signals(cls, v):
for sig in v:
if "pii" not in sig or "type" not in sig:
raise ValueError("Each signal must have 'pii' and 'type'")
return v
# Central DB Schema (run once):
# CREATE TABLE signals (
# id UUID PRIMARY KEY,
# signal_type VARCHAR(50) NOT NULL,
# pii_hash VARCHAR(64) NOT NULL,
# source VARCHAR(50),
# timestamp TIMESTAMP NOT NULL,
# expiry TIMESTAMP,
# metadata JSONB,
# UNIQUE(signal_type, pii_hash)
# );
# CREATE INDEX idx_pii_hash ON signals(pii_hash);
# CREATE INDEX idx_expiry ON signals(expiry) WHERE expiry IS NOT NULL;
def get_db_cursor():
return psycopg2.connect(DB_URL).cursor(cursor_factory=RealDictCursor)
def hash_pii(pii: str) -> str:
"""Normalize and hash PII for privacy."""
normalized = pii.lower().strip()
return hashlib.sha256(normalized.encode()).hexdigest()
def store_signal(signal: Signal):
"""Idempotent upsert to Postgres."""
with get_db_cursor() as cur:
cur.execute("""
INSERT INTO signals (id, signal_type, pii_hash, source, timestamp, expiry, metadata)
VALUES (%s, %s, %s, %s, %s, %s, %s)
ON CONFLICT (signal_type, pii_hash)
DO UPDATE SET
timestamp = GREATEST(signals.timestamp, EXCLUDED.timestamp),
metadata = COALESCE(signals.metadata, EXCLUDED.metadata)
""", (signal.id, signal.signal_type, signal.pii_hash, signal.source, signal.timestamp, signal.expiry, json.dumps(signal.metadata)))
cur.connection.commit()
def propagate_to_effectors(signal: Signal):
"""Fan-out to downstream systems."""
effectors = [
{"name": "CDP", "endpoint": os.getenv("CDP_API")},
{"name": "ESP", "endpoint": os.getenv("ESP_API")},
{"name": "AdPlatform", "endpoint": os.getenv("AD_PLATFORM_API")},
]
for effector in effectors:
try:
requests.post(
effector["endpoint"],
json={"action": "suppress", "pii_hash": signal.pii_hash, "type": signal.signal_type},
timeout=10
)
except Exception as e:
# Log error, retry via dead letter queue
print(f"Failed to propagate to {effector['name']}: {e}")
# Celery Tasks
@celery_app.task
def process_signal_async(signal_data: Dict[str, Any]):
signal = Signal(**signal_data)
store_signal(signal)
propagate_to_effectors(signal)
# Cache in Redis for fast lookups (TTL = expiry or 10y)
ttl = int((signal.expiry or datetime.now() + timedelta(days=3650)).timestamp())
redis_client.setex(f"suppress:{signal.pii_hash}:{signal.signal_type}", ttl, "1")
# API Endpoints
@app.post("/ingest")
async def ingest_signals(payload: SignalPayload, background_tasks: BackgroundTasks):
"""Real-time webhook ingestion."""
processed = []
for raw_sig in payload.signals:
sig_id = str(uuid.uuid4())
pii_hash = hash_pii(raw_sig["pii"])
expiry = datetime.now() + timedelta(days=3650) # Default 10y for legal signals
signal_data = {
"id": sig_id,
"signal_type": SignalType(raw_sig["type"]),
"pii_hash": pii_hash,
"source": Source(payload.source),
"timestamp": datetime.utcnow(),
"expiry": expiry,
"metadata": raw_sig.get("metadata", {})
}
background_tasks.add_task(process_signal_async.delay, signal_data)
processed.append(pii_hash)
return {"processed": len(processed), "hashes": processed}
@app.get("/check/{pii}")
async def check_suppression(pii: str, signal_type: SignalType = SignalType.SUPPRESSION):
"""Fast lookup for suppression status."""
pii_hash = hash_pii(pii)
cached = redis_client.get(f"suppress:{pii_hash}:{signal_type}")
if cached:
return {"suppressed": True}
with get_db_cursor() as cur:
cur.execute("SELECT 1 FROM signals WHERE pii_hash = %s AND signal_type = %s AND (expiry > NOW() OR expiry IS NULL)", (pii_hash, signal_type))
return {"suppressed": bool(cur.fetchone())}
@app.post("/batch")
async def batch_upload(file_path: str): # In prod, use file upload
"""Process batch file (CSV/JSON)."""
# Placeholder: Parse file, call ingest_signals in chunks
pass
@app.get("/metrics")
async def metrics():
"""Compliance dashboard metrics."""
with get_db_cursor() as cur:
cur.execute("SELECT signal_type, COUNT(*) FROM signals GROUP BY signal_type")
return {"signals_by_type": cur.fetchall()}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Deployment Guide
-
Setup DB:
CREATE DATABASE privacy_signals;
-- Run schema as above.
-
Environment Vars:
DB_URL=postgresql://...
REDIS_URL=redis://...
CELERY_BROKER=redis://...
CDP_API=https://cdp.example.com/suppress
ESP_API=https://esp.example.com/optout
AD_PLATFORM_API=https://ads.example.com/privacy
-
Run Services:
# API
uvicorn main:app --reload
# Celery Worker (in separate terminal)
celery -A main.celery_app worker --loglevel=info
# Redis/Postgres running
-
Scaling:
- Kubernetes/AWS: Deploy API as Lambda/Fargate, Celery on ECS.
- High Volume: Use Kafka/SQS for ingress queue.
- PII Security: Encrypt DB at rest; never store raw PII.
-
Testing:
curl -X POST "http://localhost:8000/ingest" \
-H "Content-Type: application/json" \
-d '{"signals": [{"pii": "user@example.com", "type": "do_not_sell"}]}'
curl "http://localhost:8000/check/user@example.com?signal_type=do_not_sell"
-
Compliance Notes:
- Honors "universal opt-out" (e.g., Global Privacy Control).
- Audit logs via DB timestamps.
- Extend for deletions (DSAR) by adding
SignalType.DELETE.
This orchestrator ensures signals are processed reliably, propagated atomically, and queryable in <10ms. Customize effectors as needed!