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 @@ -6,6 +6,10 @@ CHANGES

Unreleased
==========
- Add ``multi_set()`` to store several items, pipelined on one connection. It
raises ``ClientException`` if any item is not stored; when memcached rejects
only some (e.g. too large), the exception maps each rejected key to the
server's reply.
- Drop what an interrupted command still had buffered when its connection is
discarded, instead of sending it. memcached could carry out a ``set()`` after
the caller got ``TimeoutError``.
Expand Down
1 change: 1 addition & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ The API looks very similar to the other memcache clients:
await mc.set(b"some_key", b"Some value")
value = await mc.get(b"some_key")
print(value)
await mc.multi_set({b"other_key": b"Other value", b"third_key": b"Third value"})
values = await mc.multi_get(b"some_key", b"other_key")
print(values)
await mc.delete(b"another_key")
Expand Down
94 changes: 94 additions & 0 deletions aiomcache/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@
_GetFlagHandler = Callable[[bytes, int], Awaitable[_T]]
_SetFlagHandler = Callable[[_T], Awaitable[tuple[bytes, int]]]

# multi_set() writes its commands in batches of at most this many items or
# about this many bytes, whichever comes first.
_MULTI_SET_BATCH_SIZE = 1000
_MULTI_SET_BATCH_BYTES = 1024 * 1024


class FlagClient(Generic[_T]):
__slots__ = ("__weakref__", "_pool", "_get_flag_handler", "_set_flag_handler", "_timeout")
Expand Down Expand Up @@ -385,6 +390,95 @@ async def set(self, key: bytes, value: bytes | _T,
exptime = self._validate_exptime(exptime)
return await self._storage_command(b"set", key, value, exptime)

async def multi_set(self, mapping: Mapping[bytes, bytes | _T],
exptime: int | datetime.datetime = 0) -> None:
"""Set several keys to values on the server.

The commands are pipelined on one connection. The client's
``timeout`` covers waiting for a connection and sending every batch,
but not the flag handler, which runs for every item first; its results
are kept until the call ends. After a timeout or cancellation, some
items may still have been stored.

:param mapping: ``Mapping`` of ``bytes`` keys to the data to store.
:param exptime: ``int``, is the number of seconds until the items
expire. If it's 0, the items never expire. A timezone-aware
``datetime`` is the time at which the items expire.
:raises: ``ValidationException`` before anything is sent.
``ClientException`` if any item was not stored. If memcached
rejected only some items (e.g. too large), its second argument maps
each rejected key to the reply and every other item was stored;
otherwise it is the unexpected reply, and any item may not have been
stored.
"""
exptime = self._validate_exptime(exptime)
# A copy, so a flag handler changing the mapping can't break the loop.
items = list(mapping.items())
if not items:
return

# Each batch is the keys and the chunks of their commands.
batches: list[tuple[list[bytes], list[bytes]]] = []
batch_bytes = 0
for key, value in items:
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
self._validate_key(key)
flags = 0
if not isinstance(value, 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)
if (not batches or len(batches[-1][0]) >= _MULTI_SET_BATCH_SIZE
or batch_bytes >= _MULTI_SET_BATCH_BYTES):
batches.append(([], []))
batch_bytes = 0
keys, chunks = batches[-1]
keys.append(key)
header = b"set %b %a %a %a\r\n" % (key, flags, exptime, len(value))
chunks.extend((header, value, b"\r\n"))
Comment on lines +435 to +437

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

multi_get() is just one command, right? I had assumed from the feature request that memcached had another command for doing multiple sets in the same fashion.

If the only thing this is gaining is pipelining a sequence of sets I'm a little more skeptical on its utility (I'd expect the performance to not be that much better than just doing asyncio.gather() on a sequence of set() requests). If we really want this, maybe there's a way to make pipelining a general purpose solution that can be used with any method?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Dreamsorcerer Right, there's no multi-set command; get takes several keys but set doesn't, so it's only pipelining. It makes a big difference though, as gather() pays a round trip per item across pool_size connections. Against local memcached (default pool_size=2):

Items gather(set) multi_set
100 × 100 B 54 ms 1.8 ms
1,000 × 100 B 209 ms 3.7 ms
10,000 × 100 B 1,367 ms 33 ms
1,000 × 10 KB 114 ms 28 ms

