Coverage for abb_rws_client_python_rw6/highlevel/subscription.py: 99%
154 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-13 22:17 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-13 22:17 +0000
1# abb_rws_client_python_rw6/highlevel/subscription.py
2"""High-level RWS subscription management for ABB RobotWare 6.
4Author: Clement RACINET
6Wraps the ABB RWS Subscription Service (POST/PUT/DELETE /subscription) and
7the WebSocket event stream behind a resource-oriented API: the caller
8declares a list of `SubscribedResource` (name + RWS resource URI + ABB
9priority), and gets back logical `(name, value)` events instead of raw XML.
11ABB RWS subscription flow (confirmed from official ABB doc, "Subscriptions"
12section):
13 1. POST /subscription with a form body:
14 resources=<N>
15 1=<resource-uri>&1-p=<priority>
16 2=<resource-uri>&2-p=<priority>
17 ...
18 Response: HTTP 201, body = initial events for each resource, plus a
19 ``Location`` header = the WebSocket URL (``ws://host:port/poll/<id>``).
20 2. Open a WebSocket on that URL, subprotocol ``robapi2_subscription``,
21 reusing the RWS session cookies (``-http-session-``, ``ABBCX``).
22 3. Each subscribed-resource change is pushed as an XML/XHTML event.
23 4. DELETE /subscription/{group-id} to tear down the group.
25ABB priority semantics (confirmed, ABB doc "Subscriptions"):
26 "0" = Low (delay <= 5s)
27 "1" = Medium (delay <= 200ms)
28 "2" = High (as soon as possible; PERS RAPID variables and IO signals
29 only; max 64 High-priority resources across the
30 controller)
31"""
33from __future__ import annotations
35from collections.abc import AsyncGenerator, Sequence
36from dataclasses import dataclass
37import re
38from typing import Literal
39from urllib.parse import urlparse, urlunparse
41import websockets.asyncio.client
42from websockets.typing import Subprotocol
44from abb_rws_client_python_rw6.core.client import RWSClient
45from abb_rws_client_python_rw6.core.logger import get_logger
46from abb_rws_client_python_rw6.rws.subscription import (
47 unsubscribe_or_remove_the_subscription_group_resources,
48)
50logger = get_logger(__name__)
52# ---------------------------------------------------------------------------
53# Constants
54# ---------------------------------------------------------------------------
56#: ABB subscription priority. Confirmed by ABB doc: "0"=Low, "1"=Medium,
57#: "2"=High (PERS RAPID variables and IO signals only, max 64 resources).
58SubscriptionPriority = Literal["0", "1", "2"]
60#: ABB RW6 WebSocket subscription subprotocol (confirmed by ABB doc,
61#: confirmed working on real hardware in examples/06). Do NOT use
62#: "rws_subscription": some RW6 controllers reject it with
63#: "Unsupported Sec-WebSocket-Protocol".
64_RWS_SUBPROTOCOLS: tuple[Subprotocol, ...] = (Subprotocol("robapi2_subscription"),)
66#: Prefix stripped to recover a bare RAPID symbolurl (e.g.
67#: "RAPID/T_ROB1/MOD/VAR") from a full resource URI (e.g.
68#: "/rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR;value"). ABB uses the bare
69#: form in the "title" attribute of "rap-data" <li> elements.
70_SYMBOL_DATA_PREFIX = "/rw/rapid/symbol/data/"
72#: ABB hard limits, confirmed by ABB doc "Subscriptions".
73_MAX_RESOURCES_TOTAL = 1000
74_MAX_HIGH_PRIORITY_RESOURCES = 64
76# XML parsing patterns. ABB events are XHTML fragments, not well-formed
77# enough to justify a full XML parser dependency; the structure is stable
78# and documented (title/href/span attributes).
79_LI_BLOCK_RE = re.compile(r"<li\b[^>]*>.*?</li>", re.IGNORECASE | re.DOTALL)
80_TITLE_RE = re.compile(r'title=["\']([^"\']*)["\']', re.IGNORECASE)
81_HREF_RE = re.compile(r'href=["\']([^"\']+)["\']', re.IGNORECASE)
82_VALUE_SPAN_RE = re.compile(
83 r'<span[^>]*class=["\'][^"\']*value[^"\']*["\'][^>]*>([^<]*)</span>',
84 re.IGNORECASE,
85)
86_WS_HREF_RE = re.compile(r'href=["\'](wss?://[^"\']+)["\']', re.IGNORECASE)
87_GROUP_ID_RE = re.compile(r"/poll/([^/?#]+)")
90# ---------------------------------------------------------------------------
91# Public data model
92# ---------------------------------------------------------------------------
95@dataclass(frozen=True)
96class SubscribedResource:
97 """One RWS resource to watch within a subscription group.
99 Args:
100 name: Caller-chosen logical identifier for this resource. Used only
101 client-side to route incoming events back to the caller; never
102 sent to ABB.
103 resource_uri: Full ABB RWS resource URI to subscribe on, e.g.
104 ``/rw/rapid/symbol/data/RAPID/T_ROB1/MOD/VAR;value``.
105 priority: ABB subscription priority. ``"0"``=Low, ``"1"``=Medium,
106 ``"2"``=High (PERS RAPID variables and IO signals only).
108 Example:
109 ```python
110 >>> SubscribedResource(
111 ... name="watched_value",
112 ... resource_uri="/rw/rapid/symbol/data/RAPID/T_ROB1/Subscription/WatchedValue;value",
113 ... priority="1",
114 ... )
115 ```
116 """
118 name: str
119 resource_uri: str
120 priority: SubscriptionPriority = "1"
123@dataclass(frozen=True)
124class SubscriptionHandle:
125 """Result of a successfully created ABB RWS subscription group.
127 Args:
128 group_id: ABB subscription group identifier (from the WebSocket
129 URL path, e.g. ``"9"`` in ``ws://host/poll/9``).
130 ws_url: WebSocket URL to open for this subscription group,
131 normalized so that ``127.0.0.1``/``localhost`` (as sometimes
132 returned by ABB) is replaced by the actual controller host.
133 cookie_header: Session cookie header to send during the WebSocket
134 handshake (``-http-session-=...; ABBCX=...``).
135 resources: The resources this group was created with, kept to
136 resolve incoming events back to their logical ``name``.
137 initial_values: Values returned by ABB in the ``POST /subscription``
138 response body itself (one entry per resource whose initial
139 state ABB included), keyed by ``SubscribedResource.name``.
140 """
142 group_id: str
143 ws_url: str
144 cookie_header: str
145 resources: tuple[SubscribedResource, ...]
146 initial_values: dict[str, str]
149def build_rapid_pers_resource_uri(task: str, module: str, variable: str) -> str:
150 """Build the ABB RWS subscription resource URI for a RAPID PERS variable.
152 Route: N/A — local string helper, no HTTP call performed.
154 ABB constraints: The variable must be declared ``PERS`` in RAPID.
155 Subscriptions on non-persistent (``VAR``) data are not supported by
156 ABB (confirmed by ABB doc: "Subscribe on RAPID persistent variable").
158 Args:
159 task: RAPID task name, e.g. ``"T_ROB1"``.
160 module: RAPID module name, e.g. ``"Subscription"``.
161 variable: RAPID PERS variable name, e.g. ``"WatchedValue"``.
163 Returns:
164 Resource URI suitable for ``SubscribedResource.resource_uri``.
166 Example:
167 ```python
168 >>> build_rapid_pers_resource_uri("T_ROB1", "Subscription", "WatchedValue")
169 '/rw/rapid/symbol/data/RAPID/T_ROB1/Subscription/WatchedValue;value'
170 ```
171 """
172 return f"{_SYMBOL_DATA_PREFIX}RAPID/{task}/{module}/{variable};value"
175# ---------------------------------------------------------------------------
176# Private helpers — payload / response parsing
177# ---------------------------------------------------------------------------
180def _validate_resources(resources: Sequence[SubscribedResource]) -> None:
181 """Validate a resource list against ABB's documented hard limits.
183 Args:
184 resources: Resources about to be subscribed.
186 Raises:
187 ValueError: If the list is empty, exceeds 1000 total resources, or
188 exceeds 64 High-priority ("2") resources (both limits confirmed
189 by ABB doc "Subscriptions").
190 """
191 if not resources:
192 raise ValueError("resources must contain at least one SubscribedResource")
194 if len(resources) > _MAX_RESOURCES_TOTAL:
195 raise ValueError(
196 f"ABB allows at most {_MAX_RESOURCES_TOTAL} subscribed resources "
197 f"(low/medium priority); got {len(resources)}"
198 )
200 high_count = sum(1 for r in resources if r.priority == "2")
201 if high_count > _MAX_HIGH_PRIORITY_RESOURCES:
202 raise ValueError(
203 f"ABB allows at most {_MAX_HIGH_PRIORITY_RESOURCES} High-priority "
204 f"('2') resources; got {high_count}"
205 )
208def _build_subscription_payload(resources: Sequence[SubscribedResource]) -> dict[str, str]:
209 """Build the ABB RWS form-data payload for ``POST /subscription``.
211 ABB constraints: Format confirmed by ABB doc ("Subscriptions" section):
212 ``resources=<N>`` (total resource count) followed by, for each
213 resource ``i`` (1-based index): ``<i>=<resource-uri>`` and
214 ``<i>-p=<priority>``.
216 Args:
217 resources: Resources to subscribe to, in order (index i = position + 1).
219 Returns:
220 Flat dict ready for ``client.post("/subscription", data=...)``.
221 """
222 payload: dict[str, str] = {"resources": str(len(resources))}
223 for index, resource in enumerate(resources, start=1):
224 payload[str(index)] = resource.resource_uri
225 payload[f"{index}-p"] = resource.priority
226 return payload
229def _build_resource_lookup(resources: Sequence[SubscribedResource]) -> dict[str, str]:
230 """Build a URI-to-name lookup table to resolve incoming ABB events.
232 ABB identifies the changed resource either by:
233 - the full resource URI in an ``<a href="...">`` (e.g. IO signal events,
234 or the "rap-value-ev" link for RAPID PERS variables), or
235 - the bare RAPID symbolurl in a ``title="..."`` attribute (the "rap-data"
236 sibling <li>, confirmed by ABB doc "Subscribe on RAPID persistent
237 variable" sample response).
239 Args:
240 resources: Resources this subscription group was created with.
242 Returns:
243 Dict mapping both the full ``resource_uri`` and (for RAPID symbol
244 resources) the bare symbolurl to the caller's logical ``name``.
245 """
246 lookup: dict[str, str] = {}
247 for resource in resources:
248 lookup[resource.resource_uri] = resource.name
249 if resource.resource_uri.startswith(_SYMBOL_DATA_PREFIX):
250 # ABB's "rap-data" <li> uses the bare symbolurl (no ";value"
251 # suffix, no "/rw/rapid/symbol/data/" prefix) in its "title"
252 # attribute — register that alternate identity too.
253 symbolurl = resource.resource_uri[len(_SYMBOL_DATA_PREFIX) :].split(";")[0]
254 lookup[symbolurl] = resource.name
255 return lookup
258def _extract_li_blocks(text: str) -> list[str]:
259 """Split an ABB XHTML fragment into its top-level ``<li>...</li>`` blocks.
261 Args:
262 text: Raw XHTML fragment (POST response body or WebSocket message).
264 Returns:
265 List of ``<li>`` blocks in document order, as raw strings.
266 """
267 return _LI_BLOCK_RE.findall(text)
270def _extract_resource_identity(block: str) -> str | None:
271 """Extract the resource identity carried by one ``<li>`` block, if any.
273 ABB carries resource identity in one of two ways (both confirmed by ABB
274 doc samples):
275 - ``<a href="{resource-uri}" .../>`` — the full subscribed URI, matches
276 ``SubscribedResource.resource_uri`` directly.
277 - ``title="{symbolurl}"`` on a RAPID "rap-data" block — matches the bare
278 symbolurl form registered by ``_build_resource_lookup``. A generic
279 title with no ``/`` (e.g. ``title="value"`` on "rap-value-ev" blocks)
280 carries no resource identity and is ignored.
282 Args:
283 block: One ``<li>...</li>`` XHTML block.
285 Returns:
286 The extracted identity string, or ``None`` if this block carries
287 no resolvable resource identity.
288 """
289 href_match = _HREF_RE.search(block)
290 if href_match:
291 return href_match.group(1)
293 title_match = _TITLE_RE.search(block)
294 if title_match and "/" in title_match.group(1):
295 return title_match.group(1)
297 return None
300def _extract_value(block: str) -> str | None:
301 """Extract the value carried by one ``<li>`` block, if any.
303 Matches ``<span class="...value...">...</span>``, covering both
304 ``class="value"`` (RAPID events) and ``class="lvalue"`` (IO signal
305 events) — both documented by ABB.
307 Args:
308 block: One ``<li>...</li>`` XHTML block.
310 Returns:
311 The extracted value as a string, or ``None`` if this block carries
312 no value span.
313 """
314 value_match = _VALUE_SPAN_RE.search(block)
315 return value_match.group(1).strip() if value_match else None
318def _parse_events(text: str, lookup: dict[str, str]) -> dict[str, str]:
319 """Parse ABB subscription events into ``{name: value}``.
321 Handles both documented ABB XML shapes:
322 - Single-block events, where identity and value are in the same
323 ``<li>`` (generic IO signal example in ABB doc).
324 - Split-block events, where an "-ev" ``<li>`` carries only the
325 identity (``href``) and the immediately following ``<li>`` carries
326 only the value (the "rap-data" block, confirmed by ABB doc "Subscribe
327 on RAPID persistent variable" sample response).
329 Args:
330 text: Raw XHTML fragment (POST response body or WebSocket message).
331 lookup: Resource-identity-to-name table from ``_build_resource_lookup``.
333 Returns:
334 Dict of ``{SubscribedResource.name: value}`` for every resolvable
335 event found in ``text``. Events for resources not present in
336 ``lookup`` are silently ignored (logged at DEBUG level) — this
337 happens if ABB pushes an event for a resource outside this group.
338 """
339 events: dict[str, str] = {}
340 pending_identity: str | None = None
342 for block in _extract_li_blocks(text):
343 identity = _extract_resource_identity(block)
344 value = _extract_value(block)
346 if identity is not None:
347 pending_identity = identity
349 if value is None:
350 continue
352 resolved_identity = identity if identity is not None else pending_identity
353 if resolved_identity is None:
354 logger.debug("Value span with no resolvable resource identity: %r", block)
355 continue
357 name = lookup.get(resolved_identity)
358 if name is None:
359 logger.debug("Event for unsubscribed resource %r ignored", resolved_identity)
360 continue
362 events[name] = value
363 pending_identity = None # Consumed — avoid leaking into next block.
365 return events
368def _extract_ws_url_and_group_id(response_text: str, headers: dict[str, str]) -> tuple[str, str]:
369 """Extract the WebSocket URL and group id from ABB's subscription response.
371 ABB constraints: The WebSocket URL is normally in the ``Location``
372 header; some controllers only expose it as an
373 ``<a href="ws://...">`` link in the response body.
375 Args:
376 response_text: Raw ``POST /subscription`` response body.
377 headers: Response headers (case preserved, matched case-insensitively).
379 Returns:
380 ``(ws_url, group_id)``, e.g. ``("ws://host:80/poll/9", "9")``.
382 Raises:
383 ValueError: If no WebSocket URL, or no group id within it, can be found.
384 """
385 ws_url: str | None = None
387 for key, value in headers.items():
388 if key.lower() == "location":
389 candidate = value.strip()
390 if candidate.startswith(("ws://", "wss://")): 390 ↛ 387line 390 didn't jump to line 387 because the condition on line 390 was always true
391 ws_url = candidate
392 break
394 if ws_url is None:
395 match = _WS_HREF_RE.search(response_text)
396 if match:
397 ws_url = match.group(1).strip()
399 if ws_url is None:
400 raise ValueError(
401 "Could not extract WebSocket URL from ABB subscription response "
402 f"(headers={headers!r}, body[:500]={response_text[:500]!r})"
403 )
405 group_id_match = _GROUP_ID_RE.search(ws_url)
406 if not group_id_match:
407 raise ValueError(f"Could not extract subscription group id from ws_url={ws_url!r}")
409 return ws_url, group_id_match.group(1)
412def _normalize_ws_url(ws_url: str, client: RWSClient) -> str:
413 """Replace a loopback host in an ABB WebSocket URL by the real controller host.
415 ABB constraints: Some RW6 controllers return ``ws://127.0.0.1:9696/...``
416 (loopback from the controller's own point of view). From a remote
417 client, ``127.0.0.1`` points to the client itself, not the robot.
419 Args:
420 ws_url: Raw WebSocket URL returned by ABB.
421 client: Active RWS client, used to recover the real controller host.
423 Returns:
424 Normalized WebSocket URL, unchanged if the host was not a loopback
425 address.
426 """
427 parsed = urlparse(ws_url)
428 hostname = parsed.hostname or client.host
429 port = parsed.port
431 if hostname in {"127.0.0.1", "localhost"}:
432 hostname = client.host
434 netloc = hostname if port is None else f"{hostname}:{port}"
436 return urlunparse(
437 (parsed.scheme, netloc, parsed.path, parsed.params, parsed.query, parsed.fragment)
438 )
441# ---------------------------------------------------------------------------
442# Public API
443# ---------------------------------------------------------------------------
446async def create_subscription(
447 client: RWSClient,
448 resources: Sequence[SubscribedResource],
449) -> SubscriptionHandle:
450 """Create an ABB RWS subscription group for one or more resources.
452 Route: ``POST /subscription``
454 ABB constraints:
455 - Max 1000 total resources per client (low/medium priority).
456 - Max 64 resources at High priority ("2"), RAPID PERS variables and
457 IO signals only.
458 - Max 2 subscription groups per client.
459 - The response body contains the initial event state for the
460 subscribed resources (parsed here into ``initial_values``); the
461 ``Location`` header carries the WebSocket URL.
463 Args:
464 client: Open RWSClient instance.
465 resources: Resources to subscribe to (1 to N).
467 Returns:
468 SubscriptionHandle with the group id, normalized WebSocket URL,
469 session cookie header, and any initial values ABB returned inline.
471 Raises:
472 ValueError: If ``resources`` is empty, exceeds ABB's resource-count
473 limits, or if ABB's response cannot be parsed (missing
474 WebSocket URL / group id).
475 RWSAuthenticationError: On HTTP 401.
476 RWSHTTPError: On any other HTTP >= 400 (e.g. bad resource URI).
478 Example:
479 ```python
480 >>> handle = await create_subscription(
481 ... client,
482 ... [SubscribedResource(
483 ... "watched",
484 ... "/rw/rapid/symbol/data/RAPID/T_ROB1/M/x;value",
485 ... "1",
486 ... )],
487 ... )
488 ```
489 """
490 # FIXME(Clement RACINET): The multi-resource POST payload built by
491 # _build_subscription_payload (single "resources=<total>" key + per-index
492 # "<i>"/"<i>-p" pairs) is inferred from ABB's documentation, which is
493 # internally inconsistent on this exact point (its own 2-resource sample
494 # repeats the "resources" key with two different values instead of
495 # sending the total once). This has ONLY been confirmed on real RW6
496 # hardware for N=1 resource (examples/06). MUST be re-tested on a real
497 # controller with N>=2 resources (including mixed priorities) before
498 # this is considered production-ready. If ABB rejects the payload, or
499 # returns an unexpected initial-event XML shape for N>=2, fix
500 # _build_subscription_payload and/or _parse_events accordingly — do not
501 # patch around it blindly.
502 _validate_resources(resources)
503 payload = _build_subscription_payload(resources)
504 lookup = _build_resource_lookup(resources)
506 logger.info("Creating subscription on %d resource(s)", len(resources))
507 response = await client.post("/subscription", data=payload)
509 headers = dict(response.headers)
510 ws_url_raw, group_id = _extract_ws_url_and_group_id(response.text, headers)
511 ws_url = _normalize_ws_url(ws_url_raw, client)
512 cookie_header = client.session_cookie_header()
513 initial_values = _parse_events(response.text, lookup)
515 logger.info("Subscription created: group_id=%s, ws_url=%s", group_id, ws_url)
517 return SubscriptionHandle(
518 group_id=group_id,
519 ws_url=ws_url,
520 cookie_header=cookie_header,
521 resources=tuple(resources),
522 initial_values=initial_values,
523 )
526async def delete_subscription(client: RWSClient, handle: SubscriptionHandle) -> None:
527 """Delete an ABB RWS subscription group.
529 Route: ``DELETE /subscription/{group-id}``
531 ABB constraints: Not supported in bootserver mode.
533 Args:
534 client: Open RWSClient instance.
535 handle: Handle returned by ``create_subscription``.
537 Raises:
538 RWSAuthenticationError: On HTTP 401.
539 RWSNotFoundError: If the group was already removed (e.g. session
540 expired server-side).
541 RWSHTTPError: On any other HTTP >= 400.
543 Example:
544 ```python
545 >>> await delete_subscription(client, handle)
546 ```
547 """
548 logger.info("Deleting subscription group_id=%s", handle.group_id)
549 await unsubscribe_or_remove_the_subscription_group_resources(client, handle.group_id)
550 logger.info("Subscription group_id=%s deleted", handle.group_id)
553async def watch_resources(
554 client: RWSClient,
555 resources: Sequence[SubscribedResource],
556 *,
557 yield_initial_values: bool = True,
558) -> AsyncGenerator[tuple[str, str], None]:
559 """Subscribe to resources and yield ``(name, value)`` events as they occur.
561 Route: ``POST /subscription`` then WebSocket ``ws://.../poll/{group-id}``,
562 ``DELETE /subscription/{group-id}`` on exit.
564 ABB constraints:
565 - WebSocket subprotocol must be ``robapi2_subscription``.
566 - The WebSocket handshake must carry the same session cookies
567 (``-http-session-``, ``ABBCX``) as the HTTP session.
568 - permessage-deflate must be disabled (``compression=None``): some
569 RW6 controllers reject the negotiated extension with HTTP 400.
570 - The subscription group is always deleted on exit (normal
571 completion, exception, or generator close/cancellation), via
572 ``try/finally``.
574 Args:
575 client: Open RWSClient instance.
576 resources: Resources to subscribe to (1 to N). See
577 ``SubscribedResource`` and ``build_rapid_pers_resource_uri``.
578 yield_initial_values: If ``True`` (default), yield the initial
579 values ABB returns inline in the ``POST /subscription``
580 response body before entering the WebSocket loop. If ``False``,
581 only events received over the WebSocket are yielded.
583 Yields:
584 ``(name, value)`` tuples, where ``name`` is the
585 ``SubscribedResource.name`` the event belongs to, and ``value`` is
586 the raw string value as sent by ABB.
588 Raises:
589 ValueError: Invalid resource list, or ABB response could not be
590 parsed (see ``create_subscription``).
591 RWSAuthenticationError: On HTTP 401 during subscription setup.
592 RWSHTTPError: On any other HTTP >= 400 during subscription setup.
593 OSError: If the WebSocket connection cannot be established.
595 Example:
596 ```python
597 >>> resources = [
598 ... SubscribedResource("a", build_rapid_pers_resource_uri("T_ROB1", "M", "X"), "1"),
599 ... SubscribedResource("b", build_rapid_pers_resource_uri("T_ROB1", "M", "Y"), "1"),
600 ... ]
601 >>> async for name, value in watch_resources(client, resources):
602 ... print(name, value)
603 ```
604 """
605 lookup = _build_resource_lookup(resources)
606 handle = await create_subscription(client, resources)
608 try:
609 if yield_initial_values:
610 for name, value in handle.initial_values.items():
611 yield name, value
613 # ABB RW6 WebSocket notes (confirmed on real hardware, examples/06):
614 # - subprotocol MUST be "robapi2_subscription", NOT "rws_subscription"
615 # (some RW6 controllers reject the latter with
616 # "Unsupported Sec-WebSocket-Protocol").
617 # - compression=None avoids Sec-WebSocket-Extensions negotiation,
618 # which some RW6 controllers reject with HTTP 400.
619 # - ping_interval=None: ABB documents its own application-level
620 # ping/pong; the websockets library's built-in ping is disabled
621 # to avoid sending a frame ABB does not expect.
622 async with websockets.asyncio.client.connect(
623 handle.ws_url,
624 additional_headers={"Cookie": handle.cookie_header},
625 subprotocols=_RWS_SUBPROTOCOLS,
626 open_timeout=10.0,
627 ping_interval=None,
628 compression=None,
629 ) as websocket:
630 logger.info("WebSocket connected: %s", handle.ws_url)
632 async for message in websocket:
633 text = str(message)
634 logger.debug("WebSocket message: %s", text)
636 for name, value in _parse_events(text, lookup).items():
637 yield name, value
639 finally:
640 try:
641 await delete_subscription(client, handle)
642 except Exception as exc:
643 # Teardown must never raise: a failed DELETE here (e.g. session
644 # already expired) must not mask the original error, if any.
645 logger.warning("Could not delete subscription group_id=%s: %s", handle.group_id, exc)