Skip to content

Commit 03beaaa

Browse files
rustyconoverclaude
andcommitted
storage: demo and fixture S3 storage implement ObjectStore and return object_id
Since vgi-rpc protocol 3.4 every UploadUrlProvider must return the object_id of the object a grant creates (the server seals it into the grant's ref), and a storage that can fetch objects by id (ObjectStore: put_object/get) is what holds stored StateRefs and resolves argument references. The fixture server's SigV4 S3 storage returned none: the S3 Offload Tests failure "generate_upload_url returned no object_id (required since vgi-rpc protocol 3.4)". It now returns the key and implements put_object (SigV4 PutObject with ChecksumSHA256) and get (NoSuchKey -> ObjectMissingError, capped at max_fetch_bytes), as vgi-rpc's S3Storage does. DemoBlobStorage returns object_id too and implements ObjectStore; its internal blob accessor is renamed get_entry so get() can take the protocol signature. A vended upload that was never PUT reads as missing. The fixture HTTP server also passes token_ttl 21600 and cursor_rule="error" and advertises VGI-Arguments-Ref-Bytes (VGI_TEST_DISABLE_ARGUMENTS_REF=1 turns that off); see the next commit. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 300be9b commit 03beaaa

3 files changed

Lines changed: 143 additions & 14 deletions

File tree

‎tests/test_http_demo_storage.py‎

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from __future__ import annotations
66

7+
import hashlib
78
import os
89
import subprocess
910
import sys
@@ -126,7 +127,7 @@ def test_upload_and_get(self) -> None:
126127
assert url.endswith(".arrow")
127128

128129
key = url.rsplit("/", 1)[1]
129-
entry = storage.get(key)
130+
entry = storage.get_entry(key)
130131
assert entry is not None
131132
data, encoding = entry
132133
assert data == b"hello"
@@ -140,7 +141,7 @@ def test_upload_with_zstd_encoding(self) -> None:
140141
assert url.endswith(".arrow.zst")
141142

142143
key = url.rsplit("/", 1)[1]
143-
entry = storage.get(key)
144+
entry = storage.get_entry(key)
144145
assert entry is not None
145146
data, encoding = entry
146147
assert data == b"compressed"
@@ -154,7 +155,7 @@ def test_upload_with_gzip_encoding(self) -> None:
154155
assert url.endswith(".arrow.gz")
155156

156157
key = url.rsplit("/", 1)[1]
157-
entry = storage.get(key)
158+
entry = storage.get_entry(key)
158159
assert entry is not None
159160
data, encoding = entry
160161
assert data == b"compressed"
@@ -172,12 +173,12 @@ def test_eviction(self) -> None:
172173
# First two should have been evicted.
173174
for url in urls[:2]:
174175
key = url.rsplit("/", 1)[1]
175-
assert storage.get(key) is None
176+
assert storage.get_entry(key) is None
176177

177178
# Last three should still be present.
178179
for url in urls[2:]:
179180
key = url.rsplit("/", 1)[1]
180-
assert storage.get(key) is not None
181+
assert storage.get_entry(key) is not None
181182

182183
def test_generate_upload_url(self) -> None:
183184
"""generate_upload_url returns matching PUT/GET URLs with .arrow extension."""
@@ -211,10 +212,29 @@ def test_put_and_get(self) -> None:
211212
"""Direct put/get stores and retrieves blob data with encoding."""
212213
storage = DemoBlobStorage()
213214
storage.put("test-key.arrow", b"payload", "zstd")
214-
entry = storage.get("test-key.arrow")
215+
entry = storage.get_entry("test-key.arrow")
215216
assert entry is not None
216217
assert entry == (b"payload", "zstd")
217218

219+
def test_object_store(self) -> None:
220+
"""The ObjectStore half (protocol 3.4): put_object/get by id, missing ids, vended uploads."""
221+
from vgi_rpc.external import ObjectMissingError, ObjectStore
222+
223+
storage = DemoBlobStorage()
224+
assert isinstance(storage, ObjectStore)
225+
object_id = storage.put_object(b"state")
226+
assert storage.get(object_id) == b"state"
227+
with pytest.raises(ValueError, match="max_fetch_bytes"):
228+
storage.get(object_id, max_bytes=2)
229+
with pytest.raises(ObjectMissingError):
230+
storage.get("nope.bin")
231+
grant = storage.generate_upload_url(3, hashlib.sha256(b"abc").hexdigest())
232+
assert grant.object_id
233+
with pytest.raises(ObjectMissingError):
234+
storage.get(grant.object_id) # vended but never PUT
235+
storage.put(grant.object_id, b"abc")
236+
assert storage.get(grant.object_id) == b"abc"
237+
218238
def test_localhost_only_validator_accepts_localhost(self) -> None:
219239
"""localhost_only_validator accepts 127.0.0.1 and localhost URLs."""
220240
localhost_only_validator("http://127.0.0.1:8080/__blobs__/abc.arrow")

‎vgi/_test_fixtures/http_server.py‎

Lines changed: 69 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,8 +120,66 @@ def generate_upload_url(self, size: int, sha256_hex: str) -> UploadUrl:
120120
download_url=get_url,
121121
expires_at=expires_at,
122122
headers={"x-amz-checksum-sha256": checksum},
123+
# Protocol 3.4: the server seals the key into the grant's argument
124+
# reference and fetches it back with get().
125+
object_id=key,
123126
)
124127