With pool_size=10 it's still 3–21× faster, and over a real network the gap would be wider. A general pipeline API would be nice, but it's a bigger change: each command's reply parsing would need splitting from sending it. I'm happy to try that if you'd prefer it over multi_set(), or as a follow-up.

batch_bytes += len(header) + len(value) + 2

rejected: dict[bytes, bytes] = {}
async with self._connection() as conn:
# Write each batch, then read the replies to the one before it,
# so the server always has commands to work on. Writing never
# waits (there is no drain()), so it can't block on memcached,
# which stops reading while its replies back up. Keeping only
# about two batches buffered bounds memory, and the time asyncio
# spends per write on the number of chunks buffered.
sent: list[bytes] = []
for keys, chunks in batches:
conn.writer.writelines(chunks)
await self._read_multi_set_replies(conn, sent, rejected)
sent = keys
await self._read_multi_set_replies(conn, sent, rejected)

# Every reply was read, so the connection was kept.
if rejected:
raise ClientException("Memcached multi_set failed for some keys", rejected)

async def _read_multi_set_replies(self, conn: Connection, keys: list[bytes],
rejected: dict[bytes, bytes]) -> None:
"""Read the replies to the set commands for keys, in order.

Add each key memcached rejected to rejected, with its reply.
"""
for key in keys:
line = await conn.reader.readline()
if not line.endswith(b"\r\n"):
raise ClientException(
"Connection closed by the server before receiving a full response",
)
reply = line[:-2]
if reply == const.STORED:
continue
# memcached skips the data block of an item it rejects, so the
# replies still line up with the commands.
if reply.startswith(b"SERVER_ERROR "):
rejected[key] = reply
else:
# The stream can't be trusted, so the connection is discarded.
raise ClientException("Memcached multi_set failed", reply)

