Skip to content

Ministack: Free, open-source local AWS emulator - 60+ services, Terraform compatible, real databases. Free forever. MIT licensed.

fix(iot): keep unacknowledged QoS 1 messages across a session resume (#2259)

iot-rocket2b73e547ad62
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e39aa5ef..c3df1190 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Versioning follows [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed
+- **IoT — unacknowledged QoS 1 messages survive a persistent session reconnect** — a QoS 1 message the subscriber had not acknowledged was dropped when its persistent session disconnected; the session now keeps it with its packet identifier, and the resumed connection sends it again once its retransmit interval has passed (at once when it passed while the client was offline, ahead of the messages queued meanwhile), continuing the session's packet identifiers. Contributed by @iot-rocket.
- **IoT — job documents nested too deep** — `CreateJob` and `CreateJobTemplate` accepted an inline document that is not JSON, and a document nested deeper than Python's JSON parser goes answered 500 (from `documentSource`, or inline once it headed a thing's queue, after which every later `CreateJob` for that thing answered 500 too); they now refuse a document that is not JSON or nests more than 1000 levels deep with AWS's `InvalidRequestException`, and a device gets a 1000-level document compact. Contributed by @iot-rocket.
- **IoT — job execution versions, `statusDetails`, execution numbers and timeouts** — `UpdateJobExecution` answered a stale `expectedVersion` with 409 `InvalidStateTransitionException` and now answers 400 `InvalidRequestException` (`VersionMismatch` over MQTT, as before); an execution has no `statusDetails` until a device reports some, and a reported empty map replaces the previous one; the MQTT `get` and `update` topics answer `ResourceNotFound` for an `executionNumber` other than the execution's; and `DescribeJobExecution`, `ListJobExecutionsForJob`, `ListJobExecutionsForThing` and `DescribeJob` time out an expired `IN_PROGRESS` execution as the device reads do. Contributed by @iot-rocket.
- **IoT — Jobs MQTT messages are written as AWS writes them** — the `$aws/things/<thing>/jobs` messages were spaced, ASCII-escaped JSON with `clientToken` last, a `thingName` and an empty `statusDetails` in the `get` and `start-next` executions and no `jobDocument` in an execution whose document is `null`; they are now compact UTF-8 in AWS's member order with `clientToken` first, the job document as the HTTP plane sends it, characters outside the BMP escaped in `statusDetails` and in the update and rejected responses, and `"jobDocument":null` kept. Contributed by @iot-rocket.
diff --git a/ministack/services/iot.py b/ministack/services/iot.py
index 54d5b554..f22ad70c 100644
--- a/ministack/services/iot.py
+++ b/ministack/services/iot.py
@@ -8777,7 +8777,7 @@ _MAX_QUEUED_MESSAGES = 1000
class _PersistentSessionState:
__slots__ = (
"subscriptions", "queued_messages", "created_at", "expiry_interval",
- "session_identifier",
+ "session_identifier", "in_flight", "next_packet_id",
)
def __init__(
@@ -8798,6 +8798,10 @@ class _PersistentSessionState:
self.expiry_interval: int | None = expiry_interval
# Reported as ``sessionIdentifier`` by every connection that resumes it.
self.session_identifier: str = session_identifier or str(uuid.uuid4())
+ # QoS 1 messages sent but not acknowledged when the connection ended,
+ # and the packet identifier counter, both handed to the next resume.
+ self.in_flight: dict[int, "_InFlightMessage"] = {}
+ self.next_packet_id: int = 1
def _is_session_expired(session_state: _PersistentSessionState) -> bool:
@@ -10891,22 +10895,28 @@ class _WSSession:
async def _retransmit_loop(self) -> None:
try:
while self._in_flight:
- await asyncio.sleep(_RETRANSMIT_INTERVAL_SECONDS)
+ oldest = min(msg.sent_at for msg in self._in_flight.values())
now = asyncio.get_event_loop().time()
- for pid, msg in list(self._in_flight.items()):
- if now - msg.sent_at >= _RETRANSMIT_INTERVAL_SECONDS:
- msg.retransmit_count += 1
- msg.sent_at = now
- await self.send_bytes(
- _make_publish(
- msg.topic, msg.payload, qos=1, packet_id=pid, dup=True,
- retain=msg.retain,
- properties=self._publish_properties(msg.properties),
- )
- )
+ await asyncio.sleep(max(oldest + _RETRANSMIT_INTERVAL_SECONDS - now, 0))
+ await self._retransmit_due()
except asyncio.CancelledError:
pass
+ async def _retransmit_due(self) -> None:
+ """Resend every in-flight QoS 1 message that has waited a retransmit interval for its PUBACK."""
+ now = asyncio.get_event_loop().time()
+ for pid, msg in list(self._in_flight.items()):
+ if now - msg.sent_at >= _RETRANSMIT_INTERVAL_SECONDS:
+ msg.retransmit_count += 1
+ msg.sent_at = now
+ await self.send_bytes(
+ _make_publish(
+ msg.topic, msg.payload, qos=1, packet_id=pid, dup=True,
+ retain=msg.retain,
+ properties=self._publish_properties(msg.properties),
+ )
+ )
+
async def send_bytes(self, b: bytes) -> None:
async with self._send_lock:
await self._send({"type": "websocket.send", "bytes": b})
@@ -11262,6 +11272,12 @@ class _WSSession:
await self._send_connack(
session_present=True, assigned_client_id=assigned_client_id
)
+ # Unacknowledged messages keep their packet identifiers and
+ # go out again once their retransmit interval has passed.
+ self._next_pid = existing_ps.next_packet_id
+ self._in_flight.update(existing_ps.in_flight)
+ existing_ps.in_flight = {}
+ await self._retransmit_due()
queued = existing_ps.queued_messages[:]
existing_ps.queued_messages.clear()
for q_topic, q_payload, q_qos, q_properties, q_received_at in queued:
@@ -11273,6 +11289,8 @@ class _WSSession:
await self.deliver_to_client(q_topic, q_payload, q_qos)
finally:
_delivery_properties.reset(token)
+ if self._in_flight:
+ self._ensure_retransmit_timer()
await self._publish_connected()
return True
else:
@@ -11502,7 +11520,6 @@ class _WSSession:
except asyncio.CancelledError:
pass
self._retransmit_task = None
- self._in_flight.clear()
if not self._graceful_disconnect and self._will_topic is not None:
await broker_publish(
self.account_id,
@@ -11526,6 +11543,7 @@ class _WSSession:
_persistent_sessions.pop(
(self.account_id, self.region, self._client_id), None
)
+ self._in_flight.clear()
for sid in self._sub_ids:
await broker_unsubscribe(sid)
self._sub_ids.clear()
@@ -11552,12 +11570,15 @@ class _WSSession:
existing.created_at = time.time()
existing.expiry_interval = self._session_expiry_interval
else:
- _persistent_sessions[session_key] = _PersistentSessionState(
+ existing = _persistent_sessions[session_key] = _PersistentSessionState(
subscriptions=unprefixed_filters,
created_at=time.time(),
expiry_interval=self._session_expiry_interval,
session_identifier=self._session_identifier,
)
+ pending = list(self._in_flight.items())[-_MAX_QUEUED_MESSAGES:]
+ existing.in_flight = dict(pending)
+ existing.next_packet_id = self._next_pid
async def _feed_session(session: _WSSession, data: bytes, max_buffer: int) -> bool:
diff --git a/tests/test_iot.py b/tests/test_iot.py
index 2db668f2..8720e267 100644
--- a/tests/test_iot.py
+++ b/tests/test_iot.py
@@ -5755,6 +5755,98 @@ def test_offline_qos1_messages_queued_and_delivered_on_reconnect():
reset()
+def test_unacknowledged_qos1_message_is_resent_when_the_session_resumes(monkeypatch):
+ """A QoS 1 message without a PUBACK stays with the session and keeps its packet identifier."""
+ from ministack.services import iot as iot_module
+
+ monkeypatch.setattr(iot_module, "_RETRANSMIT_INTERVAL_SECONDS", 0.3)
+ reset()
+ connect = _build_connect_body(client_id="unacked", clean_session=False)
+
+ async def _run():
+ send1, sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+ await session1.handle_packet(PKT_CONNECT, 0, connect)
+ await session1.handle_packet(PKT_SUBSCRIBE, 0x02, _build_subscribe_body(1, [("data/unacked", 1)]))
+ await publish("123456789012", "data/unacked", b"m1", qos=1)
+ assert _extract_publish_frames(sent1) == [("data/unacked", b"m1", 1, 1, False)]
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ await publish("123456789012", "data/unacked", b"m2", qos=1)
+ # The retransmit interval passes while the client is offline.
+ await asyncio.sleep(0.4)
+
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+ await session2.handle_packet(PKT_CONNECT, 0, connect)
+ assert _parse_connack(sent2) == (True, 0)
+ assert _extract_publish_frames(sent2) == [
+ ("data/unacked", b"m1", 1, 1, True),
+ ("data/unacked", b"m2", 1, 2, False),
+ ]
+ for pid in (1, 2):
+ await session2.handle_packet(PKT_PUBACK, 0, struct.pack("!H", pid))
+ await session2.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session2.cleanup()
+
+ send3, sent3 = _mock_send()
+ session3 = _WSSession(send3, "123456789012")
+ await session3.handle_packet(PKT_CONNECT, 0, connect)
+ assert _parse_connack(sent3) == (True, 0)
+ assert _extract_publish_frames(sent3) == []
+ await session3.cleanup()
+
+ asyncio.run(_run())
+ reset()
+
+
+def test_unacknowledged_qos1_message_waits_for_its_retransmit_interval_after_a_resume(monkeypatch):
+ """Resumed before the interval runs out, the message goes out when it does; a clean start drops it."""
+ from ministack.services import iot as iot_module
+
+ monkeypatch.setattr(iot_module, "_RETRANSMIT_INTERVAL_SECONDS", 0.3)
+ reset()
+ key = ("123456789012", _TEST_REGION, "unacked5")
+ connect = _build_mqtt5_connect_body("unacked5", clean_start=False, session_expiry=300)
+
+ async def _run():
+ send1, _sent1 = _mock_send()
+ session1 = _WSSession(send1, "123456789012")
+ await session1.handle_packet(PKT_CONNECT, 0, connect)
+ await session1.handle_packet(
+ PKT_SUBSCRIBE, 0x02, _build_mqtt5_subscribe_body(1, "data/unacked5", 0x01)
+ )
+ await publish("123456789012", "data/unacked5", b"m1", qos=1)
+ await session1.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session1.cleanup()
+
+ send2, sent2 = _mock_send()
+ session2 = _WSSession(send2, "123456789012")
+ await session2.handle_packet(PKT_CONNECT, 0, connect)
+ assert _parse_connack(sent2) == (True, 0)
+ assert _extract_publish_frames(sent2) == []
+ await asyncio.sleep(0.5)
+ # The payload follows an empty property block.
+ assert _extract_publish_frames(sent2) == [("data/unacked5", b"\x00m1", 1, 1, True)]
+ await session2.handle_packet(PKT_DISCONNECT, 0, b"")
+ await session2.cleanup()
+ assert list(_persistent_sessions[key].in_flight) == [1]
+
+ send3, sent3 = _mock_send()
+ session3 = _WSSession(send3, "123456789012")
+ await session3.handle_packet(
+ PKT_CONNECT, 0, _build_mqtt5_connect_body("unacked5", clean_start=True)
+ )
+ await asyncio.sleep(0.5)
+ assert _extract_publish_frames(sent3) == []
+ await session3.cleanup()
+ assert key not in _persistent_sessions
+
+ asyncio.run(_run())
+ reset()
+
+
def test_qos0_messages_not_queued_for_offline_sessions():
"""QoS 0 messages should NOT be queued for offline persistent sessions."""
reset()