diff --git a/ably/pubsub/http/channel.py b/ably/pubsub/http/channel.py index 3fa079c2..5003f597 100644 --- a/ably/pubsub/http/channel.py +++ b/ably/pubsub/http/channel.py @@ -197,6 +197,7 @@ async def _send_update( version=version, extras=message.extras, annotations=message.annotations, + patches=message.patches, ) # Encrypt if needed @@ -265,6 +266,21 @@ async def append_message(self, message: Message, operation: MessageOperation = N """ return await self._send_update(message, MessageAction.MESSAGE_APPEND, operation, params) + async def patch_message(self, message: Message, operation: MessageOperation = None, params: dict = None): + """Patches an existing message on this channel (PSRFC-44): changes parts of its data at JSON + Pointer paths, and its headers, without sending the whole message. + + Parameters: + - message: Message object with a serial field, and the changes in its patches field, a + MessagePatches. Its other fields are sent as they are. + - operation: Optional MessageOperation containing description and metadata for the patch. + - params: Optional dict of query parameters. + + Returns: + - UpdateDeleteResult containing the version serial of the patched message. + """ + return await self._send_update(message, MessageAction.MESSAGE_PATCH, operation, params) + async def get_message(self, serial_or_message): """Retrieves a single message by its serial. diff --git a/ably/pubsub/realtime/channel.py b/ably/pubsub/realtime/channel.py index 56d7ea29..b778d4f9 100644 --- a/ably/pubsub/realtime/channel.py +++ b/ably/pubsub/realtime/channel.py @@ -566,6 +566,7 @@ async def _send_update( version=version, extras=message.extras, annotations=message.annotations, + patches=message.patches, ) # Encrypt if needed @@ -681,6 +682,35 @@ async def append_message( """ return await self._send_update(message, MessageAction.MESSAGE_APPEND, operation, params) + async def patch_message( + self, + message: Message, + operation: MessageOperation | None = None, + params: dict | None = None, + ) -> UpdateDeleteResult: + """Patches an existing message on this channel (PSRFC-44): changes parts of its data at JSON + Pointer paths, and its headers, without sending the whole message. + + Parameters + ---------- + message : Message + Message object with a serial field, and the changes in its patches field, a MessagePatches. + Its other fields are sent as they are. + operation : MessageOperation, optional + Optional MessageOperation containing description and metadata for the patch. + + Returns + ------- + UpdateDeleteResult + Result containing the version serial of the patched message. + + Raises + ------ + AblyException + If message serial is missing or connection/channel state prevents the patch + """ + return await self._send_update(message, MessageAction.MESSAGE_PATCH, operation, params) + async def get_message(self, serial_or_message): """Retrieves a single message by its serial using the REST API. diff --git a/ably/pubsub/server/__init__.py b/ably/pubsub/server/__init__.py index 6ba52623..a378757b 100644 --- a/ably/pubsub/server/__init__.py +++ b/ably/pubsub/server/__init__.py @@ -57,6 +57,14 @@ from ably.pubsub.types.connectionstate import ConnectionEvent, ConnectionState, ConnectionStateChange from ably.pubsub.types.device import DeviceDetails, DevicePushDetails from ably.pubsub.types.message import Message, MessageAction, MessageVersion +from ably.pubsub.types.messagepatch import ( + MessagePatchDataOperation, + MessagePatches, + MessagePatchExtras, + MessagePatchHeaderOperation, + MessagePatchPrivilegedOperation, + MessagePatchUserClaimOperation, +) from ably.pubsub.types.operations import MessageOperation, PublishResult, UpdateDeleteResult from ably.pubsub.types.options import Options, VCDiffDecoder from ably.pubsub.types.presence import Presence, PresenceAction, PresenceMessage @@ -326,6 +334,12 @@ def create_realtime_client(**kwargs) -> PubSubRealtimeClient: 'Message', 'MessageAction', 'MessageOperation', + 'MessagePatchDataOperation', + 'MessagePatchExtras', + 'MessagePatchHeaderOperation', + 'MessagePatchPrivilegedOperation', + 'MessagePatchUserClaimOperation', + 'MessagePatches', 'MessageVersion', 'Options', 'PaginatedResult', diff --git a/ably/pubsub/server/sync.py b/ably/pubsub/server/sync.py index 5698d806..a8f8c30b 100644 --- a/ably/pubsub/server/sync.py +++ b/ably/pubsub/server/sync.py @@ -42,6 +42,14 @@ from ably.pubsub.sync.types.channelsubscription import PushChannelSubscription from ably.pubsub.sync.types.device import DeviceDetails, DevicePushDetails from ably.pubsub.sync.types.message import Message, MessageAction, MessageVersion +from ably.pubsub.sync.types.messagepatch import ( + MessagePatchDataOperation, + MessagePatches, + MessagePatchExtras, + MessagePatchHeaderOperation, + MessagePatchPrivilegedOperation, + MessagePatchUserClaimOperation, +) from ably.pubsub.sync.types.operations import MessageOperation, PublishResult, UpdateDeleteResult from ably.pubsub.sync.types.options import Options, VCDiffDecoder from ably.pubsub.sync.types.presence import PresenceAction, PresenceMessage, PresenceSync @@ -118,6 +126,12 @@ def create_http_client(**kwargs) -> PubSubHttpClient: 'Message', 'MessageAction', 'MessageOperation', + 'MessagePatchDataOperation', + 'MessagePatchExtras', + 'MessagePatchHeaderOperation', + 'MessagePatchPrivilegedOperation', + 'MessagePatchUserClaimOperation', + 'MessagePatches', 'MessageVersion', 'Options', 'PaginatedResultSync', diff --git a/ably/pubsub/types/message.py b/ably/pubsub/types/message.py index aaf1b4d6..f9587095 100644 --- a/ably/pubsub/types/message.py +++ b/ably/pubsub/types/message.py @@ -4,6 +4,7 @@ import os from enum import IntEnum +from ably.pubsub.types.messagepatch import MessagePatches, apply_to_message_fields, check_patch from ably.pubsub.types.mixins import DeltaExtras, EncodeDataMixin from ably.pubsub.types.typedbuffer import TypedBuffer from ably.pubsub.util.crypto import CipherData @@ -133,6 +134,7 @@ class MessageAction(IntEnum): META = 3 MESSAGE_SUMMARY = 4 MESSAGE_APPEND = 5 + MESSAGE_PATCH = 6 # PSRFC-44 class Message(EncodeDataMixin): @@ -151,6 +153,7 @@ def __init__(self, action=None, # TM2j version=None, # TM2s annotations=None, # TM2t + patches=None, # TM2v: the MessagePatches of a MESSAGE_PATCH ): super().__init__(encoding) @@ -167,6 +170,7 @@ def __init__(self, self.__action = action self.__version = version self.__annotations = annotations + self.__patches = patches def __eq__(self, other): if isinstance(other, Message): @@ -235,6 +239,40 @@ def action(self): def annotations(self): return self.__annotations + @property + def patches(self): + """The changes a MESSAGE_PATCH makes (TM2v), as MessagePatches: set by the user to send with + patch_message, and decoded on receipt per MPD4. None for other actions.""" + return self.__patches + + def apply_patch(self, patch: 'Message') -> 'Message': + """Applies ``patch``, a received MESSAGE_PATCH of this message, to a copy of it (PSRFC-44), with the + same result as Ably: the data operations to its data, then the header operations and those set by Ably + to its extras. The copy has the patch's version and the action MESSAGE_UPDATE; every other field is this + message's. JSON data that arrived as text, in a string or binary, keeps every character an operation + does not change; decoded JSON is copied only along each path, so this message is unchanged. + + :raises AblyException: with code 40000 if ``patch`` is not a patch of this message, or any operation + cannot be applied, in which case none is. Fetch the latest version with ``get_message(serial)``. + """ + check_patch(self.serial, patch) + data, encoding, extras = apply_to_message_fields(self.data, self.encoding, self.extras, patch.patches) + return Message( + name=self.name, + data=data, + client_id=self.client_id, + id=self.id, + connection_id=self.connection_id, + connection_key=self.connection_key, + encoding=encoding, + timestamp=self.timestamp, + extras=extras, + serial=self.serial, + action=MessageAction.MESSAGE_UPDATE, + version=patch.version, + annotations=self.annotations, + ) + def encrypt(self, channel_cipher): if isinstance(self.data, CipherData): return @@ -280,6 +318,7 @@ def as_dict(self, binary=False): 'serial': self.serial, 'action': int(self.action) if self.action is not None else None, 'annotations': self.annotations.as_dict() if self.annotations else None, + 'patches': self.patches.as_dict(binary) if isinstance(self.patches, MessagePatches) else None, **encode_data(self.data, self._encoding_array, binary), } @@ -365,6 +404,7 @@ def from_encoded(obj, cipher=None, context=None): action=action, version=version, annotations=annotations, + patches=MessagePatches.from_dict(obj.get('patches')), **decoded_data ) diff --git a/ably/pubsub/types/messagepatch.py b/ably/pubsub/types/messagepatch.py new file mode 100644 index 00000000..7fea5f30 --- /dev/null +++ b/ably/pubsub/types/messagepatch.py @@ -0,0 +1,919 @@ +"""Message patches (PSRFC-44): encoding them to send, decoding received ones, and applying them. + +A patch changes part of a published message: data operations at JSON Pointer paths (``set``, +``append``, ``remove``), header operations, and operations Ably adds on the user claim and +privileged extras. A subscriber receives a ``message.patch`` and applies it to its own copy of the +message with :meth:`Message.apply_patch`, which gives the same result as Ably. + +The applier follows ably-pubsub-js's ``messagepatch.ts``, which follows Ably's own implementation: +operations follow their path through decoded JSON values (dicts and lists), copying only the +containers along it, and are spliced into JSON text in a string or binary, so every character an +operation does not change is kept. +""" +import base64 +import binascii +import json +from typing import Any, List, Optional + +from ably.pubsub.util.exceptions import AblyException + +SET = 'set' +APPEND = 'append' +REMOVE = 'remove' + +_KNOWN_OPS = (SET, APPEND, REMOVE) +_END_OF_ARRAY = '-' + +_REMEDIATION = ('Your copy of the message differs from the version the patch applies to: fetch the latest ' + 'version with get_message(serial), and apply later patches to it.') +_UNKNOWN_REMEDIATION = ('The patch uses an operation this SDK does not know: fetch the latest version of the ' + 'message with get_message(serial), or update the SDK.') +_NOT_A_CONTAINER = 'a patch operation with a path requires the message data to be a JSON object or array' +_INVALID_DATA = 'the message data is not valid JSON' + + +# ---- Encoding a patch to send ---- + +def _encode_value(value, encoding: str, binary: bool) -> dict: + # MPD3: a string unchanged, with its encoding (MPD3a); binary per RSL4c1/RSL4d1 (MPD3b); and any other + # JSON value, including a number, boolean or null, as JSON text with the encoding json (MPD3c). + if isinstance(value, str): + return {'data': value, 'encoding': encoding} if encoding else {'data': value} + if isinstance(value, (bytes, bytearray)): + if binary: + return {'data': bytes(value), 'encoding': encoding} if encoding else {'data': bytes(value)} + return {'data': base64.b64encode(value).decode('ascii'), 'encoding': _join(encoding, 'base64')} + try: + text = json.dumps(value, separators=(',', ':'), ensure_ascii=False, allow_nan=False) + except (TypeError, ValueError) as e: + raise AblyException(f'A patch value of type {type(value).__name__} cannot be sent as JSON: {e}', + 400, 40013) from e + return {'data': text, 'encoding': 'json'} + + +def _join(encoding: str, transform: str) -> str: + return f'{encoding}/{transform}' if encoding else transform + + +# ---- Received patches ---- + +class _Absent: + """The default of ``MessagePatchDataOperation.data``, which tells an operation without a value, such as a + ``remove``, from one whose value is JSON ``null`` (``data=None``).""" + + def __repr__(self): + return 'ABSENT' + + +_ABSENT = _Absent() + + +class MessagePatchDataOperation: + """An operation that changes a message's data, or a value inside it (MPD2). + + - ``op``: ``'set'``, ``'append'`` or ``'remove'`` (or, on receipt, one this SDK does not know). + - ``path``: a JSON Pointer (RFC 6901) to a value inside the data, such as ``'/content/0/text'``; ``None`` + for the whole of the data. + - ``data``: the value the operation uses. To send, a ``str``, ``bytes``, or any JSON value: a dict, list, + number, bool or ``None`` (JSON ``null``). Leave it out for an operation without a value, such as a + ``remove``. + - ``encoding``: the transforms applied to ``data``. Leave it out to send a raw value. + + On receipt the value is decoded as a message's data is, except that a JSON value is left as its JSON + text, with the ``encoding`` ``'json'`` (MPD4a), so that it can be spliced into JSON text verbatim and + parsed by the user into the type it changes. Binary is a ``bytearray``. A received operation can be sent + again as it is. + + Example:: + + MessagePatchDataOperation('append', path='/text', data=' world') + MessagePatchDataOperation('set', path='/status', data={'done': True}) + MessagePatchDataOperation('remove', path='/draft') + """ + + def __init__(self, op: str, path: Optional[str] = None, data: Any = _ABSENT, + encoding: Optional[str] = None): + self.__op = op + self.__path = path + self.__data = data + self.__encoding = encoding or '' + + @property + def op(self) -> str: + return self.__op + + @property + def path(self) -> Optional[str]: + return self.__path + + @property + def data(self) -> Any: + """The value, or ``None`` if the operation has none.""" + return None if self.__data is _ABSENT else self.__data + + @property + def has_data(self) -> bool: + """Whether the operation has a value, which tells a JSON ``null`` from none.""" + return self.__data is not _ABSENT + + @property + def encoding(self) -> str: + """The transforms of the value not yet inverted: ``'json'`` for a received JSON value, empty for a + decoded one or a raw value to send.""" + return self.__encoding + + def as_dict(self, binary: bool = False) -> dict: + """The operation in its wire form, with its value encoded per MPD3. Values are never encrypted + (MPD3e).""" + entry = {'op': self.op} + if self.path is not None: + entry['path'] = self.path + if self.has_data: # MPD3d: without data, no data or encoding + entry.update(_encode_value(self.__data, self.encoding, binary)) + return entry + + def __repr__(self): + return (f'MessagePatchDataOperation(op={self.op!r}, path={self.path!r}, data={self.__data!r}, ' + f'encoding={self.encoding!r})') + + +class MessagePatchHeaderOperation: + """An operation that changes a header in a message's ``extras.headers`` (MPH2): ``op``, ``'set'`` or + ``'remove'``; the header ``key``; and, for ``set``, its new ``value``, a string, number or bool. + + Example: ``MessagePatchHeaderOperation('set', 'status', 'complete')``. + """ + + def __init__(self, op: str, key: str, value: Any = None): + self.op = op + self.key = key + self.value = value + + def as_dict(self) -> dict: + entry = {'op': self.op, 'key': self.key} + if self.value is not None: + entry['value'] = self.value + return entry + + +class MessagePatchUserClaimOperation: + """A received operation on the user claim, set by Ably (MPU2): ``op`` and the claim's new ``value``.""" + + def __init__(self, op: str, value: Optional[str] = None): + self.op = op + self.value = value + + def as_dict(self) -> dict: + entry = {'op': self.op} + if self.value is not None: + entry['value'] = self.value + return entry + + +class MessagePatchPrivilegedOperation: + """A received operation on the privileged extras, set by Ably (MPP2): ``op``, always ``'remove'``.""" + + def __init__(self, op: str = REMOVE): + self.op = op + + def as_dict(self) -> dict: + return {'op': self.op} + + +class MessagePatchExtras: + """The operations of a patch on the message's extras (MPA2b): ``headers``, applied in order, and the + ``user_claim`` and ``privileged`` operations, which only Ably sets.""" + + def __init__(self, headers: Optional[List[MessagePatchHeaderOperation]] = None, + user_claim: Optional[MessagePatchUserClaimOperation] = None, + privileged: Optional[MessagePatchPrivilegedOperation] = None): + self.headers: List[MessagePatchHeaderOperation] = list(headers or []) + self.user_claim: Optional[MessagePatchUserClaimOperation] = user_claim + self.privileged: Optional[MessagePatchPrivilegedOperation] = privileged + + def as_dict(self) -> dict: + result = {} + if self.headers: + result['headers'] = [op.as_dict() for op in self.headers] + if self.user_claim is not None: + result['userClaim'] = self.user_claim.as_dict() + if self.privileged is not None: + result['privileged'] = self.privileged.as_dict() + return result + + +class MessagePatches: + """The changes a ``MESSAGE_PATCH`` makes to a message (MPA2): ``data``, operations on its data applied in + order, and ``extras``, operations on its extras, or ``None`` if it changes none. Set it as a message's + ``patches`` to send it with ``patch_message``; a received patch carries one in ``message.patches``, and + can be sent again as it is. + + Example:: + + patches = MessagePatches( + data=[MessagePatchDataOperation('append', path='/text', data=delta)], + extras=MessagePatchExtras(headers=[MessagePatchHeaderOperation('set', 'status', 'complete')]), + ) + await channel.patch_message(Message(serial=serial, patches=patches)) + """ + + def __init__(self, data: Optional[List[MessagePatchDataOperation]] = None, + extras: Optional[MessagePatchExtras] = None): + self.data: List[MessagePatchDataOperation] = list(data or []) + self.extras: Optional[MessagePatchExtras] = extras + + def as_dict(self, binary: bool = False) -> dict: + """The patch in its wire form, with each operation's value encoded per MPD3.""" + result = {} + if self.data: + result['data'] = [op.as_dict(binary) for op in self.data] + if self.extras is not None: + result['extras'] = self.extras.as_dict() + return result + + @staticmethod + def from_dict(obj) -> Optional['MessagePatches']: + """Decodes the wire form of a received patch (MPD4).""" + if not isinstance(obj, dict): + return None + return MessagePatches( + data=[_decode_data_operation(op) for op in obj.get('data') or [] if isinstance(op, dict)], + extras=_decode_extras(obj.get('extras')), + ) + + def apply_to_data(self, data): + """Applies the data operations to JSON ``data`` kept outside a message: text (a ``str``), UTF-8 + bytes, or decoded JSON (a dict or list, copied only along each path). The result has the same + form. + + :raises AblyException: with code 40000 if an operation cannot be applied. + """ + result, _ = _apply_data(data, '', self.data) + if _form(result) != _form(data): + raise AblyException('Unable to apply the patch to the data: an operation without a path changed ' + 'what form the data has. Apply a patch that replaces the whole of the data to ' + 'a message, with Message.apply_patch', 400, 40000) + if isinstance(data, bytes): + return bytes(result) + return result + + +def _form(data) -> str: + """Whether data is JSON text, UTF-8 JSON bytes, or decoded JSON.""" + if isinstance(data, str): + return 'text' + if isinstance(data, (bytes, bytearray)): + return 'binary' + return 'json' + + +def _decode_extras(obj) -> Optional[MessagePatchExtras]: + if not isinstance(obj, dict): + return None + user_claim = obj.get('userClaim') + privileged = obj.get('privileged') + return MessagePatchExtras( + headers=[MessagePatchHeaderOperation(op.get('op') or '', op.get('key') or '', op.get('value')) + for op in obj.get('headers') or [] if isinstance(op, dict)], + user_claim=MessagePatchUserClaimOperation(user_claim.get('op') or '', user_claim.get('value')) + if isinstance(user_claim, dict) else None, + privileged=MessagePatchPrivilegedOperation(privileged.get('op') or '') + if isinstance(privileged, dict) else None, + ) + + +def _decode_data_operation(op: dict) -> MessagePatchDataOperation: + # MPD4: the transforms of the encoding are inverted from the last, as RSL6a inverts a message's, except + # that a first transform of json is left (MPD4a), and with no decryption or delta decoding (MPD4c). A + # transform that cannot be inverted is left with every one before it, and the data as it is (RSL6b). + data = op.get('data') + if isinstance(data, bytes): + data = bytearray(data) + steps = [step for step in (op.get('encoding') or '').split('/') if step] + while steps: + step = steps[-1] + if step == 'json' and len(steps) == 1: + # MPD4a: JSON text, as a string. A JSON value MessagePack carried as itself is stringified. + if isinstance(data, (bytes, bytearray)): + try: + data = bytes(data).decode('utf-8') + except UnicodeDecodeError: + pass + elif isinstance(data, (dict, list)): + data = json.dumps(data, separators=(',', ':'), ensure_ascii=False) + break + try: + if step == 'base64': + raw = data if isinstance(data, (bytes, bytearray)) else data.encode('utf-8') + data = bytearray(base64.b64decode(raw, validate=True)) + elif step == 'utf-8': + if isinstance(data, (bytes, bytearray)): + data = bytes(data).decode('utf-8') + elif step == 'json': + text = bytes(data).decode('utf-8') if isinstance(data, (bytes, bytearray)) else data + if isinstance(text, str): + data = json.loads(text) + else: + break + except (binascii.Error, ValueError, TypeError, AttributeError): + break + steps.pop() + return MessagePatchDataOperation(op.get('op') or '', op.get('path'), data if 'data' in op else _ABSENT, + '/'.join(steps)) + + +# ---- Applying ---- + +class _PatchError(Exception): + """An operation that cannot be applied; the caller adds which one and why.""" + + +def _fail(message: str): + raise _PatchError(message) + + +def _patch_error(message: str, remediation: str) -> AblyException: + return AblyException(f'{message}. {remediation}', 400, 40000) + + +def check_patch(serial, patch) -> None: + """Checks that ``patch``, a received message, is a patch of the message ``serial``.""" + from ably.pubsub.types.message import MessageAction # message.py imports this module + + if patch.action != MessageAction.MESSAGE_PATCH: + action = patch.action.name if patch.action is not None else 'unknown' + raise _patch_error(f'Unable to apply a {action} message as a patch: only a message.patch can be applied', + 'Apply only messages whose action is MessageAction.MESSAGE_PATCH; replace your copy ' + 'with any other') + if serial != patch.serial: + raise _patch_error(f'Unable to apply a patch to message {serial}: the patch is for message {patch.serial}', + "Look up your copy of the message with the patch's serial") + + +def apply_to_message_fields(data, encoding: str, extras, patches: Optional[MessagePatches]): + """The data, remaining encoding and extras of a message once ``patches`` are applied.""" + if patches is None: + return data, encoding, extras + data, encoding = _apply_data(data, encoding, patches.data) + return data, encoding, _apply_extras(extras, patches) + + +def _apply_data(data, encoding: str, ops: List[MessagePatchDataOperation]): + for index, op in enumerate(ops): + try: + if op.op not in _KNOWN_OPS: + _unknown_operation(op) + if op.path: + data = _apply_at_path(data, op, op.path) + elif op.op == SET: + data, encoding = _set_whole(op) + else: + data, encoding = _apply_to_whole(data, encoding, op) + except _PatchError as e: + where = _quote(op.path or '') + raise _patch_error(f'Unable to apply data patch operation {index} ({op.op} at {where}): {e}', + _REMEDIATION) from None + return data, encoding + + +def _set_whole(op): + # TM9f2a: a JSON value must be an object or array, and is decoded, as a message.update's data would be; + # any other value replaces the data with its encoding. + if op.encoding == 'json': + value = _json_value(op) + if not isinstance(value, (dict, list)): + _fail('a set patch operation without a path requires a JSON value that is an object or array') + return value, '' + return op.data, op.encoding + + +def _apply_to_whole(data, encoding, op): + value = op.data + if op.op == APPEND: + if op.encoding: + _fail('an append patch operation requires a string or binary value with no encoding') + # TM9f2b: as with message.append, appending to no data gives the value. + if data is None and isinstance(value, (str, bytes, bytearray)): + return value, '' + # TM9f2c + if isinstance(data, str) and isinstance(value, str) and not encoding: + return data + value, '' + if isinstance(data, (bytes, bytearray)) and isinstance(value, (bytes, bytearray)) and not encoding: + return bytearray(data) + value, '' + _fail('an append patch operation without a path requires the message data and the operation data to ' + 'both be strings or both be binary') + # TM9f2d + _fail('a remove patch operation requires a path') + + +def _apply_at_path(data, op, path): + if op.encoding and op.encoding != 'json': + # MPD4c leaves a value this SDK cannot decode with its encoding: there is no value to apply. + _fail(f'its value has the encoding {op.encoding}, which this SDK cannot decode') + if isinstance(data, str): + return _JsonText.apply(data, op, path) + if isinstance(data, (bytes, bytearray)): + try: + text = bytes(data).decode('utf-8') + except UnicodeDecodeError: + _fail(_INVALID_DATA) + return bytearray(_JsonText.apply(text, op, path).encode('utf-8')) + if isinstance(data, (dict, list)): + return _apply_at(data, _parse_path(path), 0, op, path) + _fail(_NOT_A_CONTAINER) + + +def _apply_at(container, tokens, index, op, path): + # Copies each dict and list on the path, and returns the new container. + token = tokens[index] + if index < len(tokens) - 1: + # Every token but the last locates the target. + if isinstance(container, list): + i = _parse_index(token) + if i < 0 or i >= len(container): + _fail(_path_not_found(path)) + copy = list(container) + copy[i] = _apply_at(_require_container(container[i], path), tokens, index + 1, op, path) + return copy + if isinstance(container, dict): + if token not in container: + _fail(_path_not_found(path)) + copy = dict(container) + copy[token] = _apply_at(_require_container(container[token], path), tokens, index + 1, op, path) + return copy + _fail(_parent_not_container(path)) + if isinstance(container, list): + return _update_list(container, token, op, path) + if isinstance(container, dict): + return _update_dict(container, token, op, path) + _fail(_parent_not_container(path)) + + +def _require_container(value, path): + if not isinstance(value, (dict, list)): + _fail(_parent_not_container(path)) + return value + + +def _update_list(array, token, op, path): + elements = list(array) + if token == _END_OF_ARRAY: + if op.op != SET: + _fail(_end_of_array_not_set(op, path)) + elements.append(_tree_value(op)) + return elements + i = _parse_index(token) + if i < 0 or i >= len(elements): + _fail(_path_not_found(path)) + if op.op == SET: + elements[i] = _tree_value(op) + elif op.op == APPEND: + elements[i] = _append_string(elements[i], op, path) + elif op.op == REMOVE: + del elements[i] + else: + _unknown_operation(op) + return elements + + +def _update_dict(obj, key, op, path): + fields = dict(obj) + if op.op == SET: + fields[key] = _tree_value(op) + elif op.op == APPEND: + if key not in fields: + _fail(_path_not_found(path)) + fields[key] = _append_string(fields[key], op, path) + elif op.op == REMOVE: + if key not in fields: + _fail(_path_not_found(path)) + del fields[key] + else: + _unknown_operation(op) + return fields + + +def _append_string(value, op, path): + if not isinstance(value, str): + _fail(f'unable to append at path {_quote(path)}: the value there is not a string') + _require_string_value(op) + return value + op.data + + +def _require_string_value(op): + # TM9f3f + if not isinstance(op.data, str) or op.encoding: + _fail('an append patch operation with a path requires data that is a string, with no encoding') + + +def _tree_value(op): + # TM9f3h: the value an operation sets, as a decoded JSON value: binary as base64, as JSON holds it. + if op.encoding == 'json': + return _json_value(op) + if isinstance(op.data, (bytes, bytearray)): + return base64.b64encode(op.data).decode('ascii') + return op.data + + +def _json_text_of(op) -> str: + """The JSON text of an operation whose encoding is json (MPD4a).""" + data = op.data + if isinstance(data, (bytes, bytearray)): + try: + data = bytes(data).decode('utf-8') + except UnicodeDecodeError: + data = None + if not isinstance(data, str): + _fail('its JSON value is not JSON text') + return data + + +def _json_value(op): + """The JSON value that an operation whose encoding is json represents.""" + try: + return json.loads(_json_text_of(op)) + except ValueError: + _fail('its JSON value is not valid JSON') + + +def _apply_extras(extras, patches: MessagePatches): + if patches.extras is None: + return extras + result = _apply_headers(extras, patches.extras.headers) + result = _apply_user_claim(result, patches.extras.user_claim) + return _apply_privileged(result, patches.extras.privileged) + + +def _apply_headers(extras, ops): + if not ops: + return extras + headers = dict((extras or {}).get('headers') or {}) + for index, op in enumerate(ops): + if op.op == SET: + headers[op.key] = op.value + elif op.op == REMOVE: + if op.key not in headers: + raise _patch_error(f'Unable to apply header patch operation {index} (remove of {_quote(op.key)}): ' + 'the header does not exist', _REMEDIATION) + del headers[op.key] + else: + raise _patch_error(f'Unable to apply header patch operation {index}: unknown operation ' + f'{_quote(op.op)}', _UNKNOWN_REMEDIATION) + result = dict(extras or {}) + result['headers'] = headers + return result + + +def _apply_user_claim(extras, op): + # Unlike a header, removing a claim the message does not have succeeds. + if op is None: + return extras + rest = {k: v for k, v in (extras or {}).items() if k != 'userClaim'} + if op.op == SET: + rest['userClaim'] = op.value + return rest + if op.op == REMOVE: + # TM9g4 + return rest or None + raise _patch_error(f'Unable to apply the user claim patch operation: unknown operation {_quote(op.op)}', + _UNKNOWN_REMEDIATION) + + +def _apply_privileged(extras, op): + # Removing privileged extras the message does not have succeeds. + if op is None: + return extras + if op.op != REMOVE: + raise _patch_error('Unable to apply the privileged extras patch operation: unknown operation ' + f'{_quote(op.op)}', _UNKNOWN_REMEDIATION) + rest = {k: v for k, v in (extras or {}).items() if k != 'privileged'} + return rest or None + + +def _unknown_operation(op): + _fail(f'unknown message patch operation {_quote(op.op)}') + + +def _end_of_array_not_set(op, path): + return f'unable to {op.op} at path {_quote(path)}: "-" can only be used to set a new array element' + + +def _path_not_found(path): + return f'path {_quote(path)} does not exist in the message data' + + +def _parent_not_container(path): + return f'unable to apply a patch operation at path {_quote(path)}: its parent is not an object or array' + + +def _parse_path(path: str) -> List[str]: + """A path's tokens, unescaped (RFC 6901).""" + invalid = (f'invalid path {_quote(path)}: a patch operation path must be a JSON Pointer, such as ' + '/content/0/text') + if not path or path[0] != '/': + _fail(invalid) + for i, c in enumerate(path): + if c == '~' and (i + 1 >= len(path) or path[i + 1] not in '01'): + _fail(invalid) + return [token.replace('~1', '/').replace('~0', '~') for token in path[1:].split('/')] + + +def _parse_index(token: str) -> int: + """An array index token, decimal digits without leading zeros (RFC 6901), or -1 if it is not one.""" + if not token or (len(token) > 1 and token[0] == '0') or any(c not in '0123456789' for c in token): + return -1 + return int(token) + + +def _quote(s: str) -> str: + """A string as JSON, escaped as Ably escapes it: ``"``, ``\\`` and control characters, and no others. Ably + replaces invalid UTF-8 with U+FFFD, as a lone surrogate becomes here.""" + out = ['"'] + for c in s: + if c == '"': + out.append('\\"') + elif c == '\\': + out.append('\\\\') + elif c == '\n': + out.append('\\n') + elif c == '\r': + out.append('\\r') + elif c == '\t': + out.append('\\t') + elif c == '\b': + out.append('\\b') + elif c == '\f': + out.append('\\f') + elif c < ' ': + out.append(f'\\u{ord(c):04x}') + elif '\ud800' <= c <= '\udfff': + out.append('�') # a lone surrogate: Python strings hold pairs as one character + else: + out.append(c) + out.append('"') + return ''.join(out) + + +class _Loc: + def __init__(self, open_at): + self.open = open_at + self.found = False + self.start = 0 # the start of the member's key, or of the element + self.val_start = 0 + self.val_end = 0 + self.prev_end = -1 # the end of the previous value, or -1 if this is the first + self.next_start = -1 # the start of the next member or element, or -1 if this is the last + self.last_end = -1 # when not found, the end of the last value, or -1 if the container is empty + + +class _JsonText: + """JSON text, edited by splicing. Every character that delimits JSON is ASCII, so indices into a Python + string locate values as byte offsets do in Ably's implementation.""" + + @staticmethod + def apply(doc: str, op, path: str) -> str: + if op.op == SET: + return _JsonText._set(doc, path, _JsonText._json_text(op)) + if op.op == APPEND: + _require_string_value(op) + _, loc = _JsonText._locate(doc, path, op.op) + if not loc.found: + _fail(_path_not_found(path)) + if doc[loc.val_start] != '"': + _fail(f'unable to append at path {_quote(path)}: the value there is not a string') + at = loc.val_end - 1 # just before the closing quote + return doc[:at] + _quote(op.data)[1:-1] + doc[at:] + if op.op == REMOVE: + _, loc = _JsonText._locate(doc, path, op.op) + if not loc.found: + _fail(_path_not_found(path)) + if loc.next_start >= 0: + return doc[:loc.start] + doc[loc.next_start:] + if loc.prev_end >= 0: + # The last of several: remove the comma before it. + return doc[:loc.prev_end] + doc[loc.val_end:] + return doc[:loc.start] + doc[loc.val_end:] + _unknown_operation(op) + + @staticmethod + def _json_text(op) -> str: + # TM9f5a: the operation's value as JSON text: a JSON value verbatim, once it is known to be valid, a + # string quoted, binary as base64, and a JSON value MessagePack carried without an encoding as JSON. + if op.encoding == 'json': + _json_value(op) + return _json_text_of(op) + if isinstance(op.data, str): + return _quote(op.data) + if isinstance(op.data, (bytes, bytearray)): + return _quote(base64.b64encode(op.data).decode('ascii')) + return json.dumps(op.data, separators=(',', ':'), ensure_ascii=False) + + @staticmethod + def _set(doc, path, value): + target, loc = _JsonText._locate(doc, path, SET) + if loc.found: + return doc[:loc.val_start] + value + doc[loc.val_end:] + # A new member or element, after the last one. + insertion = ',' if loc.last_end >= 0 else '' + if doc[target] == '{': + insertion += _quote(_parse_path(path)[-1]) + ':' + insertion += value + at = loc.last_end if loc.last_end >= 0 else loc.open + return doc[:at] + insertion + doc[at:] + + @staticmethod + def _locate(doc, path, op): + # The start of the object or array holding the value at path, and the value's location in it. + start = _JsonText._skip_ws(doc, 0) + if start >= len(doc) or doc[start] not in '{[': + _fail(_NOT_A_CONTAINER) + tokens = _parse_path(path) + last = tokens[-1] + target = start + for token in tokens[:-1]: + if doc[target] == '{': + loc = _JsonText._find_member(doc, target, token, full=False) + elif doc[target] == '[': + i = _parse_index(token) + if i < 0: + _fail(_path_not_found(path)) + loc = _JsonText._find_element(doc, target, i, full=False) + else: + _fail(_path_not_found(path)) + if not loc.found: + _fail(_path_not_found(path)) + target = loc.val_start + if doc[target] not in '{[': + _fail(_parent_not_container(path)) + if doc[target] == '{': + return target, _JsonText._find_member(doc, target, last, full=True) + if last == _END_OF_ARRAY: + if op != SET: + _fail(f'unable to {op} at path {_quote(path)}: "-" can only be used to set a new array element') + return target, _JsonText._find_element(doc, target, -1, full=True) + index = _parse_index(last) + if index < 0: + _fail(_path_not_found(path)) + loc = _JsonText._find_element(doc, target, index, full=True) + if not loc.found: + _fail(_path_not_found(path)) + return target, loc + + @staticmethod + def _find_member(doc, start, key, full): + # Locates the member `key` in the object at doc[start], scanning past its value only if `full`. + loc = _Loc(start + 1) + i = start + 1 + while True: + i = _JsonText._skip_ws(doc, i) + if i >= len(doc): + _fail(_INVALID_DATA) + if doc[i] == '}' and loc.last_end < 0: + return loc + if doc[i] != '"': + _fail(_INVALID_DATA) + key_start = i + key_end = _JsonText._skip_string(doc, i) + match = _JsonText._key_equals(doc[i + 1:key_end - 1], key) + i = _JsonText._skip_ws(doc, key_end) + if i >= len(doc) or doc[i] != ':': + _fail(_INVALID_DATA) + val_start = _JsonText._skip_ws(doc, i + 1) + if val_start >= len(doc): + _fail(_INVALID_DATA) + if match and not full: + loc.found = True + loc.val_start = val_start + return loc + val_end = _JsonText._skip_value(doc, val_start) + i = _JsonText._skip_ws(doc, val_end) + if i >= len(doc): + _fail(_INVALID_DATA) + if match: + loc.found = True + loc.start = key_start + loc.val_start = val_start + loc.val_end = val_end + loc.prev_end = loc.last_end + if doc[i] == ',': + loc.next_start = _JsonText._skip_ws(doc, i + 1) + return loc + loc.last_end = val_end + if doc[i] == ',': + i += 1 + elif doc[i] == '}': + return loc + else: + _fail(_INVALID_DATA) + + @staticmethod + def _find_element(doc, start, index, full): + # Locates element `index` of the array at doc[start], scanning past it only if `full`. An index of -1 + # finds none, and so locates the end of the array. + loc = _Loc(start + 1) + i = _JsonText._skip_ws(doc, start + 1) + if i >= len(doc): + _fail(_INVALID_DATA) + if doc[i] == ']': + return loc + n = 0 + while True: + val_start = i + if val_start >= len(doc): + _fail(_INVALID_DATA) + if n == index and not full: + loc.found = True + loc.val_start = val_start + return loc + val_end = _JsonText._skip_value(doc, i) + i = _JsonText._skip_ws(doc, val_end) + if i >= len(doc): + _fail(_INVALID_DATA) + if n == index: + loc.found = True + loc.start = val_start + loc.val_start = val_start + loc.val_end = val_end + loc.prev_end = loc.last_end + if doc[i] == ',': + loc.next_start = _JsonText._skip_ws(doc, i + 1) + return loc + loc.last_end = val_end + if doc[i] == ',': + i = _JsonText._skip_ws(doc, i + 1) + elif doc[i] == ']': + return loc + else: + _fail(_INVALID_DATA) + n += 1 + + @staticmethod + def _key_equals(raw, key): + # Compares a raw, still escaped, JSON object key with a decoded key. + if '\\' not in raw: + return raw == key + try: + return json.loads('"' + raw + '"') == key + except ValueError: + return False + + @staticmethod + def _skip_ws(doc, start): + i = start + while i < len(doc) and doc[i] in ' \t\n\r': + i += 1 + return i + + @staticmethod + def _skip_value(doc, start): + # The index just past the value at doc[start]. + if start >= len(doc): + _fail(_INVALID_DATA) + c = doc[start] + if c == '"': + return _JsonText._skip_string(doc, start) + if c in '{[': + return _JsonText._skip_container(doc, start) + # A number, true, false or null. + j = start + while j < len(doc) and doc[j] not in ',}] \t\n\r': + j += 1 + if j == start: + _fail(_INVALID_DATA) + return j + + @staticmethod + def _skip_string(doc, start): + # The index just past the string at doc[start]. + j = start + 1 + while True: + q = doc.find('"', j) + if q < 0: + _fail(_INVALID_DATA) + # The quote is escaped if an odd number of backslashes precede it. + backslashes = 0 + p = q - 1 + while p > start and doc[p] == '\\': + backslashes += 1 + p -= 1 + if backslashes % 2 == 0: + return q + 1 + j = q + 1 + + @staticmethod + def _skip_container(doc, start): + # The index just past the object or array at doc[start]. + depth = 0 + j = start + while j < len(doc): + c = doc[j] + if c == '"': + j = _JsonText._skip_string(doc, j) - 1 + elif c in '{[': + depth += 1 + elif c in '}]': + depth -= 1 + if depth == 0: + return j + 1 + j += 1 + _fail(_INVALID_DATA) diff --git a/test/unit/message_patch_test.py b/test/unit/message_patch_test.py new file mode 100644 index 00000000..3e661f3f --- /dev/null +++ b/test/unit/message_patch_test.py @@ -0,0 +1,428 @@ +"""Message patches (PSRFC-44): building and sending them, decoding received ones, and applying them. + +The applier tests are ported from ably-pubsub-js's `test/unit/message_patch.test.js` (by way of +ably-pubsub-kotlin's `MessagePatchingTest`), so that the SDKs give Ably's result. The UTS derivations of +the specification's own tests are under `test/uts`: `rest/unit/channel/patch_message_test.py`, +`rest/unit/types/message_patch_types_test.py`, `rest/unit/types/message_apply_patch_test.py` and +`realtime/unit/channels/channel_patch_message_test.py`. +""" + +import base64 +import json +import uuid + +import msgpack +import pytest + +from ably.pubsub.realtime.connection import ConnectionState +from ably.pubsub.server import ( + MessageAction, + MessagePatchDataOperation, + MessagePatches, + MessagePatchExtras, + MessagePatchHeaderOperation, +) +from ably.pubsub.transport.websockettransport import ProtocolMessageAction +from ably.pubsub.types.message import Message +from ably.pubsub.types.messagepatch import _quote +from ably.pubsub.types.operations import MessageOperation +from ably.pubsub.util.exceptions import AblyException +from test.uts.helpers.client import await_connection_state, realtime_client, rest_client +from test.uts.helpers.mock_http import MockHttpClient +from test.uts.helpers.mock_websocket import MockWebSocket, attached_message, connected_message + + +def decode(**fields): + """A received message, from the fields of its wire form.""" + return Message.from_encoded({'serial': 's1', 'timestamp': 1, **fields}) + + +def decode_patch(patches, **fields): + return decode(action=6, version={'serial': 'v2', 'timestamp': 2}, patches=patches, **fields) + + +def assert_rejected(message, error): + with pytest.raises(AblyException) as e: + message() + assert e.value.code == 40000 + assert error in e.value.message + + +# ---- Decoding and encoding ---- + +def test_decodes_a_patch_keeping_json_values_as_text(): + patch = decode_patch({ + 'data': [ + {'op': 'set', 'path': '/a', 'data': '{"b":1}', 'encoding': 'json'}, + {'op': 'set', 'path': '/c', 'data': 'AQI=', 'encoding': 'base64'}, + {'op': 'append', 'path': '/d', 'data': 'text'}, + ], + 'extras': {'headers': [{'op': 'set', 'key': 'status', 'value': 'complete'}]}, + }) + + assert patch.action == MessageAction.MESSAGE_PATCH + ops = patch.patches.data + assert (ops[0].op, ops[0].path, ops[0].data, ops[0].encoding) == ('set', '/a', '{"b":1}', 'json') + assert (ops[1].data, ops[1].encoding) == (bytearray([1, 2]), '') + assert (ops[2].op, ops[2].data) == ('append', 'text') + header = patch.patches.extras.headers[0] + assert (header.op, header.key, header.value) == ('set', 'status', 'complete') + + +def test_a_data_operations_value_is_decoded_as_message_data_is_except_for_json(): + patch = decode_patch({'data': [ + {'op': 'set', 'path': '/n', 'data': '42', 'encoding': 'json'}, + {'op': 'set', 'path': '/b', 'data': 'false', 'encoding': 'json'}, + {'op': 'set', 'path': '/s', 'data': 'plain'}, + {'op': 'set', 'path': '/m', 'data': {'over': 'msgpack'}}, + ]}) + + # MPD4a: a JSON value is left as its text, with the encoding json. + assert [op.data for op in patch.patches.data] == ['42', 'false', 'plain', {'over': 'msgpack'}] + assert [op.encoding for op in patch.patches.data] == ['json', 'json', '', ''] + + +@pytest.mark.parametrize('binary', [False, True], ids=['JSON', 'MsgPack']) +def test_encodes_a_patch_for_the_wire(binary): + patch = MessagePatches( + data=[ + MessagePatchDataOperation('set', path='/a', data={'b': 1}), + MessagePatchDataOperation('set', path='/c', data=b'\x01\x02'), + MessagePatchDataOperation('remove', path='/d'), + MessagePatchDataOperation('set', path='/e', data='text'), + MessagePatchDataOperation('set', path='/f', data=True), + MessagePatchDataOperation('set', data=None), + ], + extras=MessagePatchExtras(headers=[ + MessagePatchHeaderOperation('set', 'stage', 'done'), + MessagePatchHeaderOperation('remove', 'old'), + ]), + ) + + wire = Message(serial='s1', action=MessageAction.MESSAGE_PATCH, patches=patch).as_dict(binary=binary) + + assert wire['action'] == 6 + assert wire['serial'] == 's1' + binary_op = {'op': 'set', 'path': '/c', 'data': b'\x01\x02'} if binary \ + else {'op': 'set', 'path': '/c', 'data': 'AQI=', 'encoding': 'base64'} + assert wire['patches'] == { + 'data': [ + {'op': 'set', 'path': '/a', 'data': '{"b":1}', 'encoding': 'json'}, + binary_op, + {'op': 'remove', 'path': '/d'}, + {'op': 'set', 'path': '/e', 'data': 'text'}, + {'op': 'set', 'path': '/f', 'data': 'true', 'encoding': 'json'}, + {'op': 'set', 'data': 'null', 'encoding': 'json'}, + ], + 'extras': {'headers': [{'op': 'set', 'key': 'stage', 'value': 'done'}, {'op': 'remove', 'key': 'old'}]}, + } + + +def test_a_value_json_cannot_hold_fails_before_sending(): + with pytest.raises(AblyException) as e: + MessagePatches(data=[MessagePatchDataOperation('set', path='/a', data=object())]).as_dict() + assert e.value.code == 40013 + + +def test_a_received_patch_is_sent_again_as_it_is(): + wire = { + 'data': [ + {'op': 'set', 'path': '/a', 'data': '{"b":1}', 'encoding': 'json'}, + {'op': 'set', 'path': '/c', 'data': 'AQI=', 'encoding': 'base64'}, + {'op': 'remove', 'path': '/d'}, + ], + 'extras': {'headers': [{'op': 'set', 'key': 'h', 'value': 'v'}], 'userClaim': {'op': 'remove'}, + 'privileged': {'op': 'remove'}}, + } + + assert decode_patch(wire).patches.as_dict() == wire + + +# ---- Applying ---- + +def test_applies_operations_to_decoded_json_data(): + message = decode( + name='reply', + data='{"content":[{"type":"text","text":"Hel"}],"meta":{"kept":true}}', + encoding='json', + extras={'headers': {'status': 'streaming', 'model': 'm1'}}, + ) + patch = decode_patch({ + 'data': [ + {'op': 'append', 'path': '/content/0/text', 'data': 'lo'}, + {'op': 'set', 'path': '/content/-', 'data': '{"type":"tool"}', 'encoding': 'json'}, + {'op': 'set', 'path': '/done', 'data': 'true', 'encoding': 'json'}, + ], + 'extras': {'headers': [{'op': 'set', 'key': 'status', 'value': 'complete'}, + {'op': 'remove', 'key': 'model'}]}, + }) + + patched = message.apply_patch(patch) + + assert patched.action == MessageAction.MESSAGE_UPDATE + assert (patched.serial, patched.name, patched.version.serial) == ('s1', 'reply', 'v2') + assert patched.data == {'content': [{'type': 'text', 'text': 'Hello'}, {'type': 'tool'}], + 'meta': {'kept': True}, 'done': True} + assert patched.extras == {'headers': {'status': 'complete'}} + assert patched.patches is None + + +def test_keeps_the_copys_fields_other_than_data_extras_and_version(): + message = decode(clientId='author', connectionId='c1', data='Hel') + patch = decode_patch({'data': [{'op': 'append', 'data': 'lo'}]}, clientId='patcher', connectionId='c2') + + patched = message.apply_patch(patch) + + assert (patched.client_id, patched.connection_id, patched.timestamp) == ('author', 'c1', 1) + assert patched.version.serial == 'v2' + assert patched.data == 'Hello' + + +def test_does_not_change_the_copy_and_shares_unchanged_parts(): + message = decode(data='{"a":{"text":"x"},"b":{"unchanged":true}}', encoding='json', + extras={'headers': {'h': 'v'}}) + before = message.data + patch = decode_patch({'data': [{'op': 'append', 'path': '/a/text', 'data': 'y'}], + 'extras': {'headers': [{'op': 'set', 'key': 'h', 'value': 'w'}]}}) + + patched = message.apply_patch(patch) + + assert message.data == {'a': {'text': 'x'}, 'b': {'unchanged': True}} + assert message.data is before + assert message.extras == {'headers': {'h': 'v'}} + assert patched.data['a'] == {'text': 'xy'} + assert patched.data['b'] is before['b'] + + +def test_splices_operations_into_json_text_keeping_its_formatting(): + text = '{ "content" : [ {"text":"Hel"} ], "n": 1.0 }' + patch = decode_patch({'data': [ + {'op': 'append', 'path': '/content/0/text', 'data': 'lo "world"'}, + {'op': 'set', 'path': '/obj', 'data': '{ "spaced" : 1 }', 'encoding': 'json'}, + {'op': 'set', 'path': '/content/-', 'data': 'end'}, + ]}) + expected = '{ "content" : [ {"text":"Hello \\"world\\""},"end" ], "n": 1.0,"obj":{ "spaced" : 1 } }' + + assert decode(data=text).apply_patch(patch).data == expected + from_binary = decode(data=base64.b64encode(text.encode()).decode(), encoding='base64').apply_patch(patch) + assert bytes(from_binary.data).decode() == expected + + +def test_patches_json_kept_outside_a_message(): + patches = decode_patch({'data': [{'op': 'remove', 'path': '/a/1'}, {'op': 'remove', 'path': '/b'}, + {'op': 'remove', 'path': '/c'}]}).patches + + assert patches.apply_to_data('{"a":[1,2,3],"b":2,"c":3}') == '{"a":[1,3]}' + assert patches.apply_to_data(b'{"a":[1,2,3],"b":2,"c":3}') == b'{"a":[1,3]}' + assert patches.apply_to_data({'a': [1, 2, 3], 'b': 2, 'c': 3}) == {'a': [1, 3]} + + +def test_applies_operations_to_the_whole_of_data(): + append = decode_patch({'data': [{'op': 'append', 'data': ' world'}]}) + assert decode(data='hello').apply_patch(append).data == 'hello world' + + append_binary = decode_patch({'data': [{'op': 'append', 'data': 'Aw==', 'encoding': 'base64'}]}) + assert decode(data='AQI=', encoding='base64').apply_patch(append_binary).data == bytearray([1, 2, 3]) + + # Appending to no data gives the value. + assert decode().apply_patch(append).data == ' world' + + replaced = decode(data='hello').apply_patch(decode_patch({'data': [{'op': 'set', 'data': '{"a":1}', + 'encoding': 'json'}]})) + assert replaced.data == {'a': 1} + assert replaced.encoding == '' + + +def test_rejects_the_whole_patch_if_any_operation_is_rejected(): + message = decode(data='{"a":"x"}', encoding='json', extras={'headers': {'h': 'v'}}) + patch = decode_patch({'data': [{'op': 'append', 'path': '/a', 'data': 'y'}, + {'op': 'append', 'path': '/missing', 'data': 'y'}]}) + + assert_rejected(lambda: message.apply_patch(patch), + 'Unable to apply data patch operation 1 (append at "/missing"): ' + 'path "/missing" does not exist') + assert message.data == {'a': 'x'} + + +@pytest.mark.parametrize('data,op,error', [ + ('{"a":1}', {'op': 'append', 'path': '/a', 'data': 'x'}, 'the value there is not a string'), + ('{"a":[]}', {'op': 'append', 'path': '/a/-', 'data': 'x'}, '"-" can only be used to set'), + ('{"a":[]}', {'op': 'set', 'path': '/a/0', 'data': 'x'}, 'does not exist'), + ('{"a":1}', {'op': 'set', 'path': '/a/b', 'data': 'x'}, 'its parent is not an object or array'), + ('{"a":1}', {'op': 'set', 'path': 'a', 'data': 'x'}, 'must be a JSON Pointer'), + ('{"a":1}', {'op': 'remove', 'path': '/b'}, 'does not exist'), + ('{"a":1}', {'op': 'remove'}, 'requires a path'), + ('{"a":1}', {'op': 'move', 'path': '/a'}, 'unknown message patch operation "move"'), +]) +@pytest.mark.parametrize('decoded', [True, False], ids=['decoded', 'text']) +def test_rejects_invalid_operations(data, op, error, decoded): + message = decode(data=data, encoding='json') if decoded else decode(data=data) + + assert_rejected(lambda: message.apply_patch(decode_patch({'data': [op]})), error) + + +def test_rejects_appending_to_the_whole_of_data_that_is_not_a_string_or_binary(): + message = decode(data='{"a":1}', encoding='json') + + assert_rejected(lambda: message.apply_patch(decode_patch({'data': [{'op': 'append', 'data': 'x'}]})), + 'both be strings or both be binary') + + +def test_sets_or_removes_the_claim_takes_the_patchs_version_and_ignores_the_patchs_own_extras(): + message = decode(data='x', extras={'headers': {'h': 'v'}, 'userClaim': 'moderator'}) + + patched = message.apply_patch(decode_patch( + {'data': [{'op': 'append', 'data': 'y'}], + 'extras': {'userClaim': {'op': 'set', 'value': 'guest'}}}, + extras={'push': {'notification': {'title': 't'}}, 'userClaim': 'guest'}, + )) + assert patched.extras == {'headers': {'h': 'v'}, 'userClaim': 'guest'} + assert patched.version.serial == 'v2' + + remove = decode_patch({'data': [{'op': 'append', 'data': 'y'}], 'extras': {'userClaim': {'op': 'remove'}}}) + assert message.apply_patch(remove).extras == {'headers': {'h': 'v'}} + # Removing a claim the message does not have succeeds. + assert decode(data='x').apply_patch(remove).extras is None + + +def test_removes_privileged_extras(): + message = decode(data='x', extras={'headers': {'h': 'v'}, 'privileged': {'skipRule': '*'}}) + patch = decode_patch({'extras': {'headers': [{'op': 'set', 'key': 'h', 'value': 'w'}], + 'privileged': {'op': 'remove'}}}) + + assert message.apply_patch(patch).extras == {'headers': {'h': 'w'}} + + +def test_rejects_removing_a_header_that_does_not_exist(): + patch = decode_patch({'extras': {'headers': [{'op': 'remove', 'key': 'h'}]}}) + + assert_rejected(lambda: decode(data='x').apply_patch(patch), 'the header does not exist') + + +def test_rejects_a_patch_for_another_message_or_a_message_that_is_not_a_patch(): + message = decode(data='x') + other = decode_patch({'data': [{'op': 'append', 'data': 'y'}]}, serial='s2') + + assert_rejected(lambda: message.apply_patch(other), 'the patch is for message s2') + assert_rejected(lambda: message.apply_patch(message), 'only a message.patch can be applied') + + +def test_key_escapes_and_duplicate_keys_in_json_text(): + # A token matches a key after JSON escapes are decoded, and the first of two equal keys. + patch = decode_patch({'data': [{'op': 'set', 'path': '/café', 'data': '2', 'encoding': 'json'}]}) + + patched = decode(data='{"caf\\u00e9":1,"café":0}').apply_patch(patch) + + assert patched.data == '{"caf\\u00e9":2,"café":0}' + + +def test_rejects_an_operation_whose_value_cannot_be_decoded(): + patch = decode_patch({'data': [{'op': 'set', 'path': '/a', 'data': 'x', 'encoding': 'cipher+aes-256-cbc'}]}) + + assert_rejected(lambda: decode(data='{}', encoding='json').apply_patch(patch), 'this SDK cannot decode') + + +def test_quotes_strings_as_ably_does(): + assert _quote('a"b\\c\n\x01') == '"a\\"b\\\\c\\n\\u0001"' + # A lone surrogate becomes U+FFFD, as Ably does with invalid UTF-8. + assert _quote('x\ud800y') == '"x�y"' + assert _quote('😀') == '"😀"' + + +# ---- Sending ---- + +def random_id(): + return uuid.uuid4().hex[:8] + + +async def test_http_patch_message_sends_a_patch(): + channel_name = f'test-patch-{random_id()}' + captured = [] + + def on_request(request): + captured.append(request) + request.respond_with(200, {'versionSerial': 'v2'}) + + mock_http = MockHttpClient(on_connection_attempt=lambda conn: conn.respond_with_success(), + on_request=on_request) + channel = rest_client(mock_http).channels.get(channel_name) + + patches = MessagePatches( + data=[MessagePatchDataOperation('append', path='/text', data='lo')], + extras=MessagePatchExtras(headers=[MessagePatchHeaderOperation('set', 'stage', 'done')]), + ) + result = await channel.patch_message( + Message(serial='s1', patches=patches), + operation=MessageOperation(description='streamed'), + params={'key': 'value'}, + ) + + assert result.version_serial == 'v2' + request = captured[0] + assert request.method == 'PATCH' + assert request.url.path == f'/channels/{channel_name}/messages/s1' + assert request.url.query_params['key'] == 'value' + body = msgpack.unpackb(request.body) + assert body['action'] == 6 + assert body['serial'] == 's1' + assert body['version'] == {'description': 'streamed'} + assert body['patches'] == {'data': [{'op': 'append', 'path': '/text', 'data': 'lo'}], + 'extras': {'headers': [{'op': 'set', 'key': 'stage', 'value': 'done'}]}} + assert 'data' not in body + + +async def test_patch_message_without_a_serial_fails_before_any_request(): + captured = [] + mock_http = MockHttpClient(on_connection_attempt=lambda conn: conn.respond_with_success(), + on_request=captured.append) + channel = rest_client(mock_http).channels.get(f'test-patch-{random_id()}') + + with pytest.raises(AblyException) as e: + await channel.patch_message(Message(serial='', patches=MessagePatches( + data=[MessagePatchDataOperation('append', path='/text', data='x')]))) + + assert e.value.code == 40003 + assert captured == [] + + +async def test_realtime_patch_message_sends_a_message_with_the_patch(): + channel_name = f'test-patch-{random_id()}' + captured = [] + mock_ws = MockWebSocket(on_connection_attempt=lambda conn: conn.respond_with_success( + connected_message('connection-id', connectionKey='connection-key'))) + + def on_message_from_client(msg): + captured.append(msg) + if msg.get('action') == ProtocolMessageAction.ATTACH: + mock_ws.send_to_client(attached_message(channel_name)) + elif msg.get('action') == ProtocolMessageAction.MESSAGE: + mock_ws.send_to_client({'action': 1, 'msgSerial': msg['msgSerial'], 'count': 1, + 'res': [{'serials': ['v2']}]}) + + mock_ws.on_message_from_client = on_message_from_client + client = realtime_client(mock_ws) + channel = client.channels.get(channel_name) + client.connect() + await await_connection_state(client, ConnectionState.CONNECTED) + await channel.attach() + + result = await channel.patch_message(Message(serial='s1', patches=MessagePatches( + data=[MessagePatchDataOperation('set', path='/done', data=True)]))) + + assert result.version_serial == 'v2' + sent = [msg for msg in captured if msg.get('action') == ProtocolMessageAction.MESSAGE][-1] + message = sent['messages'][0] + assert (message['action'], message['serial']) == (6, 's1') + assert message['patches'] == {'data': [{'op': 'set', 'path': '/done', 'data': 'true', 'encoding': 'json'}]} + await client.close() + + +def test_a_received_patch_round_trips_through_its_wire_form(): + """What a publisher sends is what a subscriber decodes and applies.""" + wire = Message(serial='s1', action=MessageAction.MESSAGE_PATCH, + patches=MessagePatches(data=[MessagePatchDataOperation('append', path='/text', data='lo'), + MessagePatchDataOperation('set', path='/n', data=2)])).as_dict() + received = Message.from_encoded(json.loads(json.dumps({**wire, 'version': {'serial': 'v2'}}))) + + assert isinstance(received.patches, MessagePatches) + assert decode(data='{"text":"Hel"}', encoding='json').apply_patch(received).data == {'text': 'Hello', 'n': 2} diff --git a/test/unit/pubsub_server_test.py b/test/unit/pubsub_server_test.py index bfac982f..8df8a306 100644 --- a/test/unit/pubsub_server_test.py +++ b/test/unit/pubsub_server_test.py @@ -223,6 +223,12 @@ def test_liveobjects_names_are_all_importable(self): ('Message', 'ably.pubsub.types.message', 'Message'), ('MessageAction', 'ably.pubsub.types.message', 'MessageAction'), ('MessageOperation', 'ably.pubsub.types.operations', 'MessageOperation'), + ('MessagePatchDataOperation', 'ably.pubsub.types.messagepatch', 'MessagePatchDataOperation'), + ('MessagePatchExtras', 'ably.pubsub.types.messagepatch', 'MessagePatchExtras'), + ('MessagePatchHeaderOperation', 'ably.pubsub.types.messagepatch', 'MessagePatchHeaderOperation'), + ('MessagePatchPrivilegedOperation', 'ably.pubsub.types.messagepatch', 'MessagePatchPrivilegedOperation'), + ('MessagePatchUserClaimOperation', 'ably.pubsub.types.messagepatch', 'MessagePatchUserClaimOperation'), + ('MessagePatches', 'ably.pubsub.types.messagepatch', 'MessagePatches'), ('MessageVersion', 'ably.pubsub.types.message', 'MessageVersion'), ('Options', 'ably.pubsub.types.options', 'Options'), ('PaginatedResult', 'ably.pubsub.request.paginatedresult', 'PaginatedResult'), @@ -319,6 +325,12 @@ def test_liveobjects_names_are_all_importable(self): 'Message', 'MessageAction', 'MessageOperation', + 'MessagePatchDataOperation', + 'MessagePatchExtras', + 'MessagePatchHeaderOperation', + 'MessagePatchPrivilegedOperation', + 'MessagePatchUserClaimOperation', + 'MessagePatches', 'MessageVersion', 'Options', 'PaginatedResultSync', diff --git a/test/uts/deviations.md b/test/uts/deviations.md index c86c460e..46dc35ef 100644 --- a/test/uts/deviations.md +++ b/test/uts/deviations.md @@ -24,24 +24,24 @@ One Test ID can become more than one derived test: five Test IDs in `rest/unit` `error_types_test.py`, `fallback_test.py`, `rest_client_test.py` (two) and `paginated_result_test.py` — assert several independent things under a single id, and the derivation writes a function for each rather than one function with an unrelated -second half. That turns 1472 Test IDs into 1481 derived tests. Going the other way, one +second half. That turns 1503 Test IDs into 1512 derived tests. Going the other way, one derived test can become more than one case: five of the twelve `rest/integration` specifications, five of the twenty `realtime/integration` ones and the three `objects/integration` ones outside `proxy` carry a `## Protocol Variants` section and run every one of their tests twice, once per protocol; nine `rest/unit` tests are parametrized over a table of fixtures the specification gives inline; and five `objects/unit` tests are parametrized, three over a table and two over the scenarios the -specification loops through. That turns 1481 derived tests into 1608 pytest cases. +specification loops through. That turns 1512 derived tests into 1639 pytest cases. -Of **1472 Test IDs, derived as 1481 tests and run as 1608 pytest cases**: 1304 Test IDs -(1313 tests, 1438 cases) pass, 141 (141 tests, 143 cases) are gated behind +Of **1503 Test IDs, derived as 1512 tests and run as 1639 pytest cases**: 1335 Test IDs +(1344 tests, 1469 cases) pass, 141 (141 tests, 143 cases) are gated behind `RUN_DEVIATIONS`, and 27 (27 tests, 27 cases) cannot be run at all. The three groups are disjoint: two Test IDs have a gated part and a passing part — `TI1`, as two functions, and `TO/endpoint-affects-host`, as one parametrized test — and are counted with the gated, while their passing parts count among the passing tests and cases. Every gated test has -been confirmed to fail when enabled, so none of them passes under both behaviours. 494 of -the Test IDs come from `uts/rest/unit` (503 tests, 536 cases), 482 from -`uts/realtime/unit` (482, 482), 322 from `uts/objects/unit` (322, 344), 84 from +been confirmed to fail when enabled, so none of them passes under both behaviours. 521 of +the Test IDs come from `uts/rest/unit` (530 tests, 563 cases), 486 from +`uts/realtime/unit` (486, 486), 322 from `uts/objects/unit` (322, 344), 84 from `uts/rest/integration` (84, 122), 73 from `uts/realtime/integration` (73, 95) and 17 from `uts/objects/integration` (17, 29); 8 of the REST integration ids (8, 8), 30 of the realtime ones (30, 30) and 5 of the objects ones (5, 5) come from the `proxy` package @@ -3377,16 +3377,16 @@ The header states how many derived tests there are, how many pass, how many are gated and how many cannot run. Those numbers are the check that the file is still true: in pytest cases, the gated count must equal the number of failures under `RUN_DEVIATIONS=1`, and gated plus unrunnable must equal the number of skips without -it. As of this writing that is 143 failures, 1586 passes and 27 skips with the variable -set, and 170 skips and 1586 passes without it, the 1586 being 1438 derived cases and 148 +it. As of this writing that is 143 failures, 1617 passes and 27 skips with the variable +set, and 170 skips and 1617 passes without it, the 1617 being 1469 derived cases and 148 harness ones — 130 under `helpers/` and 18 under `objects/helpers/`. Those figures need the `submodules` checkout CI makes: without it, three `rest/unit/encoding` tests that read the ably-common fixtures skip as well. The tiers are told apart by the junit report's `classname`, `test.uts..`, with `proxy` the package within an integration tier. The other two counts are measured from the source rather than from a run. The number of -**derived tests** is the number of `# UTS:` comments, 1481. The number of **Test IDs** is -the number of *distinct* ids in them, 1472 — not the same figure, because five ids in +**derived tests** is the number of `# UTS:` comments, 1512. The number of **Test IDs** is +the number of *distinct* ids in them, 1503 — not the same figure, because five ids in `rest/unit` are carried by more than one test function. Counting the comments and calling the result Test IDs is the easy mistake here, and it overstates the specification coverage by nine. The other is to gate or un-gate a test, record it in the body, and leave the diff --git a/test/uts/realtime/unit/channels/channel_patch_message_test.py b/test/uts/realtime/unit/channels/channel_patch_message_test.py new file mode 100644 index 00000000..2c9c49b2 --- /dev/null +++ b/test/uts/realtime/unit/channels/channel_patch_message_test.py @@ -0,0 +1,282 @@ +"""Derived from uts/realtime/unit/channels/channel_patch_message.md in ably/specification. + +Spec points: RTL32, RTL32b, RTL32b1, RTL32d, RTL32f, MPD3, MPD4, MPD4a, TM2v, TM9 + +A patch is a MESSAGE protocol message and so requires an ACK; the mock answers each one, as the +specification's own handlers do, with the ACK's `res` wrapped in an array, one entry per +ProtocolMessage. The two publishing tests deliberately do not attach the channel, and their mock does +not answer ATTACH: like a publish, a patch is sent on an INITIALIZED channel. + +The specification's `extras: { "headers": [...] }` is `MessagePatchExtras(headers=[...])`, and +`Message.applyPatch(message, patch)` is the instance method `Message.apply_patch`, called through the class. +""" + +import json +import uuid + +from ably.pubsub.realtime.connection import ConnectionState +from ably.pubsub.transport.websockettransport import ProtocolMessageAction +from ably.pubsub.types.channelstate import ChannelState +from ably.pubsub.types.message import Message, MessageAction +from ably.pubsub.types.messagepatch import ( + MessagePatchDataOperation, + MessagePatches, + MessagePatchExtras, + MessagePatchHeaderOperation, +) +from ably.pubsub.types.operations import UpdateDeleteResult +from test.uts.helpers.client import await_connection_state, poll_until, realtime_client +from test.uts.helpers.mock_websocket import ( + MockWebSocket, + ack, + attached_message, + connected_message, + message_protocol_message, +) + +CONNECTED_MESSAGE = connected_message('connection-id', connectionKey='connection-key') + + +def random_id(): + return uuid.uuid4().hex[:8] + + +def acking_mock(captured_messages): + """A mock which connects and ACKs each MESSAGE, and does not answer ATTACH.""" + mock_ws = MockWebSocket( + on_connection_attempt=lambda conn: conn.respond_with_success(CONNECTED_MESSAGE), + ) + + def on_message_from_client(msg): + captured_messages.append(msg) + if msg.get('action') == ProtocolMessageAction.MESSAGE: + mock_ws.send_to_client(ack(msg, serials=['version-serial-1'])) + + mock_ws.on_message_from_client = on_message_from_client + return mock_ws + + +def attaching_mock(channel_name): + """A mock which connects and attaches `channel_name`.""" + mock_ws = MockWebSocket( + on_connection_attempt=lambda conn: conn.respond_with_success(CONNECTED_MESSAGE), + ) + + def on_message_from_client(msg): + if msg.get('action') == ProtocolMessageAction.ATTACH: + mock_ws.send_to_client(attached_message(channel_name)) + + mock_ws.on_message_from_client = on_message_from_client + return mock_ws + + +def last_message_pm(captured_messages): + message_pm = None + for pm in captured_messages: + if pm.get('action') == ProtocolMessageAction.MESSAGE: + message_pm = pm + return message_pm + + +# UTS: realtime/unit/RTL32b1/patch-message-action-0 +async def test_rtl32b1_patch_message_action(): + channel_name = f'test-RTL32-patch-{random_id()}' + captured_messages = [] + mock_ws = acking_mock(captured_messages) + client = realtime_client(mock_ws, use_binary_protocol=False) + channel = client.channels.get(channel_name) + + client.connect() + await await_connection_state(client, ConnectionState.CONNECTED) + + result = await channel.patch_message( + Message( + serial='msg-serial-1', + patches=MessagePatches( + data=[MessagePatchDataOperation(op='append', path='/text', data='lo')], + extras=MessagePatchExtras(headers=[ + MessagePatchHeaderOperation(op='set', key='status', value='complete'), + ]), + ), + ), + ) + + message_pm = last_message_pm(captured_messages) + assert message_pm is not None + + assert message_pm['channel'] == channel_name + assert len(message_pm['messages']) == 1 + + msg = message_pm['messages'][0] + assert msg['action'] == 6 # MESSAGE_PATCH numeric value + assert msg['serial'] == 'msg-serial-1' + assert msg['patches']['data'] == [{'op': 'append', 'path': '/text', 'data': 'lo'}] + assert msg['patches']['extras']['headers'] == [{'op': 'set', 'key': 'status', 'value': 'complete'}] + + assert isinstance(result, UpdateDeleteResult) + assert result.version_serial == 'version-serial-1' + + # The patch was sent without attaching the channel + assert not any(pm.get('action') == ProtocolMessageAction.ATTACH for pm in captured_messages) + assert channel.state == ChannelState.INITIALIZED + + +# UTS: realtime/unit/RTL32f/patch-values-encoded-0 +async def test_rtl32f_patch_values_encoded(): + channel_name = f'test-RTL32f-{random_id()}' + captured_messages = [] + mock_ws = acking_mock(captured_messages) + client = realtime_client(mock_ws, use_binary_protocol=False) + channel = client.channels.get(channel_name) + + client.connect() + await await_connection_state(client, ConnectionState.CONNECTED) + + await channel.patch_message( + Message( + serial='s1', + patches=MessagePatches(data=[ + MessagePatchDataOperation(op='set', path='/obj', data={'b': 1}), + MessagePatchDataOperation(op='set', path='/bin', data=bytes([0x01, 0x02])), + MessagePatchDataOperation(op='set', path='/done', data=True), + ]), + ), + ) + + message_pm = last_message_pm(captured_messages) + + ops = message_pm['messages'][0]['patches']['data'] + assert json.loads(ops[0]['data']) == {'b': 1} + assert ops[0]['encoding'] == 'json' + assert ops[1]['data'] == 'AQI=' + assert ops[1]['encoding'] == 'base64' + assert ops[2]['data'] == 'true' + assert ops[2]['encoding'] == 'json' + + +# UTS: realtime/unit/MPD4/patch-received-decoded-0 +async def test_mpd4_patch_received_decoded(): + channel_name = f'test-MPD4-{random_id()}' + mock_ws = attaching_mock(channel_name) + client = realtime_client(mock_ws, use_binary_protocol=False) + channel = client.channels.get(channel_name) + received = [] + + def on_message(msg): + received.append(msg) + + client.connect() + await await_connection_state(client, ConnectionState.CONNECTED) + await channel.subscribe(on_message) + + mock_ws.send_to_client(message_protocol_message( + channel_name, + [{ + 'action': 6, + 'serial': 'msg-serial-1', + 'version': {'serial': 'version-serial-2', 'timestamp': 1700000002000}, + 'patches': { + 'data': [ + {'op': 'set', 'path': '/a', 'data': '{"b":1}', 'encoding': 'json'}, + {'op': 'set', 'path': '/c', 'data': 'AQI=', 'encoding': 'base64'}, + {'op': 'append', 'path': '/d', 'data': 'text'}, + ], + 'extras': {'headers': [{'op': 'set', 'key': 'status', 'value': 'complete'}]}, + }, + }], + id='conn:0', + timestamp=1700000002000, + )) + await poll_until(lambda: len(received) == 1, description='the patch is delivered') + + msg = received[0] + assert msg.action == MessageAction.MESSAGE_PATCH + assert msg.serial == 'msg-serial-1' + assert msg.version.serial == 'version-serial-2' + + ops = msg.patches.data + assert len(ops) == 3 + + # MPD4a — JSON value stays as JSON text + assert ops[0].op == 'set' + assert ops[0].path == '/a' + assert ops[0].data == '{"b":1}' + assert ops[0].encoding == 'json' + + # MPD4 — Base64 is decoded to binary, leaving no encoding + assert ops[1].data == bytes([0x01, 0x02]) + assert ops[1].encoding is None or ops[1].encoding == '' + + assert ops[2].data == 'text' + assert ops[2].encoding is None or ops[2].encoding == '' + + assert msg.patches.extras.headers[0].op == 'set' + assert msg.patches.extras.headers[0].key == 'status' + assert msg.patches.extras.headers[0].value == 'complete' + + +# UTS: realtime/unit/TM9/subscriber-applies-patch-0 +async def test_tm9_subscriber_applies_patch(): + channel_name = f'test-TM9-subscriber-{random_id()}' + mock_ws = attaching_mock(channel_name) + client = realtime_client(mock_ws, use_binary_protocol=False) + channel = client.channels.get(channel_name) + + patched_message = None + patches_applied = 0 + + def on_message(msg): + nonlocal patched_message, patches_applied + if msg.action == MessageAction.MESSAGE_CREATE: + patched_message = msg + elif msg.action == MessageAction.MESSAGE_PATCH: + patched_message = Message.apply_patch(patched_message, msg) + patches_applied += 1 + + client.connect() + await await_connection_state(client, ConnectionState.CONNECTED) + await channel.subscribe(on_message) + + def send_message(msg_serial, wire_message): + mock_ws.send_to_client(message_protocol_message( + channel_name, + [wire_message], + id='conn:' + msg_serial, + timestamp=1700000000000, + )) + + send_message('0', { + 'action': 0, + 'serial': 'msg-serial-1', + 'clientId': 'author', + 'name': 'reply', + 'data': '{"text":"Hel","toolCalls":[]}', + 'encoding': 'json', + }) + send_message('1', { + 'action': 6, + 'serial': 'msg-serial-1', + 'clientId': 'patcher', + 'version': {'serial': 'version-serial-2', 'timestamp': 1700000001000}, + 'patches': {'data': [{'op': 'append', 'path': '/text', 'data': 'lo'}]}, + }) + send_message('2', { + 'action': 6, + 'serial': 'msg-serial-1', + 'version': {'serial': 'version-serial-3', 'timestamp': 1700000002000}, + 'patches': { + 'data': [{'op': 'set', 'path': '/toolCalls/-', 'data': '{"name":"search"}', 'encoding': 'json'}], + 'extras': {'headers': [{'op': 'set', 'key': 'status', 'value': 'complete'}]}, + }, + }) + await poll_until(lambda: patches_applied == 2, description='both patches are applied') + + assert patched_message.action == MessageAction.MESSAGE_UPDATE + assert patched_message.serial == 'msg-serial-1' + assert patched_message.version.serial == 'version-serial-3' + assert patched_message.data == {'text': 'Hello', 'toolCalls': [{'name': 'search'}]} + assert patched_message.extras['headers'] == {'status': 'complete'} + + # Kept from the MESSAGE_CREATE, not taken from the patches + assert patched_message.client_id == 'author' + assert patched_message.name == 'reply' diff --git a/test/uts/rest/unit/channel/patch_message_test.py b/test/uts/rest/unit/channel/patch_message_test.py new file mode 100644 index 00000000..a87b6f61 --- /dev/null +++ b/test/uts/rest/unit/channel/patch_message_test.py @@ -0,0 +1,206 @@ +"""Derived from uts/rest/unit/channel/patch_message.md in ably/specification. + +Spec points: RSL15, RSL15a, RSL15b, RSL15b1, RSL15c, RSL15e, RSL15g, MPD3, MPD3a, MPD3b, MPD3c, MPD3d + +The specification's `extras: { "headers": [...] }` is `MessagePatchExtras(headers=[...])`. +""" + +import json +import uuid + +import msgpack +import pytest + +from ably.pubsub.types.message import Message, MessageAction +from ably.pubsub.types.messagepatch import ( + MessagePatchDataOperation, + MessagePatches, + MessagePatchExtras, + MessagePatchHeaderOperation, +) +from ably.pubsub.types.operations import UpdateDeleteResult +from ably.pubsub.util.exceptions import AblyException +from test.uts.helpers.client import rest_client +from test.uts.helpers.mock_http import MockHttpClient + + +def random_id(): + return uuid.uuid4().hex[:8] + + +def capture_and_respond(captured_requests): + def on_request(request): + captured_requests.append(request) + request.respond_with(200, {'versionSerial': 'vs1'}) + + return on_request + + +def patching_channel(channel_name, captured_requests, **kwargs): + mock_http = MockHttpClient( + on_connection_attempt=lambda conn: conn.respond_with_success(), + on_request=capture_and_respond(captured_requests), + ) + client = rest_client(mock_http, **kwargs) + return client.channels.get(channel_name) + + +# UTS: rest/unit/RSL15b1/patch-sends-patch-action-0 +async def test_rsl15b1_patch_sends_patch_action(): + channel_name = f'test-RSL15-patch-{random_id()}' + captured_requests = [] + channel = patching_channel(channel_name, captured_requests, use_binary_protocol=False) + + result = await channel.patch_message( + Message( + serial='msg-serial-1', + patches=MessagePatches( + data=[ + MessagePatchDataOperation(op='append', path='/content/0/text', data=' more text'), + ], + extras=MessagePatchExtras(headers=[ + MessagePatchHeaderOperation(op='set', key='status', value='complete'), + MessagePatchHeaderOperation(op='remove', key='draft'), + ]), + ), + ), + ) + + assert len(captured_requests) == 1 + + request = captured_requests[0] + assert request.method == 'PATCH' + assert request.url.path == f'/channels/{channel_name}/messages/msg-serial-1' + + body = json.loads(request.body) + assert body['action'] == 6 # MESSAGE_PATCH numeric value + assert body['serial'] == 'msg-serial-1' + assert body['patches']['data'] == [ + {'op': 'append', 'path': '/content/0/text', 'data': ' more text'}, + ] + assert body['patches']['extras']['headers'] == [ + {'op': 'set', 'key': 'status', 'value': 'complete'}, + {'op': 'remove', 'key': 'draft'}, + ] + + assert isinstance(result, UpdateDeleteResult) + assert result.version_serial == 'vs1' + + +# UTS: rest/unit/RSL15g/patch-values-encoded-json-0 +async def test_rsl15g_patch_values_encoded_json(): + channel_name = f'test-RSL15g-json-{random_id()}' + captured_requests = [] + channel = patching_channel(channel_name, captured_requests, use_binary_protocol=False) + + await channel.patch_message( + Message( + serial='s1', + patches=MessagePatches(data=[ + MessagePatchDataOperation(op='append', path='/text', data='lo'), + MessagePatchDataOperation(op='set', path='/bin', data=bytes([0x01, 0x02])), + MessagePatchDataOperation(op='set', path='/obj', data={'b': 1}), + MessagePatchDataOperation(op='set', path='/list/-', data=[1, 2]), + MessagePatchDataOperation(op='set', path='/count', data=42), + MessagePatchDataOperation(op='set', path='/done', data=True), + MessagePatchDataOperation(op='set', path='/cleared', data=None), + MessagePatchDataOperation(op='remove', path='/old'), + ]), + ), + ) + + ops = json.loads(captured_requests[0].body)['patches']['data'] + assert len(ops) == 8 + + # MPD3a — string unchanged + assert ops[0] == {'op': 'append', 'path': '/text', 'data': 'lo'} + + # MPD3b — binary as Base64 + assert ops[1]['data'] == 'AQI=' + assert ops[1]['encoding'] == 'base64' + + # MPD3c — every other JSON value as JSON text + assert isinstance(ops[2]['data'], str) + assert json.loads(ops[2]['data']) == {'b': 1} + assert ops[2]['encoding'] == 'json' + assert json.loads(ops[3]['data']) == [1, 2] + assert ops[3]['encoding'] == 'json' + assert ops[4]['data'] == '42' + assert ops[4]['encoding'] == 'json' + assert ops[5]['data'] == 'true' + assert ops[5]['encoding'] == 'json' + assert ops[6]['data'] == 'null' + assert ops[6]['encoding'] == 'json' + + # MPD3d — no data, no encoding + assert ops[7] == {'op': 'remove', 'path': '/old'} + + +# UTS: rest/unit/RSL15g/patch-values-encoded-msgpack-1 +async def test_rsl15g_patch_values_encoded_msgpack(): + channel_name = f'test-RSL15g-msgpack-{random_id()}' + captured_requests = [] + channel = patching_channel(channel_name, captured_requests, use_binary_protocol=True) + + await channel.patch_message( + Message( + serial='s1', + patches=MessagePatches(data=[ + MessagePatchDataOperation(op='append', path='/text', data='lo'), + MessagePatchDataOperation(op='set', path='/bin', data=bytes([0x01, 0x02])), + MessagePatchDataOperation(op='set', path='/count', data=42), + ]), + ), + ) + + body = msgpack.unpackb(captured_requests[0].body) + assert body['action'] == 6 + ops = body['patches']['data'] + + assert ops[0]['data'] == 'lo' + assert 'encoding' not in ops[0] or ops[0]['encoding'] is None + + # Binary transmitted directly, no Base64 + assert ops[1]['data'] == bytes([0x01, 0x02]) + assert 'encoding' not in ops[1] or ops[1]['encoding'] is None + + # JSON value as a MessagePack string + assert isinstance(ops[2]['data'], str) + assert ops[2]['data'] == '42' + assert ops[2]['encoding'] == 'json' + + +# UTS: rest/unit/RSL15c/patch-no-mutate-message-0 +async def test_rsl15c_patch_no_mutate_message(): + channel_name = f'test-RSL15c-patch-{random_id()}' + channel = patching_channel(channel_name, [], use_binary_protocol=False) + + object_op = MessagePatchDataOperation(op='set', path='/obj', data={'b': 1}) + binary_op = MessagePatchDataOperation(op='set', path='/bin', data=bytes([0x01, 0x02])) + message = Message( + serial='s1', + patches=MessagePatches(data=[object_op, binary_op]), + ) + + await channel.patch_message(message) + + assert message.action is None or message.action == MessageAction.MESSAGE_CREATE + assert len(message.patches.data) == 2 + assert message.patches.data[0].data == {'b': 1} + assert message.patches.data[0].encoding is None or message.patches.data[0].encoding == '' + assert message.patches.data[1].data == bytes([0x01, 0x02]) + assert message.patches.data[1].encoding is None or message.patches.data[1].encoding == '' + + +# UTS: rest/unit/RSL15a/patch-serial-required-0 +async def test_rsl15a_patch_serial_required(): + captured_requests = [] + channel = patching_channel(f'test-RSL15a-patch-{random_id()}', captured_requests) + + with pytest.raises(AblyException) as excinfo: + await channel.patch_message(Message( + patches=MessagePatches(data=[MessagePatchDataOperation(op='append', path='/text', data='x')]), + )) + assert excinfo.value.code == 40003 + + assert len(captured_requests) == 0 diff --git a/test/uts/rest/unit/types/message_apply_patch_test.py b/test/uts/rest/unit/types/message_apply_patch_test.py new file mode 100644 index 00000000..97127b7d --- /dev/null +++ b/test/uts/rest/unit/types/message_apply_patch_test.py @@ -0,0 +1,398 @@ +"""Derived from uts/rest/unit/types/message_apply_patch.md in ably/specification. + +Spec points: TM9, TM9a, TM9b, TM9c, TM9d, TM9d1-TM9d4, TM9e, TM9f, TM9f1-TM9f5, TM9g, TM9g1-TM9g4 + +`Message.applyPatch(message, patch)` is the instance method `Message.apply_patch`, called here through +the class so that it reads as the specification's static function. `fromEncoded` is spelled +`from_encoded`, and `toJson` is spelled `as_dict`. Binary data decodes to a `bytearray`, which +compares equal to the `bytes` the specification writes. +""" + +import base64 +import json + +import pytest + +from ably.pubsub.types.message import Message, MessageAction +from ably.pubsub.util.exceptions import AblyException + + +def decode(**values): + return Message.from_encoded({'serial': 's1', 'timestamp': 1, **values}) + + +def decode_patch(patches, **values): + return decode(**{ + 'action': 6, # MESSAGE_PATCH + 'version': {'serial': 'v2', 'timestamp': 2}, + 'patches': patches, + **values, + }) + + +def assert_apply_fails(message, patch, description=''): + """`Message.applyPatch(message, patch) FAILS WITH error`, with the 40000/400 every failure carries.""" + with pytest.raises(AblyException) as excinfo: + Message.apply_patch(message, patch) + assert excinfo.value.code == 40000, description + assert excinfo.value.status_code == 400, description + + +# UTS: rest/unit/TM9f3/apply-to-decoded-data-0 +def test_tm9f3_apply_to_decoded_data(): + message = decode( + name='reply', + data='{"content":[{"type":"text","text":"Hel"}],"meta":{"kept":true}}', + encoding='json', + extras={'headers': {'status': 'streaming', 'model': 'm1'}}, + ) + patch = decode_patch({ + 'data': [ + {'op': 'append', 'path': '/content/0/text', 'data': 'lo'}, + {'op': 'set', 'path': '/content/-', 'data': '{"type":"tool"}', 'encoding': 'json'}, + {'op': 'set', 'path': '/done', 'data': 'true', 'encoding': 'json'}, + ], + 'extras': { + 'headers': [ + {'op': 'set', 'key': 'status', 'value': 'complete'}, + {'op': 'remove', 'key': 'model'}, + ], + }, + }) + + patched = Message.apply_patch(message, patch) + + assert patched.action == MessageAction.MESSAGE_UPDATE + assert patched.serial == 's1' + assert patched.name == 'reply' + assert patched.version.serial == 'v2' + assert patched.data == { + 'content': [{'type': 'text', 'text': 'Hello'}, {'type': 'tool'}], + 'meta': {'kept': True}, + 'done': True, + } + assert patched.encoding is None or patched.encoding == '' + assert patched.extras == {'headers': {'status': 'complete'}} + assert patched.patches is None + assert isinstance(patched, Message) + + +# UTS: rest/unit/TM9d/keeps-message-fields-0 +def test_tm9d_keeps_message_fields(): + message = decode(clientId='author', connectionId='c1', data='Hel') + patch = decode_patch( + {'data': [{'op': 'append', 'data': 'lo'}]}, + clientId='patcher', connectionId='c2', timestamp=2, + ) + + patched = Message.apply_patch(message, patch) + + assert patched.client_id == 'author' + assert patched.connection_id == 'c1' + assert patched.timestamp == 1 + assert patched.version.serial == 'v2' + assert patched.data == 'Hello' + + +# UTS: rest/unit/TM9c/message-not-mutated-0 +def test_tm9c_message_not_mutated(): + message = decode( + action=0, # MESSAGE_CREATE + data='{"a":{"text":"x"},"b":{"unchanged":true},"list":[1]}', + encoding='json', + extras={'headers': {'h': 'v'}}, + ) + before = message.as_dict() + patch = decode_patch({ + 'data': [ + {'op': 'append', 'path': '/a/text', 'data': 'y'}, + {'op': 'set', 'path': '/list/-', 'data': '2', 'encoding': 'json'}, + ], + 'extras': {'headers': [{'op': 'set', 'key': 'h', 'value': 'w'}]}, + }) + + patched = Message.apply_patch(message, patch) + + assert message.as_dict() == before + assert message.action == MessageAction.MESSAGE_CREATE + assert message.data == {'a': {'text': 'x'}, 'b': {'unchanged': True}, 'list': [1]} + assert message.extras == {'headers': {'h': 'v'}} + + assert patched.data == {'a': {'text': 'xy'}, 'b': {'unchanged': True}, 'list': [1, 2]} + assert patched.extras == {'headers': {'h': 'w'}} + + +# UTS: rest/unit/TM9f5/splice-into-json-text-0 +def test_tm9f5_splice_into_json_text(): + text = '{ "content" : [ {"text":"Hel"} ], "n": 1.0 }' + message = decode(data=text) + patch = decode_patch({ + 'data': [ + {'op': 'append', 'path': '/content/0/text', 'data': 'lo "world"'}, + {'op': 'set', 'path': '/obj', 'data': '{ "spaced" : 1 }', 'encoding': 'json'}, + {'op': 'set', 'path': '/content/-', 'data': 'end'}, + ], + }) + + patched = Message.apply_patch(message, patch) + + assert isinstance(patched.data, str) + assert patched.data == ( + '{ "content" : [ {"text":"Hello \\"world\\""},"end" ], "n": 1.0,"obj":{ "spaced" : 1 } }' + ) + assert patched.encoding is None or patched.encoding == '' + + +# UTS: rest/unit/TM9f5/splice-into-binary-json-1 +def test_tm9f5_splice_into_binary_json(): + text = '{ "content" : [ {"text":"Hel"} ] }' + message = decode(data=base64.b64encode(text.encode('utf-8')).decode('ascii'), encoding='base64') + patch = decode_patch({ + 'data': [{'op': 'append', 'path': '/content/0/text', 'data': 'lo'}], + }) + + patched = Message.apply_patch(message, patch) + + assert isinstance(patched.data, (bytes, bytearray)) + assert bytes(patched.data).decode('utf-8') == '{ "content" : [ {"text":"Hello"} ] }' + + +# UTS: rest/unit/TM9f5f/remove-from-json-text-0 +def test_tm9f5f_remove_from_json_text(): + patch = decode_patch({ + 'data': [ + {'op': 'remove', 'path': '/a/1'}, + {'op': 'remove', 'path': '/b'}, + {'op': 'remove', 'path': '/c'}, + {'op': 'remove', 'path': '/d/only'}, + ], + }) + message = Message(serial='s1', data='{"a":[1,2,3],"b":2,"c":3,"d":{"only":true}}') + + patched = Message.apply_patch(message, patch) + + # /a/1: element 2 is followed by 3, so deleted up to it (TM9f5f) + # /b and then /c: each is followed by another member, so deleted up to it (TM9f5f) + # /d/only: the only member of "d", so its text is deleted (TM9f5h) + assert patched.data == '{"a":[1,3],"d":{}}' + + # Last of several + message2 = Message(serial='s1', data='{"a":1, "b":2}') + patch2 = decode_patch({'data': [{'op': 'remove', 'path': '/b'}]}) + + patched2 = Message.apply_patch(message2, patch2) + + # TM9f5g: deleted from the end of 1, the previous value + assert patched2.data == '{"a":1}' + + +# UTS: rest/unit/TM9f5i/escaped-member-name-0 +def test_tm9f5i_escaped_member_name(): + message = decode(data='{"a\\u0062":"x","c/d":"y"}') + patch = decode_patch({ + 'data': [ + {'op': 'append', 'path': '/ab', 'data': '1'}, + {'op': 'append', 'path': '/c~1d', 'data': '2'}, + ], + }) + + patched = Message.apply_patch(message, patch) + + assert patched.data == '{"a\\u0062":"x1","c/d":"y2"}' + + +# UTS: rest/unit/TM9f5e/json-string-escaping-0 +def test_tm9f5e_json_string_escaping(): + appended = 'q"b\\n\nt\tc\u0001é<>&' + message = decode(data='{"t":""}') + patch = decode_patch({ + 'data': [ + {'op': 'append', 'path': '/t', 'data': appended}, + {'op': 'set', 'path': '/new\nkey', 'data': 'v'}, + ], + }) + + patched = Message.apply_patch(message, patch) + + assert isinstance(patched.data, str) + assert json.loads(patched.data) == {'t': appended, 'new\nkey': 'v'} + assert patched.data.startswith('{"t":"q') + assert patched.data.endswith('"}') + + +# UTS: rest/unit/TM9f2/apply-to-whole-data-0 +def test_tm9f2_apply_to_whole_data(): + append = decode_patch({'data': [{'op': 'append', 'data': ' world'}]}) + + # TM9f2c — string + assert Message.apply_patch(decode(data='hello'), append).data == 'hello world' + + # TM9f2b — absent data + appended = Message.apply_patch(decode(), append) + assert appended.data == ' world' + assert appended.encoding is None or appended.encoding == '' + + # TM9f2c — binary + append_binary = decode_patch({'data': [{'op': 'append', 'data': 'Aw==', 'encoding': 'base64'}]}) + binary = decode(data='AQI=', encoding='base64') + assert Message.apply_patch(binary, append_binary).data == bytes([0x01, 0x02, 0x03]) + + # TM9f2a — set to a JSON value + set_json = decode_patch({'data': [{'op': 'set', 'data': '{"a":1}', 'encoding': 'json'}]}) + patched = Message.apply_patch(decode(data='hello'), set_json) + assert patched.data == {'a': 1} + assert patched.encoding is None or patched.encoding == '' + + # TM9f2a — set to a string + set_string = decode_patch({'data': [{'op': 'set', 'data': 'replaced'}]}) + assert Message.apply_patch(decode(data='{"a":1}', encoding='json'), set_string).data == 'replaced' + + +# UTS: rest/unit/TM9f2d/append-whole-non-string-0 +def test_tm9f2d_append_whole_non_string(): + message = decode(data='{"a":1}', encoding='json') + + append = decode_patch({'data': [{'op': 'append', 'data': 'x'}]}) + assert_apply_fails(message, append) + + remove = decode_patch({'data': [{'op': 'remove'}]}) + assert_apply_fails(message, remove) + + # TM9f2b, TM9f2c — the operation's encoding must be empty + append_json = decode_patch({'data': [{'op': 'append', 'data': '"x"', 'encoding': 'json'}]}) + for target in [decode(), decode(data='text')]: + assert_apply_fails(target, append_json, f'append_json to {target.data!r}') + + # TM9f2a — a JSON scalar cannot replace the whole of data + for value in ['null', '1', 'true', '"s"']: + set_scalar = decode_patch({'data': [{'op': 'set', 'data': value, 'encoding': 'json'}]}) + assert_apply_fails(decode(data='hello'), set_scalar, f'set {value}') + + +# UTS: rest/unit/TM9e/atomic-rejection-0 +def test_tm9e_atomic_rejection(): + message = decode(data='{"a":"x"}', encoding='json', extras={'headers': {'h': 'v'}}) + patch = decode_patch({ + 'data': [ + {'op': 'append', 'path': '/a', 'data': 'y'}, + {'op': 'append', 'path': '/missing', 'data': 'y'}, + ], + 'extras': {'headers': [{'op': 'set', 'key': 'h', 'value': 'w'}]}, + }) + + assert_apply_fails(message, patch) + + assert message.data == {'a': 'x'} + assert message.extras == {'headers': {'h': 'v'}} + + +# UTS: rest/unit/TM9f3/invalid-operations-rejected-0 +def test_tm9f3_invalid_operations_rejected(): + cases = [ + # [data, operation] + [{'a': 1}, {'op': 'append', 'path': '/a', 'data': 'x'}], # TM9f3f: not a string + [{'a': []}, {'op': 'append', 'path': '/a/-', 'data': 'x'}], # TM9f3f: "-" + # TM9f3f: encoding not empty + [{'a': 'x'}, {'op': 'append', 'path': '/a', 'data': '"y"', 'encoding': 'json'}], + [{'a': []}, {'op': 'remove', 'path': '/a/-'}], # TM9f3g: "-" + [{'a': []}, {'op': 'set', 'path': '/a/0', 'data': 'x'}], # TM9f3e: no element 0 + [{'a': [1]}, {'op': 'set', 'path': '/a/01', 'data': 'x'}], # TM9f3e: leading zero is not an index + [{'a': 1}, {'op': 'set', 'path': '/a/b', 'data': 'x'}], # TM9f3c: parent is a number + [{'a': 1}, {'op': 'set', 'path': '/x/y', 'data': 'x'}], # TM9f3b: /x does not exist + [{'a': 1}, {'op': 'set', 'path': 'a', 'data': 'x'}], # TM9f3a: no leading "/" + [{'a': 1}, {'op': 'set', 'path': '/~2', 'data': 'x'}], # TM9f3a: invalid "~" escape + [{'a': 1}, {'op': 'remove', 'path': '/b'}], # TM9f3g: /b does not exist + [{'a': 1}, {'op': 'move', 'path': '/a'}], # TM9f1: unknown op + ] + + for data, op in cases: + for form, message in [ + ('decoded JSON', decode(data=json.dumps(data), encoding='json')), + ('JSON text', decode(data=json.dumps(data))), + ]: + patch = decode_patch({'data': [op]}) + assert_apply_fails(message, patch, f'{op} on {form} {data}') + + # TM9f3 — a path operation on data that is not a JSON object or array + not_container = decode(data='plain text') + patch = decode_patch({'data': [{'op': 'set', 'path': '/a', 'data': 'x'}]}) + with pytest.raises(AblyException) as excinfo: + Message.apply_patch(not_container, patch) + assert excinfo.value.code == 40000 + + +# UTS: rest/unit/TM9g1/remove-missing-header-0 +def test_tm9g1_remove_missing_header(): + message = decode(data='x') + patch = decode_patch({'extras': {'headers': [{'op': 'remove', 'key': 'h'}]}}) + + assert_apply_fails(message, patch) + + +# UTS: rest/unit/TM9g1/set-header-adds-extras-1 +def test_tm9g1_set_header_adds_extras(): + message = decode(data='x') + patch = decode_patch({'extras': {'headers': [{'op': 'set', 'key': 'status', 'value': 'done'}]}}) + + assert Message.apply_patch(message, patch).extras == {'headers': {'status': 'done'}} + + +# UTS: rest/unit/TM9g2/user-claim-operations-0 +def test_tm9g2_user_claim_operations(): + message = decode(data='x', extras={'headers': {'h': 'v'}, 'userClaim': 'moderator'}) + + set_claim = decode_patch( + {'data': [{'op': 'append', 'data': 'y'}], 'extras': {'userClaim': {'op': 'set', 'value': 'guest'}}}, + extras={'push': {'notification': {'title': 't'}}, 'userClaim': 'guest'}, + ) + patched = Message.apply_patch(message, set_claim) + assert patched.extras == {'headers': {'h': 'v'}, 'userClaim': 'guest'} + assert patched.version.serial == 'v2' + + remove = decode_patch({ + 'data': [{'op': 'append', 'data': 'y'}], + 'extras': {'userClaim': {'op': 'remove'}}, + }) + assert Message.apply_patch(message, remove).extras == {'headers': {'h': 'v'}} + + # Removing a missing claim succeeds, and leaves no extras (TM9g4) + unclaimed = decode(data='x') + assert Message.apply_patch(unclaimed, remove).extras is None + + +# UTS: rest/unit/TM9g3/privileged-remove-0 +def test_tm9g3_privileged_remove(): + message = decode(data='x', extras={'headers': {'h': 'v'}, 'privileged': {'skipRule': '*'}}) + patch = decode_patch({ + 'extras': { + 'headers': [{'op': 'set', 'key': 'h', 'value': 'w'}], + 'privileged': {'op': 'remove'}, + }, + }) + + assert Message.apply_patch(message, patch).extras == {'headers': {'h': 'w'}} + + +# UTS: rest/unit/TM9a/reject-non-patch-or-serial-0 +def test_tm9a_reject_non_patch_or_serial(): + message = decode(data='x') + + # TM9b + other = decode_patch({'data': [{'op': 'append', 'data': 'y'}]}, serial='s2') + assert_apply_fails(message, other) + + # TM9a + assert_apply_fails(message, message) + + +# UTS: rest/unit/TM9f4/reserved-member-name-0 +def test_tm9f4_reserved_member_name(): + message = decode(data='{}', encoding='json') + patch = decode_patch({ + 'data': [{'op': 'set', 'path': '/__proto__', 'data': '{"polluted":true}', 'encoding': 'json'}], + }) + + patched = Message.apply_patch(message, patch) + + assert list(patched.data.keys()) == ['__proto__'] + assert patched.data['__proto__'] == {'polluted': True} diff --git a/test/uts/rest/unit/types/message_patch_types_test.py b/test/uts/rest/unit/types/message_patch_types_test.py new file mode 100644 index 00000000..8c7a7908 --- /dev/null +++ b/test/uts/rest/unit/types/message_patch_types_test.py @@ -0,0 +1,154 @@ +"""Derived from uts/rest/unit/types/message_patch_types.md in ably/specification. + +Spec points: TM5, TM2v, MPA1, MPA2, MPA2a, MPA2b, MPA2b1, MPA2b2, MPA2b3, MPD2, MPD2a-MPD2d, MPD4, +MPD4a, MPH2, MPH2a-MPH2c, MPU2, MPU2a, MPU2b, MPP2, MPP2a + +`fromJson` and `fromEncoded` are spelled `from_encoded`, `toJson` is spelled `as_dict`, `userClaim` is +`user_claim`, and the specification's `extras: { "headers": [...] }` is `MessagePatchExtras(headers=[...])`. +""" + +from ably.pubsub.types.message import Message, MessageAction +from ably.pubsub.types.messagepatch import ( + MessagePatchDataOperation, + MessagePatches, + MessagePatchExtras, + MessagePatchHeaderOperation, + MessagePatchPrivilegedOperation, + MessagePatchUserClaimOperation, +) + + +# UTS: rest/unit/TM5/message-patch-action-value-0 +def test_tm5_message_patch_action_value(): + assert int(MessageAction.MESSAGE_PATCH) == 6 + assert MessageAction(6) == MessageAction.MESSAGE_PATCH + + msg = Message.from_encoded({'serial': 's1', 'action': 6}) + assert msg.action == MessageAction.MESSAGE_PATCH + + +# UTS: rest/unit/TM2v/patches-parsed-from-wire-0 +def test_tm2v_patches_parsed_from_wire(): + msg = Message.from_encoded({ + 'action': 6, + 'serial': 'msg-serial-1', + 'version': {'serial': 'version-serial-2', 'timestamp': 1700000002000}, + 'patches': { + 'data': [ + {'op': 'append', 'path': '/content/0/text', 'data': ' more'}, + {'op': 'set', 'data': 'replaced'}, + {'op': 'remove', 'path': '/old'}, + ], + 'extras': { + 'headers': [ + {'op': 'set', 'key': 'status', 'value': 'complete'}, + {'op': 'set', 'key': 'count', 'value': 3}, + {'op': 'set', 'key': 'final', 'value': True}, + {'op': 'remove', 'key': 'draft'}, + ], + 'userClaim': {'op': 'set', 'value': 'moderator'}, + 'privileged': {'op': 'remove'}, + }, + }, + }) + + assert isinstance(msg.patches, MessagePatches) + + data_ops = msg.patches.data + assert len(data_ops) == 3 + assert isinstance(data_ops[0], MessagePatchDataOperation) + assert data_ops[0].op == 'append' + assert data_ops[0].path == '/content/0/text' + assert data_ops[0].data == ' more' + assert data_ops[1].op == 'set' + assert data_ops[1].path is None or data_ops[1].path == '' + assert data_ops[1].data == 'replaced' + assert data_ops[2].op == 'remove' + assert data_ops[2].path == '/old' + assert data_ops[2].data is None + + headers = msg.patches.extras.headers + assert len(headers) == 4 + assert isinstance(headers[0], MessagePatchHeaderOperation) + assert headers[0].op == 'set' + assert headers[0].key == 'status' + assert headers[0].value == 'complete' + assert headers[1].value == 3 + assert headers[2].value is True + assert headers[3].op == 'remove' + assert headers[3].key == 'draft' + assert headers[3].value is None + + assert isinstance(msg.patches.extras.user_claim, MessagePatchUserClaimOperation) + assert msg.patches.extras.user_claim.op == 'set' + assert msg.patches.extras.user_claim.value == 'moderator' + + assert isinstance(msg.patches.extras.privileged, MessagePatchPrivilegedOperation) + assert msg.patches.extras.privileged.op == 'remove' + + +# UTS: rest/unit/MPD4/patch-values-decoded-0 +def test_mpd4_patch_values_decoded(): + msg = Message.from_encoded({ + 'action': 6, + 'serial': 's1', + 'patches': { + 'data': [ + {'op': 'set', 'path': '/a', 'data': '{"b":1}', 'encoding': 'json'}, + {'op': 'set', 'path': '/n', 'data': '42', 'encoding': 'json'}, + {'op': 'set', 'path': '/c', 'data': 'AQI=', 'encoding': 'base64'}, + {'op': 'set', 'path': '/u', 'data': 'aGk=', 'encoding': 'utf-8/base64'}, + {'op': 'set', 'path': '/j', 'data': 'eyJ4IjoxfQ==', 'encoding': 'json/utf-8/base64'}, + {'op': 'append', 'path': '/d', 'data': 'text'}, + ], + }, + }) + + ops = msg.patches.data + + # MPD4a — JSON values stay as JSON text, whatever their type + assert ops[0].data == '{"b":1}' + assert ops[0].encoding == 'json' + assert ops[1].data == '42' + assert ops[1].encoding == 'json' + + # MPD4 — other transforms are inverted, as for a message's data + assert ops[2].data == bytes([0x01, 0x02]) + assert ops[2].encoding is None or ops[2].encoding == '' + assert ops[3].data == 'hi' + assert ops[3].encoding is None or ops[3].encoding == '' + + # MPD4a — the transforms after a leading json are inverted, leaving the JSON text + assert ops[4].data == '{"x":1}' + assert ops[4].encoding == 'json' + + assert ops[5].data == 'text' + assert ops[5].encoding is None or ops[5].encoding == '' + + +# UTS: rest/unit/MPA2/patches-serialized-to-wire-0 +def test_mpa2_patches_serialized_to_wire(): + msg = Message( + serial='s1', + action=MessageAction.MESSAGE_PATCH, + patches=MessagePatches( + data=[ + MessagePatchDataOperation(op='append', path='/text', data='lo'), + MessagePatchDataOperation(op='remove', path='/old'), + ], + extras=MessagePatchExtras(headers=[ + MessagePatchHeaderOperation(op='set', key='status', value='complete'), + ]), + ), + ) + json_data = msg.as_dict(binary=False) + + assert json_data['action'] == 6 + assert json_data['serial'] == 's1' + assert json_data['patches']['data'] == [ + {'op': 'append', 'path': '/text', 'data': 'lo'}, + {'op': 'remove', 'path': '/old'}, + ] + assert json_data['patches']['extras']['headers'] == [ + {'op': 'set', 'key': 'status', 'value': 'complete'}, + ]