Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,21 @@ jobs:
env:
REDIS_URL: redis://localhost:6379/0
run: python -m pytest --cov=fastapi_cache --cov-branch --cov-report=xml
- name: Extend coverage for changed DynamoDB adapter
if: github.event_name == 'pull_request'
run: |
set -euo pipefail
# Preserve the original Redis-only suite and its coverage. The
# optional adapter needs its actual SDK installed before measuring
# its changed lines; do not exclude it from the coverage gate.
if git diff --name-only origin/stable...HEAD | grep -Fx 'fastapi_cache/backends/dynamodb.py' > /dev/null; then
python -m pip install -e ".[redis,dynamodb]"
python -m pip check
python -c "import aiobotocore; from fastapi_cache.backends.dynamodb import DynamoBackend"
python -m pytest --cov=fastapi_cache --cov-branch --cov-append --cov-report=xml \
tests/test_dynamodb_backend.py tests/test_dynamodb_transport.py \
tests/test_backend_contract_experimental.py -rs
fi
- name: Changed-line coverage
if: github.event_name == 'pull_request'
run: diff-cover coverage.xml --compare-branch=origin/stable --fail-under=100
Expand Down
1 change: 1 addition & 0 deletions changelog.d/45.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix experimental DynamoDB direct reads returning expired values, and preserve explicit nonpositive TTL as an expired entry rather than treating zero as persistent.
13 changes: 13 additions & 0 deletions docs/architecture/BACKEND_CONTRACT_C2.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,3 +89,16 @@ Redis Cluster, Sentinel, TLS, failover and all-provider parity remain
NOT RUN, outside C2. #45 and #102 remain separate; keep broad #111 open
until residual scope is independently dispositioned. #112 owns policy
changes; #53/#100 final privacy/performance and release gates remain.


## Development follow-up — #45 TTL correction (not published)

The proposed follow-up makes experimental DynamoDB direct `get()` use
the same single GetItem/expiry check as `get_with_ttl()`. Only None
persists; explicit zero/negative TTL is expired. Integer epoch seconds
avoid local wall-clock/DST arithmetic. Expired physical items may remain
until AWS TTL deletion; no client-side delete, no consistent-read or
transaction guarantee. Existing optional unit and loopback HTTP protocol
tests cover the change; the loopback server is not AWS or DynamoDB Local.
The adapter remains experimental, clear unsupported, lifecycle/close
still unresolved under #45. No changes to published C2 evidence.
32 changes: 11 additions & 21 deletions fastapi_cache/backends/dynamodb.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import datetime
import time
from typing import TYPE_CHECKING, Optional, Tuple

from aiobotocore.client import AioBaseClient
Expand All @@ -12,6 +12,10 @@
DynamoDBClient = AioBaseClient


def _now() -> int:
return int(time.time())


