Skip to content
Open
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
4 changes: 4 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ Unreleased
- Open new connections on demand up to ``pool_size`` when ``pool_minsize`` is
smaller. Before, once ``pool_minsize`` connections were open, a command that
found them all busy waited for one instead of opening another.
- Send ``exptime``, flags, the cas token and the ``incr()``/``decr()`` delta in
decimal, so an ``IntEnum`` or ``IntFlag`` is sent as its value instead of
its ``repr()``. A ``float`` cas token, flags or delta now raises
``ValidationException`` instead of being truncated.

0.8.2 (2024-05-07)
==================
Expand Down
19 changes: 14 additions & 5 deletions aiomcache/client.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import asyncio
import contextlib
import datetime
import operator
import re
import time
import warnings
Expand All @@ -21,6 +22,14 @@
_SetFlagHandler = Callable[[_T], Awaitable[tuple[bytes, int]]]


def _int(value: int) -> int:
"""Return value as an int, rejecting floats (IntEnum and IntFlag are accepted)."""
try:
return operator.index(value)
except TypeError:
raise ValidationException("not int", value) from None


class FlagClient(Generic[_T]):
__slots__ = ("__weakref__", "_pool", "_get_flag_handler", "_set_flag_handler", "_timeout")

Expand Down Expand Up @@ -359,11 +368,11 @@ async def _storage_command(self, command: bytes, key: bytes,
if self._set_flag_handler is None:
raise ValidationException("flag handler must be set for non-byte values")
value, flags = await self._set_flag_handler(value)
cas_value = b" %a" % cas if cas else b""
cas_value = b" %d" % _int(cas) if cas else b""
# Only the header is built here; the value is written once a
# connection is held, so waiting calls don't keep a copy of it.
header = b"%b %b %a %a %a%b\r\n" % (
command, key, flags, exptime, len(value), cas_value
header = b"%b %b %d %d %d%b\r\n" % (
command, key, _int(flags), exptime, len(value), cas_value
)
async with self._execute_simple_command(header, value, b"\r\n") as resp:
if resp not in (const.STORED, const.NOT_STORED, const.EXISTS, const.NOT_FOUND):
Expand Down Expand Up @@ -460,7 +469,7 @@ async def prepend(self, key: bytes, value: bytes, exptime: int = 0) -> bool:
async def _incr_decr(
self, command: bytes, key: bytes, delta: int
) -> int | None:
cmd = b"%b %b %a\r\n" % (command, key, delta)
cmd = b"%b %b %d\r\n" % (command, key, _int(delta))
async with self._execute_simple_command(cmd) as resp:
if resp == const.NOT_FOUND:
return None
Expand Down Expand Up @@ -514,7 +523,7 @@ async def touch(self, key: bytes, exptime: int | datetime.datetime) -> bool:
self._validate_key(key)
exptime = self._validate_exptime(exptime)

cmd = b"touch %b %a\r\n" % (key, exptime)
cmd = b"touch %b %d\r\n" % (key, exptime)
async with self._execute_simple_command(cmd) as resp:
if resp not in (const.TOUCHED, const.NOT_FOUND):
raise ClientException("Memcached touch failed", resp)
Expand Down
38 changes: 38 additions & 0 deletions tests/commands_test.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import datetime
import enum
import time
from collections.abc import Awaitable, Callable, Iterator
from typing import Any
Expand Down Expand Up @@ -778,3 +779,40 @@ async def test_exptime_timestamp_deprecated(mcache: Client, command: str) -> Non
# The warning must point to the caller of the command.
assert [w.filename for w in warned] == [__file__]
assert await mcache.get(key) == b"value"


class _TTL(enum.IntEnum):
HOUR = 3600


class _Flags(enum.IntFlag):
PICKLE = 1


async def test_int_enum_arguments(mcache: Client) -> None:
key = b"key:int_enum"
assert await mcache.set(key, b"1", exptime=_TTL.HOUR)
assert await mcache.touch(key, _TTL.HOUR)
assert await mcache.incr(key, _TTL.HOUR) == 3601
_, cas_token = await mcache.gets(key)
CasToken = enum.IntEnum("CasToken", {"TOKEN": cas_token})
assert await mcache.cas(key, b"2", CasToken.TOKEN)


async def test_int_flag_from_flag_handler(mcache_params: McacheParams) -> None:
async def set_handler(value: str) -> tuple[bytes, int]:
return value.encode(), _Flags.PICKLE

client = FlagClient[str](set_flag_handler=set_handler, **mcache_params)
try:
assert await client.set(b"key:int_flag", "value")
finally:
await client.close()


async def test_float_numbers_rejected(mcache: Client) -> None:
await mcache.set(b"key:float", b"1")
with pytest.raises(ValidationException):
await mcache.incr(b"key:float", 2.5) # type: ignore[arg-type]
with pytest.raises(ValidationException):
await mcache.cas(b"key:float", b"2", 1.5) # type: ignore[arg-type]
Loading