diff --git a/specifications/features.md b/specifications/features.md index a3bdbe64f..7aebbce66 100644 --- a/specifications/features.md +++ b/specifications/features.md @@ -370,6 +370,9 @@ Support for the deprecated client options `environment`, `restHost`, `realtimeHo - `(RSL15c)` The SDK must not mutate the user-supplied `Message` object. - `(RSL15d)` The request body must be encoded to the appropriate format per `RSC8`. - `(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) + - `(RSL16b)` It is a programmer error to access this property without first providing the `Objects` plugin ([PC5](#PC5)) in the client options. This programmer error should be handled in an idiomatic fashion; if this means accessing the property should throw an error, then the error should be an `ErrorInfo` with `statusCode` 400 and `code` 40019. ### Plugins @@ -377,7 +380,9 @@ Support for the deprecated client options `environment`, `restHost`, `realtimeHo - `(PC2)` No generic plugin interface is specified, and therefore there is no common API exposed by all plugins. However, for type-safety, the opaque interface `Plugin` should be used in strongly-typed languages as the type of the `ClientOptions.plugins` collection as per [TO3o](#TO3o). - `(PC3)` A plugin provided with the `PluginType` enum key value of `vcdiff` should be capable of decoding "vcdiff"-encoded messages. It must implement the `VCDiffDecoder` interface and the client library must be able to use it by casting it to this interface. - `(PC3a)` The base argument of the `VCDiffDecoder.decode` method should receive the stored base payload of the last message on a channel as specified by [RTL19](#RTL19). If the base payload is a string it should be encoded to binary using UTF-8 before being passed as base argument of the `VCDiffDecoder.decode` method. -- `(PC5)` A plugin provided with the `PluginType` enum key value of `LiveObjects` should provide the [RealtimeObject](../objects-features#RTO23) feature functionality for realtime channels ([RTL27](#RTL27)). The plugin object itself is not expected to provide a public API. The type of the plugin object, and how it enables the Objects feature for a realtime channel, are left for individual implementations to decide. +- `(PC5)` A plugin provided with the `PluginType` enum key value of `LiveObjects` should provide the capabilities described in the subclauses below. The plugin object itself is not expected to provide a public API. The type of the plugin object, and how it enables these features for a channel, are left for individual implementations to decide. + - `(PC5a)` the [RealtimeObject](../objects-features#RTO23) feature functionality for realtime channels ([RTL27](#RTL27)) + - `(PC5b)` the [RestObject](../objects-features#RSO1) feature functionality for REST channels ([RSL16](#RSL16)) - `(PC4)` A client library is allowed to accept plugins other than those specified in this specification, through the use of additional `ClientOptions.plugins` keys defined by that library. The library is responsible for defining the interface of these plugins, and for making sure that these keys do not clash with the keys defined in this specification. ### PluginType {#plugin-type} @@ -444,6 +449,10 @@ Support for the deprecated client options `environment`, `restHost`, `realtimeHo - `(RSAN3b)` Sends a GET request to the endpoint `/channels/{channelName}/messages/{messageSerial}/annotations`, where `messageSerial` is the identifier specified in the first argument, and any `params` are sent in the querystring - `(RSAN3c)` Returns a `PaginatedResult` page containing the first page of decoded `Annotation` objects in the `PaginatedResult#items` attribute +### RestObject {#rest-object} + +Reserved for `RestObject` feature specification, see [objects-features](../objects-features). Reserved spec point: `RSO` + ### Forwards compatibility {#rest-compatibility} - `(RSF1)` The library must apply the [robustness principle](https://en.wikipedia.org/wiki/Robustness_principle) in its processing of requests and responses with the Ably system. In particular, deserialization of Messages and related types, and associated enums, must be tolerant to unrecognised attributes or enum values. Such unrecognised values must be ignored. @@ -2276,6 +2285,7 @@ Each type, method, and attribute is labelled with the name of one or more clause class RestChannel: // RSL* name: String // RSL9 presence: RestPresence // RSL3 + object: RestObject // RSL16 history( start: Time, // RSL2b1 end: Time api-default now(), // RSL2b1 diff --git a/specifications/objects-features.md b/specifications/objects-features.md index 22f6792fe..d71a43f2c 100644 --- a/specifications/objects-features.md +++ b/specifications/objects-features.md @@ -4,10 +4,135 @@ title: Objects Features ## Overview -This document outlines the feature specification for the Objects feature of the Realtime system. It is currently under development and stored separately from the main specification to simplify the initial implementation of the feature in other SDKs. Once completed, it will be moved to the main [features](../features) spec. +This document outlines the feature specification for the Objects feature, including both its Realtime entry point ([RealtimeObject](#realtime-objects)) and its REST entry point ([RestObject](#rest-object)). It is currently under development and stored separately from the main specification to simplify the initial implementation of the feature in other SDKs. Once completed, it will be moved to the main [features](../features) spec. Objects feature enables clients to store shared data as "objects" on a channel. When an object is updated, changes are automatically propagated to all subscribed clients in realtime, ensuring each client always sees the latest state. +### RestObject {#rest-object} + +- `(RSO1)` `RestObject` is the entry point for object operations performed by a REST client: + - `(RSO1a)` There is one `RestObject` instance per `RestChannel`, accessed via the [`RestChannel#object`](../features#RSL16) attribute. + - `(RSO1b)` The `LiveObjects` plugin that provides [`RealtimeObject`](#realtime-objects) for realtime channels also provides `RestObject` for REST channels; see [PC5](../features#PC5). +- `(RSO2)` `RestObject#get` function: + - `(RSO2a)` Expects the following arguments: + - `(RSO2a1)` `params` `RestObjectGetParams` (optional) - the request parameters, with the following fields: + - `(RSO2a1a)` `objectId` `String` (optional) - the identifier of the object to fetch. If omitted, the channel object is used as the target + - `(RSO2a1b)` `path` `String` (optional) - a sub-path within the target, evaluated relative to the channel object or the specified `objectId`. The library must treat the value opaquely; see [RSO6](#RSO6) + - `(RSO2a1c)` `compact` `Boolean` (optional, default `true`) - selects the response format + - `(RSO2b)` The return type depends on `params.compact`: + - `(RSO2b1)` When `params.compact` is `true` or omitted, returns a `RestObjectGetCompactResult` ([RSO8](#RSO8)) + - `(RSO2b2)` When `params.compact` is `false`, returns a `RestObjectGetFullResult` ([RSO9](#RSO9)) + - `(RSO2c)` Sends a `GET` request to `/channels/{channelName}/object`, with `/{objectId}` appended only if `params.objectId` is provided. The `objectId` path segment must be percent-encoded per [RFC 3986 §2.1](https://datatracker.ietf.org/doc/html/rfc3986#section-2.1). + - `(RSO2d)` The `params.path` and `params.compact` fields, if provided, must be sent as URL query string parameters. + - `(RSO2e)` The response body must be decoded per [RSC8](../features#RSC8). + - `(RSO2f)` When `params.compact` is `true` or omitted, the decoded response body must be returned to the caller verbatim. The library must perform no further structural transformation or decoding. + - `(RSO2g)` When `params.compact` is `false`, the library must decode the response as follows. Let `wireNode` be the decoded response body: + - `(RSO2g1)` If `wireNode` has a `map` field, return a `RestLiveMap` ([RSO14](#RSO14)). Each `map.entries[key].data` must be recursively decoded by re-applying the rules of [RSO2g](#RSO2g) to the entry value + - `(RSO2g2)` If `wireNode` has a `counter` field, return a `RestLiveCounter` ([RSO15](#RSO15)) without further decoding + - `(RSO2g3)` Otherwise, treat `wireNode` as an [`ObjectData`](../features#OD1) leaf and decode it per [OD5](../features#OD5) + - `(RSO2g4)` Unrecognized object shapes or `ObjectData` fields must be passed through to the caller unmodified, in accordance with [RSF1](../features#RSF1) + - `(RSO2h)` The library must not perform client-side validation of `params.objectId` or `params.path` content; any server-returned error must be surfaced to the caller as a rejected `ErrorInfo`. +- `(RSO3)` `RestObject#publish` function: + - `(RSO3a)` Expects the following arguments: + - `(RSO3a1)` `op` `RestObjectOperation` ([RSO5](#RSO5)) or `RestObjectOperation[]` - a single operation or an array of operations to publish + - `(RSO3b)` The return type is a `RestObjectPublishResult` ([RSO10](#RSO10)). + - `(RSO3c)` When `op` is an array, all operations must be sent in a single server request. + - `(RSO3d)` Constructs the wire payload for each operation as follows: + - `(RSO3d1)` If the operation includes a `mapCreate.semantics` field, the library must encode the semantics value per [OMP2](../features#OMP2). If the value is unrecognized, the library should throw an `ErrorInfo` error with `statusCode` 400 and `code` 40003 + - `(RSO3d2)` Any [`ObjectData`](../features#OD1) values reachable from the operation must be encoded per [OD4](../features#OD4). This applies at least to `mapSet.value` and to the `data` field of each entry in `mapCreate.entries` + - `(RSO3d3)` The `id`, `objectId`, and `path` fields of the operation, if provided by the caller, must be preserved verbatim in the wire payload + - `(RSO3d4)` The library must not include an explicit [`ObjectOperationAction`](../features#OOP2) `action` field in the wire payload; the action is inferred from the operation-specific field that is set + - `(RSO3e)` Sends a `POST` request to `/channels/{channelName}/object` with the encoded operations as a JSON array body, encoded per [RSC8](../features#RSC8). + - `(RSO3f)` The library must not auto-generate `RestObjectOperation.id` values. The [`idempotentRestPublishing`](../features#TO3n) option ([RSL1k1](../features#RSL1k1)) does not apply to `RestObject#publish`. + - `(RSO3g)` The library must not perform client-side validation of operation targeting (combinations of `objectId` and `path`); any server-returned error must be surfaced to the caller as a rejected `ErrorInfo`. + - `(RSO3h)` The library must not enforce a client-side limit on the number of operations in a batch; any size limit is server-enforced and surfaced via the response as a rejected `ErrorInfo`. +- `(RSO4)` `RestObject#generateObjectId` function: + - `(RSO4a)` Expects the following arguments: + - `(RSO4a1)` `createBody` `RestObjectGenerateIdBody` ([RSO12](#RSO12)) - a body containing either a `mapCreate` or a `counterCreate` field + - `(RSO4b)` The return type is a `RestObjectGenerateIdResult` ([RSO11](#RSO11)). The library performs no I/O for this function: the returned values are computed locally and are intended to be supplied by the caller to a subsequent `mapCreateWithObjectId` ([RSO5d](#RSO5d)) or `counterCreateWithObjectId` ([RSO5h](#RSO5h)) operation. + - `(RSO4c)` If neither `createBody.mapCreate` nor `createBody.counterCreate` is provided, the library should throw an `ErrorInfo` error with `statusCode` 400 and `code` 40003. + - `(RSO4d)` The `type` argument for [RTO14](#RTO14) is `map` if `createBody.mapCreate` was provided, or `counter` if `createBody.counterCreate` was provided. + - `(RSO4e)` Constructs the JSON-encoded `initialValue` string as follows. The `initialValue` is always carried as a JSON string regardless of the connection's negotiated transport format, so encoding must use the JSON protocol rules from [OD4d](../features#OD4d): + - `(RSO4e1)` If `createBody.mapCreate` was provided: + - `(RSO4e1a)` The library must encode `createBody.mapCreate.semantics` per [OMP2](../features#OMP2). If the value is unrecognized, the library should throw an `ErrorInfo` error with `statusCode` 400 and `code` 40003 + - `(RSO4e1b)` For each entry in `createBody.mapCreate.entries`, the library must encode the entry's `data` value per [OD4d](../features#OD4d) + - `(RSO4e1c)` The library must produce a JSON-string representation of the resulting body, equivalent to [RTO11f15](#RTO11f15) + - `(RSO4e2)` If `createBody.counterCreate` was provided, the library must produce a JSON-string representation of the body, equivalent to [RTO12f13](#RTO12f13) + - `(RSO4f)` Generates a unique string `nonce`, as described in [RTO11f6](#RTO11f6). + - `(RSO4g)` Retrieves the current server time as described in [RTO16](#RTO16). + - `(RSO4h)` Constructs an `objectId` as described in [RTO14](#RTO14), passing the `type` from [RSO4d](#RSO4d), the `initialValue` from [RSO4e](#RSO4e), the `nonce` from [RSO4f](#RSO4f), and the server time from [RSO4g](#RSO4g). + - `(RSO4i)` Returns a `RestObjectGenerateIdResult` containing the `objectId`, `nonce`, and `initialValue`. + - `(RSO4j)` Two invocations with the same `createBody` produce different `objectId` and `nonce` values, because `nonce` is freshly generated per call ([RSO4f](#RSO4f)) and feeds into the `objectId` derivation ([RTO14](#RTO14)). + - `(RSO4k)` The `initialValue` is deterministic for a given `createBody`: identical input produces identical output. This follows from the encoding procedure in [RSO4e](#RSO4e), which depends only on the input. +- `(RSO5)` `RestObjectOperation` is the public input type accepted by [`RestObject#publish`](#RSO3). It is a tagged union of operation payloads: + - `(RSO5a)` Common fields available on every `RestObjectOperation`: + - `(RSO5a1)` `id` `String` (optional) - per-operation message ID for idempotent publishing; see [RSO3f](#RSO3f) + - `(RSO5a2)` `objectId` `String` (optional) - targets a specific object by ID + - `(RSO5a3)` `path` `String` (optional) - targets one or more objects by their location in the channel object; see [RSO6](#RSO6) + - `(RSO5b)` Each `RestObjectOperation` must include exactly one of the operation-specific body fields defined in [RSO5c](#RSO5c) through [RSO5i](#RSO5i). + - `(RSO5b1)` If a caller-supplied `RestObjectOperation` has zero, or more than one, of these body fields set, the library should throw an `ErrorInfo` error with `statusCode` 400 and `code` 40003 before sending any HTTP request. + - `(RSO5c)` `mapCreate` operation - creates a new map. Body type is `RestObjectMapCreate`: + - `(RSO5c1)` `semantics` `ObjectsMapSemantics` enum ([OMP2](../features#OMP2)) + - `(RSO5c2)` `entries` `Dict` ([RSO13](#RSO13)) - the initial entries for the map + - `(RSO5c3)` The `objectId` common field ([RSO5a2](#RSO5a2)) must not be set; the `path` common field ([RSO5a3](#RSO5a3)) is optional. If `path` is also omitted, the operation creates a standalone object whose identifier is returned in the response. + - `(RSO5d)` `mapCreateWithObjectId` operation - creates a new map using a client-supplied object ID generated via [`generateObjectId`](#RSO4). Body type is `RestObjectCreateWithObjectId`: + - `(RSO5d1)` `initialValue` `String` - the JSON-encoded initial value used when generating the `objectId`. The caller must use the value returned by [`generateObjectId`](#RSO4) unchanged + - `(RSO5d2)` `nonce` `String` - the nonce used when generating the `objectId`. The caller must use the value returned by [`generateObjectId`](#RSO4) unchanged + - `(RSO5d3)` The `objectId` common field ([RSO5a2](#RSO5a2)) must be set to the `objectId` value returned by the [`generateObjectId`](#RSO4) call that produced `initialValue` and `nonce`; the `path` common field ([RSO5a3](#RSO5a3)) must not be set. + - `(RSO5e)` `mapSet` operation - sets a key in an existing map. Body type is `RestObjectMapSet`: + - `(RSO5e1)` `key` `String` - the key to set + - `(RSO5e2)` `value` `PublishObjectData` ([RSO7](#RSO7)) - the value to assign to the key + - `(RSO5e3)` Exactly one of the `objectId` ([RSO5a2](#RSO5a2)) or `path` ([RSO5a3](#RSO5a3)) common fields must be set. + - `(RSO5f)` `mapRemove` operation - removes a key from an existing map. Body type is `RestObjectMapRemove`: + - `(RSO5f1)` `key` `String` - the key to remove + - `(RSO5f2)` Exactly one of the `objectId` ([RSO5a2](#RSO5a2)) or `path` ([RSO5a3](#RSO5a3)) common fields must be set. + - `(RSO5g)` `counterCreate` operation - creates a new counter. Body type is `RestObjectCounterCreate`: + - `(RSO5g1)` `count` `Number` - the initial value of the counter + - `(RSO5g2)` The `objectId` common field ([RSO5a2](#RSO5a2)) must not be set; the `path` common field ([RSO5a3](#RSO5a3)) is optional. If `path` is also omitted, the operation creates a standalone object whose identifier is returned in the response. + - `(RSO5h)` `counterCreateWithObjectId` operation - creates a new counter using a client-supplied object ID generated via [`generateObjectId`](#RSO4). Body type and field constraints (including the targeting rules of [RSO5d3](#RSO5d3)) are the same as [RSO5d](#RSO5d). + - `(RSO5i)` `counterInc` operation - changes the value of an existing counter by a signed `Number` amount. Body type is `RestObjectCounterInc`: + - `(RSO5i1)` `number` `Number` - the amount to add to the counter (use a negative value to decrement) + - `(RSO5i2)` Exactly one of the `objectId` ([RSO5a2](#RSO5a2)) or `path` ([RSO5a3](#RSO5a3)) common fields must be set. + - `(RSO5j)` For plain `mapCreate` ([RSO5c](#RSO5c)) and `counterCreate` ([RSO5g](#RSO5g)) operations, the server generates the `objectId` and returns it in [`RestObjectPublishResult.objectIds`](#RSO10c). This differs from the realtime client, where the client library generates the `objectId` locally per [RTO14](#RTO14) for objects created from [`LiveMap`](#RTLMV1) and [`LiveCounter`](#RTLCV1) value types before publishing the create operation. The `mapCreateWithObjectId` ([RSO5d](#RSO5d)) and `counterCreateWithObjectId` ([RSO5h](#RSO5h)) operations provide equivalent client-side ID generation for REST callers via [`RestObject#generateObjectId`](#RSO4), which is useful when a batch needs to reference newly-created objects by ID before the server has assigned them. +- `(RSO6)` The library must pass caller-supplied `path` strings (in [`RestObject#get`](#RSO2) `params` and in [`RestObjectOperation`](#RSO5)) to the server without modification or normalization. Path semantics are server-defined. +- `(RSO7)` `PublishObjectData` is the user-facing leaf value type used in [`RestObjectOperation`](#RSO5) fields that carry a leaf value, such as the `value` field of [`mapSet`](#RSO5e) and the `data` field of each entry in `mapCreate.entries` ([RSO5c2](#RSO5c2)). Exactly one of the following typed fields must be set: + - `(RSO7a)` `string` `String` + - `(RSO7b)` `number` `Number` + - `(RSO7c)` `boolean` `Boolean` + - `(RSO7d)` `bytes` `Binary` + - `(RSO7e)` `json` `JsonObject | JsonArray` + - `(RSO7f)` `objectId` `String` - a reference to an existing object by its ID +- `(RSO8)` `RestObjectGetCompactResult` is the return type of [`RestObject#get`](#RSO2) when `params.compact` is `true` or omitted. The library returns the decoded response body verbatim per [RSO2f](#RSO2f); the shape and value formats are server-defined and are not transformed by the library. +- `(RSO9)` `RestObjectGetFullResult` is the return type of [`RestObject#get`](#RSO2) when `params.compact` is `false`. It is one of: + - `(RSO9a)` `RestLiveMap` ([RSO14](#RSO14)), returned when the response body has a `map` field per [RSO2g1](#RSO2g1) + - `(RSO9b)` `RestLiveCounter` ([RSO15](#RSO15)), returned when the response body has a `counter` field per [RSO2g2](#RSO2g2) + - `(RSO9c)` A decoded [`ObjectData`](../features#OD1) leaf, returned when the response is a typed leaf value per [RSO2g3](#RSO2g3). The library must return an `ObjectData` instance with: + - `(RSO9c1)` The [`objectId`](../features#OD2a) and [`encoding`](../features#OD2b) fields unset. (If the response carried an object reference, the result would instead be a `RestLiveMap` ([RSO9a](#RSO9a)), `RestLiveCounter` ([RSO9b](#RSO9b)), or unrecognized-object fallback ([RSO9d](#RSO9d)).) + - `(RSO9c2)` Values decoded per [OD5](../features#OD5): in particular, `bytes` holds a native `Binary` value rather than a Base64-encoded string, and any JSON-encoded payload appears as the parsed `JsonObject` or `JsonArray` rather than as a JSON-encoded string + - `(RSO9d)` For object types unrecognized by the library, an object containing at minimum `{ objectId: String }`, with additional fields passed through unmodified per [RSF1](../features#RSF1) +- `(RSO10)` `RestObjectPublishResult` is the return type of [`RestObject#publish`](#RSO3). Its attributes are: + - `(RSO10a)` `messageId` `String` + - `(RSO10b)` `channel` `String` + - `(RSO10c)` `objectIds` `Array` - the identifiers of the objects affected by the operations +- `(RSO11)` `RestObjectGenerateIdResult` is the return type of [`RestObject#generateObjectId`](#RSO4). Its attributes are: + - `(RSO11a)` `objectId` `String` - the generated object identifier + - `(RSO11b)` `nonce` `String` - the nonce used to derive the `objectId`; the caller passes this verbatim into the matching [RSO5d](#RSO5d) or [RSO5h](#RSO5h) operation + - `(RSO11c)` `initialValue` `String` - the JSON-encoded initial value used to derive the `objectId`; the caller passes this verbatim into the matching [RSO5d](#RSO5d) or [RSO5h](#RSO5h) operation +- `(RSO12)` `RestObjectGenerateIdBody` is the argument type for [`RestObject#generateObjectId`](#RSO4). Exactly one of the following fields must be set: + - `(RSO12a)` `mapCreate` `RestObjectMapCreate` ([RSO5c](#RSO5c)) + - `(RSO12b)` `counterCreate` `RestObjectCounterCreate` ([RSO5g](#RSO5g)) +- `(RSO13)` `RestObjectMapEntry` is the user-facing entry type used in `RestObjectMapCreate.entries` ([RSO5c2](#RSO5c2)). Its attributes are: + - `(RSO13a)` `data` `PublishObjectData` ([RSO7](#RSO7)) +- `(RSO14)` `RestLiveMap` is the full-format representation of a map object returned by [`RestObject#get`](#RSO2) with `params.compact` set to `false`. Its attributes are: + - `(RSO14a)` `objectId` `String` - the identifier of the map object + - `(RSO14b)` `map.semantics` `ObjectsMapSemantics` ([OMP2](../features#OMP2)) - the conflict-resolution semantics. Unrecognized server values must be preserved per [RSF1](../features#RSF1) + - `(RSO14c)` `map.entries` `Dict` ([RSO16](#RSO16)) +- `(RSO15)` `RestLiveCounter` is the full-format representation of a counter object returned by [`RestObject#get`](#RSO2) with `params.compact` set to `false`. Its attributes are: + - `(RSO15a)` `objectId` `String` - the identifier of the counter object + - `(RSO15b)` `counter.data.number` `Number` - the current value of the counter +- `(RSO16)` `RestLiveMapEntry` is the entry type used in `RestLiveMap.map.entries` ([RSO14c](#RSO14c)). Its attributes are: + - `(RSO16a)` `data` `RestObjectGetFullResult` ([RSO9](#RSO9)) - recursively decoded per [RSO2g](#RSO2g) + ### RealtimeObject {#realtime-objects} - `(RTO1)` This clause has been replaced by [RTO23](#RTO23). @@ -1138,9 +1263,92 @@ An `Instance` holds a direct reference to a specific resolved `LiveObject` or pr ## Interface Definition {#idl} -Describes types for RealtimeObject.\ +Describes types for RestObject and RealtimeObject.\ Types and their properties/methods are public and exposed to users by default. An `internal` label may be used to indicate that a type or its property/method must not be exposed to users and is intended for internal SDK use only. + class RestObject: // RSO* + get(RestObjectGetParams params?) => io RestObjectGetCompactResult | RestObjectGetFullResult // RSO2 + publish(RestObjectOperation | RestObjectOperation[] op) => io RestObjectPublishResult // RSO3 + generateObjectId(RestObjectGenerateIdBody createBody) => RestObjectGenerateIdResult // RSO4 + + class RestObjectGetParams: // RSO2a1 + objectId: String? // RSO2a1a + path: String? // RSO2a1b + compact: Boolean default true // RSO2a1c + + class RestObjectOperation: // RSO5 + id: String? // RSO5a1 + objectId: String? // RSO5a2 + path: String? // RSO5a3 + mapCreate: RestObjectMapCreate? // RSO5c + mapCreateWithObjectId: RestObjectCreateWithObjectId? // RSO5d + mapSet: RestObjectMapSet? // RSO5e + mapRemove: RestObjectMapRemove? // RSO5f + counterCreate: RestObjectCounterCreate? // RSO5g + counterCreateWithObjectId: RestObjectCreateWithObjectId? // RSO5h + counterInc: RestObjectCounterInc? // RSO5i + + class RestObjectMapCreate: // RSO5c + semantics: ObjectsMapSemantics // RSO5c1 + entries: Dict // RSO5c2 + + class RestObjectMapSet: // RSO5e + key: String // RSO5e1 + value: PublishObjectData // RSO5e2 + + class RestObjectMapRemove: // RSO5f + key: String // RSO5f1 + + class RestObjectCounterCreate: // RSO5g + count: Number // RSO5g1 + + class RestObjectCounterInc: // RSO5i + number: Number // RSO5i1 + + class RestObjectCreateWithObjectId: // RSO5d, RSO5h + initialValue: String // RSO5d1 + nonce: String // RSO5d2 + + class RestObjectMapEntry: // RSO13 + data: PublishObjectData // RSO13a + + class PublishObjectData: // RSO7 + string: String? // RSO7a + number: Number? // RSO7b + boolean: Boolean? // RSO7c + bytes: Binary? // RSO7d + json: JsonObject | JsonArray? // RSO7e + objectId: String? // RSO7f + + class RestObjectGenerateIdBody: // RSO12 + mapCreate: RestObjectMapCreate? // RSO12a + counterCreate: RestObjectCounterCreate? // RSO12b + + class RestObjectPublishResult: // RSO10 + messageId: String // RSO10a + channel: String // RSO10b + objectIds: [String] // RSO10c + + class RestObjectGenerateIdResult: // RSO11 + objectId: String // RSO11a + nonce: String // RSO11b + initialValue: String // RSO11c + + class RestLiveMap: // RSO14 + objectId: String // RSO14a + map: { semantics: ObjectsMapSemantics, entries: Dict } // RSO14b, RSO14c + + class RestLiveCounter: // RSO15 + objectId: String // RSO15a + counter: { data: { number: Number } } // RSO15b + + class RestLiveMapEntry: // RSO16 + data: RestObjectGetFullResult // RSO16a + + // RestObjectGetCompactResult (RSO8) is opaque to the library and not modelled here. + // RestObjectGetFullResult (RSO9) is a discriminated union of RestLiveMap, RestLiveCounter, + // ObjectData, and a forwards-compatibility fallback; see the corresponding spec clauses. + class RealtimeObject: // RTO* get() => io PathObject // RTO23 on(ObjectsEvent event, (() ->) callback) -> StatusSubscription // RTO18 diff --git a/uts/docs/completion-status.md b/uts/docs/completion-status.md index 8ce03db1f..98d4e07b8 100644 --- a/uts/docs/completion-status.md +++ b/uts/docs/completion-status.md @@ -100,6 +100,7 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | 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` | +| RSL16 | Object attribute (RSL16a–RSL16b) | Yes — `objects/unit/rest_object_get.md` | ### Plugins @@ -109,6 +110,23 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | PT1–PT2 | PluginType enum | | | VD1–VD2 | VCDiffDecoder | Partial — `realtime/unit/helpers/mock_vcdiff.md` references VD2a | +### RestObject + +Spec items in [objects-features.md](../../specifications/objects-features.md#rest-object). + +| Spec item | Description | UTS test spec | +|-----------|-------------|---------------| +| RSO1 | RestObject entry point (RSO1a–RSO1b) | Yes — `objects/unit/rest_object_get.md` | +| RSO2 | Get function (RSO2a–RSO2h) | Yes — `objects/unit/rest_object_get.md`, `objects/integration/rest_object_test.md` | +| RSO3 | Publish function (RSO3a–RSO3h) | Yes — `objects/unit/rest_object_publish.md`, `objects/integration/rest_object_test.md` | +| RSO4 | GenerateObjectId function (RSO4a–RSO4k) | Yes — `objects/unit/rest_object_generate_id.md`, `objects/integration/rest_object_test.md` | +| RSO5 | RestObjectOperation (RSO5a–RSO5j) | Yes — `objects/unit/rest_object_publish.md`, `objects/integration/rest_object_test.md` | +| RSO6 | Paths passed through verbatim | Yes — `objects/unit/rest_object_get.md`, `objects/unit/rest_object_publish.md`, `objects/integration/rest_object_test.md` | +| RSO7 | PublishObjectData | Yes — `objects/unit/rest_object_publish.md` | +| RSO8–RSO9 | Get result types (compact, full) | Yes — `objects/unit/rest_object_get.md` | +| RSO10–RSO13 | Publish/generateObjectId result and input types | Yes — `objects/unit/rest_object_publish.md`, `objects/unit/rest_object_generate_id.md` | +| RSO14–RSO16 | RestLiveMap, RestLiveCounter, RestLiveMapEntry | Yes — `objects/unit/rest_object_get.md`, `objects/integration/rest_object_test.md` | + ### RestPresence | Spec item | Description | UTS test spec | @@ -434,10 +452,11 @@ This matrix lists all spec items from the [Ably features spec](../../specificati | **REST client** (RSC) | 18 | 16 | Partial | | **REST auth** (RSA) | 15 | 15 | Full | | **REST channels** (RSN) | 4 | 4 | Full | -| **REST channel** (RSL) | 13 | 13 | Full | +| **REST channel** (RSL) | 14 | 14 | Full | | **REST presence** (RSP) | 5 | 4 | Mostly | | **REST encryption** (RSE) | 2 | 0 | None | | **REST annotations** (RSAN) | 3 | 3 | Full | +| **REST objects** (RSO) | 10 | 10 | Full | | **Realtime client** (RTC) | 14 | 14 | Full | | **Connection** (RTN) | 23 | 19 | Partial | | **Realtime channels** (RTS) | 5 | 5 | Full | diff --git a/uts/objects/helpers/standard_test_pool.md b/uts/objects/helpers/standard_test_pool.md index 731e9931b..e48374a4c 100644 --- a/uts/objects/helpers/standard_test_pool.md +++ b/uts/objects/helpers/standard_test_pool.md @@ -489,4 +489,4 @@ Operation shapes (target by `objectId` or `path`; an optional `id` on any operat { counterInc: { number: }, objectId|path: "" } # negative number = decrement ``` -where `` is a primitive value object: `{ string: "..." }`, `{ number: ... }`, `{ boolean: ... }`, `{ bytes: "" }`, or a reference `{ objectId: "..." }` (`string`/`bytes` may also carry an optional `encoding`). +where `` is a primitive value object: `{ string: "..." }`, `{ number: ... }`, `{ boolean: ... }`, `{ bytes: "" }`, or a reference `{ objectId: "..." }`. diff --git a/uts/objects/integration/rest_object_test.md b/uts/objects/integration/rest_object_test.md new file mode 100644 index 000000000..d22d40b04 --- /dev/null +++ b/uts/objects/integration/rest_object_test.md @@ -0,0 +1,985 @@ +# RestObject Integration Tests + +Spec points: `RSL16`, `RSO2`, `RSO2g`, `RSO3`, `RSO3c`, `RSO4`, `RSO5`, `RSO5a1`, `RSO5c3`, `RSO5d`, `RSO5e`, `RSO5f`, `RSO5g2`, `RSO5h`, `RSO5i`, `RSO5j`, `RSO6`, `RSO7`, `RSO9`, `RSO10`, `RSO13`, `RSO14`, `RSO15` + +## Test Type +Integration test against Ably sandbox + +## Protocol Variants +json, msgpack + +Each test in this file runs once per protocol variant. The `PROTOCOL` variable +is set to `"json"` or `"msgpack"` for the current run. Client options should set +`useBinaryProtocol: PROTOCOL == "msgpack"`. + +## Purpose + +End-to-end verification that `RestObject#publish`, `RestObject#get` and +`RestObject#generateObjectId` interoperate with the real service: the wire encodings the SDK +produces are accepted, the responses the service returns are decoded into the documented types, and +locally generated object IDs are accepted by the server. + +Server-defined behaviour (compact formatting of bytes and JSON leaves, path syntax, error codes for +unresolvable targets) is deliberately not asserted beyond what the SDK specification requires. + +## Corresponding Unit Tests +- `objects/unit/rest_object_get.md` — RSL16, RSO2, RSO9 +- `objects/unit/rest_object_publish.md` — RSO3, RSO5, RSO7, RSO10 +- `objects/unit/rest_object_generate_id.md` — RSO4, RSO11 + +## Sandbox Setup + +Tests run against the Ably Sandbox at `https://sandbox.realtime.ably-nonprod.net`. + +### App Provisioning + +```pseudo +BEFORE ALL TESTS: + response = POST https://sandbox.realtime.ably-nonprod.net/apps + WITH body from ably-common/test-resources/test-app-setup.json + + app_config = parse_json(response.body) + api_key = app_config.keys[0].key_str + app_id = app_config.app_id + +AFTER ALL TESTS: + DELETE https://sandbox.realtime.ably-nonprod.net/apps/{app_id} + WITH Authorization: Basic {api_key} +``` + +### Common Client Setup + +`objects_plugin` denotes the SDK's `Objects` plugin, supplied under the `Objects` `PluginType` key. + +```pseudo +create_rest_channel(test_name): + client = Rest(options: ClientOptions( + key: api_key, + endpoint: "nonprod:sandbox", + useBinaryProtocol: PROTOCOL == "msgpack", + plugins: { Objects: objects_plugin } + )) + channel = client.channels.get("objects-rest-" + test_name + "-" + random_id()) + RETURN { client, channel } +``` + +### Notes +- Each test uses a unique channel name, so every test starts from an empty channel object. +- Reads that follow a write use `poll_until_success`: a value written by `publish` may not be + visible to an immediately following `get`, and a read of a path that does not exist yet fails with + a not-found error until it does. +- `keys[0]` has the default `{"*":["*"]}` capability, which permits object reads and writes. + +--- + +## RSO3, RSO2 - mapSet primitives on the channel object, read back in compact and full modes + +**Test ID**: `objects/integration/RSO3/mapset-primitives-roundtrip-0` + +| Spec | Requirement | +|------|-------------| +| RSO3 | `publish` sends operations to the server | +| RSO5e | `mapSet` sets a key on an existing map | +| RSO10 | Publish result carries `messageId`, `channel` and `objectIds` | +| RSO2f | Compact result is the server's response, verbatim | +| RSO2g1, RSO14 | Full map result is a `RestLiveMap` | +| RSO9c | Full leaf entries decoded per OD5 | + +Tests that every `PublishObjectData` leaf type round-trips through the server. Compact assertions are +limited to string, number and boolean leaves, whose compact representation the SDK does not transform. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO3-primitives") +``` + +### Test Steps +```pseudo +publish_result = AWAIT channel.object.publish([ + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "str", value: PublishObjectData(string: "hello"))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "num", value: PublishObjectData(number: 42.5))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "bool", value: PublishObjectData(boolean: true))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "bin", value: PublishObjectData(bytes: bytes([0x01, 0x02, 0x03])))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "jobj", value: PublishObjectData(json: { "a": [1, 2] }))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "jarr", value: PublishObjectData(json: ["x", 1]))) +]) + +compact = poll_until_success( + condition: FUNCTION() => + c = AWAIT channel.object.get() + IF c["jarr"] IS NOT null: + RETURN c + RETURN null +) + +full = AWAIT channel.object.get(RestObjectGetParams(compact: false)) +``` + +### Assertions +```pseudo +ASSERT publish_result.messageId IS String +ASSERT publish_result.messageId.length > 0 +ASSERT publish_result.channel == channel.name +ASSERT publish_result.objectIds IS List + +ASSERT compact["str"] == "hello" +ASSERT compact["num"] == 42.5 +ASSERT compact["bool"] == true + +ASSERT full IS RestLiveMap +ASSERT full.objectId == "root" +ASSERT full.map.semantics == "LWW" +ASSERT full.map.entries["str"].data.string == "hello" +ASSERT full.map.entries["num"].data.number == 42.5 +ASSERT full.map.entries["bool"].data.boolean == true +ASSERT full.map.entries["bin"].data.bytes IS Binary +ASSERT full.map.entries["bin"].data.bytes == bytes([0x01, 0x02, 0x03]) +ASSERT full.map.entries["jobj"].data.json == { "a": [1, 2] } +ASSERT full.map.entries["jarr"].data.json == ["x", 1] +``` + +--- + +## RSO3, RSO2 - Edge-case leaf values round-trip without being dropped or altered + +**Test ID**: `objects/integration/RSO3/mapset-edge-values-roundtrip-1` + +| Spec | Requirement | +|------|-------------| +| RSO3d2 | `mapSet.value` is encoded per OD4 and accepted by the server | +| RSO2f | Compact result is the server's response, verbatim | +| RSO9c2 | Full leaf entries decoded per OD5; `bytes` holds a native `Binary` | + +Tests leaf values that an implementation can mistake for "absent" (empty string, empty bytes, `0`, +`false`) or lose precision on (the largest and smallest integers exactly representable as an IEEE 754 +double, `±(2^53 - 1)`). Each must be stored and read back exactly. Compact assertions are limited to +string, number and boolean leaves, whose compact representation the SDK does not transform. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO3-edge-values") + +MAX_EXACT_INT = 9007199254740991 # 2^53 - 1 +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "emptyStr", value: PublishObjectData(string: ""))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "emptyBin", value: PublishObjectData(bytes: bytes([])))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "zero", value: PublishObjectData(number: 0))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "maxInt", value: PublishObjectData(number: MAX_EXACT_INT))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "minInt", value: PublishObjectData(number: -MAX_EXACT_INT))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "no", value: PublishObjectData(boolean: false))) +]) + +compact = poll_until_success( + condition: FUNCTION() => + c = AWAIT channel.object.get() + IF "no" IN c: + RETURN c + RETURN null +) + +full = AWAIT channel.object.get(RestObjectGetParams(compact: false)) +``` + +### Assertions +```pseudo +ASSERT compact["emptyStr"] == "" +ASSERT compact["zero"] == 0 +ASSERT compact["maxInt"] == MAX_EXACT_INT +ASSERT compact["minInt"] == -MAX_EXACT_INT +ASSERT compact["no"] == false + +ASSERT full.map.entries["emptyStr"].data.string == "" +ASSERT full.map.entries["emptyBin"].data.bytes IS Binary +ASSERT full.map.entries["emptyBin"].data.bytes == bytes([]) +ASSERT full.map.entries["zero"].data.number == 0 +ASSERT full.map.entries["maxInt"].data.number == MAX_EXACT_INT +ASSERT full.map.entries["minInt"].data.number == -MAX_EXACT_INT +ASSERT full.map.entries["no"].data.boolean == false +``` + +--- + +## RSO2g3 - Full-mode get of a leaf value via path + +**Test ID**: `objects/integration/RSO2g3/full-leaf-via-path-0` + +**Spec requirement:** RSO2g3 — When the full-mode target is a leaf, it is returned as an `ObjectData` decoded per OD5, with `objectId` unset (RSO9c1). + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO2g3-leaf") + +AWAIT channel.object.publish([ + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "bin", value: PublishObjectData(bytes: bytes([0xFF, 0x00])))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "prefs", value: PublishObjectData(json: { "theme": "dark" }))) +]) +``` + +### Test Steps +```pseudo +bin_leaf = poll_until_success( + condition: FUNCTION() => AWAIT channel.object.get(RestObjectGetParams(path: "bin", compact: false)) +) +json_leaf = poll_until_success( + condition: FUNCTION() => AWAIT channel.object.get(RestObjectGetParams(path: "prefs", compact: false)) +) +``` + +### Assertions +```pseudo +ASSERT bin_leaf.bytes IS Binary +ASSERT bin_leaf.bytes == bytes([0xFF, 0x00]) + +ASSERT json_leaf.json == { "theme": "dark" } +``` + +--- + +## RSO5g2, RSO5i, RSO15 - counterCreate at a path, counterInc via path and objectId + +**Test ID**: `objects/integration/RSO5i/counter-create-increment-0` + +| Spec | Requirement | +|------|-------------| +| RSO5g2 | `counterCreate` with `path` creates a counter at that location | +| RSO5i | `counterInc` changes a counter by a signed amount; targeted by `objectId` or `path` | +| RSO10c | `objectIds` identifies the affected objects | +| RSO15 | Full-mode counter is a `RestLiveCounter` | + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO5i-counter") +``` + +### Test Steps +```pseudo +create_result = AWAIT channel.object.publish(RestObjectOperation( + path: "visits", + counterCreate: RestObjectCounterCreate(count: 10) +)) + +counter_id = create_result.objectIds.find(id => id STARTS WITH "counter:") + +AWAIT channel.object.publish(RestObjectOperation( + path: "visits", + counterInc: RestObjectCounterInc(number: 5) +)) +AWAIT channel.object.publish(RestObjectOperation( + objectId: counter_id, + counterInc: RestObjectCounterInc(number: -3) +)) + +poll_until_success( + condition: FUNCTION() => (AWAIT channel.object.get(RestObjectGetParams(path: "visits"))) == 12 +) + +full = AWAIT channel.object.get(RestObjectGetParams(objectId: counter_id, compact: false)) +``` + +### Assertions +```pseudo +ASSERT counter_id IS NOT null + +ASSERT full IS RestLiveCounter +ASSERT full.objectId == counter_id +ASSERT full.counter.data.number == 12 +``` + +--- + +## RSO5g2, RSO5j - Standalone counterCreate returns a server-generated objectId + +**Test ID**: `objects/integration/RSO5g2/standalone-counter-create-1` + +| Spec | Requirement | +|------|-------------| +| RSO5g2 | `counterCreate` with neither `objectId` nor `path` creates a standalone object whose identifier is returned | +| RSO5j | For plain `counterCreate`, the server generates the `objectId` and returns it in `objectIds` | +| RSO15 | Full-mode counter is a `RestLiveCounter` | + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO5g2-standalone") +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.publish(RestObjectOperation( + counterCreate: RestObjectCounterCreate(count: 42) +)) + +counter_id = result.objectIds[0] + +full = poll_until_success( + condition: FUNCTION() => AWAIT channel.object.get(RestObjectGetParams(objectId: counter_id, compact: false)) +) +``` + +### Assertions +```pseudo +ASSERT result.objectIds.length == 1 +ASSERT counter_id STARTS WITH "counter:" + +ASSERT full IS RestLiveCounter +ASSERT full.objectId == counter_id +ASSERT full.counter.data.number == 42 +``` + +--- + +## RSO5c3, RSO5j - Standalone mapCreate returns a server-generated objectId + +**Test ID**: `objects/integration/RSO5j/standalone-map-create-0` + +| Spec | Requirement | +|------|-------------| +| RSO5c3 | `mapCreate` with neither `objectId` nor `path` creates a standalone object whose identifier is returned | +| RSO5j | For plain `mapCreate`, the server generates the `objectId` and returns it in `objectIds` | +| RSO3d2, RSO13 | Entry data of every `PublishObjectData` leaf type is encoded per OD4 and accepted by the server | + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO5j-standalone") +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.publish(RestObjectOperation( + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: { + "name": RestObjectMapEntry(data: PublishObjectData(string: "Alice")), + "age": RestObjectMapEntry(data: PublishObjectData(number: 30)), + "active": RestObjectMapEntry(data: PublishObjectData(boolean: true)), + "avatar": RestObjectMapEntry(data: PublishObjectData(bytes: bytes([0x0A, 0x0B]))), + "prefs": RestObjectMapEntry(data: PublishObjectData(json: { "theme": "dark" })), + "tags": RestObjectMapEntry(data: PublishObjectData(json: ["a", "b"])) + }) +)) + +map_id = result.objectIds[0] + +full = poll_until_success( + condition: FUNCTION() => AWAIT channel.object.get(RestObjectGetParams(objectId: map_id, compact: false)) +) +``` + +### Assertions +```pseudo +ASSERT result.objectIds.length == 1 +ASSERT map_id STARTS WITH "map:" + +ASSERT full IS RestLiveMap +ASSERT full.objectId == map_id +ASSERT full.map.entries["name"].data.string == "Alice" +ASSERT full.map.entries["age"].data.number == 30 +ASSERT full.map.entries["active"].data.boolean == true +ASSERT full.map.entries["avatar"].data.bytes IS Binary +ASSERT full.map.entries["avatar"].data.bytes == bytes([0x0A, 0x0B]) +ASSERT full.map.entries["prefs"].data.json == { "theme": "dark" } +ASSERT full.map.entries["tags"].data.json == ["a", "b"] +``` + +--- + +## RSO5c3, RSO2g1 - mapCreate at a path is reachable from the channel object + +**Test ID**: `objects/integration/RSO5c3/map-create-at-path-0` + +| Spec | Requirement | +|------|-------------| +| RSO5c3 | `mapCreate` with `path` creates the map at that location | +| RSO2g1 | Nested maps in a full-mode response are decoded recursively as `RestLiveMap` | +| RSO2d | `path` and `objectId` targeting of `get` | + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO5c3-path") +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish(RestObjectOperation( + path: "profile", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: { + "nickname": RestObjectMapEntry(data: PublishObjectData(string: "ally")) + }) +)) + +root_full = poll_until_success( + condition: FUNCTION() => + r = AWAIT channel.object.get(RestObjectGetParams(compact: false)) + IF "profile" IN r.map.entries: + RETURN r + RETURN null +) + +profile = root_full.map.entries["profile"].data +nickname_via_path = AWAIT channel.object.get(RestObjectGetParams(path: "profile.nickname")) +nickname_via_id = AWAIT channel.object.get(RestObjectGetParams(objectId: profile.objectId, path: "nickname")) +``` + +### Assertions +```pseudo +ASSERT profile IS RestLiveMap +ASSERT profile.objectId STARTS WITH "map:" +ASSERT profile.map.entries["nickname"].data.string == "ally" + +ASSERT nickname_via_path == "ally" +ASSERT nickname_via_id == "ally" +``` + +--- + +## RSO5e, RSO6 - mapSet targeted by a nested path + +**Test ID**: `objects/integration/RSO5e/mapset-nested-path-0` + +| Spec | Requirement | +|------|-------------| +| RSO5e | `mapSet` sets a key on an existing map, targeted by `path` | +| RSO6 | Caller-supplied `path` strings, including dot-separated nested paths, are passed to the server without modification | + +Tests `mapSet` targeted by a single-segment path and by a dot-separated nested path (without +wildcards), observing that each key lands on the intended map. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO5e-nested-path") + +AWAIT channel.object.publish(RestObjectOperation(path: "outer", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {}))) +poll_until_success( + condition: FUNCTION() => (AWAIT channel.object.get(RestObjectGetParams(path: "outer"))) IS NOT null +) + +AWAIT channel.object.publish(RestObjectOperation(path: "outer.inner", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {}))) +poll_until_success( + condition: FUNCTION() => (AWAIT channel.object.get(RestObjectGetParams(path: "outer.inner"))) IS NOT null +) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation(path: "outer", + mapSet: RestObjectMapSet(key: "shallow", value: PublishObjectData(number: 1))), + RestObjectOperation(path: "outer.inner", + mapSet: RestObjectMapSet(key: "deep", value: PublishObjectData(string: "value"))) +]) + +compact = poll_until_success( + condition: FUNCTION() => + c = AWAIT channel.object.get() + IF c["outer"]["shallow"] == 1 AND c["outer"]["inner"]["deep"] == "value": + RETURN c + RETURN null +) +``` + +### Assertions +```pseudo +ASSERT compact["outer"] == { "shallow": 1, "inner": { "deep": "value" } } +``` + +--- + +## RSO5e, RSO7 - mapSet with an objectId reference to an existing object + +**Test ID**: `objects/integration/RSO5e/mapset-object-reference-1` + +| Spec | Requirement | +|------|-------------| +| RSO5e | `mapSet` sets a key on an existing map | +| RSO7 | `PublishObjectData.objectId` references an existing object | +| RSO10 | Publish result carries `messageId`, `channel` and `objectIds` | +| RSO2g | Full-mode response carries the referenced object's `objectId` under each referencing key | + +Tests that a `mapSet` whose value is an `objectId` reference to an object created by an earlier, +separate publish makes a second key reference the same object. + +When an object is reachable under several keys, the server may inline its contents under only one of +them and return the others as a bare object reference; which key gets the inlined contents is +server-defined. The assertions therefore check only the `objectId` under each key, and read the +counter's value by `objectId`. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO5e-object-ref") + +create_result = AWAIT channel.object.publish(RestObjectOperation( + path: "first", + counterCreate: RestObjectCounterCreate(count: 5) +)) +counter_id = create_result.objectIds.find(id => id STARTS WITH "counter:") + +poll_until_success( + condition: FUNCTION() => (AWAIT channel.object.get(RestObjectGetParams(path: "first"))) == 5 +) +``` + +### Test Steps +```pseudo +set_result = AWAIT channel.object.publish(RestObjectOperation( + objectId: "root", + mapSet: RestObjectMapSet(key: "second", value: PublishObjectData(objectId: counter_id)) +)) + +full = poll_until_success( + condition: FUNCTION() => + r = AWAIT channel.object.get(RestObjectGetParams(compact: false)) + IF "second" IN r.map.entries: + RETURN r + RETURN null +) + +counter = AWAIT channel.object.get(RestObjectGetParams(objectId: counter_id, compact: false)) +``` + +### Assertions +```pseudo +ASSERT counter_id IS NOT null + +ASSERT set_result.messageId IS String +ASSERT set_result.messageId.length > 0 +ASSERT set_result.channel == channel.name +ASSERT set_result.objectIds IS List + +ASSERT full.map.entries["first"].data.objectId == counter_id +ASSERT full.map.entries["second"].data.objectId == counter_id + +ASSERT counter IS RestLiveCounter +ASSERT counter.counter.data.number == 5 +``` + +--- + +## RSO5f - mapRemove via path and via objectId + +**Test ID**: `objects/integration/RSO5f/map-remove-0` + +**Spec requirement:** RSO5f — `mapRemove` removes a key from an existing map, targeted by `objectId` or `path`. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO5f-remove") + +AWAIT channel.object.publish([ + RestObjectOperation(path: "settings", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: { + "a": RestObjectMapEntry(data: PublishObjectData(number: 1)), + "b": RestObjectMapEntry(data: PublishObjectData(number: 2)) + })), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "keep", value: PublishObjectData(string: "x"))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "drop", value: PublishObjectData(string: "y"))) +]) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation(path: "settings", mapRemove: RestObjectMapRemove(key: "a")), + RestObjectOperation(objectId: "root", mapRemove: RestObjectMapRemove(key: "drop")) +]) + +compact = poll_until_success( + condition: FUNCTION() => + c = AWAIT channel.object.get() + IF "drop" NOT IN c AND c["settings"] IS NOT null AND "a" NOT IN c["settings"]: + RETURN c + RETURN null +) +``` + +### Assertions +```pseudo +ASSERT compact["keep"] == "x" +ASSERT "drop" NOT IN compact +ASSERT compact["settings"] == { "b": 2 } +``` + +--- + +## RSO6 - Wildcard path passed through to the server + +**Test ID**: `objects/integration/RSO6/wildcard-path-passthrough-0` + +**Spec requirement:** RSO6 — Caller-supplied `path` strings are passed to the server without modification; path semantics are server-defined. + +Tests end-to-end that a path using the server's `*` wildcard segment is passed through unmodified, +by observing its server-side effect on every child of a map. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO6-wildcard") + +AWAIT channel.object.publish(RestObjectOperation(path: "items", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {}))) +poll_until_success( + condition: FUNCTION() => (AWAIT channel.object.get(RestObjectGetParams(path: "items"))) IS NOT null +) + +AWAIT channel.object.publish([ + RestObjectOperation(path: "items.one", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {})), + RestObjectOperation(path: "items.two", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {})) +]) +poll_until_success( + condition: FUNCTION() => + i = AWAIT channel.object.get(RestObjectGetParams(path: "items")) + RETURN "one" IN i AND "two" IN i +) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish(RestObjectOperation( + path: "items.*", + mapSet: RestObjectMapSet(key: "flag", value: PublishObjectData(boolean: true)) +)) + +items = poll_until_success( + condition: FUNCTION() => + i = AWAIT channel.object.get(RestObjectGetParams(path: "items")) + IF i["one"]["flag"] == true AND i["two"]["flag"] == true: + RETURN i + RETURN null +) +``` + +### Assertions +```pseudo +ASSERT items["one"]["flag"] == true +ASSERT items["two"]["flag"] == true +``` + +--- + +## RSO6, RSO5f, RSO5i - Wildcard path with mapRemove and counterInc + +**Test ID**: `objects/integration/RSO6/wildcard-remove-increment-1` + +| Spec | Requirement | +|------|-------------| +| RSO6 | Caller-supplied `path` strings are passed to the server without modification | +| RSO5f | `mapRemove` targeted by `path` | +| RSO5i | `counterInc` targeted by `path` | + +Tests that a wildcard path works with operations other than `mapSet`: a `mapRemove` that removes the +same key from every child map, and a `counterInc` that increments every child counter. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO6-wildcard-ops") + +AWAIT channel.object.publish([ + RestObjectOperation(path: "maps", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {})), + RestObjectOperation(path: "counters", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {})) +]) +poll_until_success( + condition: FUNCTION() => + c = AWAIT channel.object.get() + RETURN "maps" IN c AND "counters" IN c +) + +AWAIT channel.object.publish([ + RestObjectOperation(path: "maps.one", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: { + "foo": RestObjectMapEntry(data: PublishObjectData(string: "a")), + "keep": RestObjectMapEntry(data: PublishObjectData(number: 1)) + })), + RestObjectOperation(path: "maps.two", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: { + "foo": RestObjectMapEntry(data: PublishObjectData(string: "b")), + "keep": RestObjectMapEntry(data: PublishObjectData(number: 2)) + })), + RestObjectOperation(path: "counters.c1", counterCreate: RestObjectCounterCreate(count: 10)), + RestObjectOperation(path: "counters.c2", counterCreate: RestObjectCounterCreate(count: 20)) +]) +poll_until_success( + condition: FUNCTION() => + c = AWAIT channel.object.get() + RETURN "one" IN c["maps"] AND "two" IN c["maps"] AND "c1" IN c["counters"] AND "c2" IN c["counters"] +) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation(path: "maps.*", mapRemove: RestObjectMapRemove(key: "foo")), + RestObjectOperation(path: "counters.*", counterInc: RestObjectCounterInc(number: 5)) +]) + +compact = poll_until_success( + condition: FUNCTION() => + c = AWAIT channel.object.get() + IF "foo" NOT IN c["maps"]["one"] AND "foo" NOT IN c["maps"]["two"] + AND c["counters"]["c1"] == 15 AND c["counters"]["c2"] == 25: + RETURN c + RETURN null +) +``` + +### Assertions +```pseudo +ASSERT compact["maps"]["one"] == { "keep": 1 } +ASSERT compact["maps"]["two"] == { "keep": 2 } +ASSERT compact["counters"]["c1"] == 15 +ASSERT compact["counters"]["c2"] == 25 +``` + +--- + +## RSO4, RSO5d, RSO5h - Locally generated object IDs accepted in a single batch + +**Test ID**: `objects/integration/RSO4/generated-ids-batch-0` + +| Spec | Requirement | +|------|-------------| +| RSO4 | `generateObjectId` computes `objectId`, `nonce`, `initialValue` locally | +| RSO5d | `mapCreateWithObjectId` creates a map with the client-generated ID | +| RSO5h | `counterCreateWithObjectId` creates a counter with the client-generated ID | +| RSO3c | All operations in an array are sent in a single request | + +Tests that IDs generated by the SDK are accepted by the server — which validates the `objectId` +against `initialValue` and `nonce` — and that a batch can reference the new objects before the server +has assigned anything. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO4-generated") +``` + +### Test Steps +```pseudo +counter = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + counterCreate: RestObjectCounterCreate(count: 7) +)) +map = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: { + "visits": RestObjectMapEntry(data: PublishObjectData(objectId: counter.objectId)), + "label": RestObjectMapEntry(data: PublishObjectData(string: "stats")), + "raw": RestObjectMapEntry(data: PublishObjectData(bytes: bytes([0x01]))) + }) +)) + +result = AWAIT channel.object.publish([ + RestObjectOperation(objectId: counter.objectId, + counterCreateWithObjectId: RestObjectCreateWithObjectId( + initialValue: counter.initialValue, nonce: counter.nonce)), + RestObjectOperation(objectId: map.objectId, + mapCreateWithObjectId: RestObjectCreateWithObjectId( + initialValue: map.initialValue, nonce: map.nonce)), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "stats", value: PublishObjectData(objectId: map.objectId))) +]) + +stats = poll_until_success( + condition: FUNCTION() => AWAIT channel.object.get(RestObjectGetParams(path: "stats", compact: false)) +) +``` + +### Assertions +```pseudo +ASSERT counter.objectId STARTS WITH "counter:" +ASSERT map.objectId STARTS WITH "map:" +ASSERT result.objectIds CONTAINS counter.objectId +ASSERT result.objectIds CONTAINS map.objectId + +ASSERT stats IS RestLiveMap +ASSERT stats.objectId == map.objectId +ASSERT stats.map.entries["label"].data.string == "stats" +ASSERT stats.map.entries["raw"].data.bytes == bytes([0x01]) + +visits = stats.map.entries["visits"].data +ASSERT visits IS RestLiveCounter +ASSERT visits.objectId == counter.objectId +ASSERT visits.counter.data.number == 7 +``` + +--- + +## RSO5a1 - Operation id makes a publish idempotent + +**Test ID**: `objects/integration/RSO5a1/idempotent-operation-id-0` + +**Spec requirement:** RSO5a1 — `id` is a per-operation message ID for idempotent publishing; the SDK sends a caller-supplied `id` unchanged (RSO3d3), so the server can de-duplicate. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO5a1-idempotent") + +AWAIT channel.object.publish(RestObjectOperation( + path: "count", + counterCreate: RestObjectCounterCreate(count: 0) +)) +poll_until_success( + condition: FUNCTION() => (AWAIT channel.object.get(RestObjectGetParams(path: "count"))) == 0 +) + +op_id = "idem-" + random_id() +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish(RestObjectOperation( + id: op_id, path: "count", counterInc: RestObjectCounterInc(number: 1))) +AWAIT channel.object.publish(RestObjectOperation( + id: op_id, path: "count", counterInc: RestObjectCounterInc(number: 1))) + +# Marker write published after both increments; once it is visible, both increments have been processed +AWAIT channel.object.publish(RestObjectOperation( + objectId: "root", mapSet: RestObjectMapSet(key: "marker", value: PublishObjectData(boolean: true)))) +compact = poll_until_success( + condition: FUNCTION() => + c = AWAIT channel.object.get() + IF c["marker"] == true: + RETURN c + RETURN null +) +``` + +### Assertions +```pseudo +ASSERT compact["count"] == 1 +``` + +--- + +## RSL16, RSO2g - State written by a realtime client is readable via REST + +**Test ID**: `objects/integration/RSL16/realtime-write-rest-read-0` + +| Spec | Requirement | +|------|-------------| +| RSL16 | `RestChannel#object` reads the same channel object that realtime clients write | +| RSO2f | Compact result is the server's response, verbatim | +| RSO2g1, RSO2g2, RSO2g3 | Full-mode response decoded into `RestLiveMap`, `RestLiveCounter` and `ObjectData` leaves | + +Tests interoperability between the realtime and REST object APIs: objects created over a realtime +connection (via `PathObject#set` with `LiveMap`/`LiveCounter` value types) are decoded correctly by +`RestObject#get`. All other tests in this file write via REST. + +### Setup +```pseudo +channel_name = "objects-rest-RSL16-interop-" + random_id() + +realtime = Realtime(options: ClientOptions( + key: api_key, + endpoint: "nonprod:sandbox", + autoConnect: false, + useBinaryProtocol: PROTOCOL == "msgpack", + plugins: { Objects: objects_plugin } +)) +realtime.connect() +AWAIT_STATE realtime.connection.state == CONNECTED + +realtime_channel = realtime.channels.get(channel_name, { modes: ["OBJECT_SUBSCRIBE", "OBJECT_PUBLISH"] }) +root = AWAIT realtime_channel.object.get() + +rest = Rest(options: ClientOptions( + key: api_key, + endpoint: "nonprod:sandbox", + useBinaryProtocol: PROTOCOL == "msgpack", + plugins: { Objects: objects_plugin } +)) +channel = rest.channels.get(channel_name) +``` + +### Test Steps +```pseudo +AWAIT root.set("str", "hello") +AWAIT root.set("bin", bytes([0x01, 0x02, 0x03])) +AWAIT root.set("prefs", { "theme": "dark" }) +AWAIT root.set("visits", LiveCounter.create(7)) +AWAIT root.set("profile", LiveMap.create({ "nickname": "ally" })) + +full = poll_until_success( + condition: FUNCTION() => + r = AWAIT channel.object.get(RestObjectGetParams(compact: false)) + IF "profile" IN r.map.entries: + RETURN r + RETURN null +) +compact = AWAIT channel.object.get() +``` + +### Assertions +```pseudo +ASSERT compact["str"] == "hello" +ASSERT compact["visits"] == 7 +ASSERT compact["profile"]["nickname"] == "ally" + +ASSERT full IS RestLiveMap +ASSERT full.objectId == "root" +ASSERT full.map.entries["str"].data.string == "hello" +ASSERT full.map.entries["bin"].data.bytes IS Binary +ASSERT full.map.entries["bin"].data.bytes == bytes([0x01, 0x02, 0x03]) +ASSERT full.map.entries["prefs"].data.json == { "theme": "dark" } + +visits = full.map.entries["visits"].data +ASSERT visits IS RestLiveCounter +ASSERT visits.objectId STARTS WITH "counter:" +ASSERT visits.counter.data.number == 7 + +profile = full.map.entries["profile"].data +ASSERT profile IS RestLiveMap +ASSERT profile.objectId STARTS WITH "map:" +ASSERT profile.map.entries["nickname"].data.string == "ally" +``` + +### Teardown +```pseudo +realtime.close() +``` + +--- + +## RSO2h - Server error for an unresolvable target surfaced as ErrorInfo + +**Test ID**: `objects/integration/RSO2h/unresolvable-target-error-0` + +**Spec requirement:** RSO2h — The library does not validate `objectId` or `path`; server-returned errors are surfaced to the caller as a rejected `ErrorInfo`. + +The specific error codes are server-defined, so this test asserts only that the rejection is a +client-error `ErrorInfo`. + +### Setup +```pseudo +{ channel } = create_rest_channel("RSO2h-errors") +``` + +### Test Steps and Assertions +```pseudo +AWAIT channel.object.get(RestObjectGetParams( + objectId: "map:doesNotExistAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA@1700000000000" +)) FAILS WITH error +ASSERT error IS ErrorInfo +ASSERT error.statusCode >= 400 AND error.statusCode < 500 + +AWAIT channel.object.get(RestObjectGetParams(path: "no.such.path")) FAILS WITH path_error +ASSERT path_error IS ErrorInfo +ASSERT path_error.statusCode >= 400 AND path_error.statusCode < 500 +``` diff --git a/uts/objects/unit/rest_object_generate_id.md b/uts/objects/unit/rest_object_generate_id.md new file mode 100644 index 000000000..221b523b8 --- /dev/null +++ b/uts/objects/unit/rest_object_generate_id.md @@ -0,0 +1,459 @@ +# RestObject generateObjectId Tests + +Spec points: `RSO4`, `RSO4a1`, `RSO4b`, `RSO4c`, `RSO4d`, `RSO4e`, `RSO4e1`, `RSO4e1a`, `RSO4e1b`, `RSO4e1c`, `RSO4e2`, `RSO4f`, `RSO4g`, `RSO4h`, `RSO4j`, `RSO4k`, `RSO5d`, `RSO5h`, `RSO12` + +## Test Type +Unit test with mocked HTTP client + +## Mock HTTP Infrastructure + +See `rest/unit/helpers/mock_http.md` for the full Mock HTTP Infrastructure specification. + +## Purpose + +Tests local object ID generation for REST callers: the `initialValue` encoding, nonce generation, +use of server time, and the derivation of `objectId` per RTO14. The mocked HTTP client answers the +server time request (RTO16, via `RestClient#time`) and any `publish` request; no other requests are +expected. + +## Common Setup + +`objects_plugin` denotes the SDK's `Objects` plugin ([PC5](../../../specifications/features.md#PC5)), +supplied under the `Objects` `PluginType` key. + +`mapCreate.semantics` is written as the symbolic enum value `"LWW"` in inputs (see *Enum values* in the +UTS README), and is asserted inside `initialValue` as its `ObjectsMapSemantics` integer encoding (`0`, +per OMP2). + +```pseudo +SERVER_TIME = 1700000000000 + +setup_rest_object(channel_name, use_binary_protocol: false): + captured_requests = [] + + mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + IF req.url.path == "/time": + req.respond_with(200, [SERVER_TIME]) + ELSE: + req.respond_with(201, { "messageId": "msg-id-1", "channel": channel_name, "objectIds": [] }) + } + ) + install_mock(mock_http) + + client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: use_binary_protocol, + plugins: { Objects: objects_plugin } + )) + channel = client.channels.get(channel_name) + + RETURN { client, channel, captured_requests } +``` + +--- + +## RSO4d - Map create body yields a map objectId + +**Test ID**: `objects/unit/RSO4d/map-type-objectid-0` + +**Spec requirement:** RSO4d — The RTO14 `type` is `map` when `createBody.mapCreate` is provided. + +### Setup +```pseudo +{ channel } = setup_rest_object("test-RSO4d-map-" + random_id()) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {}) +)) +``` + +### Assertions +```pseudo +ASSERT result.objectId STARTS WITH "map:" +``` + +--- + +## RSO4d - Counter create body yields a counter objectId + +**Test ID**: `objects/unit/RSO4d/counter-type-objectid-1` + +**Spec requirement:** RSO4d — The RTO14 `type` is `counter` when `createBody.counterCreate` is provided. + +### Setup +```pseudo +{ channel } = setup_rest_object("test-RSO4d-counter-" + random_id()) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + counterCreate: RestObjectCounterCreate(count: 5) +)) +``` + +### Assertions +```pseudo +ASSERT result.objectId STARTS WITH "counter:" +``` + +--- + +## RSO4g, RSO4h - objectId derived per RTO14 from initialValue, nonce and server time + +**Test ID**: `objects/unit/RSO4h/objectid-derivation-0` + +| Spec | Requirement | +|------|-------------| +| RSO4g | Retrieves the current server time as described in RTO16 | +| RSO4h | Constructs the `objectId` per RTO14 from the `type`, `initialValue`, `nonce` and server time | +| RTO14 | `[type]:[base64url(SHA-256(utf8("[initialValue]:[nonce]")))]@[timestamp]` | + +Tests that the returned `objectId` is consistent with the returned `initialValue` and `nonce`, and +that its timestamp is the server time. The client is newly created, so it has no persisted server +time offset (RTO16a) and must obtain server time from `/time`. + +### Setup +```pseudo +{ channel, captured_requests } = setup_rest_object("test-RSO4h-" + random_id()) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + counterCreate: RestObjectCounterCreate(count: 42) +)) +``` + +### Assertions +```pseudo +time_requests = captured_requests.filter(r => r.url.path == "/time") +ASSERT time_requests.length == 1 +ASSERT time_requests[0].method == "GET" + +expected_hash = base64url_encode(sha256(utf8_encode(result.initialValue + ":" + result.nonce))) +ASSERT result.objectId == "counter:" + expected_hash + "@" + str(SERVER_TIME) +``` + +--- + +## RSO4e2 - Counter initialValue is the JSON representation of the counter create body + +**Test ID**: `objects/unit/RSO4e2/counter-initial-value-0` + +**Spec requirement:** RSO4e2 — If `createBody.counterCreate` was provided, the `initialValue` is a JSON-string representation of the body, equivalent to RTO12f13. + +### Setup +```pseudo +{ channel } = setup_rest_object("test-RSO4e2-" + random_id()) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + counterCreate: RestObjectCounterCreate(count: 42) +)) +``` + +### Assertions +```pseudo +ASSERT parse_json(result.initialValue) == { "count": 42 } +``` + +--- + +## RSO4e1 - Map initialValue encodes semantics and entry data with JSON protocol rules + +**Test ID**: `objects/unit/RSO4e1/map-initial-value-0` + +| Spec | Requirement | +|------|-------------| +| RSO4e1a | `mapCreate.semantics` encoded per OMP2 | +| RSO4e1b | Each entry's `data` encoded per OD4d | +| RSO4e1c | The `initialValue` is a JSON-string representation of the resulting body, equivalent to RTO11f15 | + +### Setup +```pseudo +{ channel } = setup_rest_object("test-RSO4e1-" + random_id()) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + mapCreate: RestObjectMapCreate( + semantics: "LWW", + entries: { + "name": RestObjectMapEntry(data: PublishObjectData(string: "Alice")), + "age": RestObjectMapEntry(data: PublishObjectData(number: 30)), + "active": RestObjectMapEntry(data: PublishObjectData(boolean: true)), + "avatar": RestObjectMapEntry(data: PublishObjectData(bytes: bytes([0x01, 0x02, 0x03]))), + "prefs": RestObjectMapEntry(data: PublishObjectData(json: { "theme": "dark" })), + "visits": RestObjectMapEntry(data: PublishObjectData(objectId: "counter:h@1")) + } + ) +)) +``` + +### Assertions +```pseudo +initial_value = parse_json(result.initialValue) +ASSERT initial_value["semantics"] == 0 + +entries = initial_value["entries"] +ASSERT entries.keys() == {"name", "age", "active", "avatar", "prefs", "visits"} +ASSERT entries["name"] == { "data": { "string": "Alice" } } +ASSERT entries["age"] == { "data": { "number": 30 } } +ASSERT entries["active"] == { "data": { "boolean": true } } +ASSERT entries["avatar"] == { "data": { "bytes": "AQID" } } +ASSERT entries["prefs"]["data"].keys() == {"json"} +ASSERT parse_json(entries["prefs"]["data"]["json"]) == { "theme": "dark" } +ASSERT entries["visits"] == { "data": { "objectId": "counter:h@1" } } +``` + +--- + +## RSO4e - initialValue uses JSON encoding regardless of the client protocol + +**Test ID**: `objects/unit/RSO4e/json-regardless-of-protocol-0` + +**Spec requirement:** RSO4e — The `initialValue` is always carried as a JSON string regardless of the negotiated transport format, so encoding must use the JSON protocol rules from OD4d. + +Tests that a client using the binary protocol produces the same `initialValue` as a JSON-protocol +client, with `bytes` Base64-encoded. + +### Setup +```pseudo +create_body = RestObjectGenerateIdBody( + mapCreate: RestObjectMapCreate( + semantics: "LWW", + entries: { + "avatar": RestObjectMapEntry(data: PublishObjectData(bytes: bytes([0x01, 0x02, 0x03]))) + } + ) +) + +{ channel: json_channel } = setup_rest_object("test-RSO4e-json-" + random_id()) +{ channel: binary_channel } = setup_rest_object("test-RSO4e-binary-" + random_id(), + use_binary_protocol: true) +``` + +### Test Steps +```pseudo +json_result = AWAIT json_channel.object.generateObjectId(create_body) +binary_result = AWAIT binary_channel.object.generateObjectId(create_body) +``` + +### Assertions +```pseudo +ASSERT binary_result.initialValue IS String +ASSERT binary_result.initialValue == json_result.initialValue +ASSERT parse_json(binary_result.initialValue)["entries"]["avatar"]["data"]["bytes"] == "AQID" +``` + +--- + +## RSO4e1a - Unrecognized mapCreate semantics rejected + +**Test ID**: `objects/unit/RSO4e1a/unrecognized-semantics-error-0` + +**Spec requirement:** RSO4e1a — If the `mapCreate.semantics` value is unrecognized, the library should throw an `ErrorInfo` with `statusCode` 400 and `code` 40003. + +Not applicable to SDKs whose `ObjectsMapSemantics` type makes an unrecognized value unrepresentable. + +### Setup +```pseudo +{ channel } = setup_rest_object("test-RSO4e1a-" + random_id()) +``` + +### Test Steps and Assertions +```pseudo +AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + mapCreate: RestObjectMapCreate(semantics: "not-a-semantics", entries: {}) +)) FAILS WITH error + +ASSERT error.code == 40003 +ASSERT error.statusCode == 400 +``` + +--- + +## RSO4c - Missing create body rejected + +**Test ID**: `objects/unit/RSO4c/missing-create-body-error-0` + +**Spec requirement:** RSO4c — If neither `createBody.mapCreate` nor `createBody.counterCreate` is provided, the library should throw an `ErrorInfo` with `statusCode` 400 and `code` 40003. + +Not applicable to SDKs whose `RestObjectGenerateIdBody` representation makes an empty body +unrepresentable. + +### Setup +```pseudo +{ channel, captured_requests } = setup_rest_object("test-RSO4c-" + random_id()) +``` + +### Test Steps and Assertions +```pseudo +AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody()) FAILS WITH error + +ASSERT error.code == 40003 +ASSERT error.statusCode == 400 +ASSERT captured_requests.length == 0 +``` + +--- + +## RSO4f - Nonce is a string of at least 16 characters + +**Test ID**: `objects/unit/RSO4f/nonce-generated-0` + +**Spec requirement:** RSO4f — Generates a unique string `nonce`, as described in RTO11f6 (16+ characters). + +### Setup +```pseudo +{ channel } = setup_rest_object("test-RSO4f-" + random_id()) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + counterCreate: RestObjectCounterCreate(count: 0) +)) +``` + +### Assertions +```pseudo +ASSERT result.nonce.length >= 16 +``` + +--- + +## RSO4j - Repeated calls produce different objectId and nonce + +**Test ID**: `objects/unit/RSO4j/unique-per-call-0` + +**Spec requirement:** RSO4j — Two invocations with the same `createBody` produce different `objectId` and `nonce` values. + +### Setup +```pseudo +{ channel } = setup_rest_object("test-RSO4j-" + random_id()) +create_body = RestObjectGenerateIdBody(counterCreate: RestObjectCounterCreate(count: 1)) +``` + +### Test Steps +```pseudo +first = AWAIT channel.object.generateObjectId(create_body) +second = AWAIT channel.object.generateObjectId(create_body) +``` + +### Assertions +```pseudo +ASSERT first.nonce != second.nonce +ASSERT first.objectId != second.objectId +``` + +--- + +## RSO4k - initialValue is deterministic for a given create body + +**Test ID**: `objects/unit/RSO4k/initial-value-deterministic-0` + +**Spec requirement:** RSO4k — The `initialValue` is deterministic for a given `createBody`: identical input produces identical output. + +### Setup +```pseudo +{ channel } = setup_rest_object("test-RSO4k-" + random_id()) +create_body = RestObjectGenerateIdBody( + mapCreate: RestObjectMapCreate( + semantics: "LWW", + entries: { + "a": RestObjectMapEntry(data: PublishObjectData(string: "x")), + "b": RestObjectMapEntry(data: PublishObjectData(json: { "k": [1, 2] })) + } + ) +) +``` + +### Test Steps +```pseudo +first = AWAIT channel.object.generateObjectId(create_body) +second = AWAIT channel.object.generateObjectId(create_body) +``` + +### Assertions +```pseudo +ASSERT first.initialValue == second.initialValue +``` + +--- + +## RSO4b, RSO5d, RSO5h - Generated values publish verbatim in *WithObjectId operations + +**Test ID**: `objects/unit/RSO4b/generated-id-publish-roundtrip-0` + +| Spec | Requirement | +|------|-------------| +| RSO4b | The returned values are intended to be supplied to a subsequent `mapCreateWithObjectId` or `counterCreateWithObjectId` operation | +| RSO5d | `mapCreateWithObjectId` carries `initialValue` and `nonce`, with `objectId` set to the generated ID | +| RSO5h | `counterCreateWithObjectId` has the same body and constraints as RSO5d | + +Tests that values from `generateObjectId` are sent unchanged when used in a batch with an operation +that references the new object by ID. + +### Setup +```pseudo +channel_name = "test-RSO4b-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps +```pseudo +counter = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + counterCreate: RestObjectCounterCreate(count: 3) +)) +map = AWAIT channel.object.generateObjectId(RestObjectGenerateIdBody( + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: { + "visits": RestObjectMapEntry(data: PublishObjectData(objectId: counter.objectId)) + }) +)) + +AWAIT channel.object.publish([ + RestObjectOperation( + objectId: counter.objectId, + counterCreateWithObjectId: RestObjectCreateWithObjectId( + initialValue: counter.initialValue, nonce: counter.nonce) + ), + RestObjectOperation( + objectId: map.objectId, + mapCreateWithObjectId: RestObjectCreateWithObjectId( + initialValue: map.initialValue, nonce: map.nonce) + ), + RestObjectOperation( + objectId: "root", + mapSet: RestObjectMapSet(key: "stats", value: PublishObjectData(objectId: map.objectId)) + ) +]) +``` + +### Assertions +```pseudo +publish_requests = captured_requests.filter(r => r.method == "POST") +ASSERT publish_requests.length == 1 +ASSERT publish_requests[0].url.path == "/channels/" + encode_uri_component(channel_name) + "/object" + +body = parse_json(publish_requests[0].body) +ASSERT body[0] == { + "objectId": counter.objectId, + "counterCreateWithObjectId": { "initialValue": counter.initialValue, "nonce": counter.nonce } +} +ASSERT body[1] == { + "objectId": map.objectId, + "mapCreateWithObjectId": { "initialValue": map.initialValue, "nonce": map.nonce } +} +ASSERT body[2]["mapSet"]["value"] == { "objectId": map.objectId } +``` diff --git a/uts/objects/unit/rest_object_get.md b/uts/objects/unit/rest_object_get.md new file mode 100644 index 000000000..e54f4e968 --- /dev/null +++ b/uts/objects/unit/rest_object_get.md @@ -0,0 +1,753 @@ +# RestObject Attribute and Get Tests + +Spec points: `RSL16`, `RSL16b`, `RSO1`, `RSO1a`, `RSO2`, `RSO2a1`, `RSO2b`, `RSO2c`, `RSO2d`, `RSO2e`, `RSO2f`, `RSO2g`, `RSO2g1`, `RSO2g2`, `RSO2g3`, `RSO2g4`, `RSO2h`, `RSO6`, `RSO8`, `RSO9`, `RSO9a`, `RSO9b`, `RSO9c`, `RSO9c1`, `RSO9c2`, `RSO9d`, `RSO14`, `RSO15`, `RSO16` + +## Test Type +Unit test with mocked HTTP client + +## Mock HTTP Infrastructure + +See `rest/unit/helpers/mock_http.md` for the full Mock HTTP Infrastructure specification. + +## Purpose + +Tests the REST entry point to LiveObjects: the `RestChannel#object` attribute, and +`RestObject#get` request formation and response decoding in both compact and full +modes. Server behaviour (path resolution, compact formatting) is out of scope; these +tests verify only what the SDK sends and how it decodes what it receives. + +## Common Setup + +`objects_plugin` denotes the SDK's `Objects` plugin ([PC5](../../../specifications/features.md#PC5)), +supplied under the `Objects` `PluginType` key. How the plugin value is obtained is SDK-specific. + +Unless a test states otherwise, clients use the JSON protocol (`useBinaryProtocol: false`) so +request and response bodies can be inspected as JSON. + +```pseudo +setup_rest_object(channel_name, response_body, use_binary_protocol: false): + captured_requests = [] + + mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + IF use_binary_protocol: + req.respond_with(200, msgpack_encode(response_body), + headers: { "Content-Type": "application/x-msgpack" }) + ELSE: + req.respond_with(200, response_body, + headers: { "Content-Type": "application/json" }) + } + ) + install_mock(mock_http) + + client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: use_binary_protocol, + plugins: { Objects: objects_plugin } + )) + channel = client.channels.get(channel_name) + + RETURN { client, channel, captured_requests } +``` + +--- + +## RSO1a - One RestObject instance per RestChannel + +**Test ID**: `objects/unit/RSO1a/one-instance-per-channel-0` + +**Spec requirement:** RSO1a — There is one `RestObject` instance per `RestChannel`, accessed via the `RestChannel#object` attribute. + +Tests that repeated access returns the same instance, and that different channels have different instances. + +### Setup +```pseudo +{ client, channel } = setup_rest_object("test-RSO1a-a-" + random_id(), {}) +other_channel = client.channels.get("test-RSO1a-b-" + random_id()) +``` + +### Assertions +```pseudo +ASSERT channel.object IS SAME AS channel.object +ASSERT channel.object IS NOT SAME AS other_channel.object +``` + +--- + +## RSL16b - Accessing channel.object without the Objects plugin + +**Test ID**: `objects/unit/RSL16b/missing-plugin-error-0` + +**Spec requirement:** RSL16b — It is a programmer error to access `RestChannel#object` without first providing the `Objects` plugin in the client options. If this is handled by throwing, the error must be an `ErrorInfo` with `statusCode` 400 and `code` 40019. + +Tests that accessing `channel.object` on a client without the `Objects` plugin fails with 40019. + +This test applies only to SDKs that handle the programmer error by throwing. SDKs that make it +impossible to express (for example, by only exposing `object` on a channel type that exists when the +plugin is installed) should note the test as not applicable. + +### Setup +```pseudo +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => req.respond_with(200, {}) +) +install_mock(mock_http) + +client = Rest(options: ClientOptions(key: "appId.keyId:keySecret")) +channel = client.channels.get("test-RSL16b-" + random_id()) +``` + +### Test Steps and Assertions +```pseudo +channel.object FAILS WITH error +ASSERT error.code == 40019 +ASSERT error.statusCode == 400 +``` + +--- + +## RSO2c - get with no params sends GET to channel object endpoint + +**Test ID**: `objects/unit/RSO2c/get-default-endpoint-0` + +| Spec | Requirement | +|------|-------------| +| RSO2c | Sends a `GET` request to `/channels/{channelName}/object`; `/{objectId}` is appended only if `params.objectId` is provided | +| RSO2d | `params.path` and `params.compact` are sent as query parameters only if provided | + +Tests that `get()` without params targets the channel object endpoint and sends no `path` or `compact` query parameters. + +### Setup +```pseudo +channel_name = "test-RSO2c-default-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name, {}) +``` + +### Test Steps +```pseudo +AWAIT channel.object.get() +``` + +### Assertions +```pseudo +ASSERT captured_requests.length == 1 +request = captured_requests[0] +ASSERT request.method == "GET" +ASSERT request.url.path == "/channels/" + encode_uri_component(channel_name) + "/object" +ASSERT "path" NOT IN request.url.query_params +ASSERT "compact" NOT IN request.url.query_params +``` + +--- + +## RSO2c - get with objectId appends percent-encoded path segment + +**Test ID**: `objects/unit/RSO2c/get-objectid-path-segment-0` + +**Spec requirement:** RSO2c — When `params.objectId` is provided, `/{objectId}` is appended to `/channels/{channelName}/object`. The `objectId` path segment must be percent-encoded per RFC 3986 §2.1. + +Tests that the `objectId` is appended as a single percent-encoded path segment, including when it +contains characters that are not valid in a path segment. + +### Setup +```pseudo +channel_name = "test-RSO2c-objectid-" + random_id() +``` + +### Test Cases + +| ID | objectId | +|----|----------| +| 1 | `"root"` | +| 2 | `"map:QWsI5HQnz7AbhLgn9U2xlA2wq0Ax7HHYbJtJDF9mVqg@1700000000000"` | +| 3 | `"counter:a/b c?d#e@1700000000000"` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel, captured_requests } = setup_rest_object(channel_name, {}) + + AWAIT channel.object.get(RestObjectGetParams(objectId: test_case.objectId)) + + ASSERT captured_requests.length == 1 + request = captured_requests[0] + ASSERT request.method == "GET" + ASSERT request.url.path == "/channels/" + encode_uri_component(channel_name) + + "/object/" + encode_uri_component(test_case.objectId) +``` + +--- + +## RSO2d - path and compact sent as query parameters + +**Test ID**: `objects/unit/RSO2d/path-compact-query-params-0` + +**Spec requirement:** RSO2d — The `params.path` and `params.compact` fields, if provided, must be sent as URL query string parameters. + +Tests that `path` and `compact` are sent as query parameters, alone and combined with `objectId`. + +### Setup +```pseudo +channel_name = "test-RSO2d-" + random_id() +``` + +### Test Cases + +| ID | params | Expected path suffix | Expected query params | +|----|--------|----------------------|-----------------------| +| 1 | `{ path: "a.b.c" }` | `"/object"` | `{ "path": "a.b.c" }` | +| 2 | `{ compact: false }` | `"/object"` | `{ "compact": "false" }` | +| 3 | `{ compact: true }` | `"/object"` | `{ "compact": "true" }` | +| 4 | `{ objectId: "map:abc@1", path: "x.y", compact: false }` | `"/object/" + encode_uri_component("map:abc@1")` | `{ "path": "x.y", "compact": "false" }` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel, captured_requests } = setup_rest_object(channel_name, {}) + + AWAIT channel.object.get(RestObjectGetParams(test_case.params)) + + request = captured_requests[0] + ASSERT request.url.path == "/channels/" + encode_uri_component(channel_name) + + test_case.expected_path_suffix + ASSERT request.url.query_params == test_case.expected_query_params +``` + +--- + +## RSO6 - get passes path to the server verbatim + +**Test ID**: `objects/unit/RSO6/get-path-verbatim-0` + +| Spec | Requirement | +|------|-------------| +| RSO6 | Caller-supplied `path` strings must be passed to the server without modification or normalization | +| RSO2h | The library must not perform client-side validation of `params.path` content | + +Tests that path strings the SDK might be tempted to parse, normalize or reject are sent unchanged. + +### Setup +```pseudo +channel_name = "test-RSO6-get-" + random_id() +``` + +### Test Cases + +| ID | path | +|----|------| +| 1 | `"items.*.count"` | +| 2 | `"a\\.b.c"` | +| 3 | `".a..b."` | +| 4 | `""` | +| 5 | `"with space/and?query&chars=1#frag"` | +| 6 | `"ünïcödé.键"` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel, captured_requests } = setup_rest_object(channel_name, {}) + + AWAIT channel.object.get(RestObjectGetParams(path: test_case.path)) + + ASSERT captured_requests.length == 1 + # query_params holds URL-decoded values: the decoded value must equal the input exactly + ASSERT captured_requests[0].url.query_params["path"] == test_case.path +``` + +--- + +## RSO2f, RSO8 - Compact response returned verbatim + +**Test ID**: `objects/unit/RSO2f/compact-returned-verbatim-0` + +| Spec | Requirement | +|------|-------------| +| RSO2f | When `params.compact` is `true` or omitted, the decoded response body must be returned verbatim, with no further structural transformation or decoding | +| RSO8 | `RestObjectGetCompactResult` shape and value formats are server-defined and not transformed by the library | + +Tests that a compact response is returned exactly as decoded from the wire — in particular that +string values that look like Base64 or JSON are not decoded, and that object-reference shapes are +not resolved. + +### Setup +```pseudo +compact_body = { + "name": "Alice", + "age": 30, + "active": true, + "visits": 7, + "avatar": "AQID", + "prefs": "{\"theme\":\"dark\"}", + "tags": "[\"a\",\"b\"]", + "nested": { "inner": { "deep": 1 } }, + "empty": {}, + "cycle": { "objectId": "map:cycleHash@1700000000000" } +} + +{ channel } = setup_rest_object("test-RSO2f-" + random_id(), compact_body) +``` + +### Test Steps +```pseudo +result_default = AWAIT channel.object.get() +result_explicit = AWAIT channel.object.get(RestObjectGetParams(compact: true)) +``` + +### Assertions +```pseudo +ASSERT result_default == compact_body +ASSERT result_explicit == compact_body + +# String values are not Base64- or JSON-decoded +ASSERT result_default["avatar"] == "AQID" +ASSERT result_default["avatar"] IS String +ASSERT result_default["prefs"] == "{\"theme\":\"dark\"}" +ASSERT result_default["prefs"] IS String +``` + +--- + +## RSO2f - Compact scalar response returned verbatim + +**Test ID**: `objects/unit/RSO2f/compact-scalar-verbatim-1` + +**Spec requirement:** RSO2f — When `params.compact` is `true` or omitted, the decoded response body must be returned to the caller verbatim. + +Tests that a compact response that is not a map (for example a counter value, or a leaf value +reached via `path`) is returned as-is. + +### Test Cases + +| ID | Response body | +|----|---------------| +| 1 | `42` | +| 2 | `-1.5` | +| 3 | `"hello"` | +| 4 | `false` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel } = setup_rest_object("test-RSO2f-scalar-" + random_id(), test_case.response_body) + + result = AWAIT channel.object.get(RestObjectGetParams(path: "some.key")) + + ASSERT result == test_case.response_body +``` + +--- + +## RSO2e, RSO2f - Compact msgpack response decoded per RSC8 and returned verbatim + +**Test ID**: `objects/unit/RSO2e/compact-msgpack-decoded-0` + +| Spec | Requirement | +|------|-------------| +| RSO2e | The response body must be decoded per RSC8 | +| RSO2f | The decoded compact body is returned verbatim | + +Tests that with the binary protocol the request advertises MessagePack, the MessagePack response +is decoded, and binary values in a compact response are returned as binary without further transformation. + +### Setup +```pseudo +compact_body = { + "name": "Alice", + "count": 5, + "avatar": bytes([0x01, 0x02, 0x03]) +} + +{ channel, captured_requests } = setup_rest_object( + "test-RSO2e-msgpack-" + random_id(), compact_body, use_binary_protocol: true) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.get() +``` + +### Assertions +```pseudo +ASSERT captured_requests[0].headers["Accept"] == "application/x-msgpack" + +ASSERT result["name"] == "Alice" +ASSERT result["count"] == 5 +ASSERT result["avatar"] IS Binary +ASSERT result["avatar"] == bytes([0x01, 0x02, 0x03]) +``` + +--- + +## RSO2g1, RSO2g2, RSO2g3, RSO9a, RSO14, RSO16 - Full map response decoded recursively + +**Test ID**: `objects/unit/RSO2g1/full-map-recursive-decode-0` + +| Spec | Requirement | +|------|-------------| +| RSO2g1 | A node with a `map` field is returned as a `RestLiveMap`; each `map.entries[key].data` is decoded recursively per RSO2g | +| RSO2g2 | A node with a `counter` field is returned as a `RestLiveCounter` | +| RSO2g3 | Any other node is an `ObjectData` leaf decoded per OD5 | +| RSO14 | `RestLiveMap` has `objectId`, `map.semantics`, `map.entries` | +| RSO15 | `RestLiveCounter` has `objectId`, `counter.data.number` | +| RSO16 | `RestLiveMapEntry.data` is a recursively decoded `RestObjectGetFullResult` | + +Tests that a full-mode map response is decoded into nested `RestLiveMap`, `RestLiveCounter` and +decoded `ObjectData` leaves (JSON protocol). + +`map.semantics` is sent on the wire as the name of the `ObjectsMapSemantics` value (`"LWW"`) +and asserted as the symbolic enum value (see *Enum values* in the UTS README). + +### Setup +```pseudo +full_body = { + "objectId": "root", + "map": { + "semantics": "LWW", + "entries": { + "str": { "data": { "string": "hello" } }, + "num": { "data": { "number": 42 } }, + "bool": { "data": { "boolean": true } }, + "bin": { "data": { "bytes": base64_encode(bytes([0x01, 0x02, 0x03])) } }, + "jobj": { "data": { "json": "{\"a\":1}" } }, + "jarr": { "data": { "json": "[1,2,3]" } }, + "visits": { + "data": { + "objectId": "counter:visitsHash@1700000000000", + "counter": { "data": { "number": 7 } } + } + }, + "profile": { + "data": { + "objectId": "map:profileHash@1700000000000", + "map": { + "semantics": "LWW", + "entries": { + "nickname": { "data": { "string": "ally" } } + } + } + } + } + } + } +} + +{ channel } = setup_rest_object("test-RSO2g1-" + random_id(), full_body) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.get(RestObjectGetParams(compact: false)) +``` + +### Assertions +```pseudo +ASSERT result IS RestLiveMap +ASSERT result.objectId == "root" +ASSERT result.map.semantics == "LWW" +ASSERT result.map.entries.keys() == {"str", "num", "bool", "bin", "jobj", "jarr", "visits", "profile"} + +# Leaves (RSO2g3, RSO9c) +ASSERT result.map.entries["str"].data.string == "hello" +ASSERT result.map.entries["num"].data.number == 42 +ASSERT result.map.entries["bool"].data.boolean == true +ASSERT result.map.entries["bin"].data.bytes IS Binary +ASSERT result.map.entries["bin"].data.bytes == bytes([0x01, 0x02, 0x03]) +ASSERT result.map.entries["jobj"].data.json == { "a": 1 } +ASSERT result.map.entries["jarr"].data.json == [1, 2, 3] +ASSERT result.map.entries["jobj"].data.string == null + +# Nested counter (RSO2g2, RSO15) +visits = result.map.entries["visits"].data +ASSERT visits IS RestLiveCounter +ASSERT visits.objectId == "counter:visitsHash@1700000000000" +ASSERT visits.counter.data.number == 7 + +# Nested map, decoded recursively (RSO2g1, RSO16) +profile = result.map.entries["profile"].data +ASSERT profile IS RestLiveMap +ASSERT profile.objectId == "map:profileHash@1700000000000" +ASSERT profile.map.semantics == "LWW" +ASSERT profile.map.entries["nickname"].data.string == "ally" +``` + +--- + +## RSO2g1, RSO2g3, RSO9c - Empty map and empty leaf values in a full response + +**Test ID**: `objects/unit/RSO2g1/full-empty-values-decode-1` + +| Spec | Requirement | +|------|-------------| +| RSO2g1 | A node with a `map` field is returned as a `RestLiveMap`, including when `map.entries` is empty | +| RSO2g3 | Leaves are decoded per OD5 | +| RSO9c2 | `bytes` holds a native `Binary`, including when it is zero-length | + +Tests that values an implementation can mistake for "absent" survive full-mode decoding: an empty +nested map keeps empty `entries`, and empty-string, zero-length-bytes, `0` and `false` leaves keep +their field and value. + +### Setup +```pseudo +full_body = { + "objectId": "root", + "map": { + "semantics": "LWW", + "entries": { + "emptyMap": { + "data": { + "objectId": "map:emptyHash@1700000000000", + "map": { "semantics": "LWW", "entries": {} } + } + }, + "emptyStr": { "data": { "string": "" } }, + "emptyBin": { "data": { "bytes": "" } }, + "zero": { "data": { "number": 0 } }, + "no": { "data": { "boolean": false } } + } + } +} + +{ channel } = setup_rest_object("test-RSO2g1-empty-" + random_id(), full_body) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.get(RestObjectGetParams(compact: false)) +``` + +### Assertions +```pseudo +ASSERT result.map.entries.keys() == {"emptyMap", "emptyStr", "emptyBin", "zero", "no"} + +empty_map = result.map.entries["emptyMap"].data +ASSERT empty_map IS RestLiveMap +ASSERT empty_map.objectId == "map:emptyHash@1700000000000" +ASSERT empty_map.map.semantics == "LWW" +ASSERT empty_map.map.entries == {} + +ASSERT result.map.entries["emptyStr"].data.string == "" +ASSERT result.map.entries["emptyBin"].data.bytes IS Binary +ASSERT result.map.entries["emptyBin"].data.bytes == bytes([]) +ASSERT result.map.entries["zero"].data.number == 0 +ASSERT result.map.entries["no"].data.boolean == false +``` + +--- + +## RSO2g2, RSO9b, RSO15 - Full counter response + +**Test ID**: `objects/unit/RSO2g2/full-counter-0` + +| Spec | Requirement | +|------|-------------| +| RSO2g2 | A response with a `counter` field is returned as a `RestLiveCounter` without further decoding | +| RSO15 | `RestLiveCounter` has `objectId` and `counter.data.number` | + +### Setup +```pseudo +full_body = { + "objectId": "counter:abcHash@1700000000000", + "counter": { "data": { "number": -3.5 } } +} + +{ channel } = setup_rest_object("test-RSO2g2-" + random_id(), full_body) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.get(RestObjectGetParams( + objectId: "counter:abcHash@1700000000000", + compact: false +)) +``` + +### Assertions +```pseudo +ASSERT result IS RestLiveCounter +ASSERT result.objectId == "counter:abcHash@1700000000000" +ASSERT result.counter.data.number == -3.5 +``` + +--- + +## RSO2g3, RSO9c - Full leaf response decoded per OD5 (JSON protocol) + +**Test ID**: `objects/unit/RSO2g3/full-leaf-decode-json-0` + +| Spec | Requirement | +|------|-------------| +| RSO2g3 | A response with neither `map` nor `counter` is an `ObjectData` leaf decoded per OD5 | +| RSO9c1 | The returned `ObjectData` has `objectId` unset | +| RSO9c2 | `bytes` holds a native `Binary`; JSON-encoded payloads appear parsed | + +Tests decoding of each leaf type when the full-mode target is a leaf value. + +### Test Cases + +| ID | Response body | Expected field | Expected value | +|----|---------------|----------------|----------------| +| 1 | `{ "string": "hello" }` | `string` | `"hello"` | +| 2 | `{ "number": 3.25 }` | `number` | `3.25` | +| 3 | `{ "boolean": false }` | `boolean` | `false` | +| 4 | `{ "bytes": "AQID" }` | `bytes` | `bytes([0x01, 0x02, 0x03])` | +| 5 | `{ "json": "{\"k\":\"v\"}" }` | `json` | `{ "k": "v" }` | +| 6 | `{ "json": "[1,\"a\",null]" }` | `json` | `[1, "a", null]` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel } = setup_rest_object("test-RSO2g3-" + random_id(), test_case.response_body) + + result = AWAIT channel.object.get(RestObjectGetParams(path: "leaf", compact: false)) + + ASSERT result IS ObjectData + ASSERT result[test_case.expected_field] == test_case.expected_value + ASSERT result.objectId == null + IF test_case.expected_field == "bytes": + ASSERT result.bytes IS Binary +``` + +--- + +## RSO2g3, RSO9c2 - Full leaf response decoded per OD5 (MessagePack protocol) + +**Test ID**: `objects/unit/RSO2g3/full-leaf-decode-msgpack-1` + +**Spec requirement:** RSO2g3 — Leaves are decoded per OD5: with MessagePack, `bytes` arrives as binary and is returned as-is, and the JSON-encoded string in `json` is parsed as JSON (OD5a2). + +### Test Cases + +| ID | Response body | Expected field | Expected value | +|----|---------------|----------------|----------------| +| 1 | `{ "bytes": bytes([0xFF, 0x00]) }` | `bytes` | `bytes([0xFF, 0x00])` | +| 2 | `{ "json": "{\"k\":[1,2]}" }` | `json` | `{ "k": [1, 2] }` | +| 3 | `{ "string": "plain" }` | `string` | `"plain"` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel } = setup_rest_object("test-RSO2g3-msgpack-" + random_id(), + test_case.response_body, use_binary_protocol: true) + + result = AWAIT channel.object.get(RestObjectGetParams(path: "leaf", compact: false)) + + ASSERT result[test_case.expected_field] == test_case.expected_value +``` + +--- + +## RSO2g4, RSO9d - Unrecognized object shape passed through + +**Test ID**: `objects/unit/RSO2g4/unrecognized-object-passthrough-0` + +| Spec | Requirement | +|------|-------------| +| RSO2g4 | Unrecognized object shapes must be passed through unmodified, per RSF1 | +| RSO9d | For unrecognized object types, the result contains at minimum `objectId`, with additional fields passed through unmodified | + +Tests that a full-mode response for an object type the SDK does not know about does not fail +decoding, and that the `objectId` and the unrecognized fields reach the caller — both at the top level +and as a map entry. + +In SDKs whose result types cannot carry arbitrary extra fields, the assertions on `futureType` are not +applicable; the `objectId` assertions still apply. + +### Setup +```pseudo +full_body = { + "objectId": "root", + "map": { + "semantics": "LWW", + "entries": { + "known": { "data": { "string": "ok" } }, + "future": { + "data": { + "objectId": "future:xyzHash@1700000000000", + "futureType": { "someField": 1 } + } + } + } + } +} +top_level_body = { + "objectId": "future:topHash@1700000000000", + "futureType": { "someField": 2 } +} +``` + +### Test Steps +```pseudo +{ channel } = setup_rest_object("test-RSO2g4-entry-" + random_id(), full_body) +map_result = AWAIT channel.object.get(RestObjectGetParams(compact: false)) + +{ channel: channel2 } = setup_rest_object("test-RSO2g4-top-" + random_id(), top_level_body) +top_result = AWAIT channel2.object.get(RestObjectGetParams(compact: false)) +``` + +### Assertions +```pseudo +ASSERT map_result IS RestLiveMap +ASSERT map_result.map.entries["known"].data.string == "ok" + +future_entry = map_result.map.entries["future"].data +ASSERT future_entry.objectId == "future:xyzHash@1700000000000" +ASSERT future_entry.futureType == { "someField": 1 } + +ASSERT top_result.objectId == "future:topHash@1700000000000" +ASSERT top_result.futureType == { "someField": 2 } +``` + +--- + +## RSO2h - get performs no client-side validation and surfaces server errors + +**Test ID**: `objects/unit/RSO2h/no-validation-server-error-0` + +**Spec requirement:** RSO2h — The library must not perform client-side validation of `params.objectId` or `params.path` content; any server-returned error must be surfaced to the caller as a rejected `ErrorInfo`. + +Tests that unusual `objectId`/`path` values are sent to the server, and the server's error response is +surfaced as the rejection. + +### Setup +```pseudo +channel_name = "test-RSO2h-" + random_id() +captured_requests = [] + +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + req.respond_with(404, { + "error": { "code": 40400, "statusCode": 404, "message": "Object not found" } + }) + } +) +install_mock(mock_http) + +client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: false, + plugins: { Objects: objects_plugin } +)) +channel = client.channels.get(channel_name) +``` + +### Test Steps and Assertions +```pseudo +AWAIT channel.object.get(RestObjectGetParams( + objectId: "not-a-valid-object-id", + path: "..*..", + compact: false +)) FAILS WITH error + +ASSERT captured_requests.length == 1 +ASSERT captured_requests[0].url.path == "/channels/" + encode_uri_component(channel_name) + + "/object/" + encode_uri_component("not-a-valid-object-id") +ASSERT captured_requests[0].url.query_params["path"] == "..*.." + +ASSERT error.code == 40400 +ASSERT error.statusCode == 404 +``` diff --git a/uts/objects/unit/rest_object_publish.md b/uts/objects/unit/rest_object_publish.md new file mode 100644 index 000000000..637fda189 --- /dev/null +++ b/uts/objects/unit/rest_object_publish.md @@ -0,0 +1,722 @@ +# RestObject Publish Tests + +Spec points: `RSO3`, `RSO3a1`, `RSO3b`, `RSO3c`, `RSO3d`, `RSO3d1`, `RSO3d2`, `RSO3d3`, `RSO3d4`, `RSO3e`, `RSO3f`, `RSO3g`, `RSO3h`, `RSO5`, `RSO5a`, `RSO5b`, `RSO5b1`, `RSO5c`, `RSO5d`, `RSO5e`, `RSO5f`, `RSO5g`, `RSO5h`, `RSO5i`, `RSO6`, `RSO7`, `RSO10`, `RSO13` + +## Test Type +Unit test with mocked HTTP client + +## Mock HTTP Infrastructure + +See `rest/unit/helpers/mock_http.md` for the full Mock HTTP Infrastructure specification. + +## Purpose + +Tests `RestObject#publish` request formation: endpoint, batching, the wire shape of each +`RestObjectOperation` variant, `ObjectData` encoding of leaf values, the absence of client-side +validation that is delegated to the server, and decoding of the `RestObjectPublishResult`. + +## Common Setup + +`objects_plugin` denotes the SDK's `Objects` plugin ([PC5](../../../specifications/features.md#PC5)), +supplied under the `Objects` `PluginType` key. + +Unless a test states otherwise, clients use the JSON protocol (`useBinaryProtocol: false`) so the +request body can be inspected with `parse_json`. + +`mapCreate.semantics` is written as the symbolic enum value `"LWW"` in operations the test constructs +(see *Enum values* in the UTS README), and is asserted on the wire as its `ObjectsMapSemantics` +integer encoding (`0`, per OMP2). + +```pseudo +DEFAULT_PUBLISH_RESPONSE = { + "messageId": "msg-id-1", + "channel": "ignored-by-tests", + "objectIds": [] +} + +setup_rest_object(channel_name, use_binary_protocol: false, client_options: {}): + captured_requests = [] + + mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + IF use_binary_protocol: + req.respond_with(201, msgpack_encode(DEFAULT_PUBLISH_RESPONSE), + headers: { "Content-Type": "application/x-msgpack" }) + ELSE: + req.respond_with(201, DEFAULT_PUBLISH_RESPONSE, + headers: { "Content-Type": "application/json" }) + } + ) + install_mock(mock_http) + + client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: use_binary_protocol, + plugins: { Objects: objects_plugin }, + ...client_options + )) + channel = client.channels.get(channel_name) + + RETURN { client, channel, captured_requests } +``` + +--- + +## RSO3e - Single operation sent as POST with a one-element JSON array body + +**Test ID**: `objects/unit/RSO3e/single-op-post-0` + +| Spec | Requirement | +|------|-------------| +| RSO3a1 | `op` is a single `RestObjectOperation` or an array of them | +| RSO3e | Sends a `POST` to `/channels/{channelName}/object` with the encoded operations as an array body, encoded per RSC8 | + +Tests that a single (non-array) operation is sent as a POST whose body is an array containing that one operation. + +### Setup +```pseudo +channel_name = "test-RSO3e-single-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish(RestObjectOperation( + objectId: "root", + mapSet: RestObjectMapSet(key: "greeting", value: PublishObjectData(string: "hello")) +)) +``` + +### Assertions +```pseudo +ASSERT captured_requests.length == 1 +request = captured_requests[0] +ASSERT request.method == "POST" +ASSERT request.url.path == "/channels/" + encode_uri_component(channel_name) + "/object" +ASSERT request.headers["Content-Type"] == "application/json" + +body = parse_json(request.body) +ASSERT body IS List +ASSERT body.length == 1 +ASSERT body[0]["objectId"] == "root" +ASSERT body[0]["mapSet"] == { "key": "greeting", "value": { "string": "hello" } } +``` + +--- + +## RSO3e - Request body encoded as MessagePack with the binary protocol + +**Test ID**: `objects/unit/RSO3e/msgpack-body-1` + +**Spec requirement:** RSO3e — The request body is encoded per RSC8: MessagePack when the binary protocol is in use. + +### Setup +```pseudo +channel_name = "test-RSO3e-msgpack-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name, use_binary_protocol: true) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish(RestObjectOperation( + path: "visits", + counterInc: RestObjectCounterInc(number: 1) +)) +``` + +### Assertions +```pseudo +request = captured_requests[0] +ASSERT request.method == "POST" +ASSERT request.headers["Content-Type"] == "application/x-msgpack" + +body = msgpack_decode(request.body) +ASSERT body IS List +ASSERT body.length == 1 +ASSERT body[0]["path"] == "visits" +ASSERT body[0]["counterInc"] == { "number": 1 } +``` + +--- + +## RSO3c - Array of operations sent in a single request, in order + +**Test ID**: `objects/unit/RSO3c/batch-single-request-0` + +**Spec requirement:** RSO3c — When `op` is an array, all operations must be sent in a single server request. + +### Setup +```pseudo +channel_name = "test-RSO3c-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation(path: "a", mapSet: RestObjectMapSet(key: "x", value: PublishObjectData(number: 1))), + RestObjectOperation(objectId: "root", mapRemove: RestObjectMapRemove(key: "old")), + RestObjectOperation(path: "score", counterInc: RestObjectCounterInc(number: -2)) +]) +``` + +### Assertions +```pseudo +ASSERT captured_requests.length == 1 + +body = parse_json(captured_requests[0].body) +ASSERT body.length == 3 +ASSERT body[0]["mapSet"]["key"] == "x" +ASSERT body[1]["mapRemove"] == { "key": "old" } +ASSERT body[2]["counterInc"] == { "number": -2 } +``` + +--- + +## RSO3h - No client-side limit on batch size + +**Test ID**: `objects/unit/RSO3h/no-batch-size-limit-0` + +**Spec requirement:** RSO3h — The library must not enforce a client-side limit on the number of operations in a batch. + +### Setup +```pseudo +channel_name = "test-RSO3h-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) + +ops = [] +FOR i IN 0..999: + ops.append(RestObjectOperation( + objectId: "root", + mapSet: RestObjectMapSet(key: "k" + str(i), value: PublishObjectData(number: i)) + )) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish(ops) +``` + +### Assertions +```pseudo +ASSERT captured_requests.length == 1 +body = parse_json(captured_requests[0].body) +ASSERT body.length == 1000 +ASSERT body[999]["mapSet"]["key"] == "k999" +``` + +--- + +## RSO3b, RSO10 - Publish result decoded from the response + +**Test ID**: `objects/unit/RSO10/publish-result-0` + +| Spec | Requirement | +|------|-------------| +| RSO3b | The return type is a `RestObjectPublishResult` | +| RSO10 | `RestObjectPublishResult` has `messageId`, `channel` and `objectIds` | + +### Setup +```pseudo +channel_name = "test-RSO10-" + random_id() + +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => req.respond_with(201, { + "messageId": "abc123:0", + "channel": channel_name, + "objectIds": ["map:newHash@1700000000000", "root"] + }) +) +install_mock(mock_http) + +client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: false, + plugins: { Objects: objects_plugin } +)) +channel = client.channels.get(channel_name) +``` + +### Test Steps +```pseudo +result = AWAIT channel.object.publish(RestObjectOperation( + path: "profile", + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {}) +)) +``` + +### Assertions +```pseudo +ASSERT result.messageId == "abc123:0" +ASSERT result.channel == channel_name +ASSERT result.objectIds == ["map:newHash@1700000000000", "root"] +``` + +--- + +## RSO3d4, RSO5c-RSO5i - Wire shape of each operation type, without an action field + +**Test ID**: `objects/unit/RSO3d4/op-wire-shape-no-action-0` + +| Spec | Requirement | +|------|-------------| +| RSO3d4 | The wire payload must not include an explicit `action` field; the action is inferred from the operation-specific field | +| RSO5c | `mapCreate` body: `semantics`, `entries` | +| RSO5d | `mapCreateWithObjectId` body: `initialValue`, `nonce` (with `objectId` set) | +| RSO5e | `mapSet` body: `key`, `value` | +| RSO5f | `mapRemove` body: `key` | +| RSO5g | `counterCreate` body: `count` | +| RSO5h | `counterCreateWithObjectId` body: `initialValue`, `nonce` (with `objectId` set) | +| RSO5i | `counterInc` body: `number` | + +Tests that each `RestObjectOperation` variant is encoded under its operation-specific field name with +the expected body, and that no `action` field is present. + +### Setup +```pseudo +channel_name = "test-RSO3d4-" + random_id() +``` + +### Test Cases + +| ID | Operation | Expected wire object | +|----|-----------|----------------------| +| 1 | `RestObjectOperation(path: "m", mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {}))` | `{ "path": "m", "mapCreate": { "semantics": 0, "entries": {} } }` | +| 2 | `RestObjectOperation(objectId: "map:h@1", mapCreateWithObjectId: RestObjectCreateWithObjectId(initialValue: "{\"semantics\":0,\"entries\":{}}", nonce: "nonce-0123456789ab"))` | `{ "objectId": "map:h@1", "mapCreateWithObjectId": { "initialValue": "{\"semantics\":0,\"entries\":{}}", "nonce": "nonce-0123456789ab" } }` | +| 3 | `RestObjectOperation(objectId: "root", mapSet: RestObjectMapSet(key: "k", value: PublishObjectData(boolean: true)))` | `{ "objectId": "root", "mapSet": { "key": "k", "value": { "boolean": true } } }` | +| 4 | `RestObjectOperation(path: "a.b", mapRemove: RestObjectMapRemove(key: "k"))` | `{ "path": "a.b", "mapRemove": { "key": "k" } }` | +| 5 | `RestObjectOperation(counterCreate: RestObjectCounterCreate(count: 10))` | `{ "counterCreate": { "count": 10 } }` | +| 6 | `RestObjectOperation(objectId: "counter:h@1", counterCreateWithObjectId: RestObjectCreateWithObjectId(initialValue: "{\"count\":10}", nonce: "nonce-0123456789ab"))` | `{ "objectId": "counter:h@1", "counterCreateWithObjectId": { "initialValue": "{\"count\":10}", "nonce": "nonce-0123456789ab" } }` | +| 7 | `RestObjectOperation(objectId: "counter:h@1", counterInc: RestObjectCounterInc(number: -5))` | `{ "objectId": "counter:h@1", "counterInc": { "number": -5 } }` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel, captured_requests } = setup_rest_object(channel_name) + + AWAIT channel.object.publish(test_case.operation) + + wire_op = parse_json(captured_requests[0].body)[0] + ASSERT wire_op == test_case.expected_wire_object + ASSERT "action" NOT IN wire_op +``` + +--- + +## RSO3d3 - id, objectId and path preserved verbatim + +**Test ID**: `objects/unit/RSO3d3/targeting-fields-verbatim-0` + +**Spec requirement:** RSO3d3 — The `id`, `objectId`, and `path` fields of the operation, if provided by the caller, must be preserved verbatim in the wire payload. + +### Setup +```pseudo +channel_name = "test-RSO3d3-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation( + id: "my-op-id:0", + objectId: "map:Ab-_9@1700000000000", + mapRemove: RestObjectMapRemove(key: "k") + ), + RestObjectOperation( + id: " spaced id ", + path: "a\\.b.*.c", + counterInc: RestObjectCounterInc(number: 1) + ) +]) +``` + +### Assertions +```pseudo +body = parse_json(captured_requests[0].body) + +ASSERT body[0]["id"] == "my-op-id:0" +ASSERT body[0]["objectId"] == "map:Ab-_9@1700000000000" +ASSERT "path" NOT IN body[0] + +ASSERT body[1]["id"] == " spaced id " +ASSERT body[1]["path"] == "a\\.b.*.c" +ASSERT "objectId" NOT IN body[1] +``` + +--- + +## RSO6 - publish passes path to the server verbatim + +**Test ID**: `objects/unit/RSO6/publish-path-verbatim-0` + +**Spec requirement:** RSO6 — The library must pass caller-supplied `path` strings in `RestObjectOperation` to the server without modification or normalization. + +### Setup +```pseudo +channel_name = "test-RSO6-publish-" + random_id() +``` + +### Test Cases + +| ID | path | +|----|------| +| 1 | `"items.*"` | +| 2 | `"a\\.b.c"` | +| 3 | `".a..b."` | +| 4 | `""` | +| 5 | `"ünïcödé.键"` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel, captured_requests } = setup_rest_object(channel_name) + + AWAIT channel.object.publish(RestObjectOperation( + path: test_case.path, + mapSet: RestObjectMapSet(key: "k", value: PublishObjectData(string: "v")) + )) + + ASSERT captured_requests.length == 1 + ASSERT parse_json(captured_requests[0].body)[0]["path"] == test_case.path +``` + +--- + +## RSO3d1 - mapCreate semantics encoded per OMP2 + +**Test ID**: `objects/unit/RSO3d1/mapcreate-semantics-encoded-0` + +**Spec requirement:** RSO3d1 — If the operation includes a `mapCreate.semantics` field, the library must encode the semantics value per OMP2 (`LWW` = `0`). + +### Setup +```pseudo +channel_name = "test-RSO3d1-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish(RestObjectOperation( + mapCreate: RestObjectMapCreate(semantics: "LWW", entries: {}) +)) +``` + +### Assertions +```pseudo +ASSERT parse_json(captured_requests[0].body)[0]["mapCreate"]["semantics"] == 0 +``` + +--- + +## RSO3d1 - Unrecognized mapCreate semantics rejected + +**Test ID**: `objects/unit/RSO3d1/unrecognized-semantics-error-1` + +**Spec requirement:** RSO3d1 — If the `mapCreate.semantics` value is unrecognized, the library should throw an `ErrorInfo` with `statusCode` 400 and `code` 40003. + +Not applicable to SDKs whose `ObjectsMapSemantics` type makes an unrecognized value unrepresentable +(see *Language-inapplicable inputs* in the UTS README). + +### Setup +```pseudo +channel_name = "test-RSO3d1-invalid-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps and Assertions +```pseudo +AWAIT channel.object.publish(RestObjectOperation( + mapCreate: RestObjectMapCreate(semantics: "not-a-semantics", entries: {}) +)) FAILS WITH error + +ASSERT error.code == 40003 +ASSERT error.statusCode == 400 +ASSERT captured_requests.length == 0 +``` + +--- + +## RSO3d2, RSO7 - mapSet value encoded per OD4 (JSON protocol) + +**Test ID**: `objects/unit/RSO3d2/mapset-value-encoded-json-0` + +| Spec | Requirement | +|------|-------------| +| RSO3d2 | `ObjectData` values reachable from the operation, including `mapSet.value`, must be encoded per OD4 | +| RSO7 | `PublishObjectData` has exactly one of `string`, `number`, `boolean`, `bytes`, `json`, `objectId` | +| OD4d | JSON protocol: `bytes` Base64-encoded; JSON object/array stringified into `json` (OD4d5) | + +### Setup +```pseudo +channel_name = "test-RSO3d2-json-" + random_id() +``` + +### Test Cases + +| ID | value | Expected wire `value` | +|----|-------|-----------------------| +| 1 | `PublishObjectData(string: "hello")` | `{ "string": "hello" }` | +| 2 | `PublishObjectData(number: 1.5)` | `{ "number": 1.5 }` | +| 3 | `PublishObjectData(boolean: false)` | `{ "boolean": false }` | +| 4 | `PublishObjectData(bytes: bytes([0x01, 0x02, 0x03]))` | `{ "bytes": "AQID" }` | +| 5 | `PublishObjectData(json: { "a": [1, 2] })` | `{ "json": "{\"a\":[1,2]}" }` | +| 6 | `PublishObjectData(json: [1, "x"])` | `{ "json": "[1,\"x\"]" }` | +| 7 | `PublishObjectData(objectId: "counter:h@1")` | `{ "objectId": "counter:h@1" }` | + +For JSON-encoded payloads (cases 5–6), compare `parse_json(value["json"])` against the input rather +than the exact string, since key order and whitespace of the stringified JSON are not specified. + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + { channel, captured_requests } = setup_rest_object(channel_name) + + AWAIT channel.object.publish(RestObjectOperation( + objectId: "root", + mapSet: RestObjectMapSet(key: "k", value: test_case.value) + )) + + wire_value = parse_json(captured_requests[0].body)[0]["mapSet"]["value"] + IF test_case.value.json IS NOT null: + ASSERT wire_value.keys() == {"json"} + ASSERT wire_value["json"] IS String + ASSERT parse_json(wire_value["json"]) == test_case.value.json + ELSE: + ASSERT wire_value == test_case.expected_wire_value +``` + +--- + +## RSO3d2 - mapSet value encoded per OD4 (MessagePack protocol) + +**Test ID**: `objects/unit/RSO3d2/mapset-value-encoded-msgpack-1` + +**Spec requirement:** RSO3d2 — `ObjectData` values are encoded per OD4. With MessagePack (OD4c), `bytes` is sent as MessagePack binary and JSON payloads are stringified into `json` as a MessagePack string (OD4c5). + +### Setup +```pseudo +channel_name = "test-RSO3d2-msgpack-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name, use_binary_protocol: true) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "bin", value: PublishObjectData(bytes: bytes([0x01, 0x02, 0x03])))), + RestObjectOperation(objectId: "root", + mapSet: RestObjectMapSet(key: "obj", value: PublishObjectData(json: { "a": 1 }))) +]) +``` + +### Assertions +```pseudo +body = msgpack_decode(captured_requests[0].body) + +ASSERT body[0]["mapSet"]["value"]["bytes"] IS Binary +ASSERT body[0]["mapSet"]["value"]["bytes"] == bytes([0x01, 0x02, 0x03]) + +ASSERT body[1]["mapSet"]["value"].keys() == {"json"} +ASSERT body[1]["mapSet"]["value"]["json"] IS String +ASSERT parse_json(body[1]["mapSet"]["value"]["json"]) == { "a": 1 } +``` + +--- + +## RSO3d2, RSO13 - mapCreate entries encoded per OD4 + +**Test ID**: `objects/unit/RSO3d2/mapcreate-entries-encoded-2` + +| Spec | Requirement | +|------|-------------| +| RSO3d2 | The `data` field of each entry in `mapCreate.entries` must be encoded per OD4 | +| RSO13 | `RestObjectMapEntry` has a `data` `PublishObjectData` | + +### Setup +```pseudo +channel_name = "test-RSO3d2-entries-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish(RestObjectOperation( + path: "profile", + mapCreate: RestObjectMapCreate( + semantics: "LWW", + entries: { + "name": RestObjectMapEntry(data: PublishObjectData(string: "Alice")), + "age": RestObjectMapEntry(data: PublishObjectData(number: 30)), + "active": RestObjectMapEntry(data: PublishObjectData(boolean: true)), + "avatar": RestObjectMapEntry(data: PublishObjectData(bytes: bytes([0x01, 0x02, 0x03]))), + "prefs": RestObjectMapEntry(data: PublishObjectData(json: { "theme": "dark" })), + "visits": RestObjectMapEntry(data: PublishObjectData(objectId: "counter:h@1")) + } + ) +)) +``` + +### Assertions +```pseudo +entries = parse_json(captured_requests[0].body)[0]["mapCreate"]["entries"] + +ASSERT entries["name"] == { "data": { "string": "Alice" } } +ASSERT entries["age"] == { "data": { "number": 30 } } +ASSERT entries["active"] == { "data": { "boolean": true } } +ASSERT entries["avatar"] == { "data": { "bytes": "AQID" } } +ASSERT entries["prefs"]["data"].keys() == {"json"} +ASSERT parse_json(entries["prefs"]["data"]["json"]) == { "theme": "dark" } +ASSERT entries["visits"] == { "data": { "objectId": "counter:h@1" } } +``` + +--- + +## RSO3f - No auto-generated operation id, even with idempotentRestPublishing + +**Test ID**: `objects/unit/RSO3f/no-auto-generated-id-0` + +**Spec requirement:** RSO3f — The library must not auto-generate `RestObjectOperation.id` values. The `idempotentRestPublishing` option does not apply to `RestObject#publish`. + +Tests that, with `idempotentRestPublishing: true`, operations without an `id` are sent without one, and +operations with an `id` keep it unchanged. + +### Setup +```pseudo +channel_name = "test-RSO3f-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name, + client_options: { idempotentRestPublishing: true }) +``` + +### Test Steps +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation(path: "a", counterInc: RestObjectCounterInc(number: 1)), + RestObjectOperation(id: "caller-id", path: "b", counterInc: RestObjectCounterInc(number: 1)) +]) +``` + +### Assertions +```pseudo +body = parse_json(captured_requests[0].body) +ASSERT "id" NOT IN body[0] +ASSERT body[1]["id"] == "caller-id" +``` + +--- + +## RSO5b1 - Operation with no body field rejected before any request + +**Test ID**: `objects/unit/RSO5b1/no-body-field-error-0` + +**Spec requirement:** RSO5b1 — If a `RestObjectOperation` has zero of the operation-specific body fields set, the library should throw an `ErrorInfo` with `statusCode` 400 and `code` 40003 before sending any HTTP request. + +Not applicable to SDKs whose `RestObjectOperation` representation makes an operation with no body +unrepresentable. + +### Setup +```pseudo +channel_name = "test-RSO5b1-none-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps and Assertions +```pseudo +AWAIT channel.object.publish(RestObjectOperation(objectId: "root")) FAILS WITH error + +ASSERT error.code == 40003 +ASSERT error.statusCode == 400 +ASSERT captured_requests.length == 0 +``` + +--- + +## RSO5b1 - Operation with multiple body fields rejected; no partial batch sent + +**Test ID**: `objects/unit/RSO5b1/multiple-body-fields-error-1` + +**Spec requirement:** RSO5b1 — If a `RestObjectOperation` has more than one of the operation-specific body fields set, the library should throw an `ErrorInfo` with `statusCode` 400 and `code` 40003 before sending any HTTP request. + +Tests that one invalid operation in a batch causes the whole publish to fail without any request being +sent. Not applicable to SDKs whose `RestObjectOperation` representation makes an operation with more +than one body unrepresentable. + +### Setup +```pseudo +channel_name = "test-RSO5b1-multi-" + random_id() +{ channel, captured_requests } = setup_rest_object(channel_name) +``` + +### Test Steps and Assertions +```pseudo +AWAIT channel.object.publish([ + RestObjectOperation(path: "ok", counterInc: RestObjectCounterInc(number: 1)), + RestObjectOperation( + objectId: "root", + mapSet: RestObjectMapSet(key: "k", value: PublishObjectData(string: "v")), + mapRemove: RestObjectMapRemove(key: "k") + ) +]) FAILS WITH error + +ASSERT error.code == 40003 +ASSERT error.statusCode == 400 +ASSERT captured_requests.length == 0 +``` + +--- + +## RSO3g - No client-side validation of targeting; server error surfaced + +**Test ID**: `objects/unit/RSO3g/no-targeting-validation-0` + +**Spec requirement:** RSO3g — The library must not perform client-side validation of operation targeting (combinations of `objectId` and `path`); any server-returned error must be surfaced to the caller as a rejected `ErrorInfo`. + +Tests that operations with targeting combinations the operation's constraints disallow (RSO5c3, RSO5e3) +are still sent to the server, and the server's error response is surfaced. + +### Setup +```pseudo +channel_name = "test-RSO3g-" + random_id() +captured_requests = [] + +mock_http = MockHttpClient( + onConnectionAttempt: (conn) => conn.respond_with_success(), + onRequest: (req) => { + captured_requests.append(req) + req.respond_with(400, { + "error": { "code": 40000, "statusCode": 400, "message": "Invalid operation targeting" } + }) + } +) +install_mock(mock_http) + +client = Rest(options: ClientOptions( + key: "appId.keyId:keySecret", + useBinaryProtocol: false, + plugins: { Objects: objects_plugin } +)) +channel = client.channels.get(channel_name) +``` + +### Test Cases + +| ID | Operation | +|----|-----------| +| 1 | `RestObjectOperation(objectId: "root", path: "a", mapSet: RestObjectMapSet(key: "k", value: PublishObjectData(string: "v")))` | +| 2 | `RestObjectOperation(mapRemove: RestObjectMapRemove(key: "k"))` | +| 3 | `RestObjectOperation(objectId: "counter:h@1", counterCreate: RestObjectCounterCreate(count: 1))` | + +### Test Steps and Assertions +```pseudo +FOR EACH test_case IN test_cases: + captured_requests.clear() + + AWAIT channel.object.publish(test_case.operation) FAILS WITH error + + ASSERT captured_requests.length == 1 + ASSERT error.code == 40000 + ASSERT error.statusCode == 400 +```