class DynamoBackend(Backend):
"""
Amazon DynamoDB backend provider
Expand Down Expand Up @@ -59,34 +63,20 @@ async def get_with_ttl(self, key: str) -> Tuple[int, Optional[bytes]]:
return -1, value

# It's only eventually consistent so we need to check ourselves
expire = int(ttl) - int(datetime.datetime.now().timestamp())
expire = int(ttl) - _now()
if expire > 0:
return expire, value

return 0, None

async def get(self, key: str) -> Optional[bytes]:
response = await self.client.get_item(TableName=self.table_name, Key={"key": {"S": key}})
if "Item" in response:
return response["Item"].get("value", {}).get("B")
return None
_, value = await self.get_with_ttl(key)
return value

async def set(self, key: str, value: bytes, expire: Optional[int] = None) -> None:
ttl = (
{
"ttl": {
"N": str(
int(
(
datetime.datetime.now() + datetime.timedelta(seconds=expire)
).timestamp()
)
)
}
}
if expire
else {}
)
# Only None is persistent. An explicit zero or negative TTL is
# already expired, even while DynamoDB retains the physical item.
ttl = {"ttl": {"N": str(_now() + expire)}} if expire is not None else {}

await self.client.put_item(
TableName=self.table_name,
Expand Down
4 changes: 2 additions & 2 deletions tests/test_backend_contract_experimental.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ async def verify() -> None:
assert profile.clear_key is profile.clear_namespace is Capability.UNSUPPORTED
assert profile.app_scope is Capability.UNSUPPORTED
assert profile.ownership == "experimental"
# Explicitly reproduce #45, do not mark this as supported behavior.
assert await backend.get("expired") == b"expired"
# Expired items are rejected by both reads; close remains experimental.
assert await backend.get("expired") is None
assert await backend.get_with_ttl("expired") == (0, None)
with pytest.raises(NotImplementedError):
await backend.clear(key="expired")
Expand Down
67 changes: 52 additions & 15 deletions tests/test_dynamodb_backend.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import asyncio
import datetime
from typing import Any, Dict, List, Optional, Tuple
import importlib
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple

import pytest

try:
if TYPE_CHECKING:
from fastapi_cache.backends.dynamodb import DynamoBackend
except ImportError:
DynamoBackend = None


class FakeDynamoClient:
Expand Down Expand Up @@ -36,8 +35,9 @@ async def put_item(

@pytest.fixture
def dynamodb_backend_cls() -> Any:
if DynamoBackend is None:
pytest.skip("aiobotocore is not installed")
pytest.importorskip("aiobotocore")
from fastapi_cache.backends.dynamodb import DynamoBackend

return DynamoBackend


Expand All @@ -53,12 +53,12 @@ def backend(client: FakeDynamoClient, dynamodb_backend_cls: Any) -> Any:
return instance


def test_get_miss_returns_none(backend: DynamoBackend) -> None:
def test_get_miss_returns_none(backend: "DynamoBackend") -> None:
assert asyncio.run(backend.get("app:missing")) is None


def test_set_writes_key_and_value_attributes(
backend: DynamoBackend, client: FakeDynamoClient
backend: "DynamoBackend", client: FakeDynamoClient
) -> None:
asyncio.run(backend.set("app:key", b"value"))

Expand All @@ -70,7 +70,7 @@ def test_set_writes_key_and_value_attributes(


def test_set_with_expire_writes_ttl_attribute(
backend: DynamoBackend, client: FakeDynamoClient
backend: "DynamoBackend", client: FakeDynamoClient
) -> None:
before = int(datetime.datetime.now().timestamp())
asyncio.run(backend.set("app:key", b"value", expire=60))
Expand All @@ -81,15 +81,15 @@ def test_set_with_expire_writes_ttl_attribute(
assert before + 60 <= ttl <= after + 60


def test_get_returns_stored_value(backend: DynamoBackend) -> None:
def test_get_returns_stored_value(backend: "DynamoBackend") -> None:
async def run() -> Optional[bytes]:
await backend.set("app:key", b"value", expire=60)
return await backend.get("app:key")

assert asyncio.run(run()) == b"value"


def test_get_with_ttl_returns_remaining_seconds(backend: DynamoBackend) -> None:
def test_get_with_ttl_returns_remaining_seconds(backend: "DynamoBackend") -> None:
async def run() -> Tuple[int, Optional[bytes]]:
await backend.set("app:key", b"value", expire=60)
return await backend.get_with_ttl("app:key")
Expand All @@ -101,7 +101,7 @@ async def run() -> Tuple[int, Optional[bytes]]:


def test_get_with_ttl_returns_minus_one_without_expire(
backend: DynamoBackend,
backend: "DynamoBackend",
) -> None:
async def run() -> Tuple[int, Optional[bytes]]:
await backend.set("app:key", b"value")
Expand All @@ -114,7 +114,7 @@ async def run() -> Tuple[int, Optional[bytes]]:


def test_get_with_ttl_treats_expired_entry_as_miss(
backend: DynamoBackend, client: FakeDynamoClient
backend: "DynamoBackend", client: FakeDynamoClient
) -> None:
client.items["app:key"] = {
"key": {"S": "app:key"},
Expand All @@ -129,15 +129,15 @@ def test_get_with_ttl_treats_expired_entry_as_miss(


def test_get_with_ttl_miss_returns_zero_and_none(
backend: DynamoBackend,
backend: "DynamoBackend",
) -> None:
ttl, value = asyncio.run(backend.get_with_ttl("app:missing"))

assert ttl == 0
assert value is None


def test_clear_is_not_implemented(backend: DynamoBackend) -> None:
def test_clear_is_not_implemented(backend: "DynamoBackend") -> None:
with pytest.raises(NotImplementedError):
asyncio.run(backend.clear())

Expand All @@ -146,3 +146,40 @@ def test_clear_is_not_implemented(backend: DynamoBackend) -> None:

with pytest.raises(NotImplementedError):
asyncio.run(backend.clear(key="app:key"))


@pytest.mark.parametrize("expire", [-1, 0, 1])
def test_direct_and_ttl_reads_agree_at_deadline(
backend: "DynamoBackend", client: FakeDynamoClient,
monkeypatch: pytest.MonkeyPatch, expire: int,
) -> None:
module = importlib.import_module("fastapi_cache.backends.dynamodb")
now = [1000]
monkeypatch.setattr(module, "_now", lambda: now[0])

async def verify() -> None:
await backend.set("key", b"", expire=expire)
assert client.items["key"]["ttl"] == {"N": str(1000 + expire)}
if expire > 0:
assert await backend.get("key") == b""
assert await backend.get_with_ttl("key") == (expire, b"")
now[0] += expire
assert await backend.get("key") is None
assert await backend.get_with_ttl("key") == (0, None)
# DynamoDB may retain the expired item; reads must still miss.
assert "key" in client.items
await backend.set("key", b"fresh", expire=None)
assert "ttl" not in client.items["key"]
assert await backend.get("key") == b"fresh"
assert await backend.get_with_ttl("key") == (-1, b"fresh")

asyncio.run(verify())


def test_direct_expired_read_does_not_delete_item(
backend: "DynamoBackend", client: FakeDynamoClient,
) -> None:
client.items["key"] = {"value": {"B": b"old"}, "ttl": {"N": "1"}}
assert asyncio.run(backend.get("key")) is None
assert "key" in client.items
assert [call[0] for call in client.calls] == ["get_item"]
7 changes: 7 additions & 0 deletions tests/test_dynamodb_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,13 @@ async def round_trip() -> None:
ttl, value = await backend.get_with_ttl("app:key")
assert ttl == -1
assert value == b"cached-value"
for expire in (0, -1):
await backend.set("app:expired", b"expired", expire=expire)
assert "app:expired" in server.items
assert await backend.get("app:expired") is None
assert await backend.get_with_ttl("app:expired") == (0, None)
await backend.set("app:expired", b"fresh")
assert await backend.get("app:expired") == b"fresh"
finally:
await backend.close()

Expand Down
Loading