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
9 changes: 8 additions & 1 deletion src/tests/amqp_imposter/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_my_client(seed: int) -> None:
The runs above each spawn their own imposter process, so they can be parallelised, for example using `pytest-xdist`.
If running serially, calling `imposter.configure(config)` will disconnect the client and prepare a new session on the same imposter process.

Optionally tune the behaviour of the imposter with weights and scripts.
Optionally tune the behaviour of the imposter with `weights` and `script`:

```py
from amqp_imposter.control.client import (
Expand All @@ -74,6 +74,12 @@ config = pb.SessionConfig(script=script, weights=weights, seed=seed)
```
<!-- fmt:on -->

Configure the handshake with `negotiation_options`.
The following capabilities are offered by default:
- `publisher_confirms`
- `basic.nack`
- `consumer_cancel_notify`

### Other languages

Run the imposter as a foreground process from a command line:
Expand Down Expand Up @@ -218,6 +224,7 @@ For example, in the imposter, publishing to an undeclared exchange will not dete

In practice, vhosts are shared resources and their topologies volatile.
All those states -- existence and non-existence, changed arguments, changed message counts, etc. -- need to be represented by the model, so it does not need to track past declarations and bindings.
For more detail, and notes on exclusive queues, see [model/docs/TOPOLOGY.md](amqp_imposter/model/docs/TOPOLOGY.md).

### Decision register

Expand Down
127 changes: 63 additions & 64 deletions src/tests/amqp_imposter/amqp_imposter/amqp/method_framing.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

import calendar
import struct
from collections.abc import Callable, Mapping
from collections.abc import Callable, Iterator
from dataclasses import dataclass
from datetime import UTC, datetime
from decimal import Decimal
Expand All @@ -34,11 +34,6 @@
PROTOCOL_HEADER_091 = b"AMQP\x00\x00\x09\x01"
AMQP_TUPLE_DELIMITER = " "

CAPABILITIES = "capabilities"
PUBLISHER_CONFIRMS = "publisher_confirms"
BASIC_NACK = "basic.nack"
CONSUMER_CANCEL_NOTIFY = "consumer_cancel_notify"


@dataclass(frozen=True, slots=True)
class ProtocolHeader:
Expand Down Expand Up @@ -142,14 +137,6 @@ def from_amqp_tuple(value: str | bytes | None) -> tuple[str, ...]:
return tuple(text.split(AMQP_TUPLE_DELIMITER)) if text else ()


def capabilities_of(spec: Any) -> Mapping[str, Any]:
match (spec.server_properties or {}).get(CAPABILITIES):
case Mapping() as capabilities:
return capabilities
case _:
return {}