128+
def put_object(self, data: bytes) -> str:
129+
"""Store *data* under a fresh key, size- and SHA-256-checked by S3 (``ObjectStore``)."""
130+
import base64
131+
import hashlib
132+
import uuid
133+
134+
key = f"{self.prefix}{uuid.uuid4().hex}.bin"
135+
self._get_client().put_object(
136+
Bucket=self.bucket,
137+
Key=key,
138+
Body=data,
139+
ContentLength=len(data),
140+
ChecksumSHA256=base64.b64encode(hashlib.sha256(data).digest()).decode("ascii"),
141+
ContentType="application/octet-stream",
142+
)
143+
return key
144+
145+
def get(self, object_id: str, *, max_bytes: int | None = None) -> bytes:
146+
"""Fetch the object at key *object_id* (``ObjectStore``).
147+
148+
Args:
149+
object_id: The object key.
150+
max_bytes: Largest object accepted; ``None`` means 256 MiB.
151+
152+
Returns:
153+
The object bytes.
154+
155+
Raises:
156+
ObjectMissingError: S3 reports ``NoSuchKey`` / 404.
157+
ValueError: The object is larger than *max_bytes* (default 256 MiB).
158+
159+
"""
160+
from vgi_rpc.external import ObjectMissingError
161+
162+
limit = max_bytes if max_bytes is not None else DEFAULT_MAX_FETCH_BYTES
163+
try:
164+
resp = self._get_client().get_object(Bucket=self.bucket, Key=object_id)
165+
except Exception as exc:
166+
error = getattr(exc, "response", None)
167+
code = error.get("Error", {}).get("Code") if isinstance(error, dict) else None
168+
if code in ("NoSuchKey", "404", "NotFound"):
169+
raise ObjectMissingError("S3 object is gone") from None
170+
raise
171+
body = resp["Body"]
172+
try:
173+
length = resp.get("ContentLength")
174+
if isinstance(length, int) and length > limit:
175+
raise ValueError(f"S3 object is {length} bytes, over max_fetch_bytes ({limit})")
176+
data: bytes = body.read(limit + 1)
177+
finally:
178+
body.close()
179+
if len(data) > limit:
180+
raise ValueError(f"S3 object exceeds max_fetch_bytes ({limit})")
181+
return data
182+
125183

126184
def _upload_fetch_config(max_upload_bytes: int) -> FetchConfig:
127185
"""Inbound fetch config able to fetch back the uploads this server advertises.
@@ -360,7 +418,7 @@ def _make_compression() -> Compression | None:
360418
)
361419
sys.stderr.flush()
362420

363-
from vgi.serve import _resolve_authenticate, _resolve_oauth_resource_metadata
421+
from vgi.serve import TOKEN_TTL_SECONDS, _resolve_authenticate, _resolve_oauth_resource_metadata
364422

365423
authenticate = _resolve_authenticate()
366424
oauth_metadata = _resolve_oauth_resource_metadata()
@@ -489,6 +547,16 @@ def _optional_bearer(req: Any) -> AuthContext:
489547
authenticate=authenticate,
490548
oauth_resource_metadata=oauth_metadata,
491549
enable_landing_page=False,
550+
token_ttl=TOKEN_TTL_SECONDS,
551+
cursor_rule="error",
552+
)
553+
# VGI-Arguments-Ref-Bytes (protocol 3.4); VGI_TEST_DISABLE_ARGUMENTS_REF=1
554+
# turns it off so the server behaves like a worker without argument
555+
# references (the extension's arguments_ref_fallback.test).
556+
from vgi.arguments_ref import install_arguments_ref_header
557+
558+
install_arguments_ref_header(
559+
wsgi_app, upload_url_provider=upload_url_provider, external_location=external_location
492560
)
493561

494562
if demo_storage:

‎vgi/http/demo_storage.py‎

Lines changed: 48 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22

33
"""In-process blob storage for demonstrating and testing external batch offloading.
44
5-
Provides a simple HTTP blob store that implements the ``ExternalStorage`` and
6-
``UploadUrlProvider`` protocols from vgi_rpc, served from the same HTTP server
7-
process. This allows the example worker to demonstrate external record batch
5+
Provides a simple HTTP blob store that implements the ``ExternalStorage``,
6+
``UploadUrlProvider`` and ``ObjectStore`` protocols from vgi_rpc, served from
7+
the same HTTP server process. This allows the example worker to demonstrate external record batch
88
offloading without requiring S3 or any cloud infrastructure.
99
1010
**Not for production use** — blobs are held in memory with LRU eviction.
@@ -24,7 +24,7 @@
2424

