Repository navigation
Fix SDK bugs found by the live docs snippet tests - #242
Conversation
* PubNubSubscriptionSet.unsubscribe() now unsubscribes the channels of the set
and removes the set from the registry. It sent an empty unsubscribe before.
* unsubscribe_all() resets the registry to dicts. It set a list, so the next
subscribe() raised TypeError and a second unsubscribe_all() AttributeError.
* subscriptions and sets get channel_metadata, user_metadata, membership and
file_message methods. The registry callback called methods that did not
exist, so the sync message worker raised on the first App Context or file
event.
* subscription.add_listener() calls SubscribeCallback listeners with
(pubnub, event) like the client does. It raised TypeError.
* PubNubUserMetadata sets _type, it set the unused _types.
* message action events expose event ("added" or "removed").
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ging * get_message_actions sends end when start is set, limit accepts int or str. * pubnub.reconnect() calls the subscription manager and no longer raises AttributeError. Added pubnub.disconnect(). * asyncio get_subscribed_channels(), get_subscribed_channel_groups() and unsubscribe_all() work before the first subscribe (PNContext starts empty). * if_matches_etag() no longer leaks the If-Match header into later requests (the headers dict was shared by the class). * total_count=True in MembershipIncludes and MemberIncludes requests a count. The two include_object cassettes now record count=True. * parse_token() raises PubNubException for every malformed token. * grant() counts delete as a flag. * fetch_messages items parse custom_message_type. * setup.py: aiohttp>=3.10.11, the old range did not overlap the dev pin. Adds offline regression tests in tests/unit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
✅ Snyk checks have passed. No issues have been found so far.
💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse. |
The example passed start below end. The SDK dropped end, so the call worked by accident. Now that get_message_actions sends both bounds the service answers HTTP 400 "Start must be greater than or equal to end". start is the newer bound (exclusive) and end the older bound (inclusive). Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
parfeon
left a comment
There was a problem hiding this comment.
Mostly looks good but still had some small questions.
| def limit(self, limit: str) -> 'GetMessageActions': | ||
| assert isinstance(limit, str) | ||
| self._limit = limit | ||
| assert isinstance(limit, (str, int)) and not isinstance(limit, bool) |
There was a problem hiding this comment.
Isn't our current contract according to the docs is str?
There was a problem hiding this comment.
limit() accepts only str again (960d1ce). I had widened the contract without need. The end fix in this file stays, and the unit test now checks that an int raises AssertionError.
| itself, so there this call does nothing. | ||
| """ | ||
| self._validate_subscribe_manager_enabled() | ||
| return self._subscription_manager.reconnect() |
There was a problem hiding this comment.
This will work only for NativeSubscriptionManager and not implemented for EventEngineSubscriptionManager (pubnub_asyncio)
There was a problem hiding this comment.
You are right, a silent no-op that claims to work is wrong. I did not add a real reconnect to the event engine manager, because the state machine does not support it safely today:
- The reconnecting states can read
context.reasoninon_enterbefore anything has set it. - Those states use the retry policy. With
PNReconnectionPolicy.NONEthey give up at once, soreconnect()would never reconnect. HeartbeatDisconnectEventhas nosuppress_leave, but the heartbeat disconnect transitions read it.
So EventEngineSubscriptionManager now raises PubNubException from both reconnect() and disconnect(), through one helper in PubNubCore (960d1ce). The old no-op came from the empty base SubscriptionManager.reconnect(). @abstractmethod is not enforced there on Python 3, because __metaclass__ has no effect. set_state on this manager behaves as before. A real implementation fits a separate change.
| if not hasattr(self._subscription_manager, 'disconnect'): | ||
| raise PubNubException( | ||
| errormsg="disconnect() is not supported by %s" % type(self._subscription_manager).__name__) | ||
| return self._subscription_manager.disconnect() |
There was a problem hiding this comment.
Situation similar to the reconnect. Should we add same exception for reconnect?
There was a problem hiding this comment.
Yes. reconnect() and disconnect() now raise the same PubNubException for a manager that does not support them (960d1ce).
| @staticmethod | ||
| def _set_origin(result, channel, subscription): | ||
| # subscription and subscription set listeners match App Context events by these attributes | ||
| result.channel = channel | ||
| result.subscription = subscription |
There was a problem hiding this comment.
I'm curious, why we can't follow the same pattern as we have with PNSignalMessageResult, PNMessageActionResult, and PNFileMessageResult for PNChannelMetadataResult, PNUUIDMetadataResult, and PNMembershipResult constructors where channel and subscription_match passed as one of the constructor arguments?
There was a problem hiding this comment.
There is no good reason, I should have used the constructors. Fixed in 960d1ce. PNChannelMetadataResult, PNUUIDMetadataResult and PNMembershipResult now take channel and subscription as keyword-only arguments, default None, like PNMessageActionResult. Existing callers keep working. The worker passes both and _set_origin is gone.
| "request": { | ||
| "method": "PATCH", | ||
| "uri": "https://ps.pndsn.com/v2/objects/{PN_KEY_SUBSCRIBE}/uuids/someuuid/channels?include=custom%2Cstatus%2Ctype%2CtotalCount%2Cchannel%2Cchannel.custom%2Cchannel.type%2Cchannel.status", | ||
| "uri": "https://ps.pndsn.com/v2/objects/{PN_KEY_SUBSCRIBE}/uuids/someuuid/channels?include=custom%2Cstatus%2Ctype%2CtotalCount%2Cchannel%2Cchannel.custom%2Cchannel.type%2Cchannel.status&count=True", |
There was a problem hiding this comment.
Why count=True had to be added? Also why True and not true?
REST API docs say that by default it should be omitted.
There was a problem hiding this comment.
count is still omitted by default. The SDK sends it only when the caller asks for a total count.
On master, MembershipIncludes(total_count=True) and MemberIncludes(total_count=True) only add totalCount to include. The service ignores that, so no total came back. The original recordings of these two tests show it: totalCount appears in the request and in no response. This PR also sends count when total_count=True is set, as include_total_count(True) already did. The two tests use total_count=True, so their recorded requests changed.
True is not new. ObjectsEndpoint has sent count=True since v4.8.0, and the service accepts it. native_sync/objects_v2/channel/get_all_channel.json has totalCount in its response. I agree lowercase true is the documented form. I would not change the serialization of an existing parameter in this PR, because 12 cassettes record count=True. I can open a follow-up that switches the objects endpoints to true and updates them. Does that work for you?
* get_message_actions.limit() accepts str only again, the contract stays as documented. * reconnect() and disconnect() raise the same PubNubException on a subscription manager that does not support them. The asyncio event engine manager used to inherit an empty reconnect() that did nothing silently. set_state on that manager keeps its behaviour and no longer goes through reconnect(). * PNChannelMetadataResult, PNUUIDMetadataResult and PNMembershipResult take channel and subscription as constructor arguments like the other subscribe results, the worker no longer sets them afterwards. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
@pubnub-release-bot release |
|
🚀 Release successfully completed 🚀 |
feat(pubnub): add
disconnect()toPubNubandPubNubAsyncioStop the subscribe loop and heartbeat timer without removing the subscriptions. The event engine subscription manager, the default for
PubNubAsyncio, raises a clearPubNubException.fix(pubnub): make
reconnect()work with the subscription manager in usereconnect()always raisedAttributeError. It now restarts the subscribe loop for the threaded and legacy asyncio subscription managers, and raises a clearPubNubExceptionwith the event engine subscription manager.fix(subscription): deliver App Context and file events to subscription listeners
Channel, user and membership (App Context) and file events are now delivered to subscription and subscription set listeners instead of raising on the first event.
fix(subscription): use the correct callback signature in
add_listener()Listeners added with
subscription.add_listener()now receive events with the correct callback signature instead of raisingTypeError.fix(subscription): fix registry edge cases
Fix subscription registry removal for subscription sets sharing channels,
unsubscribe_allwith a followingsubscribe(), a setunsubscribe()that sent an empty request, and thePubNubUserMetadatasubscription type.fix(event-engine): fix
get_subscribed_channelsandunsubscribe_allbefore the first subscribeBoth calls no longer raise
AttributeErrorwith the asyncio event engine before the first subscribe.fix(message-actions): send
endtogether withstartget_message_actionsnow sendsendtogether withstart, andlimit()no longer accepts onlystr.fix(message-actions): set
eventon message action eventsMessage action events now carry the
eventtype (addedorremoved).fix(fetch-messages): return
custom_message_typeon fetched messagescustom_message_typeis now parsed on items from fetch messages.fix(objects): request the total count from include options
MembershipIncludes(total_count=True)andMemberIncludes(total_count=True)now sendcount=trueon App Context requests.fix(objects): stop
If-Matchfrom leaking into other requestsThe
If-Matchheader set byif_matches_etagno longer leaks into other App Context requests through a shared class-level dict.fix(access-manager): raise
PubNubExceptionfor malformed tokensparse_tokennow raisesPubNubExceptionfor malformed tokens instead ofbinascii.ErrororTypeError.fix(grant): accept
deleteas the only permission flagGrant now accepts
deleteas the only permission flag instead of raising a no-flags error.fix(packaging): relax the
aiohttprequirementRelax
aiohttp>3.10.11to>=3.10.11so it overlaps the dev pin and pip can resolve both.test: add unit tests for the SDK fixes
Add offline unit tests for the subscription registry, message worker events,
get_message_actionsparameters and the other fixes, and re-record the App Context include cassettes withcount=True.