def to_pika_properties(properties: mf.MessageProperties) -> ps.BasicProperties:
return ps.BasicProperties(
content_type=properties.content_type,
Expand Down Expand Up @@ -203,24 +190,19 @@ def to_pika(method: m.Method) -> Any:
return ps.Connection.Start(
version_major=mf.assert_concrete(method.version_major),
version_minor=mf.assert_concrete(method.version_minor),
server_properties={
CAPABILITIES: {
PUBLISHER_CONFIRMS: mf.assert_concrete(
method.publisher_confirms
),
BASIC_NACK: mf.assert_concrete(method.basic_nack),
CONSUMER_CANCEL_NOTIFY: mf.assert_concrete(
method.consumer_cancel_notify
),
}
},
server_properties=to_pika_value(
mf.assert_concrete(method.server_properties)
),
mechanisms=AMQP_TUPLE_DELIMITER.join(
mf.assert_concrete(method.mechanisms)
),
locales=AMQP_TUPLE_DELIMITER.join(mf.assert_concrete(method.locales)),
)
case m.ConnectionStartOk():
return ps.Connection.StartOk(
client_properties=to_pika_value(
mf.assert_concrete(method.client_properties)
),
mechanism=mf.assert_concrete(method.mechanism),
locale=mf.assert_concrete(method.locale),
response=mf.assert_concrete(method.response),
Expand Down Expand Up @@ -413,21 +395,16 @@ def from_pika(
) -> m.Method | None:
match spec:
case ps.Connection.Start():
capabilities = capabilities_of(spec)

return m.ConnectionStart(
version_major=d.Octet(spec.version_major),
version_minor=d.Octet(spec.version_minor),
server_properties=from_pika_value(spec.server_properties or {}),
mechanisms=from_amqp_tuple(spec.mechanisms),
locales=from_amqp_tuple(spec.locales),
publisher_confirms=bool(capabilities.get(PUBLISHER_CONFIRMS, False)),
basic_nack=bool(capabilities.get(BASIC_NACK, False)),
consumer_cancel_notify=bool(
capabilities.get(CONSUMER_CANCEL_NOTIFY, False)
),
)
case ps.Connection.StartOk():
return m.ConnectionStartOk(
client_properties=from_pika_value(spec.client_properties or {}),
mechanism=d.ShortStr(spec.mechanism),
locale=d.ShortStr(spec.locale),
response=to_text(spec.response),
Expand Down Expand Up @@ -630,23 +607,23 @@ def encode(egress: Egress, frame_max: int) -> bytes:

case MethodOnChannel(channel, partial_method):
method, _ = mu.concretise(partial_method, DEFAULT_GEN_STATE)
encoded = cast(bytes, pf.Method(channel, to_pika(method)).marshal())
frames = cast(bytes, pf.Method(channel, to_pika(method)).marshal())

if not is_content_method(method):
return encoded
return frames

body = mf.assert_concrete(method.body)
properties = to_pika_properties(mf.assert_concrete(method.properties))

encoded += cast(bytes, pf.Header(channel, len(body), properties).marshal())
limit = frame_max - ps.FRAME_HEADER_SIZE - ps.FRAME_END_SIZE
frames += cast(bytes, pf.Header(channel, len(body), properties).marshal())
limit = (frame_max or d.Long.MAX) - ps.FRAME_HEADER_SIZE - ps.FRAME_END_SIZE

for start in range(0, len(body), limit):
encoded += cast(
frames += cast(
bytes, pf.Body(channel, body[start : start + limit]).marshal()
)

return encoded
return frames


def validate_buffer_length(buffer: bytes, max_buffer: int) -> Undecodable | None:
Expand All @@ -655,29 +632,48 @@ def validate_buffer_length(buffer: bytes, max_buffer: int) -> Undecodable | None
return None


def decode_pika_frame(buffer: bytes) -> tuple[int, Any]:
def validate_frame_size(buffer: bytes, frame_max: int) -> InvalidFrameError | None:
if (
frame_max == 0
or len(buffer) < ps.FRAME_HEADER_SIZE
or buffer.startswith(b"AMQP")
):
return None

_, _, payload_size = struct.unpack_from(">BHI", buffer)
frame_size = ps.FRAME_HEADER_SIZE + payload_size + ps.FRAME_END_SIZE

if frame_size > frame_max:
return InvalidFrameError(f"frame of {frame_size} bytes exceeds {frame_max}")
return None


def decode_pika_frame(buffer: bytes, frame_max: int) -> tuple[int, Any]:
if (oversized := validate_frame_size(buffer, frame_max)) is not None:
raise oversized

try:
return cast(tuple[int, Any], pf.decode_frame(buffer))
except (KeyError, struct.error) as bad:
raise InvalidFrameError(f"undecodable frame: {bad!r}") from bad


def decode_content_method(
buffer: bytes, offset: int, frame: Any, max_buffer: int
buffer: bytes, offset: int, frame: Any, frame_max: int, max_buffer: int
) -> tuple[Ingress | None, int]:
consumed, header = decode_pika_frame(buffer[offset:])
len_consumed, header = decode_pika_frame(buffer[offset:], frame_max)

if header is None:
return validate_buffer_length(buffer, max_buffer), len(buffer)

if not isinstance(header, pf.Header):
return Undecodable("expected a content header"), len(buffer)

offset += consumed
offset += len_consumed
body = b""

while len(body) < header.body_size:
consumed, fragment = decode_pika_frame(buffer[offset:])
len_consumed, fragment = decode_pika_frame(buffer[offset:], frame_max)

if fragment is None:
return validate_buffer_length(buffer, max_buffer), len(buffer)
Expand All @@ -686,7 +682,7 @@ def decode_content_method(
return Undecodable("expected a content body"), len(buffer)

body += fragment.fragment
offset += consumed
offset += len_consumed

return decoded(frame, from_pika(frame.method, header.properties, body), offset)

Expand All @@ -699,27 +695,29 @@ def decoded(frame: Any, method: m.Method | None, offset: int) -> tuple[Ingress,


def decode_method(
buffer: bytes, offset: int, frame: Any, max_buffer: int
buffer: bytes, offset: int, frame: Any, frame_max: int, max_buffer: int
) -> tuple[Ingress | None, int]:
if is_pika_content_method(frame.method):
return decode_content_method(buffer, offset, frame, max_buffer)
return decode_content_method(buffer, offset, frame, frame_max, max_buffer)

return decoded(frame, from_pika(frame.method), offset)


def decode_one(buffer: bytes, max_buffer: int) -> tuple[Ingress | None, int]:
def decode_one(
buffer: bytes, frame_max: int, max_buffer: int
) -> tuple[Ingress | None, int]:
try:
consumed, frame = decode_pika_frame(buffer)
len_consumed, frame = decode_pika_frame(buffer, frame_max)

match frame:
case None:
return validate_buffer_length(buffer, max_buffer), len(buffer)
case pf.ProtocolHeader():
return ProtocolHeader(buffer[:consumed]), consumed
return ProtocolHeader(buffer[:len_consumed]), len_consumed
case pf.Heartbeat():
return Heartbeat(), consumed
return Heartbeat(), len_consumed
case pf.Method():
return decode_method(buffer, consumed, frame, max_buffer)
return decode_method(buffer, len_consumed, frame, frame_max, max_buffer)
case _:
reason = f"unexpected frame: {type(frame).__name__}"
return Undecodable(reason), len(buffer)
Expand All @@ -728,17 +726,18 @@ def decode_one(buffer: bytes, max_buffer: int) -> tuple[Ingress | None, int]:
return Undecodable(str(bad)), len(buffer)


def decode(buffer: bytes, max_buffer: int) -> tuple[tuple[Ingress, ...], bytes]:
items: list[Ingress] = []
rest = buffer
def decode_many(
buffer: bytes, frame_max: Callable[[], int], max_buffer: int
) -> Iterator[tuple[Ingress, bytes]]:
while True:
item, len_consumed = decode_one(buffer, frame_max(), max_buffer)

while rest:
item, consumed = decode_one(rest, max_buffer)

if item is None:
return tuple(items), rest

items.append(item)
rest = b"" if isinstance(item, Undecodable) else rest[consumed:]

return tuple(items), rest
match item:
case None:
return
case Undecodable():
yield item, b""
return
case _:
buffer = buffer[len_consumed:]
yield item, buffer
55 changes: 42 additions & 13 deletions src/tests/amqp_imposter/amqp_imposter/amqp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
# limitations under the License.

import asyncio
import math
from collections.abc import AsyncGenerator
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass, field
Expand All @@ -25,6 +26,20 @@
READ_BYTES = 64 * 1024


def server_heartbeat_period_s(heartbeat_interval_s: int) -> float:
if heartbeat_interval_s == 0:
return math.inf

return heartbeat_interval_s / 2


def client_heartbeat_timeout_s(heartbeat_interval_s: int) -> float:
if heartbeat_interval_s == 0:
return math.inf

return heartbeat_interval_s * 2


@dataclass(slots=True)
class AmqpServer:
session: Session
Expand Down Expand Up @@ -91,13 +106,10 @@ async def do_actions(
return False

async def timebound_read(
self, reader: asyncio.StreamReader, time_s: float
self, reader: asyncio.StreamReader, deadline: float
) -> bytes | None:
if time_s <= 0.0:
return None

try:
async with asyncio.timeout(time_s):
async with asyncio.timeout_at(deadline):
return await reader.read(READ_BYTES)
except TimeoutError:
return None
Expand All @@ -108,27 +120,44 @@ async def loop(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
loop = asyncio.get_running_loop()
idle = self.session.config.idle_millis / 1_000.0
deadline = loop.time() + idle

idle_s = self.session.config.idle_millis / 1_000.0

t_idle_last = loop.time()
t_hearts_last = loop.time()
t_ingress_last = loop.time()

while True:
match await self.timebound_read(reader, deadline - loop.time()):
heart_s = self.session.effective_tunables().heartbeat

t_idle_next = t_idle_last + idle_s
t_hearts_next = t_hearts_last + server_heartbeat_period_s(heart_s)
t_heartc_next = t_ingress_last + client_heartbeat_timeout_s(heart_s)

deadline = min(t_idle_next, t_hearts_next, t_heartc_next)

match await self.timebound_read(reader, deadline):
case None if deadline == t_heartc_next:
actions = self.session.on_client_heartbeat_deadline()
case None if deadline == t_hearts_next:
t_hearts_last = loop.time()
actions = self.session.on_server_heartbeat_deadline()
case None:
t_idle_last = loop.time()
actions = self.session.on_idle()
refreshed = True
case b"": # EOF
return
case chunk:
t_ingress_last = loop.time()
before = self.session.total_ingress_methods
actions = self.session.on_ingress(chunk)
refreshed = self.session.total_ingress_methods > before

if self.session.total_ingress_methods > before:
t_idle_last = t_ingress_last

if await self.do_actions(actions, writer):
return

if refreshed:
deadline = loop.time() + idle

async def serve(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
Expand Down
Loading
Loading