diff --git a/build/data/versions.yaml b/build/data/versions.yaml index b7a966301..05ac82a18 100644 --- a/build/data/versions.yaml +++ b/build/data/versions.yaml @@ -1,2 +1,2 @@ -specification: "6.4.0" -protocol: 6 +specification: "6.5.0" +protocol: 7 diff --git a/specifications/api-docstrings.md b/specifications/api-docstrings.md index ce6cf5780..49ea577c2 100644 --- a/specifications/api-docstrings.md +++ b/specifications/api-docstrings.md @@ -307,6 +307,11 @@ Enables messages to be published and historic messages to be retrieved for a cha || `operation` ||| An optional [`MessageOperation`]{@link MessageOperation} object containing metadata about the append operation. | || `params` ||| Optional parameters sent as part of the query string. As Ably adds supported parameters, they will be documented on the [docs pages](https://ably.com/docs). | ||| `UpdateDeleteResult` || An [`UpdateDeleteResult`]{@link UpdateDeleteResult} object containing the serial of the new version of the message. | +| patchMessage(Message, operation?: MessageOperation, params?: `Dict`) => io UpdateDeleteResult ||| RSL15 | Patches an existing message: atomically sets, appends to or removes values inside its JSON `data`, and sets or removes its headers. Only the `patches` field of the supplied message changes the message. Subscribers receive the patch as a `MESSAGE_PATCH` message, and apply it to their copy of the message with [`Message.applyPatch()`]{@link Message#applyPatch}. | +|| `Message` ||| A [`Message`]{@link Message} object containing a populated `serial` field and the [`patches`]{@link MessagePatches} to apply. | +|| `operation` ||| An optional [`MessageOperation`]{@link MessageOperation} object containing metadata about the patch operation. | +|| `params` ||| Optional parameters sent as part of the query string. As Ably adds supported parameters, they will be documented on the [docs pages](https://ably.com/docs). | +||| `UpdateDeleteResult` || An [`UpdateDeleteResult`]{@link UpdateDeleteResult} object containing the serial of the new version of the message. | | getMessageVersions(serialOrMsg: String \| Message, params?: `Dict`) => io `PaginatedResult` ||| RSL14 | Retrieves all historical versions of a specific message, ordered by version. This includes the original message and all subsequent updates or delete operations. | || `serialOrMsg` ||| Either the serial identifier string of the message whose versions are to be retrieved, or a [`Message`]{@link Message} object containing a populated `serial` field. | || `params` ||| Optional parameters sent as part of the query string. | @@ -399,6 +404,11 @@ Enables messages to be published and subscribed to. Also enables historic messag || `operation` ||| An optional [`MessageOperation`]{@link MessageOperation} object containing metadata about the append operation. | || `params` ||| Optional parameters sent as part of the request. As Ably adds supported parameters, they will be documented on the [docs pages](https://ably.com/docs). | ||| `UpdateDeleteResult` || An [`UpdateDeleteResult`]{@link UpdateDeleteResult} object containing the serial of the new version of the message. | +| patchMessage(Message, operation?: MessageOperation, params?: `Dict`) => io UpdateDeleteResult ||| RTL32 | Patches an existing message: atomically sets, appends to or removes values inside its JSON `data`, and sets or removes its headers. Only the `patches` field of the supplied message changes the message. Subscribers receive the patch as a `MESSAGE_PATCH` message, and apply it to their copy of the message with [`Message.applyPatch()`]{@link Message#applyPatch}. | +|| `Message` ||| A [`Message`]{@link Message} object containing a populated `serial` field and the [`patches`]{@link MessagePatches} to apply. | +|| `operation` ||| An optional [`MessageOperation`]{@link MessageOperation} object containing metadata about the patch operation. | +|| `params` ||| Optional parameters sent as part of the request. As Ably adds supported parameters, they will be documented on the [docs pages](https://ably.com/docs). | +||| `UpdateDeleteResult` || An [`UpdateDeleteResult`]{@link UpdateDeleteResult} object containing the serial of the new version of the message. | | getMessageVersions(serialOrMsg: String \| Message, params?: `Dict`) => io `PaginatedResult` ||| RTL31 | Retrieves all historical versions of a specific message, ordered by version. This includes the original message and all subsequent updates or delete operations. | || `serialOrMsg` ||| Either the serial identifier string of the message whose versions are to be retrieved, or a [`Message`]{@link Message} object containing a populated `serial` field. | || `params` ||| Optional parameters sent as part of the query string. | @@ -703,6 +713,7 @@ Enumerates the possible types of `Message` there can be. | META | TM5 | A meta-message (a message originating from ably rather than being explicitly published on a channel), containing information such as inband channel occupancy events that has been requested by channel param. | | MESSAGE_SUMMARY | TM5 | A message containing the latest rolled-up summary of annotations that have been made to this message. | | MESSAGE_APPEND | TM5 | Message action for an appended message. The `serial` field identifies the message to which data is being appended. The `data` field is appended to the previous message's data, while all other fields replace the previous values. | +| MESSAGE_PATCH | TM5 | Message action for a patch to a message. The `serial` field identifies the patched message, and the `patches` field holds the changes to apply to it. Use [`Message.applyPatch()`]{@link Message#applyPatch} to apply them to your copy of the message. | ## class RestAnnotations @@ -865,6 +876,60 @@ Contains an individual message that is sent to, or received from, Ably. | connectionKey: String? ||| TM2h | Allows a REST client to publish a message on behalf of a Realtime client. If you set this to the [private connection key]{@link Connection.key} of a Realtime connection when publishing a message using a [`RestClient`]{@link RestClient}, the message will be published on behalf of that Realtime client. This property is only populated by a client performing a publish, and will never be populated on an inbound message. | | version: MessageVersion ||| TM2s | An object containing information about the latest version of a message. | | annotations: MessageAnnotations ||| TM2u | An object containing annotations that have been made to the message. | +| patches: MessagePatches? ||| TM2v | The changes that a `MESSAGE_PATCH` message makes to the message identified by `serial`. Use [`Message.applyPatch()`]{@link Message#applyPatch} to apply them to your copy of the message. When publishing with `patchMessage()`, the changes to make. | +| +applyPatch(message: Message, patch: Message) -> Message ||| TM9 | Applies a `MESSAGE_PATCH` to your copy of the message it patches, and returns a new copy that looks as if you had received the latest version of the message as a `MESSAGE_UPDATE`. The copy it is given is not changed. To patch JSON you keep outside an Ably message, pass it as the copy's `data`, as a string or binary. | +|| `message` ||| Your copy of the message, received as a `MESSAGE_CREATE` or `MESSAGE_UPDATE`, or returned by an earlier call to `applyPatch`. | +|| `patch` ||| The `MESSAGE_PATCH` message to apply. | +||| `Message` || The patched copy of the message. Fails with an [`ErrorInfo`]{@link ErrorInfo} if any operation of the patch cannot be applied, in which case none is applied. | + +## class MessagePatches + +The changes a `MESSAGE_PATCH` message makes to a message. Each member is optional. + +| Method / Property | Parameter | Returns | Spec | Description | +|---|---|---|---|---| +| data: [MessagePatchDataOperation]? ||| MPA2a | Operations that change the message's `data`, applied in order. | +| extras.headers: [MessagePatchHeaderOperation]? ||| MPA2b1 | Operations that change the message's `extras.headers`, applied in order after the data operations. | +| extras.userClaim: MessagePatchUserClaimOperation? ||| MPA2b2 | Sets or removes the message's `extras.userClaim`, to the claim of the patch's publisher. Only Ably sets this, on every patch it delivers. | +| extras.privileged: MessagePatchPrivilegedOperation? ||| MPA2b3 | Removes the message's `extras.privileged`, when the patch's publisher may not set privileged extras. Only Ably sets this. | + +## class MessagePatchDataOperation + +An operation that changes the message's `data`, or a value inside it. + +| Method / Property | Parameter | Returns | Spec | Description | +|---|---|---|---|---| +| op: String ||| MPD2a | The operation: `set` puts a value at the location, `append` adds a string to the end of a string (or binary to the end of binary `data`), and `remove` deletes a member of an object or an element of an array. | +| path: String? ||| MPD2b | A JSON Pointer (RFC 6901), such as `/content/0/text`, to a location inside `data` that holds a JSON object or array. Without a path, the operation applies to the whole of `data`. With `set`, the last token `-` adds an element after the last one in an array. | +| data: (String \| Binary \| JsonValue)? ||| MPD2c | The value the operation uses. When publishing, objects, arrays, numbers, booleans and `null` are sent as JSON values. On a received patch, a JSON value stays as JSON text, with an `encoding` of `json`, so that you can parse it into the type of the value it changes. | +| encoding: String? ||| MPD2d | `json` if `data` is JSON text, and otherwise typically empty, as the SDK encodes and decodes `data` as it does a message's `data`. | + +## class MessagePatchHeaderOperation + +An operation that changes a header in the message's `extras.headers`. + +| Method / Property | Parameter | Returns | Spec | Description | +|---|---|---|---|---| +| op: String ||| MPH2a | The operation: `set` sets the header, adding it if it is missing, and `remove` deletes it. | +| key: String ||| MPH2b | The header's name. | +| value: (String \| Number \| Boolean)? ||| MPH2c | The header's new value, for `set`. | + +## class MessagePatchUserClaimOperation + +An operation that sets or removes the message's `extras.userClaim`. + +| Method / Property | Parameter | Returns | Spec | Description | +|---|---|---|---|---| +| op: String ||| MPU2a | The operation: `set` sets the claim to `value`, and `remove` deletes it. | +| value: String? ||| MPU2b | The claim, for `set`. | + +## class MessagePatchPrivilegedOperation + +An operation that removes the message's `extras.privileged`. + +| Method / Property | Parameter | Returns | Spec | Description | +|---|---|---|---|---| +| op: String ||| MPP2a | The operation, which is always `remove`. | ## Class SummaryClientIdList diff --git a/specifications/features.md b/specifications/features.md index f842f9959..e1bc109c5 100644 --- a/specifications/features.md +++ b/specifications/features.md @@ -361,14 +361,15 @@ Support for the deprecated client options `environment`, `restHost`, `realtimeHo - `(RSL14a1)` In languages where method overloading is supported, the first argument should also accept a `Message` object (which must contain a populated `serial` field) - `(RSL14b)` The SDK must send a GET request to the endpoint `/channels/{channelName}/messages/{serial}/versions` - `(RSL14c)` Returns a `PaginatedResult` -- `(RSL15)` `RestChannel#updateMessage`, `RestChannel#deleteMessage`, and `RestChannel#appendMessage` functions: +- `(RSL15)` `RestChannel#updateMessage`, `RestChannel#deleteMessage`, `RestChannel#appendMessage`, and `RestChannel#patchMessage` functions: - `(RSL15a)` Take a first argument of a `Message` object (which must contain a populated `serial` field), an optional second argument of a `MessageOperation` object, and an optional third argument of `Dict` publish params - `(RSL15b)` The SDK must send a PATCH to `/channels/{channelName}/messages/{serial}`. The request body is a `Message` object (encoded per [RSL4](#RSL4)) with whatever fields were in the user-supplied `Message`, in addition to: - - `(RSL15b1)` `action` - set to `MESSAGE_UPDATE` for `updateMessage()`, `MESSAGE_DELETE` for `deleteMessage()`, and `MESSAGE_APPEND` for `appendMessage()`. + - `(RSL15b1)` `action` - set to `MESSAGE_UPDATE` for `updateMessage()`, `MESSAGE_DELETE` for `deleteMessage()`, `MESSAGE_APPEND` for `appendMessage()`, and `MESSAGE_PATCH` for `patchMessage()`. - `(RSL15b7)` `version` - set to the `MessageOperation` object if provided. - `(RSL15f)` Any params provided in the third argument must be sent in the querystring, with values stringified - `(RSL15c)` The SDK must not mutate the user-supplied `Message` object. - `(RSL15d)` The request body must be encoded to the appropriate format per `RSC8`. + - `(RSL15g)` The `data` value of each operation in the `patches` field ([TM2v](#TM2v)) of the request body must be encoded per [MPD3](#MPD3). - `(RSL15e)` On success, returns an `UpdateDeleteResult` object. The API response body will contain a superset of the fields of a `UpdateDeleteResult`. Indicates an error if the operation was not successful. - `(RSL16)` `RestChannel#object` attribute: - `(RSL16a)` Returns the `RestObject` object for this channel [RSO1](../objects-features#RSO1) @@ -841,13 +842,14 @@ The threading and/or asynchronous model for each realtime library will vary by l - `(RTL29)` This clause has been replaced by [`RTL32`](#RTL32) as of specification version 5.0.0. - `(RTL30)` This clause has been replaced by [`RTL32`](#RTL32) as of specification version 5.0.0. - `(RTL31)` `RealtimeChannel#getMessageVersions` function: same as `RestChannel#getMessageVersions` -- `(RTL32)` `RealtimeChannel#updateMessage`, `RealtimeChannel#deleteMessage`, and `RealtimeChannel#appendMessage` functions: +- `(RTL32)` `RealtimeChannel#updateMessage`, `RealtimeChannel#deleteMessage`, `RealtimeChannel#appendMessage`, and `RealtimeChannel#patchMessage` functions: - `(RTL32a)` Take a first argument of a `Message` object (which must contain a populated `serial` field), an optional second argument of a `MessageOperation` object, and an optional third argument of `Dict` publish params - `(RTL32b)` The SDK must send a `MESSAGE` `ProtocolMessage` to Ably, containing a single `Message` populated with whatever fields were in the user-supplied `Message`, in addition to: - - `(RTL32b1)` `action` - set to `MESSAGE_UPDATE` for `updateMessage()`, `MESSAGE_DELETE` for `deleteMessage()`, and `MESSAGE_APPEND` for `appendMessage()` + - `(RTL32b1)` `action` - set to `MESSAGE_UPDATE` for `updateMessage()`, `MESSAGE_DELETE` for `deleteMessage()`, `MESSAGE_APPEND` for `appendMessage()`, and `MESSAGE_PATCH` for `patchMessage()` - `(RTL32b2)` `version` - set to the `MessageOperation` object if provided. - `(RTL32e)` Any params provided in the third argument must be sent in the `TR4q` `ProtocolMessage.params` field, as a `Dict` (that is, with the values of the provided dict stringified per `RTC1f`) - `(RTL32c)` The SDK must not mutate the user-supplied `Message` object. + - `(RTL32f)` The `data` value of each operation in the `patches` field ([TM2v](#TM2v)) of the `Message` must be encoded per [MPD3](#MPD3). - `(RTL32d)` On success, returns an `UpdateDeleteResult` object containing the version serial of the published update, obtained from the first element of the `serials` array of the [TR4s](#TR4s) `res` field of the `ACK`. Indicates an error if the operation was not successful. - `(RTL33)` *Ensure-active-channel* internal procedure. When invoked, the SDK must inspect the current state of the `RealtimeChannel` (see [RTL2](#RTL2)) and proceed as follows: - `(RTL33a)` If the channel is in the `ATTACHED` or `SUSPENDED` state, the procedure completes immediately without performing any attach. @@ -1228,7 +1230,7 @@ The core SDK provides an API for wrapper SDKs to supply Ably with analytics info #### Message - `(TM1)` A `Message` represents an individual message to be sent or received via the Ably Realtime service. -- `(TM5)` `Message` `Action` enum has the following values in order from zero: `MESSAGE_CREATE`, `MESSAGE_UPDATE`, `MESSAGE_DELETE`, `META`, `MESSAGE_SUMMARY`, `MESSAGE_APPEND` +- `(TM5)` `Message` `Action` enum has the following values in order from zero: `MESSAGE_CREATE`, `MESSAGE_UPDATE`, `MESSAGE_DELETE`, `META`, `MESSAGE_SUMMARY`, `MESSAGE_APPEND`, `MESSAGE_PATCH` - `(TM2)` The attributes available in a `Message` are: - `(TM2a)` `id` string - unique ID for this message. This attribute is always populated for messages received over REST. For messages received over Realtime, if the message does not contain an `id`, it should be set to `protocolMsgId:index`, where `protocolMsgId` is the id of the `ProtocolMessage` encapsulating it, and `index` is the index of the message inside the `messages` array of the `ProtocolMessage` - `(TM2b)` `clientId` string @@ -1257,6 +1259,7 @@ The core SDK provides an API for wrapper SDKs to supply Ably with analytics info - `(TM2s4)` `description` - string - `(TM2s5)` `metadata` - Dict\ - used to contain any arbitrary key value pairs of type string. - `(TM2u)` `annotations` - an object of type `MessageAnnotations`. If not set on the wire, the SDK must set it to an empty `MessageAnnotations` object. + - `(TM2v)` `patches` `MessagePatches` (optional) - the changes that a message whose `action` is `MESSAGE_PATCH` makes to the message identified by its `serial`. The user populates it on the `Message` passed to `RestChannel#patchMessage` ([RSL15](#RSL15)) or `RealtimeChannel#patchMessage` ([RTL32](#RTL32)). It is decoded on receipt per [MPD4](#MPD4). - `(TM4)` `Message` has constructors `constructor(name: String?, data: Data?)` and `constructor(name: String?, data: Data?, clientId: String?)`. - `(TM3)` `fromEncoded` and `fromEncodedArray` are alternative constructors that take an (already deserialized) `Message`-like object (or array of such objects), and optionally a `channelOptions`, and return a `Message` (or array of such `Messages`) that's decoded and decrypted as specified in `RSL6`, using the cipher in the `channelOptions` if the message is encrypted, with any residual transforms (ones that the library cannot decode or decrypt) left in the `encoding` property per `RSL6b`. This is intended for users receiving messages other than from a REST or Realtime channel (for example, from a queue), to avoid them having to parse the `encoding` string themselves. - `(TM6)` The size of the `Message` for [TO3l8](#TO3l8) is calculated as follows: @@ -1290,6 +1293,52 @@ The core SDK provides an API for wrapper SDKs to supply Ably with analytics info - `(TM8)` The attributes available in a `MessageAnnotations` object are: - `(TM8a)` `summary` `Dict` - an object whose keys are annotation types, and the values are aggregated summaries for that annotation type. A missing `summary` field on the wire indicates an empty summary, equivalent to an object with no keys. The SDK must initialize this object if not present. - `(TM8a1)` A given annotation type has a fixed summary structure, and the currently-used structured are documented for the user's use in api-docstrings. But the sdk MUST be able to cope with structures and aggregation types that have it does not yet know about or have explicit support for, hence the loose (JsonObject) type. +- `(TM9)` `Message.applyPatch` is a static function that takes a `Message` (the _message_: a `MESSAGE_CREATE` or `MESSAGE_UPDATE` received from Ably, or the result of an earlier call to `applyPatch`) and a `Message` whose `action` is `MESSAGE_PATCH` (the _patch_), and returns a new `Message` that represents the copy of the message with the patch applied. + - `(TM9a)` If the `action` of the patch is not `MESSAGE_PATCH`, `applyPatch` must fail with an `ErrorInfo` with `code` 40000 and `statusCode` 400. + - `(TM9b)` If the `serial` of the patch is not equal to the `serial` of the copy, `applyPatch` must fail with an `ErrorInfo` with `code` 40000 and `statusCode` 400. + - `(TM9c)` The SDK must not mutate the copy, nor any value that it holds, such as a JSON-encodable object or array in its `data` or its `extras`. The returned `Message` may share with the copy any value that the patch does not change. + - `(TM9d)` The returned `Message` must have the same attribute values as the copy, except for the following: + - `(TM9d1)` `action` - set to `MESSAGE_UPDATE` + - `(TM9d2)` `data` and `encoding` - the result of applying the data operations of the patch, per [TM9f](#TM9f) + - `(TM9d3)` `extras` - the result of applying the extras operations of the patch, per [TM9g](#TM9g) + - `(TM9d4)` `version` - set to the `version` of the patch + - `(TM9h)` This clause is non-normative. Since only the attributes in [TM9d](#TM9d) change, the attributes of the patch itself, such as its `clientId`, `connectionId`, `timestamp` and `extras`, do not affect the result. The `extras.userClaim` and `extras.privileged` of the stored message are instead kept up to date by the operations in [TM9g2](#TM9g2) and [TM9g3](#TM9g3), which only Ably sets. + - `(TM9e)` If any operation of the patch cannot be applied, as specified by the clauses below, `applyPatch` must fail with an `ErrorInfo` with `code` 40000 and `statusCode` 400, and must not return a result. The `message` of the `ErrorInfo` should identify the operation that could not be applied, by its index in `patches.data` or `patches.extras.headers`. + - `(TM9f)` The SDK must apply the operations of `patches.data` ([MPA2a](#MPA2a)) in order, each to the `data` that results from the previous one, starting with the `data` of the copy: + - `(TM9f1)` An operation whose `op` is not `set`, `append` or `remove` cannot be applied. + - `(TM9f2)` An operation without a `path`, or with an empty `path`, applies to the whole of `data`: + - `(TM9f2a)` `set` replaces `data`. If the `encoding` of the operation is `json`, the resulting `data` is the JSON-encodable value that the operation's JSON text represents, and the resulting `encoding` is empty. Otherwise, the resulting `data` and `encoding` are the `data` and `encoding` of the operation. + - `(TM9f2b)` `append`, if `data` is absent and the `data` of the operation is a string or binary, sets `data` to the `data` of the operation. + - `(TM9f2c)` `append`, if `data` and the `data` of the operation are both strings, or both binary, and the `encoding` is empty, sets `data` to their concatenation. + - `(TM9f2d)` Any other `append`, and any `remove`, cannot be applied. + - `(TM9f3)` An operation with a non-empty `path` applies to a value inside `data`, which must be a JSON object or array, held either as a JSON-encodable object or array, or as a string or binary (UTF-8) holding JSON text whose top-level value is an object or array. If `data` is anything else, the operation cannot be applied. The `encoding` is unchanged. + - `(TM9f3a)` The `path` is a JSON Pointer, as defined by [RFC 6901](https://www.rfc-editor.org/rfc/rfc6901). If it does not start with `/`, or it contains a `~` that is not followed by `0` or `1`, the operation cannot be applied. Each reference token is unescaped as RFC 6901 section 4 specifies. + - `(TM9f3b)` Every reference token but the last must reference an existing value, starting from the top-level value: a member of an object, by its name, or an element of an array, by an index that is a sequence of decimal digits without leading zeros (as RFC 6901 section 4 specifies) and less than the length of the array. Otherwise, the operation cannot be applied. + - `(TM9f3c)` The value that every reference token but the last references (the _parent_), or the top-level value if there is only one reference token, must be an object or an array. Otherwise, the operation cannot be applied. + - `(TM9f3d)` `set`, if the parent is an object, sets the member named by the last reference token to the value of the operation ([TM9f3h](#TM9f3h)), adding the member if the object does not have it. + - `(TM9f3e)` `set`, if the parent is an array, and the last reference token is `-`, adds the value of the operation as a new element after the last one. If the last reference token is an index of an existing element, `set` replaces that element with the value of the operation. Otherwise, the operation cannot be applied. + - `(TM9f3f)` `append` requires that the last reference token references an existing value that is a string, and that the `data` of the operation is a string; it replaces the value with the concatenation of the value and the `data` of the operation. Otherwise, including if the last reference token is `-`, the operation cannot be applied. + - `(TM9f3g)` `remove` requires that the last reference token references an existing value; it removes the member from an object, or the element from an array, moving every later element to the index before it. Otherwise, including if the last reference token is `-`, the operation cannot be applied. + - `(TM9f3h)` The value of an operation is: the JSON value that its `data` represents, if its `encoding` is `json`; the string of the Base64 encoding of its `data`, if its `data` is binary; and otherwise its `data`. + - `(TM9f4)` If `data` is a JSON-encodable object or array, the result of an operation with a `path` must be a JSON-encodable object or array, as described by [TM9f3](#TM9f3). The SDK must add or set a member named by a reference token as an ordinary member of the object, whatever its name (for example, a member named `__proto__` in JavaScript). + - `(TM9f5)` If `data` is a string or binary holding JSON text, the result of an operation with a `path` must be of the same type, holding the JSON text that results from changing only the text described below. All other text, including whitespace, the order of members, and the text of every number and string, must be unchanged. + - `(TM9f5a)` The _value text_ of an operation is: its `data`, verbatim, if its `encoding` is `json`; and otherwise the JSON string ([TM9f6](#TM9f6)) of its value ([TM9f3h](#TM9f3h)). + - `(TM9f5b)` `set` of an existing member or element replaces the text of its value with the value text. + - `(TM9f5c)` `set` of a member that the object does not have inserts, immediately after the text of the value of its last member, or immediately after its `{` if it has no members: a `,` if it has members, then the JSON string ([TM9f6](#TM9f6)) of the member name, then `:`, then the value text, without whitespace. + - `(TM9f5d)` `set` with the last reference token `-` inserts, immediately after the text of the last element of the array, or immediately after its `[` if it has no elements: a `,` if it has elements, then the value text, without whitespace. + - `(TM9f5e)` `append` inserts the JSON string ([TM9f6](#TM9f6)) of the `data` of the operation, without its enclosing quotation marks, immediately before the closing quotation mark of the string that it appends to. + - `(TM9f5f)` `remove`, if the member or element is followed by another, deletes the text from the start of the member (the opening quotation mark of its name) or element, up to the start of the next member or element. + - `(TM9f5g)` `remove`, if the member or element is the last of several, deletes the text from the end of the value of the previous member or element up to the end of its value. + - `(TM9f5h)` `remove`, if the member or element is the only one, deletes the text of the member or element, from its start up to the end of its value. + - `(TM9f5i)` The SDK must compare the name of a member in the JSON text with a reference token after unescaping the JSON string of the name. + - `(TM9f5j)` If the SDK finds that the JSON text is not valid JSON, the operation cannot be applied. + - `(TM9f5k)` This clause is non-normative. These rules are those that Ably uses to apply a patch to a message whose `data` is JSON text, so a copy kept as JSON text stays identical, byte for byte, to the stored message. + - `(TM9f6)` The _JSON string_ of a string is the string enclosed in quotation marks (`"`), in which `"` and `\` are escaped as `\"` and `\\`; U+0008, U+0009, U+000A, U+000C and U+000D are escaped as `\b`, `\t`, `\n`, `\f` and `\r`; every other character from U+0000 to U+001F is escaped as `\u` followed by four lowercase hexadecimal digits; and every other character is unescaped. Where the language's strings may hold an unpaired UTF-16 surrogate, the SDK must replace it with U+FFFD. + - `(TM9g)` After the data operations, the SDK must apply the operations of `patches.extras` ([MPA2b](#MPA2b)) to the `extras` of the copy: + - `(TM9g1)` The operations of `patches.extras.headers`, in order: `set` sets the member of `extras.headers` named by its `key` to its `value`, adding `extras` and `extras.headers` if they are absent. `remove` deletes the member of `extras.headers` named by its `key`, and cannot be applied if `extras.headers` does not have it. An operation whose `op` is neither cannot be applied. + - `(TM9g2)` The operation `patches.extras.userClaim`, if present: `set` sets `extras.userClaim` to its `value`, adding `extras` if it is absent. `remove` deletes `extras.userClaim`, if present. An operation whose `op` is neither cannot be applied. + - `(TM9g3)` The operation `patches.extras.privileged`, if present: `remove` deletes `extras.privileged`, if present. An operation whose `op` is not `remove` cannot be applied. + - `(TM9g4)` If deleting `extras.userClaim` per [TM9g2](#TM9g2), or `extras.privileged` per [TM9g3](#TM9g3), leaves `extras` with no members, the returned `Message` must have no `extras`. #### DeltaExtras @@ -1298,6 +1347,55 @@ The core SDK provides an API for wrapper SDKs to supply Ably with analytics info - `(DE2a)` `from` string - the ID of the base message the delta was generated from - `(DE2b)` `format` string -- the delta format; currently only "vcdiff" is allowed +#### MessagePatches + +- `(MPA1)` `MessagePatches` describes the changes that a message whose `action` is `MESSAGE_PATCH` makes to a message: values inside its JSON `data`, and individual fields of its `extras`. They are applied to a copy of the message by `Message.applyPatch` ([TM9](#TM9)). +- `(MPA2)` The attributes of `MessagePatches` consist of: + - `(MPA2a)` `data` array of `MessagePatchDataOperation` (optional) - operations that change the message's `data`, applied in order + - `(MPA2b)` `extras` object (optional) - operations that change fields of the message's `extras`, with the following attributes: + - `(MPA2b1)` `headers` array of `MessagePatchHeaderOperation` (optional) - operations that change the message's `extras.headers`, applied in order + - `(MPA2b2)` `userClaim` `MessagePatchUserClaimOperation` (optional) - an operation that sets or removes the message's `extras.userClaim`. Only Ably sets it. + - `(MPA2b3)` `privileged` `MessagePatchPrivilegedOperation` (optional) - an operation that removes the message's `extras.privileged`. Only Ably sets it. + +#### MessagePatchDataOperation + +- `(MPD1)` `MessagePatchDataOperation` describes an operation that changes a message's `data`, or a value inside it. +- `(MPD2)` The attributes of `MessagePatchDataOperation` consist of: + - `(MPD2a)` `op` string - the operation: `set`, `append` or `remove` + - `(MPD2b)` `path` string (optional) - a JSON Pointer ([RFC 6901](https://www.rfc-editor.org/rfc/rfc6901)) to a value inside `data`. Without a `path`, the operation applies to the whole of `data`. + - `(MPD2c)` `data` string, binary, or any JSON-encodable value, including a number, boolean or `null` (optional) - the value that the operation uses + - `(MPD2d)` `encoding` string (optional) +- `(MPD3)` When sending a `MessagePatches` ([RSL15g](#RSL15g), [RTL32f](#RTL32f)), the SDK must encode the `data` of each `MessagePatchDataOperation` as follows, and must not mutate the user-supplied operation: + - `(MPD3a)` A string is sent unchanged, as a string, and the `encoding` is unchanged. + - `(MPD3b)` A binary value is encoded per [RSL4c1](#RSL4c1) when using MessagePack, and per [RSL4d1](#RSL4d1) when using JSON. + - `(MPD3c)` Any other value, including a number, boolean or `null`, is stringified as JSON, sent as a string (a MessagePack string when using MessagePack), and the `encoding` is set to `json`. Unlike [RSL4c3](#RSL4c3) and [RSL4d3](#RSL4d3), this applies to every JSON value, not only objects and arrays. + - `(MPD3d)` An operation without `data`, such as a `remove`, is sent without `data` or `encoding`. + - `(MPD3e)` The SDK must not encrypt the `data` of an operation, even if the channel has a `cipher` ([RSL5](#RSL5)). +- `(MPD4)` When decoding a received `Message` ([RSL6](#RSL6), [TM3](#TM3)), the SDK must decode the `data` of each `MessagePatchDataOperation` of its `patches` by inverting the transforms in its `encoding` per [RSL6a](#RSL6a), except for the following: + - `(MPD4a)` If the first transform in the `encoding` is `json`, the SDK must not invert it: the `data` must be left as a string holding the JSON text, and the `encoding` must be `json`. + - `(MPD4b)` This clause is non-normative. A JSON value is left as text so that `Message.applyPatch` can insert it into JSON text verbatim ([TM9f5a](#TM9f5a)), and so that the user can parse it into the type of the value that it changes. + +#### MessagePatchHeaderOperation + +- `(MPH1)` `MessagePatchHeaderOperation` describes an operation that changes a header in a message's `extras.headers`. +- `(MPH2)` The attributes of `MessagePatchHeaderOperation` consist of: + - `(MPH2a)` `op` string - the operation: `set` or `remove` + - `(MPH2b)` `key` string - the name of the header + - `(MPH2c)` `value` string, number or boolean (optional) - the new value of the header, for `set` + +#### MessagePatchUserClaimOperation + +- `(MPU1)` `MessagePatchUserClaimOperation` describes an operation that sets or removes a message's `extras.userClaim`. +- `(MPU2)` The attributes of `MessagePatchUserClaimOperation` consist of: + - `(MPU2a)` `op` string - the operation: `set` or `remove` + - `(MPU2b)` `value` string (optional) - the claim, for `set` + +#### MessagePatchPrivilegedOperation + +- `(MPP1)` `MessagePatchPrivilegedOperation` describes an operation that removes a message's `extras.privileged`. +- `(MPP2)` The attributes of `MessagePatchPrivilegedOperation` consist of: + - `(MPP2a)` `op` string - the operation, which is `remove` + #### PresenceMessage - `(TP1)` A `PresenceMessage` represents an individual presence message to be sent or received via the Ably Realtime service. @@ -2303,6 +2401,7 @@ Each type, method, and attribute is labelled with the name of one or more clause deleteMessage(Message, operation?: MessageOperation, params?: Dict) => io UpdateDeleteResult // RSL13 getMessageVersions(serial: String, params?: Dict) => io PaginatedResult // RSL14 appendMessage(Message, operation?: MessageOperation, params?: Dict) => io UpdateDeleteResult // RSL15 + patchMessage(Message, operation?: MessageOperation, params?: Dict) => io UpdateDeleteResult // RSL15 // Only on platforms that support receiving push notifications: push: PushChannel // RSH7 @@ -2345,6 +2444,7 @@ Each type, method, and attribute is labelled with the name of one or more clause deleteMessage(Message, operation?: MessageOperation, params?: Dict) => io UpdateDeleteResult // RTL30 getMessageVersions(serial: String, params?: Dict) => io PaginatedResult // RTL31 appendMessage(Message, operation?: MessageOperation, params?: Dict) => io UpdateDeleteResult // RTL32 + patchMessage(Message, operation?: MessageOperation, params?: Dict) => io UpdateDeleteResult // RTL32 class MessageFilter: // MFI* isRef: bool // MFI2a @@ -2520,6 +2620,7 @@ Each type, method, and attribute is labelled with the name of one or more clause META // TM5 MESSAGE_SUMMARY // TM5 MESSAGE_APPEND // TM5 + MESSAGE_PATCH // TM5 enum ObjectOperationAction: // OOP2, internal MAP_CREATE // OOP2 @@ -2559,6 +2660,7 @@ Each type, method, and attribute is labelled with the name of one or more clause +summaryMultipleV1(JsonObject) -> Dict // TM7b3 +summaryFlagV1(JsonObject) -> SummaryClientIdList // TM7b4 +summaryTotalV1(JsonObject) -> SummaryTotal // TM7b5 + +applyPatch(message: Message, patch: Message) -> Message // TM9 clientId: String? // TM2b connectionId: String? // TM2c connectionKey: String? // TM2h @@ -2572,6 +2674,33 @@ Each type, method, and attribute is labelled with the name of one or more clause serial: string? // TM2r version: MessageVersion // TM2s annotations: MessageAnnotations // TM2u + patches: MessagePatches? // TM2v + + class MessagePatches: // MPA* + data: [MessagePatchDataOperation]? // MPA2a + extras: { // MPA2b + headers: [MessagePatchHeaderOperation]? // MPA2b1 + userClaim: MessagePatchUserClaimOperation? // MPA2b2 + privileged: MessagePatchPrivilegedOperation? // MPA2b3 + }? + + class MessagePatchDataOperation: // MPD* + op: String // MPD2a + path: String? // MPD2b + data: (String | Binary | JsonValue)? // MPD2c + encoding: String? // MPD2d + + class MessagePatchHeaderOperation: // MPH* + op: String // MPH2a + key: String // MPH2b + value: (String | Number | Boolean)? // MPH2c + + class MessagePatchUserClaimOperation: // MPU* + op: String // MPU2a + value: String? // MPU2b + + class MessagePatchPrivilegedOperation: // MPP* + op: String // MPP2a class PresenceMessage // TP* +fromEncoded(JsonObject, ChannelOptions?) -> PresenceMessage // TP4 diff --git a/specifications/protocol.md b/specifications/protocol.md index 761857bf2..9a9644a35 100644 --- a/specifications/protocol.md +++ b/specifications/protocol.md @@ -301,7 +301,7 @@ The members are as follows. -- i32 action := The message action, indicating the type of message operation. The following values are defined: `MESSAGE_CREATE` (0) for new messages, `MESSAGE_UPDATE` (1) for updates to existing messages, `MESSAGE_DELETE` (2) for message deletions, `META` (3) for metadata messages, `MESSAGE_SUMMARY` (4) for summary messages, and `MESSAGE_APPEND` (5) for appending data to existing messages. When publishing an update, delete, or append, the `serial` field must be populated to identify the target message. +- i32 action := The message action, indicating the type of message operation. The following values are defined: `MESSAGE_CREATE` (0) for new messages, `MESSAGE_UPDATE` (1) for updates to existing messages, `MESSAGE_DELETE` (2) for message deletions, `META` (3) for metadata messages, `MESSAGE_SUMMARY` (4) for summary messages, `MESSAGE_APPEND` (5) for appending data to existing messages, and `MESSAGE_PATCH` (6) for patching values inside existing messages. When publishing an update, delete, append, or patch, the `serial` field must be populated to identify the target message. @@ -309,7 +309,11 @@ The members are as follows. -- object version := Contains information about the latest version of a message, including version serial, timestamp, and optional operation metadata (clientId, description, metadata) for update/delete/append operations. +- object version := Contains information about the latest version of a message, including version serial, timestamp, and optional operation metadata (clientId, description, metadata) for update/delete/append/patch operations. + + + +- object patches := Present on a `MESSAGE_PATCH` message: the changes it makes to the message identified by `serial`. `data` is an array of operations on the message's data, each an object with `op` (`set`, `append` or `remove`), an optional `path` (a JSON Pointer into the data), and optional `data` and `encoding`, encoded as a message's `data` is, except that every JSON value is sent as JSON text with an `encoding` of `json`. `extras` is an object with an optional `headers` array of header operations, each with `op` (`set` or `remove`), `key` and, for `set`, `value`; and optional `userClaim` (`op` of `set` or `remove`, and `value`) and `privileged` (`op` of `remove`) operations, which only Ably sends. Delivered from protocol version 7. ### PublishResult diff --git a/uts/docs/completion-status.md b/uts/docs/completion-status.md index 8ce03db1f..908d38e0e 100644 --- a/uts/docs/completion-status.md +++ b/uts/docs/completion-status.md @@ -99,7 +99,7 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | RSL10 | Annotations attribute | Yes — `rest/unit/channel/annotations.md` | | RSL11 | GetMessage function (RSL11a–RSL11c) | Yes — `rest/unit/channel/get_message.md`, `rest/integration/mutable_messages.md` | | RSL14 | GetMessageVersions (RSL14a–RSL14c) | Yes — `rest/unit/channel/message_versions.md`, `rest/integration/mutable_messages.md` | -| RSL15 | UpdateMessage/DeleteMessage/AppendMessage (RSL15a–RSL15f) | Yes — `rest/unit/channel/update_delete_message.md`, `rest/integration/mutable_messages.md` | +| RSL15 | UpdateMessage/DeleteMessage/AppendMessage/PatchMessage (RSL15a–RSL15g) | Yes — `rest/unit/channel/update_delete_message.md`, `rest/unit/channel/patch_message.md`, `rest/integration/mutable_messages.md` | ### Plugins @@ -236,7 +236,7 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | RTL27 | Objects attribute (RTL27a–RTL27b) | | | RTL28 | GetMessage function | Yes — `realtime/unit/channels/channel_get_message.md` (proxies to RSL11 tests), `realtime/integration/mutable_messages_test.md` | | RTL31 | GetMessageVersions function | Yes — `realtime/unit/channels/channel_message_versions.md` (proxies to RSL14 tests), `realtime/integration/mutable_messages_test.md` | -| RTL32 | UpdateMessage/DeleteMessage/AppendMessage (RTL32a–RTL32e) | Yes — `realtime/unit/channels/channel_update_delete_message.md`, `realtime/integration/mutable_messages_test.md` | +| RTL32 | UpdateMessage/DeleteMessage/AppendMessage/PatchMessage (RTL32a–RTL32f) | Yes — `realtime/unit/channels/channel_update_delete_message.md`, `realtime/unit/channels/channel_patch_message.md`, `realtime/integration/mutable_messages_test.md` | ### RealtimePresence @@ -313,8 +313,13 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | Spec item | Description | UTS test spec | |-----------|-------------|---------------| -| TM1–TM8 | Message (TM1–TM8a1) | Partial — `rest/unit/types/message_types.md` covers TM1–TM5; `rest/unit/types/mutable_message_types.md` covers TM2j, TM2r, TM2s, TM2u, TM5, TM8; `realtime/unit/channels/message_field_population.md` covers TM2a, TM2c, TM2f (realtime field population) | +| TM1–TM9 | Message (TM1–TM9h) | Partial — `rest/unit/types/message_types.md` covers TM1–TM5; `rest/unit/types/mutable_message_types.md` covers TM2j, TM2r, TM2s, TM2u, TM5, TM8; `rest/unit/types/message_patch_types.md` covers TM2v, TM5 (`MESSAGE_PATCH`); `rest/unit/types/message_apply_patch.md` covers TM9; `realtime/unit/channels/message_field_population.md` covers TM2a, TM2c, TM2f (realtime field population) | | DE1–DE2 | DeltaExtras | | +| MPA1–MPA2 | MessagePatches | Yes — `rest/unit/types/message_patch_types.md` | +| MPD1–MPD4 | MessagePatchDataOperation | Yes — `rest/unit/types/message_patch_types.md` (MPD2, MPD4); `rest/unit/channel/patch_message.md`, `realtime/unit/channels/channel_patch_message.md` (MPD3) | +| MPH1–MPH2 | MessagePatchHeaderOperation | Yes — `rest/unit/types/message_patch_types.md` | +| MPU1–MPU2 | MessagePatchUserClaimOperation | Yes — `rest/unit/types/message_patch_types.md` | +| MPP1–MPP2 | MessagePatchPrivilegedOperation | Yes — `rest/unit/types/message_patch_types.md` | | TP1–TP5 | PresenceMessage | Yes — `rest/unit/types/presence_message_types.md` | | OM1–OM5 | ObjectMessage | | | OOP1–OOP5 | ObjectOperation | | @@ -449,7 +454,7 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | **Wrapper SDK** (WP) | 7 | 0 | None | | **Push notifications** (RSH) | 8 | 1 | Partial | | **Plugins** (PC/PT/VD) | 3 | 2 | Partial | -| **Data types** | 30 | 12 | Partial | +| **Data types** | 35 | 17 | Partial | | **Option types** | 8 | 5 | Partial | | **Push types** | 3 | 0 | None | | **Introspection** (CR) | 1 | 0 | None | diff --git a/uts/realtime/unit/channels/channel_patch_message.md b/uts/realtime/unit/channels/channel_patch_message.md new file mode 100644 index 000000000..18f9efd20 --- /dev/null +++ b/uts/realtime/unit/channels/channel_patch_message.md @@ -0,0 +1,374 @@ +# RealtimeChannel PatchMessage Tests + +Spec points: `RTL32`, `RTL32b`, `RTL32b1`, `RTL32d`, `RTL32f`, `MPD3`, `MPD4`, `MPD4a`, `TM2v`, `TM9` + +## Test Type +Unit test with mocked WebSocket + +## Mock WebSocket Infrastructure + +See `uts/realtime/unit/helpers/mock_websocket.md` for the full Mock WebSocket Infrastructure specification. + +## Related Tests + +`patchMessage()` shares the behaviour of the other operations that `uts/realtime/unit/channels/channel_update_delete_message.md` covers (RTL32b2, RTL32c, RTL32e). The value encoding rules of MPD3 are covered in detail by `uts/rest/unit/channel/patch_message.md`; the tests below check that the realtime path applies them. The rules of `Message.applyPatch` are covered by `uts/rest/unit/types/message_apply_patch.md`. + +--- + +## RTL32b, RTL32b1, RTL32d — patchMessage sends MESSAGE ProtocolMessage with action MESSAGE_PATCH + +**Test ID**: `realtime/unit/RTL32b1/patch-message-action-0` + +| Spec | Requirement | +|------|-------------| +| RTL32b | Send a `MESSAGE` `ProtocolMessage` containing a single `Message` populated with the fields of the user-supplied `Message` | +| RTL32b1 | `action` set to `MESSAGE_PATCH` for `patchMessage()` | +| RTL32d | Returns an `UpdateDeleteResult` containing the version serial from the `ACK` | + +Tests that `patchMessage()` sends a MESSAGE ProtocolMessage with the `MESSAGE_PATCH` action and the `patches` field, and returns the version serial from the ACK. + +### Setup +```pseudo +channel_name = "test-RTL32-patch-${random_id()}" +captured_messages = [] + +mock_ws = MockWebSocketClient( + onConnectionAttempt: (conn) => { + conn.respond_with_success(CONNECTED()) + }, + onMessageFromClient: (msg) => { + captured_messages.append(msg) + IF msg.action == ATTACH: + mock_ws.active_connection.send_to_client(ATTACHED( + channel: channel_name, + flags: PUBLISH + )) + ELSE IF msg.action == MESSAGE: + mock_ws.active_connection.send_to_client(ACK( + msgSerial: msg.msgSerial, + count: 1, + res: { "serials": ["version-serial-1"] } + )) + } +) + +client = Realtime( + options: ClientOptions(key: "appId.keyId:keySecret", autoConnect: false, useBinaryProtocol: false), + webSocketClient: mock_ws +) +channel = client.channels.get(channel_name) +``` + +### Test Steps +```pseudo +client.connect() +AWAIT_STATE connection == CONNECTED +AWAIT channel.attach() + +result = AWAIT channel.patchMessage( + Message( + serial: "msg-serial-1", + patches: MessagePatches( + data: [MessagePatchDataOperation(op: "append", path: "/text", data: "lo")], + extras: { "headers": [MessagePatchHeaderOperation(op: "set", key: "status", value: "complete")] } + ) + ) +) +``` + +### Assertions +```pseudo +message_pm = null +FOR pm IN captured_messages: + IF pm.action == MESSAGE: + message_pm = pm +ASSERT message_pm IS NOT null + +ASSERT message_pm.channel == channel_name +ASSERT message_pm.messages.length == 1 + +msg = message_pm.messages[0].toJson() +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 result IS UpdateDeleteResult +ASSERT result.versionSerial == "version-serial-1" +CLOSE_CLIENT(client) +``` + +--- + +## RTL32f — patch operation values encoded per MPD3 + +**Test ID**: `realtime/unit/RTL32f/patch-values-encoded-0` + +| Spec | Requirement | +|------|-------------| +| RTL32f | The `data` of each operation in `patches` must be encoded per MPD3 | +| MPD3b | A binary value is encoded as Base64, with `encoding` `base64`, when using JSON | +| MPD3c | Any other value, including a number or boolean, is stringified as JSON with `encoding` `json` | + +Tests that the realtime path encodes each operation's value as the REST path does. + +### Setup +```pseudo +channel_name = "test-RTL32f-${random_id()}" +captured_messages = [] + +mock_ws = MockWebSocketClient( + onConnectionAttempt: (conn) => { + conn.respond_with_success(CONNECTED()) + }, + onMessageFromClient: (msg) => { + captured_messages.append(msg) + IF msg.action == ATTACH: + mock_ws.active_connection.send_to_client(ATTACHED( + channel: channel_name, + flags: PUBLISH + )) + ELSE IF msg.action == MESSAGE: + mock_ws.active_connection.send_to_client(ACK( + msgSerial: msg.msgSerial, + count: 1, + res: { "serials": ["version-serial-1"] } + )) + } +) + +client = Realtime( + options: ClientOptions(key: "appId.keyId:keySecret", autoConnect: false, useBinaryProtocol: false), + webSocketClient: mock_ws +) +channel = client.channels.get(channel_name) +``` + +### Test Steps +```pseudo +client.connect() +AWAIT_STATE connection == CONNECTED +AWAIT channel.attach() + +AWAIT channel.patchMessage( + 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) + ]) + ) +) +``` + +### Assertions +```pseudo +message_pm = null +FOR pm IN captured_messages: + IF pm.action == MESSAGE: + message_pm = pm + +ops = message_pm.messages[0].toJson()["patches"]["data"] +ASSERT parse_json(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" +CLOSE_CLIENT(client) +``` + +--- + +## MPD4, TM2v — received MESSAGE_PATCH is decoded and delivered to subscribers + +**Test ID**: `realtime/unit/MPD4/patch-received-decoded-0` + +| Spec | Requirement | +|------|-------------| +| TM5 | `MESSAGE_PATCH` is action 6 | +| TM2v | `patches` holds the changes a `MESSAGE_PATCH` makes | +| MPD4 | The `data` of each operation is decoded by inverting its `encoding` per RSL6a | +| MPD4a | A leading `json` transform is not inverted: the `data` stays as JSON text with `encoding` `json` | + +Tests that a `MESSAGE_PATCH` received over realtime is delivered to subscribers with its operations decoded, keeping JSON values as text. + +### Setup +```pseudo +channel_name = "test-MPD4-${random_id()}" + +mock_ws = MockWebSocketClient( + onConnectionAttempt: (conn) => { + conn.respond_with_success(CONNECTED()) + }, + onMessageFromClient: (msg) => { + IF msg.action == ATTACH: + mock_ws.active_connection.send_to_client(ATTACHED(channel: channel_name)) + } +) + +client = Realtime( + options: ClientOptions(key: "appId.keyId:keySecret", autoConnect: false, useBinaryProtocol: false), + webSocketClient: mock_ws +) +channel = client.channels.get(channel_name) +received = [] +``` + +### Test Steps +```pseudo +client.connect() +AWAIT_STATE connection == CONNECTED +AWAIT channel.subscribe((msg) => received.append(msg)) + +mock_ws.active_connection.send_to_client(ProtocolMessage( + action: MESSAGE, + channel: channel_name, + id: "conn:0", + timestamp: 1700000002000, + messages: [{ + "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" }] } + } + }] +)) +poll_until(received.length == 1) +``` + +### Assertions +```pseudo +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 ops.length == 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 null OR ops[1].encoding == "" + +ASSERT ops[2].data == "text" +ASSERT ops[2].encoding IS null 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" +CLOSE_CLIENT(client) +``` + +--- + +## TM9 — subscriber keeps its copy up to date with Message.applyPatch + +**Test ID**: `realtime/unit/TM9/subscriber-applies-patch-0` + +| Spec | Requirement | +|------|-------------| +| TM9 | `Message.applyPatch` returns a new `Message` that represents the copy with the patch applied | +| TM9d1 | The result's `action` is `MESSAGE_UPDATE` | +| TM9d4 | The result's `version` is the patch's `version` | + +Tests the end-to-end use: a subscriber receives a `MESSAGE_CREATE` with JSON data, then two `MESSAGE_PATCH` messages, and applies each to its copy. + +### Setup +```pseudo +channel_name = "test-TM9-subscriber-${random_id()}" + +mock_ws = MockWebSocketClient( + onConnectionAttempt: (conn) => { + conn.respond_with_success(CONNECTED()) + }, + onMessageFromClient: (msg) => { + IF msg.action == ATTACH: + mock_ws.active_connection.send_to_client(ATTACHED(channel: channel_name)) + } +) + +client = Realtime( + options: ClientOptions(key: "appId.keyId:keySecret", autoConnect: false, useBinaryProtocol: false), + webSocketClient: mock_ws +) +channel = client.channels.get(channel_name) + +copy = null +patches_applied = 0 +``` + +### Test Steps +```pseudo +client.connect() +AWAIT_STATE connection == CONNECTED +AWAIT channel.subscribe((msg) => { + IF msg.action == MessageAction.MESSAGE_CREATE: + copy = msg + ELSE IF msg.action == MessageAction.MESSAGE_PATCH: + copy = Message.applyPatch(copy, msg) + patches_applied++ +}) + +FUNCTION send_message(msg_serial, wire_message): + mock_ws.active_connection.send_to_client(ProtocolMessage( + action: MESSAGE, + channel: channel_name, + id: "conn:" + msg_serial, + timestamp: 1700000000000, + messages: [wire_message] + )) + +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" }] } + } +}) +poll_until(patches_applied == 2) +``` + +### Assertions +```pseudo +ASSERT copy.action == MessageAction.MESSAGE_UPDATE +ASSERT copy.serial == "msg-serial-1" +ASSERT copy.version.serial == "version-serial-3" +ASSERT copy.data == { "text": "Hello", "toolCalls": [{ "name": "search" }] } +ASSERT copy.extras["headers"] == { "status": "complete" } + +# Kept from the MESSAGE_CREATE, not taken from the patches +ASSERT copy.clientId == "author" +ASSERT copy.name == "reply" +CLOSE_CLIENT(client) +``` diff --git a/uts/rest/unit/channel/patch_message.md b/uts/rest/unit/channel/patch_message.md new file mode 100644 index 000000000..f37b437a2 --- /dev/null +++ b/uts/rest/unit/channel/patch_message.md @@ -0,0 +1,335 @@ +# REST Channel PatchMessage Tests + +Spec points: `RSL15`, `RSL15a`, `RSL15b`, `RSL15b1`, `RSL15c`, `RSL15e`, `RSL15g`, `MPD3`, `MPD3a`, `MPD3b`, `MPD3c`, `MPD3d` + +## Test Type +Unit test with mocked HTTP client + +## Mock HTTP Infrastructure + +These tests use the mock HTTP infrastructure defined in `uts/rest/unit/helpers/mock_http.md`. + +## Related Tests + +`patchMessage()` shares the behaviour of `updateMessage()`, `deleteMessage()` and `appendMessage()` that `uts/rest/unit/channel/update_delete_message.md` covers (RSL15b7, RSL15c, RSL15e, RSL15f, serial URL-encoding). The tests below cover what is specific to `patchMessage()`: its action, and the encoding of the `patches` field. + +--- + +## RSL15b, RSL15b1 — patchMessage sends PATCH with action MESSAGE_PATCH + +**Test ID**: `rest/unit/RSL15b1/patch-sends-patch-action-0` + +| Spec | Requirement | +|------|-------------| +| RSL15b | The SDK must send a PATCH to `/channels/{channelName}/messages/{serial}` with whatever fields were in the user-supplied `Message` | +| RSL15b1 | `action` set to `MESSAGE_PATCH` for `patchMessage()` | +| RSL15e | On success, returns an `UpdateDeleteResult` | + +Tests that `patchMessage()` sends a PATCH request with the `MESSAGE_PATCH` action and the `patches` field, and returns the version serial. + +### Setup +```pseudo +channel_name = "test-RSL15-patch-${random_id()}" +captured_requests = [] + +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + req.respond_with(200, { "versionSerial": "vs1" }) + } +) +install_mock(mock_http) + +client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: false +)) +channel = client.channels.get(channel_name) +``` + +### Test Steps +```pseudo +result = AWAIT channel.patchMessage( + Message( + serial: "msg-serial-1", + patches: MessagePatches( + data: [ + MessagePatchDataOperation(op: "append", path: "/content/0/text", data: " more text") + ], + extras: { + "headers": [ + MessagePatchHeaderOperation(op: "set", key: "status", value: "complete"), + MessagePatchHeaderOperation(op: "remove", key: "draft") + ] + } + ) + ) +) +``` + +### Assertions +```pseudo +ASSERT captured_requests.length == 1 + +request = captured_requests[0] +ASSERT request.method == "PATCH" +ASSERT request.url.path == "/channels/" + encode_uri_component(channel_name) + "/messages/msg-serial-1" + +body = parse_json(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 result IS UpdateDeleteResult +ASSERT result.versionSerial == "vs1" +``` + +--- + +## RSL15g, MPD3 — patch operation values encoded with the JSON protocol + +**Test ID**: `rest/unit/RSL15g/patch-values-encoded-json-0` + +| Spec | Requirement | +|------|-------------| +| RSL15g | The `data` of each operation in `patches` must be encoded per MPD3 | +| MPD3a | A string is sent unchanged | +| MPD3b | A binary value is encoded per RSL4d1 when using JSON: Base64, with `encoding` `base64` | +| MPD3c | Any other value, including a number, boolean or `null`, is stringified as JSON with `encoding` `json` | +| MPD3d | An operation without `data` is sent without `data` or `encoding` | + +Tests that each operation's value is encoded for the JSON protocol, including JSON values that are not objects or arrays. + +### Setup +```pseudo +channel_name = "test-RSL15g-json-${random_id()}" +captured_requests = [] + +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + req.respond_with(200, { "versionSerial": "vs1" }) + } +) +install_mock(mock_http) + +client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: false +)) +channel = client.channels.get(channel_name) +``` + +### Test Steps +```pseudo +AWAIT channel.patchMessage( + 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: null), + MessagePatchDataOperation(op: "remove", path: "/old") + ]) + ) +) +``` + +### Assertions +```pseudo +ops = parse_json(captured_requests[0].body)["patches"]["data"] +ASSERT ops.length == 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 ops[2]["data"] IS String +ASSERT parse_json(ops[2]["data"]) == { "b": 1 } +ASSERT ops[2]["encoding"] == "json" +ASSERT parse_json(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" } +``` + +--- + +## RSL15g, MPD3 — patch operation values encoded with the MessagePack protocol + +**Test ID**: `rest/unit/RSL15g/patch-values-encoded-msgpack-1` + +| Spec | Requirement | +|------|-------------| +| RSL15g | The `data` of each operation in `patches` must be encoded per MPD3 | +| MPD3a | A string is sent unchanged, as a string | +| MPD3b | A binary value is encoded per RSL4c1 when using MessagePack: as MessagePack binary | +| MPD3c | Any other value is stringified as JSON, sent as a MessagePack string, with `encoding` `json` | + +Tests that each operation's value is encoded for the MessagePack protocol. + +### Setup +```pseudo +channel_name = "test-RSL15g-msgpack-${random_id()}" +captured_requests = [] + +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + req.respond_with(200, { "versionSerial": "vs1" }) + } +) +install_mock(mock_http) + +client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: true # MessagePack +)) +channel = client.channels.get(channel_name) +``` + +### Test Steps +```pseudo +AWAIT channel.patchMessage( + 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) + ]) + ) +) +``` + +### Assertions +```pseudo +body = msgpack_decode(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 null + +# Binary transmitted directly, no Base64 +ASSERT ops[1]["data"] == bytes([0x01, 0x02]) +ASSERT "encoding" NOT IN ops[1] OR ops[1]["encoding"] IS null + +# JSON value as a MessagePack string +ASSERT ops[2]["data"] IS String +ASSERT ops[2]["data"] == "42" +ASSERT ops[2]["encoding"] == "json" +``` + +--- + +## RSL15c — patchMessage does not mutate the user-supplied Message or its patches + +**Test ID**: `rest/unit/RSL15c/patch-no-mutate-message-0` + +| Spec | Requirement | +|------|-------------| +| RSL15c | The SDK must not mutate the user-supplied `Message` object | +| MPD3 | The SDK must not mutate the user-supplied operation | + +Tests that encoding the operation values for the request leaves the user's `Message`, and each operation's `data` and `encoding`, unchanged. + +### Setup +```pseudo +channel_name = "test-RSL15c-patch-${random_id()}" + +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => req.respond_with(200, { "versionSerial": "vs1" }) +) +install_mock(mock_http) + +client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: false +)) +channel = client.channels.get(channel_name) +``` + +### Test Steps +```pseudo +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.patchMessage(message) +``` + +### Assertions +```pseudo +ASSERT message.action IS null OR message.action == MessageAction.MESSAGE_CREATE +ASSERT message.patches.data.length == 2 +ASSERT message.patches.data[0].data == { "b": 1 } +ASSERT message.patches.data[0].encoding IS null +ASSERT message.patches.data[1].data == bytes([0x01, 0x02]) +ASSERT message.patches.data[1].encoding IS null +``` + +--- + +## RSL15a — patchMessage requires a serial + +**Test ID**: `rest/unit/RSL15a/patch-serial-required-0` + +**Spec requirement:** RSL15a — The first argument is a `Message` object, which must contain a populated `serial` field. + +Tests that `patchMessage()` fails, without sending a request, when the message has no serial. The error code matches the one `update_delete_message.md` asserts for the sibling operations. + +### Setup +```pseudo +captured_requests = [] + +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + req.respond_with(200, { "versionSerial": "vs1" }) + } +) +install_mock(mock_http) + +client = Rest(options: ClientOptions(key: "appId.keyId:keySecret")) +channel = client.channels.get("test-RSL15a-patch-${random_id()}") +``` + +### Test Steps and Assertions +```pseudo +AWAIT channel.patchMessage(Message( + patches: MessagePatches(data: [MessagePatchDataOperation(op: "append", path: "/text", data: "x")]) +)) FAILS WITH error +ASSERT error.code == 40003 + +ASSERT captured_requests.length == 0 +``` diff --git a/uts/rest/unit/types/message_apply_patch.md b/uts/rest/unit/types/message_apply_patch.md new file mode 100644 index 000000000..bf856f049 --- /dev/null +++ b/uts/rest/unit/types/message_apply_patch.md @@ -0,0 +1,626 @@ +# Message.applyPatch Tests + +Spec points: `TM9`, `TM9a`, `TM9b`, `TM9c`, `TM9d`, `TM9d1`–`TM9d4`, `TM9e`, `TM9f`, `TM9f1`–`TM9f6`, `TM9g`, `TM9g1`–`TM9g4` + +## Test Type +Unit test (no mocking needed — `Message.applyPatch` is a pure function) + +## Conventions + +The copy and the patch are built with `Message.fromEncoded` (TM3), as the SDK would decode them on receipt, so each operation's value is in the form MPD4 gives it. Two helpers keep the tests short: + +```pseudo +FUNCTION decode(values): + RETURN AWAIT Message.fromEncoded({ "serial": "s1", "timestamp": 1, ...values }) + +FUNCTION decode_patch(patches, values = {}): + RETURN decode({ + "action": 6, # MESSAGE_PATCH + "version": { "serial": "v2", "timestamp": 2 }, + "patches": patches, + ...values + }) +``` + +A copy whose `data` is decoded JSON is built with `"encoding": "json"`; a copy whose `data` is JSON text is built with the text and no encoding, so it decodes to a string. + +Every failure of `applyPatch` is an `ErrorInfo` with `code` 40000 and `statusCode` 400 (TM9a, TM9b, TM9e). + +--- + +## TM9d, TM9f3, TM9g1 — applies operations to decoded JSON data + +**Test ID**: `rest/unit/TM9f3/apply-to-decoded-data-0` + +| Spec | Requirement | +|------|-------------| +| TM9d1 | The result's `action` is `MESSAGE_UPDATE` | +| TM9d4 | The result's `version` is the patch's `version` | +| TM9f3e | `set` with the last reference token `-` adds an element after the last one | +| TM9f3d | `set` of an object member adds the member if absent | +| TM9f3f | `append` concatenates a string value | +| TM9f3h | A value with `encoding` `json` is the JSON value its text represents | +| TM9g1 | Header operations `set` and `remove` change `extras.headers` | + +Tests that `applyPatch` applies data and header operations to a copy whose `data` is a decoded JSON object. + +### Test Steps +```pseudo +copy = 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.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +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 null OR patched.encoding == "" +ASSERT patched.extras == { "headers": { "status": "complete" } } +ASSERT patched.patches IS null +ASSERT patched IS Message +``` + +--- + +## TM9d — keeps the copy's fields other than data, extras and version + +**Test ID**: `rest/unit/TM9d/keeps-copy-fields-0` + +| Spec | Requirement | +|------|-------------| +| TM9d | The result has the copy's attribute values, except those in TM9d1–TM9d4 | +| TM9h | The patch's own `clientId`, `connectionId` and `timestamp` do not affect the result | + +Tests that the result takes only `action`, `data`, `encoding`, `extras` and `version` from applying the patch. + +### Test Steps +```pseudo +copy = decode({ "clientId": "author", "connectionId": "c1", "data": "Hel" }) +patch = decode_patch( + { "data": [{ "op": "append", "data": "lo" }] }, + { "clientId": "patcher", "connectionId": "c2", "timestamp": 2 } +) + +patched = Message.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +ASSERT patched.clientId == "author" +ASSERT patched.connectionId == "c1" +ASSERT patched.timestamp == 1 +ASSERT patched.version.serial == "v2" +ASSERT patched.data == "Hello" +``` + +--- + +## TM9c — does not mutate the copy + +**Test ID**: `rest/unit/TM9c/copy-not-mutated-0` + +**Spec requirement:** TM9c — The SDK must not mutate the copy, nor any value it holds, such as a JSON-encodable object or array in its `data` or its `extras`. + +Tests that the copy, its decoded data and its extras are unchanged after `applyPatch`. + +### Test Steps +```pseudo +copy = decode({ + "data": "{\"a\":{\"text\":\"x\"},\"b\":{\"unchanged\":true},\"list\":[1]}", + "encoding": "json", + "extras": { "headers": { "h": "v" } } +}) +before = copy.toJson() +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.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +ASSERT copy.toJson() == before +ASSERT copy.action == MessageAction.MESSAGE_CREATE +ASSERT copy.data == { "a": { "text": "x" }, "b": { "unchanged": true }, "list": [1] } +ASSERT copy.extras == { "headers": { "h": "v" } } + +ASSERT patched.data == { "a": { "text": "xy" }, "b": { "unchanged": true }, "list": [1, 2] } +ASSERT patched.extras == { "headers": { "h": "w" } } +``` + +--- + +## TM9f5 — splices operations into JSON text, keeping its formatting + +**Test ID**: `rest/unit/TM9f5/splice-into-json-text-0` + +| Spec | Requirement | +|------|-------------| +| TM9f5 | For `data` holding JSON text, only the described text changes; whitespace and number text are unchanged | +| TM9f5a | The value text is the operation's `data` verbatim if its `encoding` is `json`, else the JSON string of its value | +| TM9f5c | A new member is inserted after the last member's value as `,"name":value`, without whitespace | +| TM9f5d | A new element is inserted after the last element as `,value`, without whitespace | +| TM9f5e | `append` inserts the escaped string before the closing quotation mark | + +Tests that operations on a string holding JSON text produce exactly the expected text. + +### Test Steps +```pseudo +text = "{ \"content\" : [ {\"text\":\"Hel\"} ], \"n\": 1.0 }" +copy = 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.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +ASSERT patched.data IS String +ASSERT patched.data == "{ \"content\" : [ {\"text\":\"Hello \\\"world\\\"\"},\"end\" ], \"n\": 1.0,\"obj\":{ \"spaced\" : 1 } }" +ASSERT patched.encoding IS null OR patched.encoding == "" +``` + +--- + +## TM9f5 — binary JSON text is patched as its UTF-8 text is + +**Test ID**: `rest/unit/TM9f5/splice-into-binary-json-1` + +**Spec requirement:** TM9f5 — If `data` is binary holding JSON text, the result is binary holding the changed JSON text. + +Tests that a copy whose `data` is binary UTF-8 JSON gives binary data with the same text a string copy gives. + +### Test Steps +```pseudo +text = "{ \"content\" : [ {\"text\":\"Hel\"} ] }" +copy = decode({ "data": base64_encode(utf8_encode(text)), "encoding": "base64" }) +patch = decode_patch({ + "data": [{ "op": "append", "path": "/content/0/text", "data": "lo" }] +}) + +patched = Message.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +ASSERT patched.data IS Binary +ASSERT utf8_decode(patched.data) == "{ \"content\" : [ {\"text\":\"Hello\"} ] }" +``` + +--- + +## TM9f5f, TM9f5g, TM9f5h — removes members and elements from JSON text + +**Test ID**: `rest/unit/TM9f5f/remove-from-json-text-0` + +| Spec | Requirement | +|------|-------------| +| TM9f5f | A member or element followed by another is deleted up to the start of the next | +| TM9f5g | The last of several is deleted from the end of the previous value | +| TM9f5h | The only one is deleted from its start to the end of its value | + +Tests the three cases of removing from JSON text, on JSON kept outside an Ably message, passed as the copy's `data`. + +### Test Steps +```pseudo +patch = decode_patch({ + "data": [ + { "op": "remove", "path": "/a/1" }, + { "op": "remove", "path": "/b" }, + { "op": "remove", "path": "/c" }, + { "op": "remove", "path": "/d/only" } + ] +}) +copy = Message(serial: "s1", data: "{\"a\":[1,2,3],\"b\":2,\"c\":3,\"d\":{\"only\":true}}") + +patched = Message.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +# /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\":{}}" +``` + +### Test Steps (last of several) +```pseudo +copy2 = Message(serial: "s1", data: "{\"a\":1, \"b\":2}") +patch2 = decode_patch({ "data": [{ "op": "remove", "path": "/b" }] }) + +patched2 = Message.applyPatch(copy2, patch2) +``` + +### Assertions (last of several) +```pseudo +# TM9f5g: deleted from the end of 1, the previous value +ASSERT patched2.data == "{\"a\":1}" +``` + +--- + +## TM9f5i — escaped member names are matched after unescaping + +**Test ID**: `rest/unit/TM9f5i/escaped-member-name-0` + +**Spec requirement:** TM9f5i — The SDK must compare the name of a member in the JSON text with a reference token after unescaping the JSON string of the name. + +Tests that a member whose name is escaped in the JSON text is found by its unescaped name, and that RFC 6901 escapes in the path are unescaped. + +### Test Steps +```pseudo +copy = 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.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +ASSERT patched.data == "{\"a\\u0062\":\"x1\",\"c/d\":\"y2\"}" +``` + +--- + +## TM9f6 — appended text is escaped as a JSON string + +**Test ID**: `rest/unit/TM9f6/json-string-escaping-0` + +**Spec requirement:** TM9f6 — `"` and `\` are escaped with a backslash; U+0008, U+0009, U+000A, U+000C and U+000D as `\b`, `\t`, `\n`, `\f` and `\r`; other characters from U+0000 to U+001F as `\u` with four lowercase hexadecimal digits; every other character is unescaped. + +Tests the escaping of text spliced into JSON text, for both `append` and a new member's name. + +### Test Steps +```pseudo +copy = decode({ "data": "{\"t\":\"\"}" }) +patch = decode_patch({ + "data": [ + { "op": "append", "path": "/t", "data": "q\"b\\n\nt\tc\u0001é<>&" }, + { "op": "set", "path": "/new\nkey", "data": "v" } + ] +}) + +patched = Message.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +ASSERT patched.data == "{\"t\":\"q\\\"b\\\\n\\nt\\tc\\u0001é<>&\",\"new\\nkey\":\"v\"}" +``` + +--- + +## TM9f2 — applies operations to the whole of data + +**Test ID**: `rest/unit/TM9f2/apply-to-whole-data-0` + +| Spec | Requirement | +|------|-------------| +| TM9f2a | `set` without a path replaces `data`; a `json` value is decoded and the `encoding` is empty | +| TM9f2b | `append` to absent `data` sets it to the operation's `data` | +| TM9f2c | `append` of a string to a string, or binary to binary, concatenates them | + +Tests the operations without a `path`. + +### Test Steps and Assertions +```pseudo +append = decode_patch({ "data": [{ "op": "append", "data": " world" }] }) + +# TM9f2c — string +ASSERT Message.applyPatch(decode({ "data": "hello" }), append).data == "hello world" + +# TM9f2b — absent data +ASSERT Message.applyPatch(decode({}), append).data == " world" + +# TM9f2c — binary +append_binary = decode_patch({ "data": [{ "op": "append", "data": "Aw==", "encoding": "base64" }] }) +binary = decode({ "data": "AQI=", "encoding": "base64" }) +ASSERT Message.applyPatch(binary, append_binary).data == bytes([0x01, 0x02, 0x03]) + +# TM9f2a — set to a JSON value +set = decode_patch({ "data": [{ "op": "set", "data": "{\"a\":1}", "encoding": "json" }] }) +patched = Message.applyPatch(decode({ "data": "hello" }), set) +ASSERT patched.data == { "a": 1 } +ASSERT patched.encoding IS null OR patched.encoding == "" + +# TM9f2a — set to a string +set_string = decode_patch({ "data": [{ "op": "set", "data": "replaced" }] }) +ASSERT Message.applyPatch(decode({ "data": "{\"a\":1}", "encoding": "json" }), set_string).data == "replaced" +``` + +--- + +## TM9f2d — rejects appending to whole data that is not a string or binary + +**Test ID**: `rest/unit/TM9f2d/append-whole-non-string-0` + +**Spec requirement:** TM9f2d — Any other `append` without a path, and any `remove` without a path, cannot be applied. + +Tests that appending without a path to decoded JSON data, and removing without a path, fail. + +### Test Steps and Assertions +```pseudo +copy = decode({ "data": "{\"a\":1}", "encoding": "json" }) + +append = decode_patch({ "data": [{ "op": "append", "data": "x" }] }) +Message.applyPatch(copy, append) FAILS WITH error +ASSERT error.code == 40000 +ASSERT error.statusCode == 400 + +remove = decode_patch({ "data": [{ "op": "remove" }] }) +Message.applyPatch(copy, remove) FAILS WITH error +ASSERT error.code == 40000 +ASSERT error.statusCode == 400 +``` + +--- + +## TM9e — rejects the whole patch if any operation is rejected + +**Test ID**: `rest/unit/TM9e/atomic-rejection-0` + +**Spec requirement:** TM9e — If any operation cannot be applied, `applyPatch` must fail with an `ErrorInfo` with `code` 40000 and `statusCode` 400, and must not return a result. The `message` should identify the operation by its index. + +Tests that a failure in the second operation fails the whole patch, and leaves the copy unchanged. + +### Test Steps +```pseudo +copy = 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" }] } +}) +``` + +### Assertions +```pseudo +Message.applyPatch(copy, patch) FAILS WITH error +ASSERT error.code == 40000 +ASSERT error.statusCode == 400 +ASSERT error.message CONTAINS "1" # the index of the failing operation (SHOULD) + +ASSERT copy.data == { "a": "x" } +ASSERT copy.extras == { "headers": { "h": "v" } } +``` + +--- + +## TM9f1, TM9f3 — rejects operations that cannot be applied + +**Test ID**: `rest/unit/TM9f3/invalid-operations-rejected-0` + +| Spec | Requirement | +|------|-------------| +| TM9f1 | An `op` other than `set`, `append` or `remove` cannot be applied | +| TM9f3 | A path operation requires `data` to be a JSON object or array | +| TM9f3a | A `path` must be a JSON Pointer | +| TM9f3b | Every reference token but the last must reference an existing value | +| TM9f3c | The parent must be an object or array | +| TM9f3e | `set` of an array element requires `-` or an existing index | +| TM9f3f | `append` requires an existing string, and cannot use `-` | +| TM9f3g | `remove` requires an existing value, and cannot use `-` | + +Tests each case that cannot be applied, against both decoded JSON data and JSON text, since the SDK applies operations to each form separately (TM9f4, TM9f5). + +### Test Steps and Assertions +```pseudo +cases = [ + # [data, operation] + [{ "a": 1 }, { "op": "append", "path": "/a", "data": "x" }], # TM9f3f: not a string + [{ "a": [] }, { "op": "append", "path": "/a/-", "data": "x" }], # TM9f3f: "-" + [{ "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 copy IN [ + decode({ "data": json_stringify(data), "encoding": "json" }), # decoded JSON + decode({ "data": json_stringify(data) }) # JSON text + ]: + patch = decode_patch({ "data": [op] }) + Message.applyPatch(copy, patch) FAILS WITH error + ASSERT error.code == 40000 + ASSERT error.statusCode == 400 + +# 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" }] }) +Message.applyPatch(not_container, patch) FAILS WITH error +ASSERT error.code == 40000 +``` + +--- + +## TM9g1 — rejects removing a header that does not exist + +**Test ID**: `rest/unit/TM9g1/remove-missing-header-0` + +**Spec requirement:** TM9g1 — `remove` cannot be applied if `extras.headers` does not have the header. + +### Test Steps and Assertions +```pseudo +copy = decode({ "data": "x" }) +patch = decode_patch({ "extras": { "headers": [{ "op": "remove", "key": "h" }] } }) + +Message.applyPatch(copy, patch) FAILS WITH error +ASSERT error.code == 40000 +ASSERT error.statusCode == 400 +``` + +--- + +## TM9g1 — set header adds extras and headers when absent + +**Test ID**: `rest/unit/TM9g1/set-header-adds-extras-1` + +**Spec requirement:** TM9g1 — `set` sets the member of `extras.headers` named by its `key`, adding `extras` and `extras.headers` if they are absent. + +### Test Steps and Assertions +```pseudo +copy = decode({ "data": "x" }) +patch = decode_patch({ "extras": { "headers": [{ "op": "set", "key": "status", "value": "done" }] } }) + +ASSERT Message.applyPatch(copy, patch).extras == { "headers": { "status": "done" } } +``` + +--- + +## TM9g2, TM9g4, TM9h — sets or removes the user claim, ignoring the patch's own extras + +**Test ID**: `rest/unit/TM9g2/user-claim-operations-0` + +| Spec | Requirement | +|------|-------------| +| TM9g2 | `userClaim` `set` sets `extras.userClaim`; `remove` deletes it, if present | +| TM9g4 | If deleting `extras.userClaim` leaves `extras` empty, the result has no `extras` | +| TM9h | The patch's own `extras` do not affect the result | + +### Test Steps and Assertions +```pseudo +copy = decode({ "data": "x", "extras": { "headers": { "h": "v" }, "userClaim": "moderator" } }) + +set = decode_patch( + { "data": [{ "op": "append", "data": "y" }], "extras": { "userClaim": { "op": "set", "value": "guest" } } }, + { "extras": { "push": { "notification": { "title": "t" } }, "userClaim": "guest" } } +) +patched = Message.applyPatch(copy, set) +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.applyPatch(copy, remove).extras == { "headers": { "h": "v" } } + +# Removing a missing claim succeeds, and leaves no extras (TM9g4) +unclaimed = decode({ "data": "x" }) +ASSERT Message.applyPatch(unclaimed, remove).extras IS null +``` + +--- + +## TM9g3 — removes privileged extras + +**Test ID**: `rest/unit/TM9g3/privileged-remove-0` + +**Spec requirement:** TM9g3 — `privileged` `remove` deletes `extras.privileged`, if present. + +### Test Steps and Assertions +```pseudo +copy = 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.applyPatch(copy, patch).extras == { "headers": { "h": "w" } } +``` + +--- + +## TM9a, TM9b — rejects a patch for another message, or a message that is not a patch + +**Test ID**: `rest/unit/TM9a/reject-non-patch-or-serial-0` + +| Spec | Requirement | +|------|-------------| +| TM9a | If the patch's `action` is not `MESSAGE_PATCH`, fail with 40000 | +| TM9b | If the patch's `serial` is not the copy's `serial`, fail with 40000 | + +### Test Steps and Assertions +```pseudo +copy = decode({ "data": "x" }) + +# TM9b +other = decode_patch({ "data": [{ "op": "append", "data": "y" }] }, { "serial": "s2" }) +Message.applyPatch(copy, other) FAILS WITH error +ASSERT error.code == 40000 +ASSERT error.statusCode == 400 + +# TM9a +Message.applyPatch(copy, copy) FAILS WITH error +ASSERT error.code == 40000 +ASSERT error.statusCode == 400 +``` + +--- + +## TM9f4 — sets a member named like a language-reserved key as an ordinary member + +**Test ID**: `rest/unit/TM9f4/reserved-member-name-0` + +**Spec requirement:** TM9f4 — The SDK must add or set a member named by a reference token as an ordinary member of the object, whatever its name. + +Tests that a member named `__proto__` (special in JavaScript) is set as an ordinary member. Other languages run the same test; it guards against any name the language's object model treats specially. + +### Test Steps +```pseudo +copy = decode({ "data": "{}", "encoding": "json" }) +patch = decode_patch({ + "data": [{ "op": "set", "path": "/__proto__", "data": "{\"polluted\":true}", "encoding": "json" }] +}) + +patched = Message.applyPatch(copy, patch) +``` + +### Assertions +```pseudo +ASSERT keys(patched.data) == ["__proto__"] +ASSERT patched.data["__proto__"] == { "polluted": true } +``` diff --git a/uts/rest/unit/types/message_patch_types.md b/uts/rest/unit/types/message_patch_types.md new file mode 100644 index 000000000..4459e5f5d --- /dev/null +++ b/uts/rest/unit/types/message_patch_types.md @@ -0,0 +1,212 @@ +# Message Patch Type Tests + +Spec points: `TM5`, `TM2v`, `MPA1`, `MPA2`, `MPA2a`, `MPA2b`, `MPA2b1`, `MPA2b2`, `MPA2b3`, `MPD2`, `MPD2a`–`MPD2d`, `MPD4`, `MPD4a`, `MPH2`, `MPH2a`–`MPH2c`, `MPU2`, `MPU2a`, `MPU2b`, `MPP2`, `MPP2a` + +## Test Type +Unit test (no mocking needed — pure type construction, encoding and decoding) + +## Related Tests + +The encoding of operation values when sending (MPD3) is covered by `uts/rest/unit/channel/patch_message.md` and `uts/realtime/unit/channels/channel_patch_message.md`. Applying a patch (TM9) is covered by `uts/rest/unit/types/message_apply_patch.md`. + +--- + +## TM5 — MessageAction includes MESSAGE_PATCH + +**Test ID**: `rest/unit/TM5/message-patch-action-value-0` + +**Spec requirement:** TM5 — `Message` `Action` enum has the following values in order from zero: `MESSAGE_CREATE`, `MESSAGE_UPDATE`, `MESSAGE_DELETE`, `META`, `MESSAGE_SUMMARY`, `MESSAGE_APPEND`, `MESSAGE_PATCH`. + +Tests that `MESSAGE_PATCH` has the numeric wire value 6. + +### Assertions +```pseudo +ASSERT MessageAction.MESSAGE_PATCH.toInt() == 6 +ASSERT MessageAction.fromInt(6) == MessageAction.MESSAGE_PATCH + +msg = Message.fromJson({ "serial": "s1", "action": 6 }) +ASSERT msg.action == MessageAction.MESSAGE_PATCH +``` + +--- + +## TM2v, MPA2, MPD2, MPH2, MPU2, MPP2 — received patches are parsed into typed operations + +**Test ID**: `rest/unit/TM2v/patches-parsed-from-wire-0` + +| Spec | Requirement | +|------|-------------| +| TM2v | `patches` `MessagePatches` — the changes a `MESSAGE_PATCH` makes | +| MPA2a | `data` array of `MessagePatchDataOperation` | +| MPA2b1 | `extras.headers` array of `MessagePatchHeaderOperation` | +| MPA2b2 | `extras.userClaim` `MessagePatchUserClaimOperation` | +| MPA2b3 | `extras.privileged` `MessagePatchPrivilegedOperation` | +| MPD2a–MPD2d | `op`, `path`, `data`, `encoding` | +| MPH2a–MPH2c | `op`, `key`, `value` | +| MPU2a, MPU2b | `op`, `value` | +| MPP2a | `op` | + +Tests that every attribute of a received `patches` field is exposed, including operations that only Ably sends. + +### Test Steps +```pseudo +msg = AWAIT Message.fromEncoded({ + "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" } + } + } +}) +``` + +### Assertions +```pseudo +ASSERT msg.patches IS MessagePatches + +data_ops = msg.patches.data +ASSERT data_ops.length == 3 +ASSERT data_ops[0] IS 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 null 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 null + +headers = msg.patches.extras.headers +ASSERT headers.length == 4 +ASSERT headers[0] IS 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 == true +ASSERT headers[3].op == "remove" +ASSERT headers[3].key == "draft" +ASSERT headers[3].value IS null + +ASSERT msg.patches.extras.userClaim IS MessagePatchUserClaimOperation +ASSERT msg.patches.extras.userClaim.op == "set" +ASSERT msg.patches.extras.userClaim.value == "moderator" + +ASSERT msg.patches.extras.privileged IS MessagePatchPrivilegedOperation +ASSERT msg.patches.extras.privileged.op == "remove" +``` + +--- + +## MPD4, MPD4a — operation values are decoded, keeping JSON values as text + +**Test ID**: `rest/unit/MPD4/patch-values-decoded-0` + +| Spec | Requirement | +|------|-------------| +| MPD4 | The `data` of each operation is decoded by inverting the transforms in its `encoding` per RSL6a | +| MPD4a | If the first transform is `json`, it is not inverted: `data` stays as JSON text with `encoding` `json` | + +Tests that each operation's value is decoded as a message's `data` is, except that a JSON value stays as JSON text. + +### Test Steps +```pseudo +msg = AWAIT Message.fromEncoded({ + "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" } + ] + } +}) +``` + +### Assertions +```pseudo +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 null OR ops[2].encoding == "" +ASSERT ops[3].data == "hi" +ASSERT ops[3].encoding IS null 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 null OR ops[5].encoding == "" +``` + +--- + +## MPA2, MPD2, MPH2 — patches round-trip through toJson + +**Test ID**: `rest/unit/MPA2/patches-serialized-to-wire-0` + +| Spec | Requirement | +|------|-------------| +| MPA2 | The attributes of `MessagePatches` | +| MPD2 | The attributes of `MessagePatchDataOperation` | +| MPH2 | The attributes of `MessagePatchHeaderOperation` | + +Tests that a `Message` constructed with `patches` serializes them with the wire field names. String values need no encoding (MPD3a), so they appear unchanged. + +### Test Steps +```pseudo +msg = Message( + serial: "s1", + action: MessageAction.MESSAGE_PATCH, + patches: MessagePatches( + data: [ + MessagePatchDataOperation(op: "append", path: "/text", data: "lo"), + MessagePatchDataOperation(op: "remove", path: "/old") + ], + extras: { + "headers": [MessagePatchHeaderOperation(op: "set", key: "status", value: "complete")] + } + ) +) +json_data = msg.toJson() +``` + +### Assertions +```pseudo +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" } +] +```