async def cas(self, key: bytes, value: bytes | _T, cas_token: int,
exptime: int | datetime.datetime = 0) -> bool:
"""Sets a key to a value on the server
Expand Down
1 change: 1 addition & 0 deletions examples/simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ async def hello_aiomcache() -> None:
await mc.set(b"some_key", b"Some value")
value = await mc.get(b"some_key")
print(value)
await mc.multi_set({b"other_key": b"Other value", b"third_key": b"Third value"})
values = await mc.multi_get(b"some_key", b"other_key")
print(values)
await mc.delete(b"another_key")
Expand Down
14 changes: 14 additions & 0 deletions tests/commands_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,7 @@ async def test_client_unix_socket_set_get(
"gets": lambda mc, k: mc.gets(k),
"multi_get": lambda mc, k: mc.multi_get(b"key:other", k),
"set": lambda mc, k: mc.set(k, b"v"),
"multi_set": lambda mc, k: mc.multi_set({b"key:other": b"v", k: b"v"}),
"add": lambda mc, k: mc.add(k, b"v"),
"replace": lambda mc, k: mc.replace(k, b"v"),
"append": lambda mc, k: mc.append(k, b"v"),
Expand Down Expand Up @@ -505,6 +506,7 @@ async def test_key_of_250_bytes(mcache: Client, key: bytes) -> None:
"gets": lambda mc: mc.gets(b"bad key"),
"multi_get": lambda mc: mc.multi_get(b"key:other", b"bad key"),
"set": lambda mc: mc.set(b"bad key", b"v"),
"multi_set": lambda mc: mc.multi_set({b"key:other": b"v", b"bad key": b"v"}),
"add": lambda mc: mc.add(b"bad key", b"v"),
"replace": lambda mc: mc.replace(b"bad key", b"v"),
"append": lambda mc: mc.append(b"bad key", b"v"),
Expand All @@ -518,6 +520,10 @@ async def test_key_of_250_bytes(mcache: Client, key: bytes) -> None:
"set-negative-exptime": lambda mc: mc.set(b"key", b"v", exptime=-1),
"set-float-exptime": lambda mc: mc.set(b"key", b"v", exptime=1.5), # type: ignore[arg-type]
"set-no-flag-handler": lambda mc: mc.set(b"key", object()), # type: ignore[arg-type]
"multi_set-negative-exptime": lambda mc: mc.multi_set({b"key": b"v"}, exptime=-1),
"multi_set-empty-negative-exptime": lambda mc: mc.multi_set({}, exptime=-1),
"multi_set-no-flag-handler": lambda mc: mc.multi_set(
{b"key:other": b"v", b"key": object()}), # type: ignore[dict-item]
}


Expand Down Expand Up @@ -730,6 +736,11 @@ async def _cas(mc: Client, key: bytes, exptime: int | datetime.datetime) -> bool
return await mc.cas(key, b"value", cas_token, exptime)


async def _multi_set(mc: Client, key: bytes, exptime: int | datetime.datetime) -> bool:
await mc.multi_set({key: b"value"}, exptime)
return True


async def _touch(mc: Client, key: bytes, exptime: int | datetime.datetime) -> bool:
await mc.set(key, b"value")
return await mc.touch(key, exptime)
Expand All @@ -742,6 +753,7 @@ async def _touch(mc: Client, key: bytes, exptime: int | datetime.datetime) -> bo
"add": _add,
"replace": _replace,
"cas": _cas,
"multi_set": _multi_set,
"touch": _touch,
}

Expand All @@ -767,6 +779,8 @@ async def test_exptime_past_datetime(mcache: Client, exptime: datetime.datetime)
key = b"key:exptime:past"
assert await mcache.set(key, b"value", exptime) is True
assert await mcache.get(key) is None
await mcache.multi_set({key: b"value"}, exptime)
assert await mcache.get(key) is None


@pytest.mark.parametrize("command", EXPTIME_COMMANDS)
Expand Down
172 changes: 172 additions & 0 deletions tests/multi_set_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
import asyncio
import datetime
from collections.abc import AsyncIterator
from typing import Any
from unittest import mock

import pytest

from aiomcache import Client, FlagClient
from aiomcache.client import _MULTI_SET_BATCH_BYTES
from aiomcache.exceptions import ClientException
from aiomcache.pool import MemcachePool
from .conftest import McacheParams, McacheUnixParams
from .flag_helper import FlagHelperDemo


@pytest.fixture(params=("tcp", "unix"))
async def any_client(request: pytest.FixtureRequest, mcache_params: McacheParams,
mcache_unix_params: McacheUnixParams) -> AsyncIterator[Client]:
if request.param == "tcp":
client = Client(**mcache_params)
else:
client = Client(path=mcache_unix_params["path"])
yield client
await client.close()


async def test_multi_set(any_client: Client) -> None:
await any_client.set(b"key:ms:2", b"old")
items = {b"key:ms:1": b"1", b"key:ms:2": b"", "中文".encode(): b"3" * 1000}
assert await any_client.multi_set(items) is None # type: ignore[func-returns-value]
assert await any_client.multi_get(*items) == tuple(items.values())


async def test_multi_set_empty(mcache: Client) -> None:
with mock.patch.object(MemcachePool, "acquire",
side_effect=AssertionError("connection acquired")):
await mcache.multi_set({})


async def test_multi_set_flag_handler(
mcache_flag_client: FlagClient[Any], demo_flag_helper: FlagHelperDemo
) -> None:
items: dict[bytes, Any] = {
b"key:ms:date": datetime.date(2015, 12, 28),
b"key:ms:bytes": b"bytes",
b"key:ms:list": [1, 2, 3],
}
set_count = demo_flag_helper.set_invocation_count
await mcache_flag_client.multi_set(items)
# Only non-bytes values go through the handler.
assert demo_flag_helper.set_invocation_count == set_count + 2
assert await mcache_flag_client.multi_get(*items) == tuple(items.values())


async def test_multi_set_rejected_items(mcache_params: McacheParams) -> None:
# memcached rejects an item too large, skips its data and carries on, so
# every reply is read, the rest are stored and the connection is kept.
client = Client(pool_size=1, **mcache_params)
try:
await client.set(b"key:ms:big", b"old")
conn = await client._pool.acquire()
client._pool.release(conn)
items = {b"key:ms:before": b"1", b"key:ms:big": b"x" * 2 * 1024 * 1024,
b"key:ms:after": b"2"}
with pytest.raises(ClientException) as excinfo:
await client.multi_set(items)
assert excinfo.value.args == (
"Memcached multi_set failed for some keys",
{b"key:ms:big": b"SERVER_ERROR object too large for cache"})
# memcached removes the old item rather than leave it stale.
assert await client.multi_get(*items) == (b"1", None, b"2")
reacquired = await client._pool.acquire()
client._pool.release(reacquired)
assert reacquired is conn
finally:
await client.close()


@pytest.mark.parametrize("n", (1000, 2001))
async def test_multi_set_reads_every_reply(mcache_params: McacheParams, n: int) -> None:
# A reply left unread would be taken as the reply to the next command.
client = Client(pool_size=1, **mcache_params)
try:
items = {b"key:ms:r%d" % i: b"%d" % i for i in range(n)}
await client.multi_set(items)
assert await client.delete(b"key:ms:r0") is True
assert await client.multi_get(*items) == (None, *list(items.values())[1:])
finally:
await client.close()


async def test_multi_set_many_keys(any_client: Client) -> None:
# memcached stops reading while its replies back up, so waiting for the
# commands to be sent before reading the replies would hang.
items = {b"key:ms:many%d" % i: b"%d" % i for i in range(100_000)}
async with asyncio.timeout(30):
await any_client.multi_set(items)
sample = list(items)[::997]
assert await any_client.multi_get(*sample) == tuple(items[k] for k in sample)


async def test_multi_set_bounds_buffered_bytes(any_client: Client) -> None:
# Large values are sent a batch at a time, so only about two batches
# are ever buffered, not the whole call.
value_size = 300_000
items = {b"key:ms:large%d" % i: bytes([65 + i % 26]) * value_size for i in range(30)}
buffered = []
writelines = asyncio.StreamWriter.writelines

def spy(self: asyncio.StreamWriter, data: Any) -> None:
writelines(self, data)
buffered.append(self.transport.get_write_buffer_size())

with mock.patch.object(asyncio.StreamWriter, "writelines", spy):
async with asyncio.timeout(30):
await any_client.multi_set(items)
assert max(buffered) <= 2 * (_MULTI_SET_BATCH_BYTES + value_size)
assert await any_client.multi_get(*items) == tuple(items.values())


async def _serve(replies: bytes) -> tuple[asyncio.Server, list[int]]:
"""Send replies to the first three sets, closing if they end mid-line,
then answer version."""
connections = [0]

async def handler(reader: asyncio.StreamReader,
writer: asyncio.StreamWriter) -> None:
connections[0] += 1
if connections[0] == 1:
for _ in range(6): # Three commands and their data blocks.
await reader.readline()
writer.write(replies)
if not replies.endswith(b"\r\n"):
await writer.drain()
writer.close()
return
while await reader.readline():
writer.write(b"VERSION 1.2.3\r\n")
writer.close()

return await asyncio.start_server(handler, "127.0.0.1", 0), connections


@pytest.mark.parametrize(("replies", "error"), (
(b"STORED\r\nERROR\r\nSTORED\r\n", ("Memcached multi_set failed", b"ERROR")),
(b"STORED\r\nCLIENT_ERROR bad data chunk\r\nSTORED\r\n",
("Memcached multi_set failed", b"CLIENT_ERROR bad data chunk")),
# Earlier rejected items are not reported, as the stream can't be trusted.
(b"SERVER_ERROR out of memory\r\nCLIENT_ERROR bad data chunk\r\n",
("Memcached multi_set failed", b"CLIENT_ERROR bad data chunk")),
(b"STORED\r\nSTO",
("Connection closed by the server before receiving a full response", None)),
), ids=("ERROR", "CLIENT_ERROR", "after-rejected", "closed"))
async def test_multi_set_unexpected_reply_discards_connection(
replies: bytes, error: tuple[object, ...]
) -> None:
server, connections = await _serve(replies)
port = server.sockets[0].getsockname()[1]
client = Client("127.0.0.1", port, pool_size=1)
try:
with pytest.raises(ClientException) as excinfo:
async with asyncio.timeout(5):
await client.multi_set({b"key:1": b"1", b"key:2": b"2", b"key:3": b"3"})
assert excinfo.value.args == error
# The next command gets its own reply, on a new connection.
assert await client.version() == b"1.2.3"
assert connections[0] == 2
finally:
await client.close()
server.close()
await server.wait_closed()
Loading