2525

2626
class DemoBlobStorage:
27-
"""In-memory blob store implementing ``ExternalStorage`` and ``UploadUrlProvider``.
27+
"""In-memory blob store implementing ``ExternalStorage``, ``UploadUrlProvider`` and ``ObjectStore``.
2828
2929
Blobs are stored in an ``OrderedDict`` with LRU eviction when ``max_blobs``
3030
is exceeded. Thread-safe for use with multi-threaded WSGI servers like
@@ -85,8 +85,49 @@ def generate_upload_url(self, size: int, sha256_hex: str) -> UploadUrl:
8585
download_url=url,
8686
expires_at=datetime.now(UTC) + timedelta(hours=1),
8787
headers={"x-amz-checksum-sha256": checksum},
88+
object_id=key,
8889
)
8990

91+
# -- ObjectStore protocol (protocol 3.4: StateRef objects, argument references) --
92+
93+
def put_object(self, data: bytes) -> str:
94+
"""Store *data* as one object and return its id (the blob key)."""
95+
key = f"{uuid.uuid4().hex}.bin"
96+
with self._lock:
97+
self._blobs[key] = (bytes(data), None)
98+
self._evict()
99+
return key
100+
101+
def get(self, object_id: str, *, max_bytes: int | None = None) -> bytes:
102+
"""Return the object *object_id* names.
103+
104+
Args:
105+
object_id: An id from :meth:`put_object` or :meth:`generate_upload_url`.
106+
max_bytes: Refuse objects larger than this; ``None`` means no limit.
107+
108+
Returns:
109+
The object bytes.
110+
111+
Raises:
112+
ObjectMissingError: The id is unknown, evicted, or a vended upload
113+
that was never PUT.
114+
ValueError: The object is larger than *max_bytes*.
115+
116+
"""
117+
from vgi_rpc.external import ObjectMissingError
118+
119+
with self._lock:
120+
entry = self._blobs.get(object_id)
121+
declared = self._declared.get(object_id)
122+
if entry is None or (declared is not None and len(entry[0]) != declared[0]):
123+
raise ObjectMissingError("demo blob is gone")
124+
data, content_encoding = entry
125+
if content_encoding is not None:
126+
raise ValueError(f"demo blob {object_id!r} is stored {content_encoding}-encoded, not as an object")
127+
if max_bytes is not None and len(data) > max_bytes:
128+
raise ValueError(f"demo blob is {len(data)} bytes, over max_fetch_bytes ({max_bytes})")
129+
return data
130+
90131
def check_put(self, key: str, data: bytes, checksum_header: str | None) -> tuple[str, str] | None:
91132
"""Return ``(HTTP status, S3 error code)`` when a PUT to *key* must be refused.
92133
@@ -114,7 +155,7 @@ def check_put(self, key: str, data: bytes, checksum_header: str | None) -> tuple
114155

115156
# -- Internal accessors for BlobResource --
116157

117-
def get(self, key: str) -> tuple[bytes, str | None] | None:
158+
def get_entry(self, key: str) -> tuple[bytes, str | None] | None:
118159
"""Return ``(data, content_encoding)`` or ``None``."""
119160
with self._lock:
120161
entry = self._blobs.get(key)
@@ -145,7 +186,7 @@ def __init__(self, storage: DemoBlobStorage) -> None: # noqa: D107
145186
def on_get(self, req: Any, resp: Any, blob_id: str) -> None: # noqa: D102
146187
import falcon
147188

148-
entry = self._storage.get(blob_id)
189+
entry = self._storage.get_entry(blob_id)
149190
if entry is None:
150191
raise falcon.HTTPNotFound(description=f"Blob {blob_id!r} not found")
151192
data, content_encoding = entry
@@ -165,7 +206,7 @@ def on_head(self, req: Any, resp: Any, blob_id: str) -> None: # noqa: D102
165206
# decompression.
166207
import falcon
167208

168-
entry = self._storage.get(blob_id)
209+
entry = self._storage.get_entry(blob_id)
169210
if entry is None:
170211
raise falcon.HTTPNotFound(description=f"Blob {blob_id!r} not found")
171212
data, content_encoding = entry

0 commit comments

Comments
 (0)