|
| 1 | +"""External payload storage contracts for large Durable Workflow payloads.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import hashlib |
| 6 | +from dataclasses import dataclass |
| 7 | +from pathlib import Path |
| 8 | +from typing import Protocol |
| 9 | +from urllib.parse import unquote, urlparse |
| 10 | + |
| 11 | +EXTERNAL_PAYLOAD_REFERENCE_SCHEMA = "durable-workflow.v2.external-payload-reference.v1" |
| 12 | + |
| 13 | + |
| 14 | +class ExternalPayloadIntegrityError(ValueError): |
| 15 | + """Raised when fetched external payload bytes do not match their reference.""" |
| 16 | + |
| 17 | + |
| 18 | +class ExternalStorageDriver(Protocol): |
| 19 | + """Protocol implemented by pluggable external payload storage drivers.""" |
| 20 | + |
| 21 | + def put(self, data: bytes, *, sha256: str, codec: str) -> str: |
| 22 | + """Persist *data* and return a stable URI for later fetches.""" |
| 23 | + |
| 24 | + def get(self, uri: str) -> bytes: |
| 25 | + """Fetch previously persisted payload bytes.""" |
| 26 | + |
| 27 | + def delete(self, uri: str) -> None: |
| 28 | + """Delete previously persisted payload bytes when retention removes a run.""" |
| 29 | + |
| 30 | + |
| 31 | +@dataclass(frozen=True) |
| 32 | +class ExternalPayloadReference: |
| 33 | + """Stable wire envelope for a payload stored outside workflow history.""" |
| 34 | + |
| 35 | + uri: str |
| 36 | + sha256: str |
| 37 | + size_bytes: int |
| 38 | + codec: str |
| 39 | + schema: str = EXTERNAL_PAYLOAD_REFERENCE_SCHEMA |
| 40 | + |
| 41 | + def to_dict(self) -> dict[str, str | int]: |
| 42 | + return { |
| 43 | + "schema": self.schema, |
| 44 | + "uri": self.uri, |
| 45 | + "sha256": self.sha256, |
| 46 | + "size_bytes": self.size_bytes, |
| 47 | + "codec": self.codec, |
| 48 | + } |
| 49 | + |
| 50 | + @classmethod |
| 51 | + def from_dict(cls, data: object) -> ExternalPayloadReference: |
| 52 | + if not isinstance(data, dict): |
| 53 | + raise ValueError("external payload reference must be an object") |
| 54 | + |
| 55 | + schema = data.get("schema") |
| 56 | + uri = data.get("uri") |
| 57 | + sha256 = data.get("sha256") |
| 58 | + size_bytes = data.get("size_bytes") |
| 59 | + codec = data.get("codec") |
| 60 | + |
| 61 | + if schema != EXTERNAL_PAYLOAD_REFERENCE_SCHEMA: |
| 62 | + raise ValueError("unsupported external payload reference schema") |
| 63 | + if not isinstance(uri, str) or not uri: |
| 64 | + raise ValueError("external payload reference uri must be a non-empty string") |
| 65 | + if not isinstance(sha256, str) or len(sha256) != 64: |
| 66 | + raise ValueError("external payload reference sha256 must be a hex digest") |
| 67 | + try: |
| 68 | + int(sha256, 16) |
| 69 | + except ValueError as exc: |
| 70 | + raise ValueError("external payload reference sha256 must be a hex digest") from exc |
| 71 | + if not isinstance(size_bytes, int) or size_bytes < 0: |
| 72 | + raise ValueError("external payload reference size_bytes must be a non-negative integer") |
| 73 | + if not isinstance(codec, str) or not codec: |
| 74 | + raise ValueError("external payload reference codec must be a non-empty string") |
| 75 | + |
| 76 | + return cls(uri=uri, sha256=sha256, size_bytes=size_bytes, codec=codec, schema=schema) |
| 77 | + |
| 78 | + |
| 79 | +class LocalFilesystemExternalStorage: |
| 80 | + """Dependency-free external storage driver for development and tests.""" |
| 81 | + |
| 82 | + def __init__(self, root: str | Path) -> None: |
| 83 | + self.root = Path(root).resolve() |
| 84 | + self.root.mkdir(parents=True, exist_ok=True) |
| 85 | + |
| 86 | + def put(self, data: bytes, *, sha256: str, codec: str) -> str: |
| 87 | + _validate_sha256(sha256) |
| 88 | + codec_segment = _safe_codec_segment(codec) |
| 89 | + path = self.root / codec_segment / sha256[:2] / sha256 |
| 90 | + path.parent.mkdir(parents=True, exist_ok=True) |
| 91 | + if not path.exists(): |
| 92 | + path.write_bytes(data) |
| 93 | + return path.as_uri() |
| 94 | + |
| 95 | + def get(self, uri: str) -> bytes: |
| 96 | + path = self._path_from_uri(uri) |
| 97 | + return path.read_bytes() |
| 98 | + |
| 99 | + def delete(self, uri: str) -> None: |
| 100 | + path = self._path_from_uri(uri) |
| 101 | + try: |
| 102 | + path.unlink() |
| 103 | + except FileNotFoundError: |
| 104 | + return |
| 105 | + |
| 106 | + def _path_from_uri(self, uri: str) -> Path: |
| 107 | + parsed = urlparse(uri) |
| 108 | + if parsed.scheme != "file" or parsed.netloc not in {"", "localhost"}: |
| 109 | + raise ValueError("local external storage can only read file:// URIs") |
| 110 | + |
| 111 | + path = Path(unquote(parsed.path)).resolve() |
| 112 | + try: |
| 113 | + path.relative_to(self.root) |
| 114 | + except ValueError as exc: |
| 115 | + raise ValueError("external payload URI is outside the local storage root") from exc |
| 116 | + return path |
| 117 | + |
| 118 | + |
| 119 | +def store_external_payload( |
| 120 | + driver: ExternalStorageDriver, |
| 121 | + data: bytes, |
| 122 | + *, |
| 123 | + codec: str, |
| 124 | +) -> ExternalPayloadReference: |
| 125 | + """Store encoded payload bytes and return their reference envelope.""" |
| 126 | + sha256 = hashlib.sha256(data).hexdigest() |
| 127 | + uri = driver.put(data, sha256=sha256, codec=codec) |
| 128 | + return ExternalPayloadReference( |
| 129 | + uri=uri, |
| 130 | + sha256=sha256, |
| 131 | + size_bytes=len(data), |
| 132 | + codec=codec, |
| 133 | + ) |
| 134 | + |
| 135 | + |
| 136 | +def fetch_external_payload( |
| 137 | + driver: ExternalStorageDriver, |
| 138 | + reference: ExternalPayloadReference, |
| 139 | +) -> bytes: |
| 140 | + """Fetch payload bytes and verify size/hash before replay or decode.""" |
| 141 | + data = driver.get(reference.uri) |
| 142 | + if len(data) != reference.size_bytes: |
| 143 | + raise ExternalPayloadIntegrityError("external payload size does not match its reference") |
| 144 | + |
| 145 | + actual_sha256 = hashlib.sha256(data).hexdigest() |
| 146 | + if actual_sha256 != reference.sha256: |
| 147 | + raise ExternalPayloadIntegrityError("external payload hash does not match its reference") |
| 148 | + return data |
| 149 | + |
| 150 | + |
| 151 | +def _validate_sha256(sha256: str) -> None: |
| 152 | + if len(sha256) != 64: |
| 153 | + raise ValueError("sha256 must be a hex digest") |
| 154 | + try: |
| 155 | + int(sha256, 16) |
| 156 | + except ValueError as exc: |
| 157 | + raise ValueError("sha256 must be a hex digest") from exc |
| 158 | + |
| 159 | + |
| 160 | +def _safe_codec_segment(codec: str) -> str: |
| 161 | + if not codec: |
| 162 | + raise ValueError("codec must be a non-empty string") |
| 163 | + if not all(char.isalnum() or char in {"-", "_", "."} for char in codec): |
| 164 | + raise ValueError("codec contains characters that are unsafe for local storage paths") |
| 165 | + return codec |
0 commit comments