← Back to Research Index View Raw Source

sync-audio-to-cloudflare.py

#!/usr/bin/env python3
"""
sync_audio_to_cloudflare.py — Wire hashed Studio audio receipts into Cloudflare R2 & D1 WORM ledger.
Copyright © Albert Lane. All Rights Reserved. | License v100.0 (Sovereign Aegis Protocol)
"""

from __future__ import annotations

import argparse
import hashlib
import json
import mimetypes
import re
import subprocess
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from typing import Any

from almanac_core import FOUR_RUN_CHAIN_HEAD, _sha256

AUDIO_MIME_FALLBACK = {
    ".mp3": "audio/mpeg",
    ".wav": "audio/wav",
    ".m4a": "audio/mp4",
    ".ogg": "audio/ogg",
    ".opus": "audio/opus",
    ".flac": "audio/flac",
}


def sha256_file(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for chunk in iter(lambda: f.read(65536), b""):
            h.update(chunk)
    return h.hexdigest()


def _sql_str(val: str) -> str:
    return "'" + val.replace("'", "''") + "'"


def _slug(text: str) -> str:
    return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "audio"


def parse_wrangler_toml(toml_path: Path) -> dict[str, str]:
    txt = toml_path.read_text(encoding="utf-8")
    r2_m = re.search(r'bucket_name\s*=\s*"([^"]+)"', txt)
    d1_m = re.search(r'database_name\s*=\s*"([^"]+)"', txt)
    return {
        "r2_bucket": r2_m.group(1) if r2_m else "forensic-worm-archive-lock",
        "d1_database": d1_m.group(1) if d1_m else "albertlane-d1",
    }


def _run(cmd: list[str], cwd: Path) -> str:
    proc = subprocess.run(cmd, cwd=str(cwd), check=True, capture_output=True, text=True)
    return proc.stdout


def query_d1_worm_state(d1_database: str, cloudflare_dir: Path) -> tuple[str, set[str]]:
    head_out = _run(
        [
            "npx",
            "wrangler",
            "d1",
            "execute",
            d1_database,
            "--remote",
            "--json",
            "--command",
            "SELECT chain_head FROM almanac_worm_ledger ORDER BY seq_id DESC LIMIT 1;",
        ],
        cwd=cloudflare_dir,
    )
    existing_out = _run(
        [
            "npx",
            "wrangler",
            "d1",
            "execute",
            d1_database,
            "--remote",
            "--json",
            "--command",
            "SELECT record_key FROM almanac_worm_ledger WHERE channel = 'AUDIO_OVERVIEW_RECEIPT';",
        ],
        cwd=cloudflare_dir,
    )

    def _extract_rows(raw_json: str) -> list[dict[str, Any]]:
        data = json.loads(raw_json)
        if isinstance(data, list) and data:
            return data[0].get("results", [])
        if isinstance(data, dict):
            return data.get("results", [])
        return []

    head_rows = _extract_rows(head_out)
    prev_head = head_rows[0]["chain_head"] if head_rows else FOUR_RUN_CHAIN_HEAD
    existing_keys = {r["record_key"] for r in _extract_rows(existing_out) if "record_key" in r}
    return prev_head, existing_keys


def build_audio_receipt_plan(
    bundle_dir: Path,
    r2_bucket: str,
    prev_chain_head: str,
    existing_keys: set[str],
) -> tuple[list[dict[str, Any]], str, str]:
    manifest_path = bundle_dir / "MANIFEST.json"
    if not manifest_path.exists():
        raise FileNotFoundError(f"MANIFEST.json not found in {bundle_dir}")

    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    audio_entries = [
        item
        for item in manifest.get("hydrated_artifacts", [])
        if item.get("category") == "Audio Overview"
    ]

    uploads: list[dict[str, Any]] = []
    sql_statements: list[str] = ["BEGIN TRANSACTION;"]
    curr_head = prev_chain_head
    now = datetime.now(timezone.utc).isoformat()

    for item in audio_entries:
        rel_path = item["bundle_path"]
        abs_path = bundle_dir / rel_path
        if not abs_path.is_file():
            raise FileNotFoundError(f"Manifest audio file missing on disk: {abs_path}")

        actual_sha = sha256_file(abs_path)
        actual_bytes = abs_path.stat().st_size
        if actual_sha != item["sha256"] or actual_bytes != item["bytes"]:
            raise ValueError(
                f"Audio integrity mismatch for {rel_path}: "
                f"expected ({item['sha256']}, {item['bytes']}), got ({actual_sha}, {actual_bytes})"
            )

        ep = item.get("episode", "Unmapped")
        ep_slug = _slug(ep)
        desc = item.get("description", "")
        title = desc.removeprefix("Exported Studio Audio Overview: ").strip() or abs_path.stem
        record_key = f"audio-{ep_slug}-{actual_sha[:12]}"
        r2_key = f"audio/{ep_slug}/{actual_sha}/{abs_path.name}"
        mime = (
            AUDIO_MIME_FALLBACK.get(abs_path.suffix.lower())
            or mimetypes.guess_type(abs_path.name)[0]
            or "application/octet-stream"
        )

        uploads.append(
            {
                "record_key": record_key,
                "episode": ep,
                "title": title,
                "local_path": str(abs_path),
                "r2_bucket": r2_bucket,
                "r2_key": r2_key,
                "mime_type": mime,
                "bytes": actual_bytes,
                "file_sha256": actual_sha,
            }
        )

        if record_key in existing_keys:
            continue

        payload = {
            "record_key": record_key,
            "episode": ep,
            "title": title,
            "filename": abs_path.name,
            "bundle_path": rel_path,
            "r2_bucket": r2_bucket,
            "r2_key": r2_key,
            "mime_type": mime,
            "bytes": actual_bytes,
            "file_sha256": actual_sha,
            "prior_art_sha256": manifest.get("provenance", {}).get("prior_art_operator_sha256"),
        }
        payload_json = json.dumps(payload, sort_keys=True)
        payload_sha = _sha256(payload)
        new_head = _sha256({"prev": curr_head, "key": record_key, "hash": payload_sha})

        sql_statements.append(
            "INSERT INTO almanac_worm_ledger "
            "(record_key, channel, payload_json, payload_sha256, prev_chain_head, chain_head, sovereign_binding_status, created_at_utc) "
            f"VALUES ({_sql_str(record_key)}, 'AUDIO_OVERVIEW_RECEIPT', {_sql_str(payload_json)}, "
            f"{_sql_str(payload_sha)}, {_sql_str(curr_head)}, {_sql_str(new_head)}, 'PENDING_2_OF_2', {_sql_str(now)});"
        )
        sql_statements.append(
            "INSERT OR IGNORE INTO audio_overview_receipts "
            "(record_key, episode, title, filename, bundle_path, r2_bucket, r2_key, mime_type, bytes, file_sha256, payload_sha256, prev_chain_head, chain_head, deployed_at_utc) "
            f"VALUES ({_sql_str(record_key)}, {_sql_str(ep)}, {_sql_str(title)}, {_sql_str(abs_path.name)}, "
            f"{_sql_str(rel_path)}, {_sql_str(r2_bucket)}, {_sql_str(r2_key)}, {_sql_str(mime)}, "
            f"{actual_bytes}, {_sql_str(actual_sha)}, {_sql_str(payload_sha)}, {_sql_str(curr_head)}, {_sql_str(new_head)}, {_sql_str(now)});"
        )
        curr_head = new_head
        existing_keys.add(record_key)

    sql_statements.append("COMMIT;")
    sql_script = "\n".join(sql_statements) + "\n"
    return uploads, sql_script, curr_head


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Upload hashed Studio audio files to Cloudflare R2 and append WORM receipts to D1."
    )
    parser.add_argument("--bundle-dir", type=Path, default=Path(".."), help="Bundle root containing MANIFEST.json")
    parser.add_argument("--wrangler-toml", type=Path, default=Path("wrangler.toml"), help="Path to wrangler.toml")
    parser.add_argument("--dry-run", action="store_true", help="Print upload plan and emit SQL without calling wrangler")
    parser.add_argument("--sql-out", type=Path, default=None, help="Optional path to save generated D1 SQL")
    args = parser.parse_args()

    bundle_dir = args.bundle_dir.resolve()
    toml_path = args.wrangler_toml.resolve()
    cloudflare_dir = toml_path.parent
    cfg = parse_wrangler_toml(toml_path)

    if args.dry_run:
        prev_head, existing_keys = FOUR_RUN_CHAIN_HEAD, set()
    else:
        prev_head, existing_keys = query_d1_worm_state(cfg["d1_database"], cloudflare_dir)

    uploads, sql_script, final_head = build_audio_receipt_plan(
        bundle_dir=bundle_dir,
        r2_bucket=cfg["r2_bucket"],
        prev_chain_head=prev_head,
        existing_keys=existing_keys,
    )

    if args.sql_out:
        args.sql_out.write_text(sql_script, encoding="utf-8")

    manifest_file = bundle_dir / "MANIFEST.json"
    sums_file = bundle_dir / "SHA256SUMS"
    manifest_sha = sha256_file(manifest_file) if manifest_file.exists() else ""

    if args.dry_run:
        print(
            json.dumps(
                {
                    "mode": "DRY_RUN",
                    "r2_bucket": cfg["r2_bucket"],
                    "d1_database": cfg["d1_database"],
                    "audio_uploads_planned": len(uploads),
                    "new_worm_inserts": sql_script.count("INSERT INTO almanac_worm_ledger"),
                    "start_chain_head": prev_head,
                    "end_chain_head": final_head,
                    "uploads": uploads,
                    "manifest_r2_key": f"manifests/{manifest_sha[:12]}/MANIFEST.json" if manifest_sha else None,
                },
                indent=2,
            )
        )
        return

    # 1. Upload audio objects + provenance manifests to R2
    for up in uploads:
        _run(
            [
                "npx",
                "wrangler",
                "r2",
                "object",
                "put",
                f"{up['r2_bucket']}/{up['r2_key']}",
                f"--file={up['local_path']}",
                f"--content-type={up['mime_type']}",
                "--remote",
            ],
            cwd=cloudflare_dir,
        )

    if manifest_file.exists():
        _run(
            [
                "npx",
                "wrangler",
                "r2",
                "object",
                "put",
                f"{cfg['r2_bucket']}/manifests/{manifest_sha[:12]}/MANIFEST.json",
                f"--file={manifest_file}",
                "--content-type=application/json",
                "--remote",
            ],
            cwd=cloudflare_dir,
        )
    if sums_file.exists():
        _run(
            [
                "npx",
                "wrangler",
                "r2",
                "object",
                "put",
                f"{cfg['r2_bucket']}/manifests/{manifest_sha[:12]}/SHA256SUMS",
                f"--file={sums_file}",
                "--content-type=text/plain",
                "--remote",
            ],
            cwd=cloudflare_dir,
        )

    # 2. Append WORM audio receipts to D1 if any new receipts exist
    new_inserts = sql_script.count("INSERT INTO almanac_worm_ledger")
    if new_inserts > 0:
        with tempfile.NamedTemporaryFile("w", suffix=".sql", delete=False, encoding="utf-8") as tmp:
            tmp.write(sql_script)
            tmp_path = Path(tmp.name)
        try:
            _run(
                [
                    "npx",
                    "wrangler",
                    "d1",
                    "execute",
                    cfg["d1_database"],
                    "--remote",
                    f"--file={tmp_path}",
                ],
                cwd=cloudflare_dir,
            )
        finally:
            tmp_path.unlink(missing_ok=True)

    print(
        json.dumps(
            {
                "mode": "REMOTE_APPLIED",
                "r2_bucket": cfg["r2_bucket"],
                "d1_database": cfg["d1_database"],
                "audio_files_synced": len(uploads),
                "new_worm_receipts_appended": new_inserts,
                "final_worm_chain_head": final_head,
            },
            indent=2,
        )
    )


if __name__ == "__main__":
    main()