diff --git a/README.md b/README.md index 896807c..006d333 100644 --- a/README.md +++ b/README.md @@ -497,7 +497,7 @@ class MyStorage: async def write(self, content: bytes, if_match: str | None = None) -> str: """ Conditional write. - - if_match=None → unconditional put (first write) + - if_match=None → create-only put (first write) - if_match=etag → only write if current etag matches; raise CASConflictError otherwise Returns the new etag. """ @@ -745,16 +745,12 @@ trade-off is one hash computation per read and write, but for the file sizes jqu produces (kilobytes) this is negligible. **First-write semantics.** When the queue is brand new and no blob exists yet, the -adapter receives `if_match=None`. S3 and GCS handle this differently. S3 simply omits -the `IfMatch` header, making the first write unconditional — if two processes race to -create the blob, the last one wins silently. GCS uses `if_generation_match=0`, which is -a GCS convention meaning "only succeed if the object does not exist yet." This means -GCS's first write is itself conditional — a useful extra safety net against concurrent -initialisers, but it also means you can get a `CASConflictError` on the very first write -if two processes start simultaneously. +adapter receives `if_match=None`: create-only. S3 sends `IfNoneMatch: *`, GCS uses +`if_generation_match=0`. Two processes racing to create the blob can't overwrite each +other; the loser gets `CASConflictError` and retries. In practice this rarely matters because the retry loop handles it, but it's worth -understanding if you're debugging queue initialisation issues on GCS. +understanding if you're debugging queue initialisation issues. **Error classification.** The adapters distinguish three kinds of failures: `CASConflictError` (expected, retried automatically), `StorageError` (I/O problem with diff --git a/jqueue/adapters/storage/s3.py b/jqueue/adapters/storage/s3.py index ecbe2e5..35dd320 100644 --- a/jqueue/adapters/storage/s3.py +++ b/jqueue/adapters/storage/s3.py @@ -12,7 +12,9 @@ → CASConflictError First write (if_match=None): - IfMatch is omitted — unconditional put. + IfNoneMatch="*" — create-only put (PreconditionFailed if it exists). + +409 ConditionalRequestConflict is also mapped to CASConflictError. Compatible with S3-compatible storage that supports conditional writes: MinIO, Cloudflare R2, Tigris, etc. @@ -103,16 +105,19 @@ async def write( "Body": content, "ContentType": "application/json", } - if if_match is not None: + if if_match is None: + put_kwargs["IfNoneMatch"] = "*" + else: put_kwargs["IfMatch"] = if_match try: response = await s3.put_object(**put_kwargs) return str(response["ETag"]) except Exception as exc: - if _s3_error_code(exc) == "PreconditionFailed": + code = _s3_error_code(exc) + if code in _CAS_CONFLICT_CODES: raise CASConflictError( - "S3 ETag mismatch (PreconditionFailed)" + f"S3 conditional write failed ({code})" ) from exc raise except (CASConflictError, StorageError): @@ -121,6 +126,9 @@ async def write( raise StorageError("S3 write failed", exc) from exc +_CAS_CONFLICT_CODES = frozenset({"PreconditionFailed", "ConditionalRequestConflict"}) + + def _s3_error_code(exc: Exception) -> str: """Extract the error code from a botocore ClientError, or return ''.""" try: diff --git a/jqueue/ports/storage.py b/jqueue/ports/storage.py index f55e80e..aecfe32 100644 --- a/jqueue/ports/storage.py +++ b/jqueue/ports/storage.py @@ -8,7 +8,7 @@ CAS write contract ------------------ write(content, if_match=None) - - if if_match is None → unconditional put (used for the very first write) + - if if_match is None → create-only put (fails if the object exists) - if if_match is given → conditional put succeeds → storage returns the new etag (opaque str) fails → raises CASConflictError @@ -67,7 +67,7 @@ async def write( Parameters ---------- content : new object body - if_match : etag from the previous read(), or None for unconditional write + if_match : etag from the previous read(), or None to create the object Returns ------- @@ -75,7 +75,7 @@ async def write( Raises ------ - CASConflictError if if_match is provided but does not match the current etag + CASConflictError if the etag doesn't match (or, for None, the object exists) StorageError for any other I/O failure """ ... diff --git a/tests/test_storage_s3.py b/tests/test_storage_s3.py index 7820ef1..93b1758 100644 --- a/tests/test_storage_s3.py +++ b/tests/test_storage_s3.py @@ -1,8 +1,10 @@ +import asyncio from unittest.mock import AsyncMock, MagicMock import pytest from jqueue.adapters.storage.s3 import S3Storage, _s3_error_code +from jqueue.core.direct import DirectQueue from jqueue.domain.errors import CASConflictError, StorageError # --------------------------------------------------------------------------- @@ -96,7 +98,7 @@ async def test_read_generic_exception_raises_storage_error(): # --------------------------------------------------------------------------- -async def test_write_without_if_match_no_condition_header(): +async def test_write_without_if_match_is_create_only(): storage, s3 = _make_storage() s3.put_object.return_value = {"ETag": '"new-etag"'} @@ -104,6 +106,7 @@ async def test_write_without_if_match_no_condition_header(): assert etag == '"new-etag"' call_kwargs = s3.put_object.call_args.kwargs + assert call_kwargs["IfNoneMatch"] == "*" assert "IfMatch" not in call_kwargs @@ -116,6 +119,7 @@ async def test_write_with_if_match_sends_condition(): assert etag == '"new-etag"' call_kwargs = s3.put_object.call_args.kwargs assert call_kwargs["IfMatch"] == '"old-etag"' + assert "IfNoneMatch" not in call_kwargs async def test_write_sends_correct_bucket_and_key(): @@ -138,6 +142,33 @@ async def test_write_precondition_failed_raises_cas_conflict(): await storage.write(b"data", if_match='"etag"') +async def test_create_when_object_exists_raises_cas_conflict(): + storage, s3 = _make_storage() + s3.put_object.side_effect = _client_error("PreconditionFailed") + + with pytest.raises(CASConflictError): + await storage.write(b"data") + + +@pytest.mark.parametrize("if_match", [None, '"etag"']) +async def test_write_conditional_request_conflict_raises_cas_conflict( + if_match: str | None, +) -> None: + storage, s3 = _make_storage() + s3.put_object.side_effect = _client_error("ConditionalRequestConflict") + + with pytest.raises(CASConflictError): + await storage.write(b"data", if_match=if_match) + + +async def test_write_other_client_error_is_not_cas_conflict(): + storage, s3 = _make_storage() + s3.put_object.side_effect = _client_error("AccessDenied") + + with pytest.raises(StorageError): + await storage.write(b"data") + + async def test_write_other_error_raises_storage_error(): storage, s3 = _make_storage() s3.put_object.side_effect = RuntimeError("network failure") @@ -216,3 +247,67 @@ def test_s3_error_code_empty_code(): exc = Exception() exc.response = {"Error": {"Code": ""}} # type: ignore[attr-defined] assert _s3_error_code(exc) == "" + + +# --------------------------------------------------------------------------- +# Concurrent first write (conditional-write-aware fake S3) +# --------------------------------------------------------------------------- + + +class _FakeS3: + """Single-object S3 double that honours IfMatch / IfNoneMatch.""" + + def __init__(self) -> None: + self.body: bytes | None = None + self.etag: str | None = None + self._n = 0 + + async def get_object(self, **kwargs: object) -> dict[str, object]: + snapshot, etag = self.body, self.etag + # Yield after snapshotting so concurrent readers see the same state. + await asyncio.sleep(0) + if snapshot is None: + raise _client_error("NoSuchKey") + body = AsyncMock() + body.read.return_value = snapshot + return {"Body": body, "ETag": etag} + + async def put_object(self, **kwargs: object) -> dict[str, object]: + if kwargs.get("IfNoneMatch") == "*" and self.body is not None: + raise _client_error("PreconditionFailed") + if "IfMatch" in kwargs and kwargs["IfMatch"] != self.etag: + raise _client_error("PreconditionFailed") + self._n += 1 + self.body = kwargs["Body"] # type: ignore[assignment] + self.etag = f'"{self._n}"' + return {"ETag": self.etag} + + +def _fake_s3_storage(fake: _FakeS3) -> S3Storage: + session = MagicMock() + session.client.side_effect = lambda *a, **k: _AsyncCM(fake) + return S3Storage(bucket="b", key="k", session=session) + + +async def test_racing_first_writes_second_gets_cas_conflict(): + fake = _FakeS3() + a, b = _fake_s3_storage(fake), _fake_s3_storage(fake) + + assert await a.read() == (b"", None) + assert await b.read() == (b"", None) + + await a.write(b"first") + with pytest.raises(CASConflictError): + await b.write(b"second") + assert fake.body == b"first" + + +async def test_racing_first_enqueues_both_survive(): + fake = _FakeS3() + q1 = DirectQueue(_fake_s3_storage(fake)) + q2 = DirectQueue(_fake_s3_storage(fake)) + + j1, j2 = await asyncio.gather(q1.enqueue("t", b"1"), q2.enqueue("t", b"2")) + + state = await q1.read_state() + assert {j.id for j in state.jobs} == {j1.id, j2.id}